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 
2332 
2333 
2334 
2335 
2336 
2337 
2338 
2339 
2340 
2341 
2342 
2343 
2344 
2345 
2346 
2347 
2348 
2349 
2350 
2351 
2352 
2353 
2354 
2355 
2356 
2357 
2358 
2359 
2360 
2361 
2362 
2363 
2364 
2365 
2366 
2367 
2368 
2369 
2370 
2371 
2372 
2373 
2374 
2375 
2376 
2377 
2378 
2379 
2380 
2381 
2382 
2383 
2384 
2385 
2386 
2387 
2388 
2389 
2390 
2391 
2392 
2393 
2394 
2395 
2396 
2397 
2398 
2399 
2400 
2401 
2402 
2403 
2404 
2405 
2406 
2407 
2408 
2409 
2410 
2411 
2412 
2413 
2414 
2415 
2416 
2417 
2418 
2419 
2420 
2421 
2422 
2423 
2424 
2425 
2426 
2427 
2428 
2429 
2430 
2431 
2432 
2433 
2434 
2435 
2436 
2437 
2438 
2439 
2440 
2441 
2442 
2443 
2444 
2445 
2446 
2447 
2448 
2449 
2450 
2451 
2452 
2453 
2454 
2455 
2456 
2457 
2458 
2459 
2460 
2461 
2462 
2463 
2464 
2465 
2466 
2467 
2468 
2469 
2470 
2471 
2472 
2473 
2474 
2475 
2476 
2477 
2478 
2479 
2480 
2481 
2482 
2483 
2484 
2485 
2486 
2487 
2488 
2489 
2490 
2491 
2492 
2493 
2494 
2495 
2496 
2497 
2498 
2499 
2500 
2501 
2502 
2503 
2504 
2505 
2506 
2507 
2508 
2509 
2510 
2511 
2512 
2513 
2514 
2515 
2516 
2517 
2518 
2519 
2520 
2521 
2522 
2523 
2524 
2525 
2526 
2527 
2528 
2529 
2530 
2531 
2532 
2533 
2534 
2535 
2536 
2537 
2538 
2539 
2540 
2541 
2542 
2543 
2544 
2545 
2546 
2547 
2548 
2549 
2550 
2551 
2552 
2553 
2554 
2555 
2556 
2557 
2558 
2559 
2560 
2561 
2562 
2563 
2564 
2565 
2566 
2567 
2568 
2569 
2570 
2571 
2572 
2573 
2574 
2575 
2576 
2577 
2578 
2579 
2580 
2581 
2582 
2583 
2584 
2585 
2586 
2587 
2588 
2589 
2590 
2591 
2592 
2593 
2594 
2595 
2596 
2597 
2598 
2599 
2600 
2601 
2602 
2603 
2604 
2605 
2606 
2607 
2608 
2609 
2610 
2611 
2612 
2613 
2614 
2615 
2616 
2617 
2618 
2619 
2620 
2621 
2622 
2623 
2624 
2625 
2626 
2627 
2628 
2629 
2630 
2631 
2632 
2633 
2634 
2635 
2636 
2637 
2638 
2639 
2640 
2641 
2642 
2643 
2644 
2645 
2646 
2647 
2648 
2649 
2650 
2651 
2652 
2653 
2654 
2655 
2656 
2657 
2658 
2659 
2660 
2661 
2662 
2663 
2664 
2665 
2666 
2667 
2668 
2669 
2670 
2671 
2672 
2673 
2674 
2675 
2676 
2677 
2678 
2679 
2680 
2681 
2682 
2683 
2684 
2685 
2686 
2687 
2688 
2689 
2690 
2691 
2692 
2693 
2694 
2695 
2696 
2697 
2698 
2699 
2700 
2701 
2702 
2703 
2704 
2705 
2706 
2707 
2708 
2709 
2710 
2711 
2712 
2713 
2714 
2715 
2716 
2717 
2718 
2719 
2720 
2721 
2722 
2723 
2724 
2725 
2726 
2727 
2728 
2729 
2730 
2731 
2732 
2733 
2734 
2735 
2736 
2737 
2738 
2739 
2740 
2741 
2742 
2743 
2744 
2745 
2746 
2747 
2748 
2749 
2750 
2751 
2752 
2753 
2754 
2755 
2756 
2757 
2758 
2759 
2760 
2761 
2762 
2763 
2764 
2765 
2766 
2767 
2768 
2769 
2770 
2771 
2772 
2773 
2774 
2775 
2776 
2777 
2778 
2779 
2780 
2781 
2782 
2783 
2784 
2785 
2786 
2787 
2788 
2789 
2790 
2791 
2792 
2793 
2794 
2795 
2796 
2797 
2798 
2799 
2800 
2801 
2802 
2803 
2804 
2805 
2806 
2807 
2808 
2809 
2810 
2811 
2812 
2813 
2814 
2815 
2816 
2817 
2818 
2819 
2820 
2821 
2822 
2823 
2824 
2825 
2826 
2827 
2828 
2829 
2830 
2831 
2832 
2833 
2834 
2835 
2836 
2837 
2838 
2839 
2840 
2841 
2842 
2843 
2844 
2845 
2846 
2847 
2848 
2849 
2850 
2851 
2852 
2853 
2854 
2855 
2856 
2857 
2858 
2859 
2860 
2861 
2862 
2863 
2864 
2865 
2866 
2867 
2868 
2869 
2870 
2871 
2872 
2873 
2874 
2875 
2876 
2877 
2878 
2879 
2880 
2881 
2882 
2883 
2884 
2885 
2886 
2887 
2888 
2889 
2890 
2891 
2892 
2893 
2894 
2895 
2896 
2897 
2898 
2899 
2900 
2901 
2902 
2903 
2904 
2905 
2906 
2907 
2908 
2909 
2910 
2911 
2912 
2913 
2914 
2915 
2916 
2917 
2918 
2919 
2920 
2921 
2922 
2923 
2924 
2925 
2926 
2927 
2928 
2929 
2930 
2931 
2932 
2933 
2934 
2935 
2936 
2937 
2938 
2939 
2940 
2941 
2942 
2943 
2944 
2945 
2946 
2947 
2948 
2949 
2950 
2951 
2952 
2953 
2954 
2955 
2956 
2957 
2958 
2959 
2960 
2961 
2962 
2963 
2964 
2965 
2966 
2967 
2968 
2969 
2970 
2971 
2972 
2973 
2974 
2975 
2976 
2977 
2978 
2979 
2980 
2981 
2982 
2983 
2984 
2985 
2986 
2987 
2988 
2989 
2990 
2991 
2992 
2993 
2994 
2995 
2996 
2997 
2998 
2999 
3000 
3001 
3002 
3003 
3004 
3005 
3006 
3007 
3008 
3009 
3010 
3011 
3012 
3013 
3014 
3015 
3016 
3017 
3018 
3019 
3020 
3021 
3022 
3023 
3024 
3025 
3026 
3027 
3028 
3029 
3030 
3031 
3032 
3033 
3034 
3035 
3036 
3037 
3038 
3039 
3040 
3041 
3042 
3043 
3044 
3045 
3046 
3047 
3048 
3049 
3050 
3051 
3052 
3053 
3054 
3055 
3056 
3057 
3058 
3059 
3060 
3061 
3062 
3063 
3064 
3065 
3066 
3067 
3068 
3069 
3070 
3071 
3072 
3073 
3074 
3075 
3076 
3077 
3078 
3079 
3080 
3081 
3082 
3083 
3084 
3085 
3086 
3087 
3088 
3089 
3090 
3091 
3092 
3093 
3094 
3095 
3096 
3097 
3098 
3099 
3100 
3101 
3102 
3103 
3104 
3105 
3106 
3107 
3108 
3109 
3110 
3111 
3112 
3113 
3114 
3115 
3116 
3117 
3118 
3119 
3120 
3121 
3122 
3123 
3124 
3125 
3126 
3127 
3128 
3129 
3130 
3131 
3132 
3133 
3134 
3135 
3136 
3137 
3138 
3139 
3140 
3141 
3142 
3143 
3144 
3145 
3146 
3147 
3148 
3149 
3150 
3151 
3152 
3153 
3154 
3155 
3156 
3157 
3158 
3159 
3160 
3161 
3162 
3163 
3164 
3165 
3166 
3167 
3168 
3169 
3170 
3171 
3172 
3173 
3174 
3175 
3176 
3177 
3178 
3179 
3180 
3181 
3182 
3183 
3184 
3185 
3186 
3187 
3188 
3189 
3190 
3191 
3192 
3193 
3194 
3195 
3196 
3197 
3198 
3199 
3200 
3201 
3202 
3203 
3204 
3205 
3206 
3207 
3208 
3209 
3210 
3211 
3212 
3213 
3214 
3215 
3216 
3217 
3218 
3219 
3220 
3221 
3222 
3223 
3224 
3225 
3226 
3227 
3228 
3229 
3230 
3231 
3232 
3233 
3234 
3235 
3236 
3237 
3238 
3239 
3240 
3241 
3242 
3243 
3244 
3245 
3246 
3247 
3248 
3249 
3250 
3251 
3252 
3253 
3254 
3255 
3256 
3257 
3258 
3259 
3260 
3261 
3262 
3263 
3264 
3265 
3266 
3267 
3268 
3269 
3270 
3271 
3272 
3273 
3274 
3275 
3276 
3277 
3278 
3279 
3280 
3281 
3282 
3283 
3284 
3285 
3286 
3287 
3288 
3289 
3290 
3291 
3292 
3293 
3294 
3295 
3296 
3297 
3298 
3299 
3300 
3301 
3302 
3303 
3304 
3305 
3306 
3307 
3308 
3309 
3310 
3311 
3312 
3313 
3314 
3315 
3316 
3317 
3318 
3319 
3320 
3321 
3322 
3323 
3324 
3325 
3326 
3327 
3328 
3329 
3330 
3331 
3332 
3333 
3334 
3335 
3336 
3337 
3338 
3339 
3340 
3341 
3342 
3343 
3344 
3345 
3346 
3347 
3348 
3349 
3350 
3351 
3352 
3353 
3354 
3355 
3356 
3357 
3358 
3359 
3360 
3361 
3362 
3363 
3364 
3365 
3366 
3367 
3368 
3369 
3370 
3371 
3372 
3373 
3374 
3375 
3376 
3377 
3378 
3379 
3380 
3381 
3382 
3383 
3384 
3385 
3386 
3387 
3388 
3389 
3390 
3391 
3392 
3393 
3394 
3395 
3396 
3397 
3398 
3399 
3400 
3401 
3402 
3403 
3404 
3405 
3406 
3407 
3408 
3409 
3410 
3411 
3412 
3413 
3414 
3415 
3416 
3417 
3418 
3419 
3420 
3421 
3422 
3423 
3424 
3425 
3426 
3427 
3428 
3429 
3430 
3431 
3432 
3433 
3434 
3435 
3436 
3437 
3438 
3439 
3440 
3441 
3442 
3443 
3444 
3445 
3446 
3447 
3448 
3449 
3450 
3451 
3452 
3453 
3454 
3455 
3456 
3457 
3458 
3459 
3460 
3461 
3462 
3463 
3464 
3465 
3466 
3467 
3468 
3469 
3470 
3471 
3472 
3473 
3474 
3475 
3476 
3477 
3478 
3479 
3480 
3481 
3482 
3483 
3484 
3485 
3486 
3487 
3488 
3489 
3490 
3491 
3492 
3493 
3494 
3495 
3496 
3497 
3498 
3499 
3500 
3501 
3502 
3503 
3504 
3505 
3506 
3507 
3508 
3509 
3510 
3511 
3512 
3513 
3514 
3515 
3516 
3517 
3518 
3519 
3520 
3521 
3522 
3523 
3524 
3525 
3526 
3527 
3528 
3529 
3530 
3531 
3532 
3533 
3534 
3535 
3536 
3537 
3538 
3539 
3540 
3541 
3542 
3543 
3544 
3545 
3546 
3547 
3548 
3549 
3550 
3551 
3552 
3553 
3554 
3555 
3556 
3557 
3558 
3559 
3560 
3561 
3562 
3563 
3564 
3565 
3566 
3567 
3568 
3569 
3570 
3571 
3572 
3573 
3574 
3575 
3576 
3577 
3578 
3579 
3580 
3581 
3582 
3583 
3584 
3585 
3586 
3587 
3588 
3589 
3590 
3591 
3592 
3593 
3594 
3595 
3596 
3597 
3598 
3599 
3600 
3601 
3602 
3603 
3604 
3605 
3606 
3607 
3608 
3609 
3610 
3611 
3612 
3613 
3614 
3615 
3616 
3617 
3618 
3619 
3620 
3621 
3622 
3623 
3624 
3625 
3626 
3627 
3628 
3629 
3630 
3631 
3632 
3633 
3634 
3635 
3636 
3637 
3638 
3639 
3640 
3641 
3642 
3643 
3644 
3645 
3646 
3647 
3648 
3649 
3650 
3651 
3652 
3653 
3654 
3655 
3656 
3657 
3658 
3659 
3660 
3661 
3662 
3663 
3664 
3665 
3666 
3667 
3668 
3669 
3670 
3671 
3672 
3673 
3674 
3675 
3676 
3677 
3678 
3679 
3680 
3681 
3682 
3683 
3684 
3685 
3686 
3687 
3688 
3689 
3690 
3691 
3692 
3693 
3694 
3695 
3696 
3697 
3698 
3699 
3700 
3701 
3702 
3703 
3704 
3705 
3706 
3707 
3708 
3709 
3710 
3711 
3712 
3713 
3714 
3715 
3716 
3717 
3718 
3719 
3720 
3721 
3722 
3723 
3724 
3725 
3726 
3727 
3728 
3729 
3730 
3731 
3732 
3733 
3734 
3735 
3736 
3737 
3738 
3739 
3740 
3741 
3742 
3743 
3744 
3745 
3746 
3747 
3748 
3749 
3750 
3751 
3752 
3753 
3754 
3755 
3756 
3757 
3758 
3759 
3760 
3761 
3762 
3763 
3764 
3765 
3766 
3767 
3768 
3769 
3770 
3771 
3772 
3773 
3774 
3775 
3776 
3777 
3778 
3779 
3780 
3781 
3782 
3783 
3784 
3785 
3786 
3787 
3788 
3789 
3790 
3791 
3792 
3793 
3794 
3795 
3796 
3797 
3798 
3799 
3800 
3801 
3802 
3803 
3804 
3805 
3806 
3807 
3808 
3809 
3810 
3811 
3812 
3813 
3814 
3815 
3816 
3817 
3818 
3819 
3820 
3821 
3822 
3823 
3824 
3825 
3826 
3827 
3828 
3829 
3830 
3831 
3832 
3833 
3834 
3835 
3836 
3837 
3838 
3839 
3840 
3841 
3842 
3843 
3844 
3845 
3846 
3847 
3848 
3849 
3850 
3851 
3852 
3853 
3854 
3855 
3856 
3857 
3858 
3859 
3860 
3861 
3862 
3863 
3864 
3865 
3866 
3867 
3868 
3869 
3870 
3871 
3872 
3873 
3874 
3875 
3876 
3877 
3878 
3879 
3880 
3881 
3882 
3883 
3884 
3885 
3886 
3887 
3888 
3889 
3890 
3891 
3892 
3893 
3894 
3895 
3896 
3897 
3898 
3899 
3900 
3901 
3902 
3903 
3904 
3905 
3906 
3907 
3908 
3909 
3910 
3911 
3912 
3913 
3914 
3915 
3916 
3917 
3918 
3919 
3920 
3921 
3922 
3923 
3924 
3925 
3926 
3927 
3928 
3929 
3930 
3931 
3932 
3933 
3934 
3935 
3936 
3937 
3938 
3939 
3940 
3941 
3942 
3943 
3944 
3945 
3946 
3947 
3948 
3949 
3950 
3951 
3952 
3953 
3954 
3955 
3956 
3957 
3958 
3959 
3960 
3961 
3962 
3963 
3964 
3965 
3966 
3967 
3968 
3969 
3970 
3971 
3972 
3973 
3974 
3975 
3976 
3977 
3978 
3979 
3980 
3981 
3982 
3983 
3984 
3985 
3986 
3987 
3988 
3989 
3990 
3991 
3992 
3993 
3994 
3995 
3996 
3997 
3998 
3999 
4000 
4001 
4002 
4003 
4004 
4005 
4006 
4007 
4008 
4009 
4010 
4011 
4012 
4013 
4014 
4015 
4016 
4017 
4018 
4019 
4020 
4021 
4022 
4023 
4024 
4025 
4026 
4027 
4028 
4029 
4030 
4031 
4032 
4033 
4034 
4035 
4036 
4037 
4038 
4039 
4040 
4041 
4042 
4043 
4044 
4045 
4046 
4047 
4048 
4049 
4050 
4051 
4052 
4053 
4054 
4055 
4056 
4057 
4058 
4059 
4060 
4061 
4062 
4063 
4064 
4065 
4066 
4067 
4068 
4069 
4070 
4071 
4072 
4073 
4074 
4075 
4076 
4077 
4078 
4079 
4080 
4081 
4082 
4083 
4084 
4085 
4086 
4087 
4088 
4089 
4090 
4091 
4092 
4093 
4094 
4095 
4096 
4097 
4098 
4099 
4100 
4101 
4102 
4103 
4104 
4105 
4106 
4107 
4108 
4109 
4110 
4111 
4112 
4113 
4114 
4115 
4116 
4117 
4118 
4119 
4120 
4121 
4122 
4123 
4124 
4125 
4126 
4127 
4128 
4129 
4130 
4131 
4132 
4133 
4134 
4135 
4136 
4137 
4138 
4139 
4140 
4141 
4142 
4143 
4144 
4145 
4146 
4147 
4148 
4149 
4150 
4151 
4152 
4153 
4154 
4155 
4156 
4157 
4158 
4159 
4160 
4161 
4162 
4163 
4164 
4165 
4166 
4167 
4168 
4169 
4170 
4171 
4172 
4173 
4174 
4175 
4176 
4177 
4178 
4179 
4180 
4181 
4182 
4183 
4184 
4185 
4186 
4187 
4188 
4189 
4190 
4191 
4192 
4193 
4194 
4195 
4196 
4197 
4198 
4199 
4200 
4201 
4202 
4203 
4204 
4205 
4206 
4207 
4208 
4209 
4210 
4211 
4212 
4213 
4214 
4215 
4216 
4217 
4218 
4219 
4220 
4221 
4222 
4223 
4224 
4225 
4226 
4227 
4228 
4229 
4230 
4231 
4232 
4233 
4234 
4235 
4236 
4237 
4238 
4239 
4240 
4241 
4242 
4243 
4244 
4245 
4246 
4247 
4248 
4249 
4250 
4251 
4252 
4253 
4254 
4255 
4256 
4257 
4258 
4259 
4260 
4261 
4262 
4263 
4264 
4265 
4266 
4267 
4268 
4269 
4270 
4271 
4272 
4273 
4274 
4275 
4276 
4277 
4278 
4279 
4280 
4281 
4282 
4283 
4284 
4285 
4286 
4287 
4288 
4289 
4290 
4291 
4292 
4293 
4294 
4295 
4296 
4297 
4298 
4299 
4300 
4301 
4302 
4303 
4304 
4305 
4306 
4307 
4308 
4309 
4310 
4311 
4312 
4313 
4314 
4315 
4316 
4317 
4318 
4319 
4320 
4321 
4322 
4323 
4324 
4325 
4326 
4327 
4328 
4329 
4330 
4331 
4332 
4333 
4334 
4335 
4336 
4337 
4338 
4339 
4340 
4341 
4342 
4343 
4344 
4345 
4346 
4347 
4348 
4349 
4350 
4351 
4352 
4353 
4354 
4355 
4356 
4357 
4358 
4359 
4360 
4361 
4362 
4363 
4364 
4365 
4366 
4367 
4368 
4369 
4370 
4371 
4372 
4373 
4374 
4375 
4376 
4377 
4378 
4379 
4380 
4381 
4382 
4383 
4384 
4385 
4386 
4387 
4388 
4389 
4390 
4391 
4392 
4393 
4394 
4395 
4396 
4397 
4398 
4399 
4400 
4401 
4402 
4403 
4404 
4405 
4406 
4407 
4408 
4409 
4410 
4411 
4412 
4413 
4414 
4415 
4416 
4417 
4418 
4419 
4420 
4421 
4422 
4423 
4424 
4425 
4426 
4427 
4428 
4429 
4430 
4431 
4432 
4433 
4434 
4435 
4436 
4437 
4438 
4439 
4440 
4441 
4442 
4443 
4444 
4445 
4446 
4447 
4448 
4449 
4450 
4451 
4452 
4453 
4454 
4455 
4456 
4457 
4458 
4459 
4460 
4461 
4462 
4463 
4464 
4465 
4466 
4467 
4468 
4469 
4470 
4471 
4472 
4473 
4474 
4475 
4476 
4477 
4478 
4479 
4480 
4481 
4482 
4483 
4484 
4485 
4486 
4487 
4488 
4489 
4490 
4491 
4492 
4493 
4494 
4495 
4496 
4497 
4498 
4499 
4500 
4501 
4502 
4503 
4504 
4505 
4506 
4507 
4508 
4509 
4510 
4511 
4512 
4513 
4514 
4515 
4516 
4517 
4518 
4519 
4520 
4521 
4522 
4523 
4524 
4525 
4526 
4527 
4528 
4529 
4530 
4531 
4532 
4533 
4534 
4535 
4536 
4537 
4538 
4539 
4540 
4541 
4542 
4543 
4544 
4545 
4546 
4547 
4548 
4549 
4550 
4551 
4552 
4553 
4554 
4555 
4556 
4557 
4558 
4559 
4560 
4561 
4562 
4563 
4564 
4565 
4566 
4567 
4568 
4569 
4570 
4571 
4572 
4573 
4574 
4575 
4576 
4577 
4578 
4579 
4580 
4581 
4582 
4583 
4584 
4585 
4586 
4587 
4588 
4589 
4590 
4591 
4592 
4593 
4594 
4595 
4596 
4597 
4598 
4599 
4600 
4601 
4602 
4603 
4604 
4605 
4606 
4607 
4608 
4609 
4610 
4611 
4612 
4613 
4614 
4615 
4616 
4617 
4618 
4619 
4620 
4621 
4622 
4623 
4624 
4625 
4626 
4627 
4628 
4629 
4630 
4631 
4632 
4633 
4634 
4635 
4636 
4637 
4638 
4639 
4640 
4641 
4642 
4643 
4644 
4645 
4646 
4647 
4648 
4649 
4650 
4651 
4652 
4653 
4654 
4655 
4656 
4657 
4658 
4659 
4660 
4661 
4662 
4663 
4664 
4665 
4666 
4667 
4668 
4669 
4670 
4671 
4672 
4673 
4674 
4675 
4676 
4677 
4678 
4679 
4680 
4681 
4682 
4683 
4684 
4685 
4686 
4687 
4688 
4689 
4690 
4691 
4692 
4693 
4694 
4695 
4696 
4697 
4698 
4699 
4700 
4701 
4702 
4703 
4704 
4705 
4706 
4707 
4708 
4709 
4710 
4711 
4712 
4713 
4714 
4715 
4716 
4717 
4718 
4719 
4720 
4721 
4722 
4723 
4724 
4725 
4726 
4727 
4728 
4729 
4730 
4731 
4732 
4733 
4734 
4735 
4736 
4737 
4738 
4739 
4740 
4741 
4742 
4743 
4744 
4745 
4746 
4747 
4748 
4749 
4750 
4751 
4752 
4753 
4754 
4755 
4756 
4757 
4758 
4759 
4760 
4761 
4762 
4763 
4764 
4765 
4766 
4767 
4768 
4769 
4770 
4771 
4772 
4773 
4774 
4775 
4776 
4777 
4778 
4779 
4780 
4781 
4782 
4783 
4784 
4785 
4786 
4787 
4788 
4789 
4790 
4791 
4792 
4793 
4794 
4795 
4796 
4797 
4798 
4799 
4800 
4801 
4802 
4803 
4804 
4805 
4806 
4807 
4808 
4809 
4810 
4811 
4812 
4813 
4814 
4815 
4816 
4817 
4818 
4819 
4820 
4821 
4822 
4823 
4824 
4825 
4826 
4827 
4828 
4829 
4830 
4831 
4832 
4833 
4834 
4835 
4836 
4837 
4838 
4839 
4840 
4841 
4842 
4843 
4844 
4845 
4846 
4847 
4848 
4849 
4850 
4851 
4852 
4853 
4854 
4855 
4856 
4857 
4858 
4859 
4860 
4861 
4862 
4863 
4864 
4865 
4866 
4867 
4868 
4869 
4870 
4871 
4872 
4873 
4874 
4875 
4876 
4877 
4878 
4879 
4880 
4881 
4882 
4883 
4884 
4885 
4886 
4887 
4888 
4889 
4890 
4891 
4892 
4893 
4894 
4895 
4896 
4897 
4898 
4899 
4900 
4901 
4902 
4903 
4904 
4905 
4906 
4907 
4908 
4909 
4910 
4911 
4912 
4913 
4914 
4915 
4916 
4917 
4918 
4919 
4920 
4921 
4922 
4923 
4924 
4925 
4926 
4927 
4928 
4929 
4930 
4931 
4932 
4933 
4934 
4935 
4936 
4937 
4938 
4939 
4940 
4941 
4942 
4943 
4944 
4945 
4946 
4947 
4948 
/*
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/>.
*/

// VersionCheck (check for new version)
function netVersionCheck()
{
	$.ajax({
		type: 'GET',
		url: globalVersionCheckURL,
		cache: false,
		crossDomain: false,
		timeout: 30000,
		beforeSend: function(req) {
			req.setRequestHeader('X-client', globalXClientHeader);
		},
		contentType: 'text/xml; charset=utf-8',
		processData: true,
		data: '',
		dataType: 'xml',
		error: function(objAJAXRequest, strError){
			console.log("Error: [netVersionCheck: 'GET "+globalVersionCheckURL+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'");
			return false;
		},
		success: function(data, textStatus, xml)
		{
			var count=0;
			var tmp=$(xml.responseXML).find('updates').find(globalAppName.toLowerCase());
			var type=tmp.attr('type');
			var home=tmp.attr('homeURL');
			var version_txt=tmp.attr('version');
			var build_no_txt=(typeof globalEnableDevelBuilds=='undefined' || globalEnableDevelBuilds!=true ? tmp.attr('build_no') : tmp.attr('dev_build_no'));

			if(type==undefined || type=='' || home==undefined || home=='' || version_txt==undefined || version_txt=='' || build_no_txt==undefined || build_no_txt=='')
				return false;

			var build_no=build_no_txt.match(RegExp('^([0-9]+)$'));
			if(build_no==null)
				return false;

			if(globalBuildNo<parseInt(build_no[1]))
			{
				var showNofication=false;

				if(globalNewVersionNotifyUsers.length==0)
					showNofication=true;
				else
				{
					for(var i=0;i<globalAccountSettings.length;i++)
						if(globalNewVersionNotifyUsers.indexOf(globalAccountSettings[i].userAuth.userName)!=-1)
						{
							showNofication=true;
							break;
						}
				}

				if(showNofication==true)
				{
					$('div.update_h').html(localization[globalInterfaceLanguage].updateNotification.replace('%name%',globalAppName).replace('%new_ver%','<span id="newversion" class="update_h"></span>').replace('%curr_ver%', '<span id="version" class="update_h"></span>').replace('%url%', '<span id="homeurl" class="update_h" onclick=""></span>'));
					$('div.update_h').find('span#version').text(globalVersion);

					$('div.update_h').find('span#newversion').text(version_txt);
					$('div.update_h').find('span#homeurl').attr('onclick','window.open(\''+home+'\')');
					$('div.update_h').find('span#homeurl').text(home);

					setTimeout(function(){
						var orig_width=$('div.update_d').width();
						$('div.update_d').css('width', '0px');
						$('div.update_d').css('display','');
						$('div.update_d').animate({width: '+='+orig_width+'px'}, 500);
					}, 5000);
				}
			}
		}
	});
}

// Load the configuration from XML file
function netCheckAndCreateConfiguration(configurationURL)
{
	$.ajax({
		type: 'PROPFIND',
		url: configurationURL.href,
		cache: false,
		crossDomain: (typeof configurationURL.crossDomain=='undefined' ? true : configurationURL.crossDomain),
		xhrFields: {
			withCredentials: (typeof configurationURL.withCredentials=='undefined' ? false : configurationURL.withCredentials)
		},
		timeout: configurationURL.timeOut,
		beforeSend: function(req){
			if(globalSettings.usejqueryauth.value!=true && globalLoginUsername!='' && globalLoginPassword!='')
				req.setRequestHeader('Authorization', basicAuth(globalLoginUsername,globalLoginPassword));
			req.setRequestHeader('X-client', globalXClientHeader);
			req.setRequestHeader('Depth', '0');
		},
		username: (globalSettings.usejqueryauth.value==true ? globalLoginUsername : null),
		password: (globalSettings.usejqueryauth.value==true ? globalLoginPassword : null),
		contentType: 'text/xml; charset=utf-8',
		processData: true,
		data: '<?xml version="1.0" encoding="utf-8"?><D:propfind xmlns:D="DAV:"><D:prop><D:current-user-principal/></D:prop></D:propfind>',
		dataType: 'xml',
		error: function(objAJAXRequest, strError){
			console.log("Error: [netCheckAndCreateConfiguration: 'PROPFIND "+configurationURL.href+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
			$('#LoginLoader').fadeOut(1200);
			return false;
		},
		success: function(data, textStatus, xml)
		{
			var count=0;
			if($(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').children().filterNsNode('propstat').children().filterNsNode('status').text().match(RegExp('200 OK$')))
			{
				if(typeof globalAccountSettings=='undefined')
					globalAccountSettings=[];

				globalAccountSettings[globalAccountSettings.length]=$.extend({}, configurationURL);
				globalAccountSettings[globalAccountSettings.length-1].type='network';
				if(typeof(globalAccountSettingsHook)=='function')	// Hook for globalAccountSettings (openCRX)
					globalAccountSettings[globalAccountSettings.length-1].href=globalAccountSettingsHook(configurationURL.href, globalLoginUsername);
				else	// standard version
					globalAccountSettings[globalAccountSettings.length-1].href=configurationURL.href+globalLoginUsername+'/';
				globalAccountSettings[globalAccountSettings.length-1].userAuth={userName: globalLoginUsername, userPassword: globalLoginPassword};
				count++;

				if(configurationURL.additionalResources!=undefined && configurationURL.additionalResources.length>0)
				{
					for(var i=0;i<configurationURL.additionalResources.length;i++)
					{
						if(globalLoginUsername!=configurationURL.additionalResources[i])
						{
							globalAccountSettings[globalAccountSettings.length]=$.extend({}, configurationURL);
							globalAccountSettings[globalAccountSettings.length-1].type='network';
							globalAccountSettings[globalAccountSettings.length-1].href=configurationURL.href+configurationURL.additionalResources[i]+'/';
							globalAccountSettings[globalAccountSettings.length-1].userAuth={userName: globalLoginUsername, userPassword: globalLoginPassword};
							count++;
						}
					}
				}
			}

			if(count)
			{
				if(globalAccountSettings[0].delegation)
					DAVresourceDelegation(globalAccountSettings[0], 0, 0);
				else
				{
					// start the client
					if(isAvaible('CardDavMATE'))
						runCardDAV();
					if(isAvaible('CalDavZAP'))
						runCalDAV();
					if(isAvaible('Projects'))
						runProjects();
					if(isAvaible('Settings'))
						runSettings();

					globalResourceNumber=globalAccountSettings.length;
					loadAllResources();
				}
			}
			else
				$('#LoginLoader').fadeOut(1200);
		}
	});
}

// Load the configuration from XML file
function netLoadConfiguration(configurationURL)
{
	$.ajax({
		type: 'GET',
		url: configurationURL.href+'?browser_date='+$.datepicker.formatDate("yyyy-MM-dd", new Date())+(ignoreServerSettings==true ? '&ignore_settings=1' : ''),
		cache: false,
		crossDomain: (typeof configurationURL.crossDomain=='undefined' ? true : configurationURL.crossDomain),
		xhrFields: {
			withCredentials: (typeof configurationURL.withCredentials=='undefined' ? false : configurationURL.withCredentials)
		},
		timeout: configurationURL.timeOut,
		beforeSend: function(req) {
			if(globalSettings.usejqueryauth.value!=true && globalLoginUsername!='' && globalLoginPassword!='')
				req.setRequestHeader('Authorization', basicAuth(globalLoginUsername,globalLoginPassword));
			req.setRequestHeader('X-client', globalXClientHeader);
		},
		username: (globalSettings.usejqueryauth.value==true ? globalLoginUsername : null),
		password: (globalSettings.usejqueryauth.value==true ? globalLoginPassword : null),
		contentType: 'text/xml; charset=utf-8',
		processData: true,
		data: '',
		dataType: 'xml',
		error: function(objAJAXRequest, strError){
			console.log("Error: [loadConfiguration: 'GET "+configurationURL.href+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
			$('#LoginLoader').fadeOut(1200);
			return false;
		},
		success: function(data, textStatus, xml)
		{
			if(typeof globalAccountSettings=='undefined')
				globalAccountSettings=[];

			var count=0;
			var rex=new RegExp('^re(\\|[^:]*|):(.+)$');
			$(xml.responseXML).children('resources').children('resource').each(
				function(index, element)
				{
					if($(element).children().filterNsNode('type').children().filterNsNode('addressbook').length==1 || $(element).children().filterNsNode('type').children().filterNsNode('calendar').length==1)
					{
						// numeric/text options
						var href=$(element).children('href').text();
						var tmp=$(element).children('hreflabel').text();
						var hreflabel=(tmp!='' && tmp!='null' ? tmp : null);
						var username=$(element).children('userauth').children('username').text();
						var password=$(element).children('userauth').children('password').text();
						var timeout=$(element).children('timeout').text();
						var locktimeout=$(element).children('locktimeout').text();

						// array options
						var collectionTypes=new Array();
						if($(element).children().filterNsNode('type').children().filterNsNode('addressbook').length==1)
							collectionTypes[collectionTypes.length]='addressbook';
						if($(element).children().filterNsNode('type').children().filterNsNode('calendar').length==1)
							collectionTypes[collectionTypes.length]='calendar';

						// boolean options
						var tmp=$(element).children('withcredentials').text();
						var withcredentials=((tmp=='true' || tmp=='yes' || tmp=='1') ? true : false);
						var tmp=$(element).children('crossdomain').text();
						var crossdomain=((tmp=='false' || tmp=='no' || tmp=='0') ? false : true);
						var tmp=$(element).find('settingsaccount').text();
						var settingsaccount=((tmp=='true' || tmp=='yes' || tmp=='1') ? true : false);
						var tmp=$(element).find('checkcontenttype').text();
						var checkcontenttype=((tmp=='false' || tmp=='no' || tmp=='0') ? false : true);
						var tmp=$(element).find('ignorebound').text();
						var ignorebound=((tmp=='true' || tmp=='yes' || tmp=='1') ? true : false);

						// special options
						var forcereadonly=null;
						var tmp=$(element).children('forcereadonly');
						if(tmp.text()=='true')
							var forcereadonly=true;
						else
						{
							var tmp_ro=[];
							tmp.children('collection').each(
								function(index, element)
								{
									if((matched=$(element).text().match(rex))!=null && matched.length==3)
										tmp_ro[tmp_ro.length]=new RegExp(matched[2], matched[1].substring(matched[1].length>0 ? 1 : 0));
									else
										tmp_ro[tmp_ro.length]=$(element).text();
								}
							);
							if(tmp_ro.length>0)
								var forcereadonly=tmp_ro;
						}

						var delegation=false;
						var tmp=$(element).children('delegation');
						if(tmp.text()=='true')
							var delegation=true;
						else
						{
							var tmp_de=[];
							tmp.children('resource').each(
								function(index, element)
								{
									if((matched=$(element).text().match(rex))!=null && matched.length==3)
										tmp_de[tmp_de.length]=new RegExp(matched[2], matched[1].substring(matched[1].length>0 ? 1 : 0));
									else
										tmp_de[tmp_de.length]=$(element).text();
								}
							);
							if(tmp_de.length>0)
								var delegation=tmp_de;
						}
						var extendedDelegation=false;
						var tmp=$(element).children('extendeddelegation');
						if(tmp.text()=='true')
							extendedDelegation=true;

						var ignoreAlarms=false;
						var tmp=$(element).children('ignorealarms');
						if(tmp.text()=='true')
							var ignoreAlarms=true;
						else
						{
							var tmp_ia=[];
							tmp.children('collection').each(
								function(index, element)
								{
									if((matched=$(element).text().match(rex))!=null && matched.length==3)
										tmp_ia[tmp_ia.length]=new RegExp(matched[2], matched[1].substring(matched[1].length>0 ? 1 : 0));
									else
										tmp_ia[tmp_ia.length]=$(element).text();
								}
							);
							if(tmp_ia.length>0)
								var ignoreAlarms=tmp_ia;
						}

						var backgroundCalendars=[];
						var tmp=$(element).children('backgroundcalendars');
						if(tmp.text()!='')
						{
							tmp.children('collection').each(
								function(index, element)
								{
									if((matched=$(element).text().match(rex))!=null && matched.length==3)
										backgroundCalendars[backgroundCalendars.length]=new RegExp(matched[2], matched[1].substring(matched[1].length>0 ? 1 : 0));
									else
										backgroundCalendars[backgroundCalendars.length]=$(element).text();
								}
							);
						}

						globalAccountSettings[globalAccountSettings.length]={type: 'network', href: href, hrefLabel: hreflabel, crossDomain: crossdomain, settingsAccount: settingsaccount, checkContentType: checkcontenttype, forceReadOnly: forcereadonly, withCredentials: withcredentials, userAuth: {userName: username, userPassword: password}, timeOut: timeout, lockTimeOut: locktimeout, delegation: delegation, extendedDelegation: extendedDelegation, ignoreAlarms: ignoreAlarms, backgroundCalendars: backgroundCalendars, collectionTypes: collectionTypes, ignoreBound: ignorebound};
						count++;
					}
				}
			);

			if(count)
			{
				// store the pre-cached data for the client
				var tmp=$(xml.responseXML).children('resources').children('cache_data');
				if(tmp.length)
					globalXMLCache=tmp;

				if(globalAccountSettings[0].delegation)
					DAVresourceDelegation(globalAccountSettings[0], 0, 0);
				else
				{
					// start the client
					if(isAvaible('CardDavMATE'))
					{
						runCardDAV();
					}
					if(isAvaible('CalDavZAP'))
						runCalDAV();
					if(isAvaible('Projects'))
						runProjects();
					if(isAvaible('Settings'))
						runSettings();
					globalResourceNumber = globalAccountSettings.length;
					loadAllResources();
				}
			}
			else
				$('#LoginLoader').fadeOut(1200);
		}
	});
}

// Save the collection property (stored as DAV property on server)
function netSaveProperty(inputCollection, hrefProperty, inputProperty, inputValue)
{
	var dataXML = '<?xml version="1.0" encoding="utf-8"?><D:propertyupdate xmlns:D="DAV:"><D:set><D:prop><I:'+inputProperty+' xmlns:I="'+hrefProperty+'">'+inputValue+'</I:'+inputProperty+'></D:prop></D:set></D:propertyupdate>';
	$.ajax({
		type: 'PROPPATCH',
		url: inputCollection.url+inputCollection.href,
		cache: false,
		crossDomain: (typeof inputCollection.crossDomain=='undefined' ? true: inputCollection.crossDomain),
		xhrFields: {
			withCredentials: (typeof inputCollection.withCredentials=='undefined' ? false: inputCollection.withCredentials)
		},
		timeout: inputCollection.timeOut,
		beforeSend: function(req){
			if(globalSettings.usejqueryauth.value!=true && inputCollection.userAuth.userName!='' && inputCollection.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(inputCollection.userAuth.userName, inputCollection.userAuth.userPassword));

			req.setRequestHeader('X-client', globalXClientHeader);
			req.setRequestHeader('Depth', '0');
		},
		username: (globalSettings.usejqueryauth.value==true ? inputCollection.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? inputCollection.userAuth.userPassword : null),
		contentType: 'text/xml',
		processData: true,
		data: dataXML,
		dataType: 'xml',
		error: function(objAJAXRequest, strError){
			console.log("Error: [netSaveProperty: 'PROPPATCH "+inputCollection.url+inputCollection.href+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' (this error code usually means network connection error, or your browser is trying to make a cross domain query, but it is not allowed by the destination server or the browser itself)': ''));
			if(inputProperty=='calendar-color')
			{
				if(inputCollection.listType=='vevent')
				{
					$('#ResourceCalDAVList').find('[data-id="'+inputCollection.uid+'"]').find('.resourceCalDAVColor').css('background',inputCollection.ecolor);
					$('#ResourceCalDAVList').find('[data-id="'+inputCollection.uid+'"]').find('.colorPicker').spectrum('set',inputCollection.ecolor);
				}
				else
				{
					$('#ResourceCalDAVTODOList').find('[data-id="'+inputCollection.uid+'"]').find('.resourceCalDAVColor').css('background',inputCollection.ecolor);
					$('#ResourceCalDAVTODOList').find('[data-id="'+inputCollection.uid+'"]').find('.colorPicker').spectrum('set',inputCollection.ecolor);
				}
			}
			else if(inputProperty=='addressbook-color')
			{
				$('#ResourceCardDAVList').find('[data-id="'+inputCollection.uid+'"]').find('.resourceCardDAVColor').css('background',inputCollection.color);
				$('#ResourceCardDAVList').find('[data-id="'+inputCollection.uid+'"]').find('.colorPicker').spectrum('set',inputCollection.color);
			}
			return false;
		},
		success: function(data, textStatus, xml)
		{
			var color;
			if(inputProperty=='calendar-color')
			{
				var secondColl = null;
				if(inputCollection.listType=='vevent')
				{
					color = $('#ResourceCalDAVList').find('[data-id="'+inputCollection.uid+'"]').find('.colorPicker').spectrum('get').toHexString();
					if(inputCollection.fcSource!=null)
					{
						inputCollection.fcSource.backgroundColor=hexToRgba(color,0.9);
						inputCollection.fcSource.borderColor=color;
						inputCollection.fcSource.textColor=checkFontColor(color);
					}
					secondColl = globalResourceCalDAVList.getTodoCollectionByUID(inputCollection.uid);
					if(secondColl!=null)
					{
						$('#ResourceCalDAVTODOList').find('[data-id="'+inputCollection.uid+'"]').find('.resourceCalDAVColor').css('background',color);
						$('#ResourceCalDAVTODOList').find('[data-id="'+inputCollection.uid+'"]').find('.colorPicker').spectrum('set',color);
						if(secondColl.fcSource!=null)
						{
							secondColl.fcSource.backgroundColor=hexToRgba(color,0.9);
							secondColl.fcSource.borderColor=color;
						}
					}
				}
				else
				{
					color = $('#ResourceCalDAVTODOList').find('[data-id="'+inputCollection.uid+'"]').find('.colorPicker').spectrum('get').toHexString();
					if(inputCollection.fcSource!=null)
					{
						inputCollection.fcSource.backgroundColor=hexToRgba(color,0.9);
						inputCollection.fcSource.borderColor=color;
					}
					secondColl = globalResourceCalDAVList.getEventCollectionByUID(inputCollection.uid);
					if(secondColl!=null)
					{
						$('#ResourceCalDAVList').find('[data-id="'+inputCollection.uid+'"]').find('.resourceCalDAVColor').css('background',color);
						$('#ResourceCalDAVList').find('[data-id="'+inputCollection.uid+'"]').find('.colorPicker').spectrum('set',color);
						if(secondColl.fcSource!=null)
						{
							secondColl.fcSource.backgroundColor=hexToRgba(color,0.9);
							secondColl.fcSource.borderColor=color;
							secondColl.fcSource.textColor=checkFontColor(color);
						}
					}
				}

				inputCollection.ecolor = color;
				if(secondColl!=null)
					secondColl.ecolor = color;

				if(inputCollection.listType=='vevent' || secondColl!=null)
					$('#calendar').fullCalendar('refetchEvents');
				if(inputCollection.listType=='vtodo' || secondColl!=null)
					$('#todoList').fullCalendar('refetchEvents');
			}
			else if(inputProperty=='addressbook-color')
			{
				color = $('#ResourceCardDAVList').find('[data-id="'+inputCollection.uid+'"]').find('.colorPicker').spectrum('get').toHexString();
				inputCollection.color = color;
				if($('#ResourceCardDAVList').find('[data-id="'+inputCollection.uid+'"]').parent().find('.contact_group').find('div[data-id]').length>0)
					$('#ResourceCardDAVList').find('[data-id="'+inputCollection.uid+'"]').parent().find('.contact_group').find('div[data-id]').find('.resourceCardDAVGroupColor').css('background',color);
				globalAddressbookList.applyABFilter(dataGetChecked('#ResourceCardDAVList'), false);
				var selUID = $('#vCardEditor').find('[data-attr-name="_DEST_"]').find('option:selected').attr('data-type');
				var selColl=globalResourceCardDAVList.getCollectionByUID(selUID);
				$('#ABContactColor').css('background-color', selColl.color);
			}
		}
	});
}

function DAVresourceDelegation(inputResource, index, lastIndex)
{
	globalCalDAVResourceSync=false;
	var re=new RegExp('^(https?://)([^/]+)(.*)', 'i');
	var tmp=inputResource.href.match(re);

	var baseHref=tmp[1]+tmp[2];
	var uidBase=tmp[1]+inputResource.userAuth.userName+'@'+tmp[2];
	var uidFull=tmp[1]+inputResource.userAuth.userName+'@'+tmp[2]+tmp[3]; //for the error handler
	var settingsXML='';
	var delegationXML='';
	if(typeof inputResource.extendedDelegation!='undefined' && inputResource.extendedDelegation)
	{
		if(inputResource.href.indexOf(globalLoginUsername)!=-1 && inputResource.settingsAccount && (globalSettings.settingstype.value=='' || globalSettings.settingstype.value==null || (globalSettings.settingstype.value!='' && globalSettings.settingstype.value!=null && globalSettings.settingstype.value=='principal-URL')))
			settingsXML = '<D:property name="settings" namespace="http://inf-it.com/ns/dav/"/>';
		delegationXML='<?xml version="1.0" encoding="utf-8"?><D:expand-property xmlns:D="DAV:"><D:property name="calendar-proxy-read-for" namespace="http://calendarserver.org/ns/"><D:property name="resourcetype"/><D:property name="current-user-privilege-set"/><D:property name="displayname"/><D:property name="calendar-user-address-set" namespace="urn:ietf:params:xml:ns:caldav"/><D:property name="calendar-home-set" namespace="urn:ietf:params:xml:ns:caldav"/><D:property name="addressbook-home-set" namespace="urn:ietf:params:xml:ns:carddav"/></D:property><D:property name="calendar-proxy-write-for" namespace="http://calendarserver.org/ns/"><D:property name="resourcetype"/><D:property name="current-user-privilege-set"/><D:property name="displayname"/><D:property name="calendar-user-address-set" namespace="urn:ietf:params:xml:ns:caldav"/><D:property name="calendar-home-set" namespace="urn:ietf:params:xml:ns:caldav"/><D:property name="addressbook-home-set" namespace="urn:ietf:params:xml:ns:carddav"/></D:property>'+settingsXML+'<D:property name="resourcetype"/><D:property name="current-user-privilege-set"/><D:property name="displayname"/><D:property name="calendar-user-address-set" namespace="urn:ietf:params:xml:ns:caldav"/><D:property name="calendar-home-set" namespace="urn:ietf:params:xml:ns:caldav"/><D:property name="addressbook-home-set" namespace="urn:ietf:params:xml:ns:carddav"/></D:expand-property>';
	}
	else
		delegationXML='<?xml version="1.0" encoding="utf-8"?><A:expand-property xmlns:A="DAV:"><A:property name="calendar-proxy-read-for" namespace="http://calendarserver.org/ns/"><A:property name="email-address-set" namespace="http://calendarserver.org/ns/"/><A:property name="displayname" namespace="DAV:"/><A:property name="calendar-user-address-set" namespace="urn:ietf:params:xml:ns:caldav"/></A:property><A:property name="calendar-proxy-write-for" namespace="http://calendarserver.org/ns/"><A:property name="email-address-set" namespace="http://calendarserver.org/ns/"/><A:property name="displayname" namespace="DAV:"/><A:property name="calendar-user-address-set" namespace="urn:ietf:params:xml:ns:caldav"/></A:property></A:expand-property>';

	function ajaxComplete(data, textStatus, xml)
	{
		if(typeof globalAccountSettings=='undefined')
			globalAccountSettings=[];

		var hostPart=tmp[1]+tmp[2];
		var propElement=$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').children().filterNsNode('propstat').children().filterNsNode('prop');

		var searchR=new Array();
		searchR[searchR.length]=$(propElement).children().filterNsNode('calendar-proxy-read-for');
		searchR[searchR.length]=$(propElement).children().filterNsNode('calendar-proxy-write-for');
		for(var m=0; m<searchR.length; m++)
		{
			searchR[m].children().filterNsNode('response').each(
			function(dindex,delement){
				var href = $(delement).children().filterNsNode('href').text();
				var found=false;
				for(var i=0; i<globalAccountSettings.length; i++)
					if(decodeURIComponent(globalAccountSettings[i].href)==(hostPart+href))
						found=true;
				if(!found)
				{
					globalAccountSettings[globalAccountSettings.length]=$.extend({}, inputResource);
					globalAccountSettings[globalAccountSettings.length-1].type=inputResource.type;
					globalAccountSettings[globalAccountSettings.length-1].href=decodeURIComponent(hostPart+href);
					globalAccountSettings[globalAccountSettings.length-1].userAuth={userName: inputResource.userAuth.userName, userPassword: inputResource.userAuth.userPassword};
				}
				if(typeof inputResource.extendedDelegation!='undefined' && inputResource.extendedDelegation)
				{
					$(delement).children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('calendar-user-address-set').children().each(
					function(ind, elm)
					{
						var pHref = $(elm).text();
						if(pHref.indexOf('mailto:')!=-1)
							globalAccountSettings[globalAccountSettings.length-1].principalEmail=pHref.split('mailto:')[1];
					});

					var addressbook_home=$(delement).children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('addressbook-home-set').children().filterNsNode('href').text();
					if(addressbook_home=='')	// addressbook-home-set has no 'href' value -> SabreDav
						addressbook_home=$(delement).children().filterNsNode('href').text().replace('/principals/users/caldav.php','/caldav.php');

					if(addressbook_home.match(RegExp('^https?://','i'))!=null)	// absolute URL returned
						globalAccountSettings[globalAccountSettings.length-1].abhref=addressbook_home;
					else	// relative URL returned
						globalAccountSettings[globalAccountSettings.length-1].abhref=baseHref+addressbook_home;

					var calendar_home=$(delement).children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('calendar-home-set').children().filterNsNode('href').text();
					if(calendar_home=='')	// addressbook-home-set has no 'href' value -> SabreDav
						calendar_home=$(delement).children().filterNsNode('href').text().replace('/principals/users/caldav.php','/caldav.php');

					if(calendar_home.match(RegExp('^https?://','i'))!=null)	// absolute URL returned
						globalAccountSettings[globalAccountSettings.length-1].cahref=calendar_home;
					else	// relative URL returned
						globalAccountSettings[globalAccountSettings.length-1].cahref=baseHref+calendar_home;
				}

			});
		}
		if(typeof inputResource.extendedDelegation!='undefined' && inputResource.extendedDelegation && !settingsLoaded && inputResource.href.indexOf(globalLoginUsername)!=-1 && inputResource.settingsAccount && (globalSettings.settingstype.value=='' || globalSettings.settingstype.value==null || (globalSettings.settingstype.value!='' && globalSettings.settingstype.value!=null && globalSettings.settingstype.value=='principal-URL')))
		{
			var settings=$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('settings').text();
			if(settings!='')
			{
				if(!ignoreServerSettings)
					loadSettings(settings, true, false);
				else
				{
					delete globalSettings.version.value;
					loadSettings(JSON.stringify(globalSettings), false, false);
					console.log('Ignoring server settings: '+'\n'+settings);
				}
			}
			else
			{
				delete globalSettings.version.value;
				loadSettings(JSON.stringify(globalSettings), false, false);
			}
		}
		if(typeof inputResource.extendedDelegation!='undefined' && inputResource.extendedDelegation)
		{
			var response=$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response');
			$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('calendar-user-address-set').children().each(
			function(ind, elm)
			{
				var pHref = $(elm).text();
				if(pHref.indexOf('mailto:')!=-1)
					inputResource.principalEmail=pHref.split('mailto:')[1];
			});
			if(globalEmailAddress==''&&typeof inputResource.principalEmail!= 'undefined')
					globalEmailAddress=inputResource.principalEmail;

			var addressbook_home=response.children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('addressbook-home-set').children().filterNsNode('href').text();
			if(addressbook_home=='')	// addressbook-home-set has no 'href' value -> SabreDav
				addressbook_home=response.children().filterNsNode('href').text().replace('/principals/users/caldav.php','/caldav.php');

			if(addressbook_home.match(RegExp('^https?://','i'))!=null)	// absolute URL returned
				inputResource.abhref=addressbook_home;
			else	// relative URL returned
				inputResource.abhref=baseHref+addressbook_home;

			var calendar_home=response.children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('calendar-home-set').children().filterNsNode('href').text();
			if(calendar_home=='')	// addressbook-home-set has no 'href' value -> SabreDav
				calendar_home=response.children().filterNsNode('href').text().replace('/principals/users/caldav.php','/caldav.php');

			if(calendar_home.match(RegExp('^https?://','i'))!=null)	// absolute URL returned
				inputResource.cahref=calendar_home;
			else	// relative URL returned
				inputResource.cahref=baseHref+calendar_home;
		}

		if(index==lastIndex)
		{
			// start the client
			if(isAvaible('CardDavMATE'))
				runCardDAV();
			if(isAvaible('CalDavZAP'))
				runCalDAV();
			if(isAvaible('Projects'))
				runProjects();
			if(isAvaible('Settings'))
				runSettings();
			globalResourceNumber=globalAccountSettings.length;
			loadAllResources();
		}
	}

	// first try to process the cached data (if cached results are available in the "auth module" response)
	var tmpCache;
	var tmpDav = inputResource.href.match('^(.*/)([^/]+)/$');
	if(globalXMLCache!=null && (tmpCache=globalXMLCache.children('davprincipaldelegation[request_url="'+jqueryEscapeSelector(tmpDav[1]+encodeURIComponent(tmpDav[2])+'/')+'"]').remove()).length)
	{
		if(typeof globalDebug!='undefined' && globalDebug instanceof Array && globalDebug.indexOf('cache')!=-1)
			console.log('DBG Cache OK: '+arguments.callee.name+' url: \''+inputResource.href+'\': saved one request!');
		ajaxComplete('', 'success', {responseXML: tmpCache});
	}
	else
	{
		if(typeof globalDebug!='undefined' && globalDebug instanceof Array && globalDebug.indexOf('cache')!=-1)
			console.log('DBG Cache ERROR: '+arguments.callee.name+' url: \''+inputResource.href+'\': spend one request!');
		$.ajax({
			type: 'REPORT',
			url: inputResource.href,
			cache: false,
			crossDomain: (typeof inputResource.crossDomain=='undefined' ? true: inputResource.crossDomain),
			xhrFields:
			{
				withCredentials: (typeof inputResource.withCredentials=='undefined' ? false: inputResource.withCredentials)
			},
			timeout: inputResource.timeOut,
			beforeSend: function(req)
			{
				if(globalSettings.usejqueryauth.value!=true && inputResource.userAuth.userName!='' && inputResource.userAuth.userPassword!='')
					req.setRequestHeader('Authorization', basicAuth(inputResource.userAuth.userName, inputResource.userAuth.userPassword));

				req.setRequestHeader('X-client', globalXClientHeader);
				req.setRequestHeader('Depth', '0');
			},
			username: (globalSettings.usejqueryauth.value==true ? inputResource.userAuth.userName : null),
			password: (globalSettings.usejqueryauth.value==true ? inputResource.userAuth.userPassword : null),
			contentType: 'text/xml',
			processData: true,
			data: delegationXML,
			dataType: 'xml',
			error: function(objAJAXRequest, strError)
			{
				console.log("Error: [DAVresourceDelegation: 'REPORT "+uidFull+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' (this error code usually means network connection error, or your browser is trying to make a cross domain query, but it is not allowed by the destination server or the browser itself)': ''));
			},
			success: ajaxComplete
		});
	}
}

function netFindResource(inputResource, inputResourceIndex, forceLoad, indexR, loadArray)
{
	if(globalPreventLogoutSync)
	{
		logout(true);
		return false;
	}
	if(indexR<globalAccountSettings.length)
	{
		globalResourceNumberCount++;
		if((isAvaible('CardDavMATE') && globalCardDAVInitLoad) || (isAvaible('CalDavZAP') && globalCalDAVInitLoad) || (isAvaible('Projects') && !isProjectsLoaded) || (isAvaible('Settings') && !isSettingsLoaded))
			$('#MainLoaderInner').html(localization[globalInterfaceLanguage].loadingResources.replace('%act%', globalResourceNumberCount).replace('%total%', globalResourceNumber));
	}
	if((typeof inputResource!='undefined' && typeof inputResource.collectionTypes!='undefined' && inputResource.collectionTypes!=null && (inputResource.collectionTypes.indexOf('calendar')==-1) && inputResource.collectionTypes.indexOf('addressbook')==-1) || (typeof inputResource!='undefined' && typeof loadArray!='undefined' && loadArray!=null && loadArray.indexOf(inputResource.href)==-1))
	{
		indexR++;
		netFindResource(globalAccountSettings[indexR], inputResourceIndex, forceLoad, indexR,loadArray);
		return false;
	}

	if(indexR>=globalAccountSettings.length && settingsLoaded)
	{
		if(globalResourceIntervalID==null)
			globalResourceIntervalID=setInterval(reloadResources, globalSettings.syncresourcesinterval.value);
		globalCalDAVResourceSync=false;
		globalCardDAVResourceSync=false;
		globalSyncSettingsSave=false;
		var rexo=new RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@(.*)');
		var rex=new RegExp('^(https?://)(.*)', 'i');
		var accRex=new RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@([^/]+)(.*/)', 'i');
		if((isAvaible('CalDavZAP') && !isCalDAVLoaded) || (isAvaible('CardDavMATE') && !isCardDAVLoaded))
		{
			if(isAvaible('CalDavZAP'))
			{
				if(!globalDefaultCalendarCollectionActiveAll)
				{
					for(var i=0; i<globalSettings.activecalendarcollections.value.length; i++)
					{
						if(typeof globalCrossServerSettingsURL!='undefined' && globalCrossServerSettingsURL!=null && globalCrossServerSettingsURL)
						{
							var tmpParts2=globalSettings.activecalendarcollections.value[i].match('^(.*/)([^/]+)/([^/]+)/$');
							var checkHref2=tmpParts2[2]+'/'+tmpParts2[3]+'/';
							if($('#ResourceCalDAVList input[data-id$="'+checkHref2+'"]:visible').length>0)
							{
								var elm=$('#ResourceCalDAVList input[data-id$="'+checkHref2+'"]');
								elm.trigger('click');
								globalVisibleCalDAVCollections.splice(globalVisibleCalDAVCollections.length, 0, elm.attr('data-id'));
							}
						}
						else
						{
							var uidPart=globalSettings.activecalendarcollections.value[i].match(rex)[1];
							var uidPart2=globalSettings.activecalendarcollections.value[i].match(rex)[2];
							if(globalLoginUsername!='')
								var uidPart3=globalLoginUsername;
							else
								var uidPart3=globalAccountSettings[0].userAuth.userName;
							var uid = uidPart+uidPart3+'@'+uidPart2;
							if($('#ResourceCalDAVList input[data-id="'+uid+'"]:visible').length>0)
							{
								$('#ResourceCalDAVList input[data-id="'+uid+'"]').trigger('click');
								globalVisibleCalDAVCollections.splice(globalVisibleCalDAVCollections.length, 0, uid);
							}
						}
					}
					if(globalSettings.activecalendarcollections.value.length>0 && globalVisibleCalDAVCollections.length==0)
						globalDefaultCalendarCollectionActiveAll=true;
				}

				if(globalDefaultCalendarCollectionActiveAll)
					for(var i=0; i<globalResourceCalDAVList.collections.length; i++)
					{
						if(globalResourceCalDAVList.collections[i].uid!=undefined && $('#ResourceCalDAVList input[data-id="'+globalResourceCalDAVList.collections[i].uid+'"]:visible').length>0)
						{
							$('#ResourceCalDAVList input[data-id="'+globalResourceCalDAVList.collections[i].uid+'"]').trigger('click');
							globalVisibleCalDAVCollections.splice(globalVisibleCalDAVCollections.length, 0, globalResourceCalDAVList.collections[i].uid);
						}
					}

				if(!globalDefaultTodoCalendarCollectionActiveAll)
				{
					for(var i=0; i<globalSettings.activetodocollections.value.length; i++)
					{
						if(typeof globalCrossServerSettingsURL!='undefined' && globalCrossServerSettingsURL!=null && globalCrossServerSettingsURL)
						{
							var tmpParts2=globalSettings.activetodocollections.value[i].match('^(.*/)([^/]+)/([^/]+)/$');
							var checkHref2=tmpParts2[2]+'/'+tmpParts2[3]+'/';
							if($('#ResourceCalDAVTODOList input[data-id$="'+checkHref2+'"]:visible').length>0)
							{
								var elm=$('#ResourceCalDAVTODOList input[data-id$="'+checkHref2+'"]');
								elm.trigger('click');
								globalVisibleCalDAVTODOCollections.splice(globalVisibleCalDAVTODOCollections.length, 0, elm.attr('data-id'));
							}
						}
						else
						{
							var uidPart=globalSettings.activetodocollections.value[i].match(rex)[1];
							var uidPart2=globalSettings.activetodocollections.value[i].match(rex)[2];
							if(globalLoginUsername!='')
								var uidPart3=globalLoginUsername;
							else
								var uidPart3=globalAccountSettings[0].userAuth.userName;
							var uid=uidPart+uidPart3+'@'+uidPart2;
							if($('#ResourceCalDAVTODOList input[data-id="'+uid+'"]:visible').length>0)
							{
								$('#ResourceCalDAVTODOList input[data-id="'+uid+'"]').trigger('click');
								globalVisibleCalDAVTODOCollections.splice(globalVisibleCalDAVTODOCollections.length, 0, uid);
							}
						}
					}

					if(globalSettings.activetodocollections.value.length>0 && globalVisibleCalDAVTODOCollections.length==0)
						globalDefaultTodoCalendarCollectionActiveAll=true;
				}

				if(globalDefaultTodoCalendarCollectionActiveAll)
					for(var i=0; i<globalResourceCalDAVList.TodoCollections.length; i++)
					{
						if(globalResourceCalDAVList.TodoCollections[i].uid!=undefined && $('#ResourceCalDAVTODOList input[data-id="'+globalResourceCalDAVList.TodoCollections[i].uid+'"]:visible').length>0)
						{
							$('#ResourceCalDAVTODOList input[data-id="'+globalResourceCalDAVList.TodoCollections[i].uid+'"]').trigger('click');
							globalVisibleCalDAVTODOCollections.splice(globalVisibleCalDAVTODOCollections.length, 0, globalResourceCalDAVList.TodoCollections[i].uid);
						}
					}
				if($('#ResourceCalDAVList .resourceCalDAV_item[data-id]:visible').length==0 && globalResourceCalDAVList.collections.length>1)
				{
					var enabledArray=new Array();
					for(var c=0; c<globalResourceCalDAVList.collections.length; c++)
						if(globalResourceCalDAVList.collections[c].uid!=undefined)
						{
							var tmp=globalResourceCalDAVList.collections[c].accountUID.match(accRex);
							var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
							if(globalAccountSettings[0].href==resourceCalDAV_href && globalAccountSettings[0].userAuth.userName==globalResourceCalDAVList.collections[c].userAuth.userName)
								enabledArray.push(globalResourceCalDAVList.collections[c]);
						}

					if(enabledArray.length==0)
						enabledArray.push(globalResourceCalDAVList.collections[1]);

					for(var c=0; c<enabledArray.length; c++)
					{
						enabledArray[c].makeLoaded=true;
						var uidParts=enabledArray[c].uid.match(rexo);
						globalSettings.loadedcalendarcollections.value.push(uidParts[1]+uidParts[3]);
						var resDOMItem=$('#ResourceCalDAVList').find('.resourceCalDAV_item[data-id="'+jqueryEscapeSelector(enabledArray[c].uid)+'"]');
						var resDOMHeader=resDOMItem.prevUntil('.resourceCalDAV_header').last().prev();
						if(!resDOMHeader.length)
							resDOMHeader=resDOMItem.prev();
						resDOMHeader.css('display','block');
						resDOMItem.css('display','');
						resDOMItem.find('input[type=checkbox]').not('.unloadCheck').trigger('click');
						globalVisibleCalDAVCollections.splice(globalVisibleCalDAVCollections.length, 0, enabledArray[c].uid);
					}
				}

				if($('#ResourceCalDAVTODOList .resourceCalDAVTODO_item[data-id]:visible').length==0 && globalResourceCalDAVList.TodoCollections.length>1)
				{
					var enabledArray=new Array();
					for(var c=0; c<globalResourceCalDAVList.TodoCollections.length; c++)
						if(globalResourceCalDAVList.TodoCollections[c].uid!=undefined)
						{
							var tmp=globalResourceCalDAVList.TodoCollections[c].accountUID.match(accRex);
							var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
							if(globalAccountSettings[0].href==resourceCalDAV_href && globalAccountSettings[0].userAuth.userName==globalResourceCalDAVList.TodoCollections[c].userAuth.userName)
								enabledArray.push(globalResourceCalDAVList.TodoCollections[c]);
						}

					if(enabledArray.length==0)
						enabledArray.push(globalResourceCalDAVList.TodoCollections[1]);

					for(var c=0; c<enabledArray.length; c++)
					{
						$('#ResourceCalDAVTODOList .resourceCalDAVTODO_item[data-id="'+enabledArray[c].uid+'"]').css('display','block')
						enabledArray[c].makeLoaded=true;
						var uidParts=enabledArray[c].uid.match(rexo);
						globalSettings.loadedtodocollections.value.push(uidParts[1]+uidParts[3]);
						var resDOMItem=$('#ResourceCalDAVTODOList').find('.resourceCalDAVTODO_item[data-id="'+jqueryEscapeSelector(enabledArray[c].uid)+'"]');
						var resDOMHeader=resDOMItem.prevUntil('.resourceCalDAVTODO_header').last().prev();
						if(!resDOMHeader.length)
							resDOMHeader=resDOMItem.prev();
						resDOMHeader.css('display','block');
						resDOMItem.css('display','');
						resDOMItem.find('input[type=checkbox]').not('.unloadCheck').trigger('click');
						globalVisibleCalDAVTODOCollections.splice(globalVisibleCalDAVTODOCollections.length, 0, enabledArray[c].uid);
					}
				}
				$('#ResourceCalDAVList').children('.resourceCalDAV_header').each(function(){
					if(!$(this).nextUntil('.resourceCalDAV_header').filter(':visible').length)
						$(this).css('display','none');
				});
				$('#ResourceCalDAVTODOList').children('.resourceCalDAVTODO_header').each(function(){
					if(!$(this).nextUntil('.resourceCalDAVTODO_header').filter(':visible').length)
						$(this).css('display','none');
				});
				selectActiveCalendar();
			}

			if(isAvaible('CardDavMATE'))
			{
				if($('#ResourceCardDAVList .resourceCardDAV_item:visible').length==0 && globalResourceCardDAVList.collections.length>1)
				{
					var enabledArray=new Array();
					for(var c=0; c<globalResourceCardDAVList.collections.length; c++)
						if(globalResourceCardDAVList.collections[c].uid!=undefined)
						{
							var tmp=globalResourceCardDAVList.collections[c].accountUID.match(accRex);
							var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
							if(globalAccountSettings[0].href==resourceCalDAV_href && globalAccountSettings[0].userAuth.userName==globalResourceCardDAVList.collections[c].userAuth.userName)
								enabledArray.push(globalResourceCardDAVList.collections[c]);
						}

					if(enabledArray.length==0)
						enabledArray.push(globalResourceCardDAVList.collections[1]);

					for(var c=0; c<enabledArray.length; c++)
					{
						$('#ResourceCardDAVList .resourceCardDAV_item .resourceCardDAV[data-id="'+enabledArray[c].uid+'"]').parent().css('display','block')
						enabledArray[c].makeLoaded=true;
						//$('#ResourceCardDAVList').find('.resourceCardDAV_item .resourceCardDAV').find('input[data-id="'+enabledArray[c].uid+'"]').trigger('click');
						var uidParts=enabledArray[c].uid.match(rexo);
						globalSettings.loadedaddressbookcollections.value.push(uidParts[1]+uidParts[3]);
						globalSettings.activeaddressbookcollections.value.push(uidParts[1]+uidParts[3]);
					}
				}

				$('#ResourceCardDAVList').children('.resourceCardDAV_header').each(function(){
					if(!$(this).nextUntil('.resourceCardDAV_header').filter(':visible').length)
						$(this).css('display','none');
				});
			}

			loadNextApplication(true);
		}

		var isTodoAv=false,isEventAv=false;
		if(isAvaible('CalDavZAP'))
		{
			setCalendarNumber(false);
			selectActiveCalendar();
			var cals=globalResourceCalDAVList.TodoCollections;

			if(cals.length==0 || (cals.length==1 && typeof cals[0].uid=='undefined'))
			{
				$('#intCaldavTodo').css('display','none');
				isTodoAv=false;
			}
			else
			{
				$('#intCaldavTodo').css('display','block');
				isTodoAv=true;
			}

			var calendarsArray=new Array();
			for(var i=0; i<cals.length; i++)
				if(cals[i].uid!=undefined)
					calendarsArray[calendarsArray.length]={displayValue:cals[i].displayvalue,uid:cals[i].uid, permissions_read_only:cals[i].permissions.read_only,makeLoaded:cals[i].makeLoaded};
			calendarsArray.sort(customResourceCompare);
			globalResourceCalDAVList.sortedTodoCollections=calendarsArray;
			var cals=globalResourceCalDAVList.collections;

			if(cals.length==0 || (cals.length==1 && typeof cals[0].uid=='undefined'))
			{
				$('#intCaldav').css('display','none');
				isEventAv=false;
			}
			else
			{
				$('#intCaldav').css('display','block');
				isEventAv=true;
			}

			calendarsArray=new Array();
			for(var i=0; i<cals.length; i++)
				if(cals[i].uid!=undefined)
					calendarsArray[calendarsArray.length]={displayValue:cals[i].displayvalue,uid:cals[i].uid, permissions_read_only:cals[i].permissions.read_only, makeLoaded:cals[i].makeLoaded};
			calendarsArray.sort(customResourceCompare);
			globalResourceCalDAVList.sortedCollections = calendarsArray;
		}

		var isAddrAv=false;
		if(isAvaible('CardDavMATE'))
		{
			selectActiveAddressbook();
			for(var adr in globalAddressbookList.vcard_groups)
			{
				if(globalAddressbookList.vcard_groups[adr].length>0)
				{
					extendDestSelect();
					if(typeof $('#vCardEditor').attr('data-vcard-uid')=='undefined')
						$('#vCardEditor').find('[data-attr-name="_DEST_"]').find('optiotn[data-type$="'+$('#ResourceCardDAVList').find('.resourceCardDAV_selected').find(':input[data-id]').attr('data-id')+'"]').prop('selected',true);
				}
			}

			var addrs=globalResourceCardDAVList.collections;
			if(addrs.length==0 || (addrs.length==1 && typeof addrs[0].uid == 'undefined'))
			{
				$('#intCarddav').css('display','none');
				isAddrAv=false;
			}
			else
			{
				isAddrAv=true;
				$('#intCarddav').css('display','block');
			}
		}

		if((isAvaible('CalDavZAP') && !isCalDAVLoaded) || (isAvaible('CardDavMATE') && !isCardDAVLoaded))
		{
			if(isAvaible('CalDavZAP'))
			{
				if(globalActiveApp=='CalDavTODO')
					if(!isTodoAv)
						globalActiveApp=null;

				if(globalActiveApp==null || globalActiveApp=='CalDavZAP')
				{
					if(!isEventAv)
						globalActiveApp=null;
					else
						globalActiveApp='CalDavZAP';
				}
			}
			if(isAvaible('CardDavMATE') && (globalActiveApp==null || globalActiveApp=='CardDavMATE'))
			{
				if(!isAddrAv)
					globalActiveApp=null;
				else
					globalActiveApp='CardDavMATE';
			}
			if(globalActiveApp!=null)
				checkForApplication(globalActiveApp);
		}

		ifLoadCollections();
		if(isAvaible('CalDavZAP'))
		{
			if($('#ResourceCalDAVList .resourceCalDAV_item:visible').not('.resourceCalDAV_item_ro').length==0)
			{
				$('#eventFormShower').css('display','none');
				$('#calendar').fullCalendar('setOptions',{'selectable':false});
			}
			else
			{
				$('#eventFormShower').css('display','block');
				$('#calendar').fullCalendar('setOptions',{'selectable':true});
			}

			if($('#ResourceCalDAVTODOList .resourceCalDAVTODO_item:visible').not('.resourceCalDAV_item_ro').length==0)
				$('#eventFormShowerTODO').css('display','none');
			else
				$('#eventFormShowerTODO').css('display','block');
		}
		return false;
	}
	else if(indexR>=globalAccountSettings.length && !settingsLoaded)
	{
		console.log("Error: [netFindResource]: 'Unable to load resources'");
		return false;
	}

	var re=new RegExp('^(https?://)([^/]+)(.*)','i');
	var tmp=inputResource.href.match(re);
	var uidBase=tmp[1]+inputResource.userAuth.userName+'@'+tmp[2];
	var uidFull=tmp[1]+inputResource.userAuth.userName+'@'+tmp[2]+tmp[3];	// for the error handler
	var settingsXML='';
	if(inputResource.href.indexOf(globalLoginUsername)!=-1 && inputResource.settingsAccount && (globalSettings.settingstype.value=='' || globalSettings.settingstype.value==null || (globalSettings.settingstype.value!='' && globalSettings.settingstype.value!=null && globalSettings.settingstype.value=='principal-URL')))
		settingsXML='<I:settings xmlns:I="http://inf-it.com/ns/dav/"/>';

	var baseHref=tmp[1]+tmp[2];
	if(typeof inputResource.extendedDelegation!='undefined' && inputResource.extendedDelegation && (typeof inputResource.abhref!='undefined' || typeof inputResource.cahref!='undefined'))
	{
		if(isAvaible('CardDavMATE') && isAvaible('CalDavZAP'))
		{
			if(inputResource.abhref==inputResource.cahref)
				netLoadResource(inputResource, inputResource.abhref, false, inputResourceIndex, forceLoad, indexR, loadArray);
			else
				netLoadResource(inputResource, inputResource.abhref, true, inputResourceIndex, forceLoad, indexR, loadArray);
		}
		else if(isAvaible('CardDavMATE'))
			netLoadResource(inputResource, inputResource.abhref, false, inputResourceIndex, forceLoad, indexR, loadArray);
		else if(isAvaible('CalDavZAP'))
			netLoadResource(inputResource, inputResource.cahref, false, inputResourceIndex, forceLoad, indexR, loadArray);
		return false;
	}

	$.ajax({
		type: 'PROPFIND',
		url: inputResource.href,
		cache: false,
		crossDomain: (typeof inputResource.crossDomain=='undefined' ? true : inputResource.crossDomain),
		xhrFields: {
			withCredentials: (typeof inputResource.withCredentials=='undefined' ? false : inputResource.withCredentials)
		},
		timeout: inputResource.timeOut,
		beforeSend: function(req) {
			if(globalSettings.usejqueryauth.value!=true && inputResource.userAuth.userName!='' && inputResource.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(inputResource.userAuth.userName,inputResource.userAuth.userPassword));

			req.setRequestHeader('X-client', globalXClientHeader);
			req.setRequestHeader('Depth', '0');
			if(globalSettingsSaving!=''||(isAvaible('CardDavMATE') && (!globalCardDAVInitLoad && !globalCardDAVResourceSync)) || (isAvaible('CalDavZAP') && (!globalCalDAVInitLoad && !globalCalDAVResourceSync))||(isAvaible('Projects') && isProjectsLoaded))
				/* XXX - System display:none changes */
				if(globalSettingsSaving!='' || (isAvaible('Settings') && $('#SystemSettings').css('visibility')=='visible' && $('.resourceSettings_item_selected').attr('data-type')=='setting_group_password'))
				{
					indexR++;
					if(((isAvaible('CardDavMATE') && globalCardDAVInitLoad) || (isAvaible('CalDavZAP') && globalCalDAVInitLoad)) && indexR==globalAccountSettings.length)
						$('#MainLoader').fadeOut(1200);
					netFindResource(globalAccountSettings[indexR], inputResourceIndex, forceLoad, indexR,loadArray);
					return false;
				}
		},
		username: (globalSettings.usejqueryauth.value==true ? inputResource.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? inputResource.userAuth.userPassword : null),
		contentType: 'text/xml; charset=utf-8',
		processData: true,
		data: '<?xml version="1.0" encoding="utf-8"?><D:propfind xmlns:D="DAV:"><D:prop>'+settingsXML+'<D:current-user-privilege-set/><D:displayname/><D:resourcetype/><L:calendar-home-set xmlns:L="urn:ietf:params:xml:ns:caldav"/><R:addressbook-home-set xmlns:R="urn:ietf:params:xml:ns:carddav"/></D:prop></D:propfind>',
		dataType: 'xml',
		error: function(objAJAXRequest, strError){
			console.log("Error: [netFindResource: 'PROPFIND "+uidFull+"']: code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
			indexR++;
			inputResource.errorLoaded=true;
			if(isAvaible('CalDavZAP'))
			{
				$('#intCaldav').find('.int_error').css('display', 'block');
				$('#intCaldavTodo').find('.int_error').css('display', 'block');
			}
			if(isAvaible('CardDavMATE'))
				$('#intCarddav').find('.int_error').css('display', 'block');
			var allFail=true;
			for(var i=0; i< globalAccountSettings.length; i++)
				if(typeof globalAccountSettings[i].errorLoaded=='undefined' || globalAccountSettings[i].errorLoaded==null || globalAccountSettings[i].errorLoaded===false)
					allFail=false;
			if(((isAvaible('CardDavMATE') && globalCardDAVInitLoad) || (isAvaible('CalDavZAP' && globalCalDAVInitLoad)))  && indexR==globalAccountSettings.length && allFail)
				$('#MainLoader').fadeOut(1200);
			else if((isAvaible('CardDavMATE') && !globalCardDAVInitLoad) || (isAvaible('CalDavZAP') && !globalCalDAVInitLoad))
			{
				if(isAvaible('CalDavZAP'))
					handleCalDAVError(true, inputResource);
				if(isAvaible('CardDavMATE'))
					handleCardDAVError(true, inputResource)
			}
			netFindResource(globalAccountSettings[indexR], inputResourceIndex, forceLoad, indexR,loadArray);
			return false;
		},
		success: function(data, textStatus, xml)
		{
			inputResource.errorLoaded=false;
			if(isAvaible('CalDavZAP') && isEachResourceLoaded())
			{
				$('#intCaldav').find('.int_error').css('display', 'none');
				$('#intCaldavTodo').find('.int_error').css('display', 'none');
			}

			if(isAvaible('CardDavMATE') && isEachResourceLoaded())
				$('#intCarddav').find('.int_error').css('display','none');

			if(isAvaible('CalDavZAP') && !globalCalDAVInitLoad)
				handleCalDAVError(false, inputResource);

			if(isAvaible('CardDavMATE') && !globalCardDAVInitLoad)
				handleCardDAVError(false, inputResource);

			if(!settingsLoaded && inputResource.href.indexOf(globalLoginUsername)!=-1 && inputResource.settingsAccount && (globalSettings.settingstype.value=='' || globalSettings.settingstype.value==null || (globalSettings.settingstype.value!='' && globalSettings.settingstype.value!=null && globalSettings.settingstype.value=='principal-URL')))
			{
				var settings=$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('settings').text();
				if(settings!='')
				{
					if(!ignoreServerSettings)
						loadSettings(settings, true, false);
					else
					{
						delete globalSettings.version.value;
						loadSettings(JSON.stringify(globalSettings), false, false);
						console.log('Ignoring server settings: '+'\n'+settings);
					}
				}
				else
				{
					delete globalSettings.version.value;
					loadSettings(JSON.stringify(globalSettings), false, false);
				}
			}
			else if(!globalSyncSettingsSave && inputResource.href.indexOf(globalLoginUsername)!=-1 && ((isAvaible('CardDavMATE')&&globalCardDAVResourceSync) || (isAvaible('CalDavZAP')&&globalCalDAVResourceSync)))
			{
				globalSyncSettingsSave=true;
				var loadedCals = new Array(), loadedTodoCals = new Array(), loadedAddrs = new Array();
				if(isAvaible('CardDavMATE'))
					loadedAddrs = globalSettings.loadedaddressbookcollections.value.slice();
				if(isAvaible('CalDavZAP'))
				{
					loadedCals = globalSettings.loadedcalendarcollections.value.slice();
					loadedTodoCals = globalSettings.loadedtodocollections.value.slice();
				}
				var settings = $(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('settings').text();
				if(typeof globalPreviousSupportedSettings !='undefined' && globalPreviousSupportedSettings!=null)
					loadSettings(settings, true, true);
				if(isAvaible('CardDavMATE'))
					globalSettings.loadedaddressbookcollections.value = loadedAddrs.slice();
				if(isAvaible('CalDavZAP'))
				{
					globalSettings.loadedcalendarcollections.value = loadedCals.slice();
					globalSettings.loadedtodocollections.value = loadedTodoCals.slice();
				}
				checkBeforeClose(false);
			}

			var response=$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response');

			var addressbook_home=response.children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('addressbook-home-set').children().filterNsNode('href').text();
			if(addressbook_home=='')	// addressbook-home-set has no 'href' value -> SabreDav
				addressbook_home=response.children().filterNsNode('href').text().replace('/principals/users/caldav.php','/caldav.php');

			if(addressbook_home.match(RegExp('^https?://','i'))!=null)	// absolute URL returned
				inputResource.abhref=addressbook_home;
			else	// relative URL returned
				inputResource.abhref=baseHref+addressbook_home;
			var calendar_home=response.children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('calendar-home-set').children().filterNsNode('href').text();
			if(calendar_home=='')	// addressbook-home-set has no 'href' value -> SabreDav
				calendar_home=response.children().filterNsNode('href').text().replace('/principals/users/caldav.php','/caldav.php');

			if(calendar_home.match(RegExp('^https?://','i'))!=null)	// absolute URL returned
				inputResource.cahref=calendar_home;
			else	// relative URL returned
				inputResource.cahref=baseHref+calendar_home;

			if(isAvaible('CardDavMATE') && isAvaible('CalDavZAP'))
			{
				if(inputResource.abhref==inputResource.cahref)
					netLoadResource(inputResource, inputResource.abhref, false, inputResourceIndex, forceLoad, indexR, loadArray);
				else
					netLoadResource(inputResource, inputResource.abhref, true, inputResourceIndex, forceLoad, indexR, loadArray);
			}
			else if(isAvaible('CardDavMATE'))
				netLoadResource(inputResource, inputResource.abhref, false, inputResourceIndex, forceLoad, indexR, loadArray);
			else if(isAvaible('CalDavZAP'))
				netLoadResource(inputResource, inputResource.cahref, false, inputResourceIndex, forceLoad, indexR, loadArray);
		}
	});
}

function netLoadResource(inputResource, inputHref, hrefMode, inputResourceIndex, forceLoad, indexR, loadArray)
{
	var re=new RegExp('^(https?://)([^/]+)(.*)','i');
	if(!isAvaible('CardDavMATE') || !globalCardDAVInitLoad || (globalCardDAVInitLoad && typeof inputResource.addressbookNo == 'undefined'))
		inputResource.addressbookNo=0;
	if(!isAvaible('CalDavZAP') || !globalCalDAVInitLoad || (globalCalDAVInitLoad && typeof inputResource.calendarNo=='undefined' && typeof inputResource.todoNo=='undefined'))
	{
		inputResource.calendarNo=0;
		inputResource.todoNo=0;
	}
	var tmp=inputResource.abhref.match(re);
	var baseHref=tmp[1]+tmp[2];
	var uidBase=tmp[1]+inputResource.userAuth.userName+'@'+tmp[2];
	var uidFull=tmp[1]+inputResource.userAuth.userName+'@'+tmp[2]+tmp[3];	// for the error handler

	var tmp=inputResource.href.match(RegExp('^(https?://)(.*)','i'));
	var origUID=tmp[1]+inputResource.userAuth.userName+'@'+tmp[2];

	if(typeof globalSubscribedCalendars!='undefined' && globalSubscribedCalendars!=null && typeof inputResource.calendars!='undefined' && inputResource.calendars!=null && inputResource.calendars.length>0)
	{
		var tmp1=inputResource.href.match(RegExp('^(https?://)(.*)', 'i'));
		var origUID1=tmp1[1]+inputResource.userAuth.userName+'@'+tmp1[2];
		var resultTimestamp=new Date().getTime();
		for(var k=0; k<globalSubscribedCalendars.calendars.length; k++)
		{
			color=globalSubscribedCalendars.calendars[k].color;
			if(color=='')
			{
				var par=(uidBase+globalSubscribedCalendars.calendars[k].href).split('/');
				var hash=hex_sha256(hex_sha256(par[par.length-3]+'/'+par[par.length-2]+'/'));
				var hex=hash.substring(0,6);
				while(checkColorBrightness(hex)>=252)
					hex=hex_sha256(hex_sha256(hash)).substring(0,6);
				color='#'+hex;
			}
			var syncRequired=true;
			var uidPArts=(uidBase+'/'+globalSubscribedCalendars.calendars[k].href+'/').split('/');
			if(globalSubscribedCalendars.calendars[k].typeList.indexOf('vevent')!=-1)
			{
				var uidParts=(uidBase+'/'+globalSubscribedCalendars.calendars[k].href+'/').match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@(.*)'));
				var checkHref=uidParts[1]+uidParts[3];
				if(!isHrefSet)
				{
					saveHref=uidBase+href;
					isHrefSet=true;
				}
				if(!globalDefaultCalendarCollectionLoadAll)
				{
					var toBeLoad=false;
					if(typeof globalCrossServerSettingsURL!='undefined' && globalCrossServerSettingsURL!=null && globalCrossServerSettingsURL)
					{
						var uidParts=(uidBase+'/'+globalSubscribedCalendars.calendars[k].href+'/').match(RegExp('/([^/]+/[^/]+/)$'));
						var tmpParts=uidParts[1].match('^(.*/)([^/]+)/$');
						var checkHref3=decodeURIComponent(tmpParts[1])+tmpParts[2]+'/';
						var found=false;
						for(var l=0; l<globalSettings.loadedcalendarcollections.value.length; l++)
						{
							var tmpParts2=globalSettings.loadedcalendarcollections.value[l].match('^(.*/)([^/]+)/([^/]+)/$');
							var checkHref2=decodeURIComponent(tmpParts2[2])+'/'+tmpParts2[3]+'/';
							if(checkHref3==checkHref2)
							{
								found=true;
								globalSettings.loadedcalendarcollections.value[l]=checkHref;
								break;
							}
						}
						toBeLoad=found;
					}
					else
						toBeLoad=globalSettings.loadedcalendarcollections.value.indexOf(checkHref)!=-1;
				}
				else
				{
					if(globalCalDAVInitLoad)
						globalSettings.loadedcalendarcollections.value.push(checkHref);
					var toBeLoad=true;
				}
				globalResourceCalDAVList.insertResource({makeLoaded:toBeLoad, typeList:globalSubscribedCalendars.calendars[k].typeList, listType:'vevent', syncRequired:syncRequired, ecolor: color, timestamp: resultTimestamp, uid: uidBase+'/'+globalSubscribedCalendars.calendars[k].href+'/', timeOut: inputResource.timeOut, displayvalue: globalSubscribedCalendars.calendars[k].displayName, userAuth: globalSubscribedCalendars.calendars[k].userAuth, resourceIndex: indexR, url: baseHref, accountUID: origUID1, href: globalSubscribedCalendars.calendars[k].href, hrefLabel: globalSubscribedCalendars.hrefLabel, permissions: {full: [], read_only: true}, crossDomain: inputResource.crossDomain, withCredentials: inputResource.withCredentials, interval: null, waitInterval: null, displayEventsArray: new Array(), pastUnloaded: '', fcSource: null,subscription: true, newlyAdded:toBeLoad, urlArray: new Array(), ignoreAlarms:globalSubscribedCalendars.calendars[k].ignoreAlarm,webdav_bind:false}, indexR, true);
				if(inputResource!=undefined)
					inputResource.calendarNo++;
				syncRequired=false;
			}
			if(globalSubscribedCalendars.calendars[k].typeList.indexOf('vtodo')!=-1)
			{
				var uidParts=(uidBase+'/'+globalSubscribedCalendars.calendars[k].href+'/').match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@(.*)'));
				var checkHref=uidParts[1]+uidParts[3];
				if(!isHrefSet)
				{
					saveHref=uidBase+href;
					isHrefSet=true;
				}
				if(!globalDefaultTodoCalendarCollectionLoadAll)
				{
					var toBeLoad=false;
					if(typeof globalCrossServerSettingsURL!='undefined'&&globalCrossServerSettingsURL!=null&globalCrossServerSettingsURL)
					{
						var uidParts=(uidBase+'/'+globalSubscribedCalendars.calendars[k].href+'/').match(RegExp('/([^/]+/[^/]+/)$'));
						var tmpParts=uidParts[1].match('^(.*/)([^/]+)/$');
						var checkHref3=decodeURIComponent(tmpParts[1])+tmpParts[2]+'/';
						var found=false;
						for(var l=0; l<globalSettings.loadedtodocollections.value.length; l++)
						{
							var tmpParts2=globalSettings.loadedtodocollections.value[l].match('^(.*/)([^/]+)/([^/]+)/$');
							var checkHref2=decodeURIComponent(tmpParts2[2])+'/'+tmpParts2[3]+'/';
							if(checkHref3==checkHref2)
							{
								found=true;
								globalSettings.loadedtodocollections.value[l]=checkHref;
								break;
							}
						}
						toBeLoad=found;
					}
					else
						toBeLoad=globalSettings.loadedtodocollections.value.indexOf(checkHref)!=-1;
				}
				else
				{
					var toBeLoad=true;
					if(globalCalDAVInitLoad)
						globalSettings.loadedtodocollections.value.push(checkHref);
				}
				globalResourceCalDAVList.insertResource({makeLoaded:toBeLoad, typeList:globalSubscribedCalendars.calendars[k].typeList, listType:'vtodo', syncRequired:syncRequired, ecolor: color, timestamp: resultTimestamp, uid: uidBase+'/'+globalSubscribedCalendars.calendars[k].href+'/', timeOut: inputResource.timeOut, displayvalue: globalSubscribedCalendars.calendars[k].displayName, userAuth: globalSubscribedCalendars.calendars[k].userAuth, resourceIndex: indexR, url: baseHref, accountUID: origUID1, href: globalSubscribedCalendars.calendars[k].href, hrefLabel: globalSubscribedCalendars.hrefLabel, permissions: {full: [], read_only: true}, crossDomain: inputResource.crossDomain, withCredentials: inputResource.withCredentials, interval: null, waitInterval: null, displayEventsArray: new Array(), pastUnloaded: '', fcSource: null,subscription: true, newlyAdded:toBeLoad, urlArray: new Array(), ignoreAlarms:globalSubscribedCalendars.calendars[k].ignoreAlarm,webdav_bind:false}, indexR, false);
				if(inputResource!=undefined)
					inputResource.todoNo++;
			}
		}

		//recursive call for resource loading
		indexR++;
		netFindResource(globalAccountSettings[indexR], inputResourceIndex, forceLoad, indexR,loadArray);
		return true;
	}

	var settingsXML='';
	if(inputResource.href.indexOf(globalLoginUsername)!=-1 && inputResource.settingsAccount && globalSettings.settingstype.value!='' && globalSettings.settingstype.value!=null)
		if((globalSettings.settingstype.value=='addressbook-home-set' && inputResource.abhref==inputHref) || (globalSettings.settingstype.value=='calendar-home-set' && inputResource.cahref==inputHref) || (globalSettings.settingstype.value=='principal-URL'&& ((isAvaible('CardDavMATE')&&globalCardDAVResourceSync) || (isAvaible('CalDavZAP')&&globalCalDAVResourceSync))))
			settingsXML='<I:settings xmlns:I="http://inf-it.com/ns/dav/"/>';

	function ajaxComplete(data, textStatus, xml)
	{
		var Rname='';
		inputResource.errorLoaded=false;
		if(isAvaible('CalDavZAP') && isEachResourceLoaded())
		{
			$('#intCaldav').find('.int_error').css('display','none');
			$('#intCaldavTodo').find('.int_error').css('display','none');
		}
		if(isAvaible('CardDavMATE') && isEachResourceLoaded())
			$('#intCarddav').find('.int_error').css('display','none');
		if(isAvaible('CalDavZAP') && !globalCalDAVInitLoad)
			handleCalDAVError(false, inputResource);
		if(isAvaible('CardDavMATE') && !globalCardDAVInitLoad)
			handleCardDAVError(false, inputResource);
		var saveHref='';
		isHrefSet=false;
		var calendarNo=0;
		var resultTimestamp=new Date().getTime();
		if(!settingsLoaded && inputResource.href.indexOf(globalLoginUsername)!=-1 && inputResource.settingsAccount && globalSettings.settingstype.value!='' && globalSettings.settingstype.value!=null)
		{
			if((globalSettings.settingstype.value=='addressbook-home-set' && inputResource.abhref==inputHref) || (globalSettings.settingstype.value=='calendar-home-set' && inputResource.cahref==inputHref))
			{
				var settings=$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('settings').text();
				if(settings!='')
				{
					if(!ignoreServerSettings)
						loadSettings(settings, true, false);
					else
					{
						delete globalSettings.version.value;
						loadSettings(JSON.stringify(globalSettings), false, false);
						console.log('Ignoring server settings: '+'\n'+settings);
					}
				}
				else
				{
					var calSettings=$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('cal-settings').text();
					if(calSettings!='')
					{
						if(!ignoreServerSettings)
							loadSettings(calSettings, true, false);
						else
						{
							delete globalSettings.version.value;
							loadSettings(JSON.stringify(globalSettings), false, false);
							console.log('Ignoring server settings: '+'\n'+calSettings);
						}
					}
					else
					{
						delete globalSettings.version.value;
						loadSettings(JSON.stringify(globalSettings), false, false);
					}
				}
			}
		}
		else if(!settingsLoaded && inputResource.href.indexOf(globalLoginUsername)!=-1)
		{
			delete globalSettings.version.value;
			loadSettings(JSON.stringify(globalSettings), false, false);
		}
		else if(!globalSyncSettingsSave && inputResource.href.indexOf(globalLoginUsername)!=-1 && ((isAvaible('CardDavMATE')&&globalCardDAVResourceSync) || (isAvaible('CalDavZAP')&&globalCalDAVResourceSync)))
		{
			globalSyncSettingsSave=true;
			var loadedCals = new Array(), loadedTodoCals = new Array(), loadedAddrs = new Array();
			if(isAvaible('CardDavMATE'))
				loadedAddrs = globalSettings.loadedaddressbookcollections.value.slice();
			if(isAvaible('CalDavZAP'))
			{
				loadedCals = globalSettings.loadedcalendarcollections.value.slice();
				loadedTodoCals = globalSettings.loadedtodocollections.value.slice();
			}
			var settings = $(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('settings').text();
			if(typeof globalPreviousSupportedSettings !='undefined' && globalPreviousSupportedSettings!=null)
				loadSettings(settings, true, true);
			if(isAvaible('CardDavMATE'))
				globalSettings.loadedaddressbookcollections.value = loadedAddrs.slice();
			if(isAvaible('CalDavZAP'))
			{
				globalSettings.loadedcalendarcollections.value = loadedCals.slice();
				globalSettings.loadedtodocollections.value = loadedTodoCals.slice();
			}
			checkBeforeClose(false);
		}

		$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').each(function(index, element){
			$(element).children().filterNsNode('propstat').each(function(pindex, pelement){
				var resources=$(pelement).children().filterNsNode('prop');
				var color='';

				var typeList=new Array();
				resources.children().filterNsNode('supported-calendar-component-set').children().filterNsNode('comp').each(function(pindex, pelement){
					typeList[typeList.length]=pelement.getAttribute('name').toLowerCase();
				});

				if(typeof inputResource!='undefined' && typeof inputResource.collectionTypes!='undefined' && inputResource.collectionTypes!=null && inputResource.collectionTypes.indexOf('calendar')!=-1 ||
					typeof inputResource=='undefined' || inputResource.collectionTypes==null)
					if((isAvaible('CalDavZAP') && resources.children().filterNsNode('resourcetype').children().filterNsNode('calendar').length==1 && resources.children().filterNsNode('resourcetype').children().filterNsNode('collection').length==1) && (inputResource.ignoreBound==undefined || !(inputResource.ignoreBound==true && resources.children().filterNsNode('resourcetype').children().filterNsNode('webdav-binding').length==1)))
					{
						if(resources.children().filterNsNode('calendar-color').length==1)
						{
							color=resources.children().filterNsNode('calendar-color').text();
							if(color.length==9)
								color=color.substring(0, 7);
						}

						var permissions=new Array();
						resources.children().filterNsNode('current-user-privilege-set').children().filterNsNode('privilege').each(
							function(index, element)
							{
								$(element).children().each(
									function(index, element)
									{
										permissions[permissions.length]=$(element).prop('tagName').replace(/^[^:]+:/,'');
									}
								);
							}
						);

						var read_only=false;
						var href=$(element).children().filterNsNode('href').text();
						if(href.match(RegExp('^https?://','i'))!=null)
						{
							var tmpH = href.match(RegExp('^(https?://)([^/]+)(.*)','i'))
							if(tmpH!=null)
								href = tmpH[3];
						}

						if(permissions.length>0 && permissions.indexOf('all')==-1 && permissions.indexOf('write')==-1 && permissions.indexOf('write-content')==-1)
							read_only=true;
						else if(inputResource.forceReadOnly!=undefined && (inputResource.forceReadOnly==true || inputResource.forceReadOnly instanceof Array))
						{
							if(inputResource.forceReadOnly instanceof Array)
							{
								for(var j=0; j<inputResource.forceReadOnly.length; j++)
									if(typeof inputResource.forceReadOnly[j]=='string')
									{
										var index=href.indexOf(inputResource.forceReadOnly[j]);
										if(index!=-1)
											if(href.length==(index+inputResource.forceReadOnly[j].length))
												read_only=true;
									}
									else if(typeof inputResource.forceReadOnly[j]=='object')
									{
										if(href.match(inputResource.forceReadOnly[j]) != null)
											read_only=true;
									}
							}
							else
								read_only=true;
						}
						var displayvalue=resources.children().filterNsNode('displayname').text();
						var headervalue=resources.children().filterNsNode('headervalue').text();
						var synctoken=resources.children().filterNsNode('sync-token').text();
						var oldSyncToken='';
						var tmp_dv=href.match(RegExp('.*/([^/]+)/$', 'i'));

						if(displayvalue=='') // MacOSX Lion Server
							displayvalue=tmp_dv[1];

						if(color=='')
						{
							var par=(uidBase+href).split('/');
							var hash=hex_sha256(hex_sha256(par[par.length-3]+'/'+par[par.length-2]+'/'));
							var hex=hash.substring(0,6);
							while(checkColorBrightness(hex)>=252)
								hex=hex_sha256(hex_sha256(hash)).substring(0,6);
							color='#'+hex;
						}
						var ignoreAlarms=false;
						var uidPArts=(uidBase+href).split('/');
						if(typeof inputResource.ignoreAlarms=='boolean' && inputResource.ignoreAlarms)
							ignoreAlarms = true;
						else if(inputResource.ignoreAlarms instanceof Array && inputResource.ignoreAlarms.length>0)
						{
							for(var j=0; j<inputResource.ignoreAlarms.length; j++)
							{
								if(typeof inputResource.ignoreAlarms[j]=='string')
								{
									var index=href.indexOf(inputResource.ignoreAlarms[j]);
									if(index!=-1)
										if(href.length==(index+inputResource.ignoreAlarms[j].length))
											ignoreAlarms=true;
								}
								else if (typeof inputResource.ignoreAlarms[j]=='object' && href.match(inputResource.ignoreAlarms[j])!=null)
									ignoreAlarms = true;
							}
						}

						// insert the resource
						var webdav_bind=false;
						if(resources.children().filterNsNode('resourcetype').children().filterNsNode('webdav-binding').length==1)
							webdav_bind=true;

						var checkContentType=(inputResource.checkContentType==undefined ? true : inputResource.checkContentType);

						var syncRequired=true;
						if(typeList.indexOf('vevent')!=-1)
						{
							var someChanged=false;
							var existingResource=globalResourceCalDAVList.getEventCollectionByUID(uidBase+href);
							if(existingResource!=null)
							{
								if(existingResource.syncToken!=synctoken)
									someChanged=true;
							}
							else
							{
								someChanged=true;
								if(synctoken=='')
									synctoken=null;
							}
							var uidParts=(uidBase+href).match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@(.*)'));
							var checkHref=uidParts[1]+uidParts[3];
							if(!isHrefSet)
							{
								saveHref=uidBase+href;
								isHrefSet=true;
							}
							if(!globalDefaultCalendarCollectionLoadAll)
							{
								var toBeLoad=false;
								if(typeof globalCrossServerSettingsURL!='undefined' && globalCrossServerSettingsURL!=null && globalCrossServerSettingsURL)
								{
									var uidParts=(uidBase+href).match(RegExp('/([^/]+/[^/]+/)$'));
									var tmpParts=uidParts[1].match('^(.*/)([^/]+)/$');
									var checkHref3=decodeURIComponent(tmpParts[1])+tmpParts[2]+'/';
									var found=false;
									for(var l=0; l<globalSettings.loadedcalendarcollections.value.length; l++)
									{
										var tmpParts2=globalSettings.loadedcalendarcollections.value[l].match('^(.*/)([^/]+)/([^/]+)/$');
										var checkHref2=decodeURIComponent(tmpParts2[2])+'/'+tmpParts2[3]+'/';
										if(checkHref3==checkHref2)
										{
											found=true;
											globalSettings.loadedcalendarcollections.value[l]=checkHref;
											break;
										}
									}
									toBeLoad=found;
								}
								else
									toBeLoad=globalSettings.loadedcalendarcollections.value.indexOf(checkHref)!=-1;
							}
							else
							{
								var toBeLoad=true;
								if(globalCalDAVInitLoad)
									globalSettings.loadedcalendarcollections.value.push(checkHref);
							}
							if(!toBeLoad)
								oldSyncToken='';
							globalResourceCalDAVList.insertResource({makeLoaded:toBeLoad, typeList:typeList, listType:'vevent', ecolor: color, timestamp: resultTimestamp, uid: uidBase+href, timeOut: inputResource.timeOut, displayvalue: displayvalue, headervalue:headervalue, userAuth: inputResource.userAuth, resourceIndex: indexR, url: baseHref, accountUID: origUID, href: href, hrefLabel: inputResource.hrefLabel, permissions: {full: permissions, read_only: read_only}, crossDomain: inputResource.crossDomain, withCredentials: inputResource.withCredentials, interval: null, waitInterval: null, displayEventsArray: new Array(), pastUnloaded: '', fcSource: null, subscription: false, newlyAdded:toBeLoad, urlArray:null, ignoreAlarms:ignoreAlarms,webdav_bind:webdav_bind, syncRequired:syncRequired, checkContentType: checkContentType, syncToken: synctoken, oldSyncToken: oldSyncToken, someChanged:someChanged}, indexR, true);
							if(globalAccountSettings[indexR]!=undefined)
								globalAccountSettings[indexR].calendarNo++;
							syncRequired=false;
						}
						if(typeList.indexOf('vtodo')!=-1)
						{
							var someChanged=false;
							var existingResource=globalResourceCalDAVList.getTodoCollectionByUID(uidBase+href);
							if(syncRequired && existingResource!=null)
							{
								if(existingResource.syncToken!=synctoken)
									someChanged=true;
							}
							else
							{
								someChanged=true;
								if(synctoken=='')
									synctoken=null;
							}
							var uidParts=(uidBase+href).match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@(.*)'));
							var checkHref=uidParts[1]+uidParts[3];
							if(!isHrefSet)
							{
								saveHref=uidBase+href;
								isHrefSet=true;
							}
							if(!globalDefaultTodoCalendarCollectionLoadAll)
							{
								var toBeLoad=false;
								if(typeof globalCrossServerSettingsURL!='undefined' && globalCrossServerSettingsURL!=null && globalCrossServerSettingsURL)
								{
									var uidParts=(uidBase+href).match(RegExp('/([^/]+/[^/]+/)$'));
									var tmpParts=uidParts[1].match('^(.*/)([^/]+)/$');
									var checkHref3=decodeURIComponent(tmpParts[1])+tmpParts[2]+'/';
									var found=false;
									for(var l=0; l<globalSettings.loadedtodocollections.value.length; l++)
									{
										var tmpParts2=globalSettings.loadedtodocollections.value[l].match('^(.*/)([^/]+)/([^/]+)/$');
										var checkHref2=decodeURIComponent(tmpParts2[2])+'/'+tmpParts2[3]+'/';
										if(checkHref3==checkHref2)
										{
											found=true;
											globalSettings.loadedtodocollections.value[l]=checkHref;
											break;
										}
									}
									toBeLoad=found;
								}
								else
									toBeLoad=globalSettings.loadedtodocollections.value.indexOf(checkHref)!=-1;
							}
							else
							{
								var toBeLoad=true;
								if(globalCalDAVInitLoad)
									globalSettings.loadedtodocollections.value.push(checkHref);
							}
							if(!toBeLoad)
								oldSyncToken='';
							globalResourceCalDAVList.insertResource({makeLoaded:toBeLoad, typeList:typeList, hrefArray: new Array(), listType:'vtodo', ecolor: color, timestamp: resultTimestamp, uid: uidBase+href, timeOut: inputResource.timeOut, displayvalue: displayvalue, headervalue: headervalue, userAuth: inputResource.userAuth, resourceIndex: indexR, url: baseHref, accountUID: origUID, href: href, hrefLabel: inputResource.hrefLabel, permissions: {full: permissions, read_only: read_only}, crossDomain: inputResource.crossDomain, withCredentials: inputResource.withCredentials, interval: null, waitInterval: null, displayEventsArray: new Array(), pastUnloaded: '', fcSource: null, subscription: false, newlyAdded:toBeLoad, urlArray:null, ignoreAlarms:ignoreAlarms,webdav_bind:webdav_bind,syncRequired:syncRequired, checkContentType: checkContentType, syncToken: synctoken, oldSyncToken: oldSyncToken, someChanged:someChanged}, indexR, false);
							if(globalAccountSettings[indexR]!=undefined)
								globalAccountSettings[indexR].todoNo++;
						}
					}

					if(typeof inputResource!='undefined' && typeof inputResource.collectionTypes!='undefined' && inputResource.collectionTypes!=null && inputResource.collectionTypes.indexOf('addressbook')!=-1 || typeof inputResource=='undefined' || inputResource.collectionTypes==null)
						if((isAvaible('CardDavMATE') && resources.children().filterNsNode('resourcetype').children().filterNsNode('addressbook').length==1 && resources.children().filterNsNode('resourcetype').children().filterNsNode('collection').length==1) && (inputResource.ignoreBound==undefined || !(inputResource.ignoreBound==true && resources.children().filterNsNode('resourcetype').children().filterNsNode('webdav-binding').length==1)))
						{
							if(resources.children().filterNsNode('addressbook-color').length==1)
							{
								color=resources.children().filterNsNode('addressbook-color').text();
								if(color.length==9)
									color=color.substring(0, 7);
							}

							var permissions=new Array();
							resources.children().filterNsNode('current-user-privilege-set').children().filterNsNode('privilege').each(
								function(index, element)
								{
									$(element).children().each(
										function(index, element)
										{
											permissions[permissions.length]=$(element).prop('tagName').replace(/^[^:]+:/,'');
										}
									);
								}
							);

							var disableLocking=false;
							var tmp_lock_support=resources.children().filterNsNode('supportedlock').children().filterNsNode('lockentry').children().filterNsNode('lockscope').children().filterNsNode('exclusive');
							if(typeof tmp_lock_support=='undefined' || tmp_lock_support.length==undefined || tmp_lock_support.length==0)
								disableLocking=true;

							var href=$(element).children().filterNsNode('href').text();
							if(href.match(RegExp('^https?://','i'))!=null)
							{
								var tmpH = href.match(RegExp('^(https?://)([^/]+)(.*)','i'))
								if(tmpH!=null)
									href = tmpH[3];
							}
							var tmp_cn=href.match(RegExp('/([^/]+)/?$'));	// collection name

							var read_only=false;
							if(((typeof globalDisablePermissionChecking=='undefined' || globalDisablePermissionChecking!=true) && (permissions.length>0 && permissions.indexOf('all')==-1 && permissions.indexOf('write')==-1 && permissions.indexOf('write-content')==-1)) || (inputResource.forceReadOnly!=undefined && (inputResource.forceReadOnly==true || inputResource.forceReadOnly instanceof Array && inputResource.forceReadOnly.indexOf(tmp_cn[1])!=-1)))
								read_only=true;

							var displayvalue=resources.children().filterNsNode('displayname').text();
							var headervalue=resources.children().filterNsNode('headervalue').text();
							var synctoken=resources.children().filterNsNode('sync-token').text();
							var oldSyncToken='';

							var tmp_dv=href.match(RegExp('.*/([^/]+)/$','i'));
							if(displayvalue=='')	// OS X Server
								displayvalue=tmp_dv[1];

							if(color=='')
							{
								var par=(uidBase+href).split('/');
								var hash=hex_sha256(hex_sha256(par[par.length-3]+'/'+par[par.length-2]+'/'));
								var hex=hash.substring(0,6);
								while(checkColorBrightness(hex)>=252)
									hex=hex_sha256(hex_sha256(hash)).substring(0,6);
								color='#'+hex;
							}

							var checkContentType=(inputResource.checkContentType==undefined ? true : inputResource.checkContentType);
							// insert the resource
							var someChanged=false;
							var existingResource=globalResourceCardDAVList.getCollectionByUID(uidBase+href);
							if(existingResource!=null)
							{
								if(existingResource.syncToken!=synctoken)
									someChanged=true;
								if(typeof globalForceSyncURLArray!='undefined' && globalForceSyncURLArray.length>0 && globalForceSyncURLArray.indexOf(existingResource.uid)!=-1)
								{
									someChanged=true;
								}
							}
							else
							{
								someChanged=true;
								if(synctoken=='')
									synctoken=null;
							}
							var uidParts=(uidBase+href).match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@(.*)'));
							var checkHref=uidParts[1]+uidParts[3];
							if(!isHrefSet)
							{
								saveHref=uidBase+href;
								isHrefSet=true;
							}
							if(!globalDefaultAddrCollectionLoadAll)
							{
								var toBeLoad=false;
								if(typeof globalCrossServerSettingsURL!='undefined' && globalCrossServerSettingsURL!=null && globalCrossServerSettingsURL)
								{
									var uidParts=(uidBase+href).match(RegExp('/([^/]+/[^/]+/)$'));
									var tmpParts=uidParts[1].match('^(.*/)([^/]+)/$');
									var checkHref3=decodeURIComponent(tmpParts[1])+tmpParts[2]+'/';
									var found=false;
									for(var l=0; l<globalSettings.loadedaddressbookcollections.value.length; l++)
									{
										var tmpParts2=globalSettings.loadedaddressbookcollections.value[l].match('^(.*/)([^/]+)/([^/]+)/$');
										var checkHref2=decodeURIComponent(tmpParts2[2])+'/'+tmpParts2[3]+'/';
										if(checkHref3==checkHref2)
										{
											found=true;
											globalSettings.loadedaddressbookcollections.value[l]=checkHref;
											break;
										}
									}
									toBeLoad=found;
								}
								else
									toBeLoad=globalSettings.loadedaddressbookcollections.value.indexOf(checkHref)!=-1;
							}
							else
							{
								var toBeLoad=true;
								if(globalCardDAVInitLoad)
									globalSettings.loadedaddressbookcollections.value.push(checkHref);
							}
							globalResourceCardDAVList.insertResource({makeLoaded:toBeLoad, timestamp: resultTimestamp, uid: uidBase+href, timeOut: inputResource.timeOut, displayvalue: displayvalue, headervalue: headervalue, userAuth: inputResource.userAuth, url: baseHref, accountUID: origUID, href: href, hrefLabel: inputResource.hrefLabel, color: color, permissions: {full: permissions, read_only: read_only}, crossDomain: inputResource.crossDomain, withCredentials: inputResource.withCredentials, checkContentType: checkContentType, isLoaded:false, newlyAdded:toBeLoad, indexResource:indexR, disableLocking: disableLocking, syncToken: synctoken, oldSyncToken:oldSyncToken, someChanged:someChanged}, inputResourceIndex);
							inputResource.addressbookNo++;
						}
			});
		});

		if(saveHref!='')
		{
			var saveUserHref=saveHref.replace(new RegExp('[^/]+/$'),'');
			if(typeof globalResourceCalDAVList!='undefined' && globalResourceCalDAVList!=null)
				globalResourceCalDAVList.removeOldResources(saveUserHref, resultTimestamp);
			if(typeof globalResourceCardDAVList!='undefined' && globalResourceCardDAVList!=null)
				globalResourceCardDAVList.removeOldResources(saveUserHref, resultTimestamp);
		}
		//recursive call for resource loading
		if(hrefMode)
			netLoadResource(inputResource, inputResource.cahref, false, inputResourceIndex, forceLoad, indexR, loadArray)
		else
		{
			indexR++;
			netFindResource(globalAccountSettings[indexR], inputResourceIndex, forceLoad, indexR,loadArray);
		}
	}

	// first try to process the cached data (if cached results are available in the "auth module" response)
	var tmpCache;
	if(globalXMLCache!=null && (tmpCache=globalXMLCache.children('davprincipalcollections[request_url="'+jqueryEscapeSelector(inputHref)+'"]').remove()).length)
	{
		if(typeof globalDebug!='undefined' && globalDebug instanceof Array && globalDebug.indexOf('cache')!=-1)
			console.log('DBG Cache OK: '+arguments.callee.name+' url: \''+inputHref+'\': saved one request!');
		ajaxComplete('', 'success', {responseXML: tmpCache});
	}
	else
	{
		if(typeof globalDebug!='undefined' && globalDebug instanceof Array && globalDebug.indexOf('cache')!=-1)
			console.log('DBG Cache ERROR: '+arguments.callee.name+' url: \''+inputHref+'\': spend one request!');
		$.ajax({
			type: 'PROPFIND',
			url: inputHref,
			cache: false,
			crossDomain: (typeof inputResource.crossDomain=='undefined' ? true : inputResource.crossDomain),
			xhrFields: {
				withCredentials: (typeof inputResource.withCredentials=='undefined' ? false : inputResource.withCredentials)
			},
			timeout: inputResource.timeOut,
			beforeSend: function(req){
				if(globalSettings.usejqueryauth.value!=true && inputResource.userAuth.userName!='' && inputResource.userAuth.userPassword!='')
					req.setRequestHeader('Authorization', basicAuth(inputResource.userAuth.userName, inputResource.userAuth.userPassword));

				req.setRequestHeader('X-client', globalXClientHeader);
				req.setRequestHeader('Depth', '1');
				if(globalSettingsSaving!=''||(isAvaible('CardDavMATE') && (!globalCardDAVInitLoad && !globalCardDAVResourceSync)) || (isAvaible('CalDavZAP') && (!globalCalDAVInitLoad && !globalCalDAVResourceSync))||(isAvaible('Projects') && isProjectsLoaded))
					/* XXX - System display:none changes */
					if(globalSettingsSaving!='' || (isAvaible('Settings') && $('#SystemSettings').css('visibility')=='visible' && $('.resourceSettings_item_selected').attr('data-type')=='setting_group_password'))
					{
						indexR++;
						if(((isAvaible('CardDavMATE')&&globalCardDAVInitLoad) || (isAvaible('CalDavZAP'&&globalCalDAVInitLoad))) && indexR==globalAccountSettings.length)
							$('#MainLoader').fadeOut(1200);
						netFindResource(globalAccountSettings[indexR], inputResourceIndex, forceLoad, indexR,loadArray);
						return false;
					}
			},
			username: (globalSettings.usejqueryauth.value==true ? inputResource.userAuth.userName : null),
			password: (globalSettings.usejqueryauth.value==true ? inputResource.userAuth.userPassword : null),
			contentType: 'text/xml; charset=utf-8',
			processData: true,
			data: '<?xml version="1.0" encoding="utf-8"?><D:propfind xmlns:D="DAV:"><D:prop>'+settingsXML+'<D:current-user-privilege-set/><D:displayname/><D:supportedlock/><D:resourcetype/><D:supported-report-set/><D:sync-token/><A:calendar-color xmlns:A="'+(typeof globalCalendarColorPropertyXmlns!='undefined'&&globalCalendarColorPropertyXmlns!=null&&globalCalendarColorPropertyXmlns!='' ? globalCalendarColorPropertyXmlns : 'http://apple.com/ns/ical/')+'"/><I:headervalue xmlns:I="http://inf-it.com/ns/dav/"/><I:addressbook-color xmlns:I="'+(typeof globalAddrColorPropertyXmlns!='undefined'&&globalAddrColorPropertyXmlns!=null&&globalAddrColorPropertyXmlns!='' ? globalAddrColorPropertyXmlns : 'http://inf-it.com/ns/ab/')+'"/><L:supported-calendar-component-set xmlns:L="urn:ietf:params:xml:ns:caldav"/><R:max-image-size xmlns:R="urn:ietf:params:xml:ns:carddav"/></D:prop></D:propfind>',
			dataType: 'xml',
			error: function(objAJAXRequest, strError){
				console.log("Error: [netLoadResource: 'PROPFIND "+uidFull+"']: code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
				inputResource.errorLoaded=true;
				if(isAvaible('CalDavZAP'))
				{
					$('#intCaldav').find('.int_error').css('display','block');
					$('#intCaldavTodo').find('.int_error').css('display','block');
				}
				if(isAvaible('CardDavMATE'))
					$('#intCarddav').find('.int_error').css('display','block');
				if(hrefMode)
					netLoadResource(inputResource, inputResource.cahref, false, inputResourceIndex, forceLoad, indexR, loadArray);
				else
				{
					indexR++;
					var allFail=true;
					for(var i=0; i< globalAccountSettings.length; i++)
						if(typeof globalAccountSettings[i].errorLoaded=='undefined' || globalAccountSettings[i].errorLoaded==null || globalAccountSettings[i].errorLoaded===false)
							allFail=false;
					if(((isAvaible('CardDavMATE')&&globalCardDAVInitLoad) || (isAvaible('CalDavZAP')&&globalCalDAVInitLoad)) && indexR==globalAccountSettings.length && allFail)
						$('#MainLoader').fadeOut(1200);

					if(isAvaible('CalDavZAP') && !globalCalDAVInitLoad)
						handleCalDAVError(true, inputResource);
					if(isAvaible('CardDavMATE') && !globalCardDAVInitLoad)
						handleCardDAVError(true, inputResource);
					netFindResource(globalAccountSettings[indexR], inputResourceIndex, forceLoad, indexR,loadArray);
				}
				return false;
			},
			success: ajaxComplete
		});
	}
}
// Save the client settings (stored as DAV property on server)
function netSaveSettings(inputResource, inputSettings, isFormSave, collectionLoad)
{
	var re=new RegExp('^(https?://)([^/]+)(.*)', 'i');
	var tmp=inputResource.href.match(re);
	var baseHref=tmp[1]+tmp[2];
	var uidBase=tmp[1]+inputResource.userAuth.userName+'@'+tmp[2];
	var uidFull=tmp[1]+inputResource.userAuth.userName+'@'+tmp[2]+tmp[3]; //for the error handler
	var saveHref = inputResource.href;
	var serverSettingss = transformToServer(inputSettings);

	if(globalSettings.settingstype.value!='' && globalSettings.settingstype.value!=null)
	{
		if(globalSettings.settingstype.value=='addressbook-home-set')
			saveHref = inputResource.abhref;
		else if(globalSettings.settingstype.value=='calendar-home-set')
			saveHref = inputResource.cahref;
	}

	$.ajax({
		type: 'PROPPATCH',
		url: saveHref,
		cache: false,
		crossDomain: (typeof inputResource.crossDomain=='undefined' ? true: inputResource.crossDomain),
		xhrFields: {
			withCredentials: (typeof inputResource.withCredentials=='undefined' ? false: inputResource.withCredentials)
		},
		timeout: inputResource.timeOut,
		beforeSend: function(req){
			if(globalSettings.usejqueryauth.value!=true && inputResource.userAuth.userName!='' && inputResource.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(inputResource.userAuth.userName, inputResource.userAuth.userPassword));

			req.setRequestHeader('X-client', globalXClientHeader);
			req.setRequestHeader('Depth', '0');
		},
		username: (globalSettings.usejqueryauth.value==true ? inputResource.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? inputResource.userAuth.userPassword : null),
		contentType: 'text/xml',
		processData: true,
		data: '<?xml version="1.0" encoding="utf-8"?><D:propertyupdate xmlns:D="DAV:"><D:set><D:prop><I:settings xmlns:I="http://inf-it.com/ns/dav/">'+JSON.stringify(serverSettingss)+'</I:settings></D:prop></D:set></D:propertyupdate>',
		dataType: 'xml',
		error: function(objAJAXRequest, strError){
			console.log("Error: [netSaveSettings: 'PROPPATCH "+uidFull+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' (this error code usually means network connection error, or your browser is trying to make a cross domain query, but it is not allowed by the destination server or the browser itself)': ''));

			if(isAvaible('Settings'))
				show_editor_loader_messageSettings('message_error', localization[globalInterfaceLanguage].errSettingsSaved);

			var loader=null;
			if(typeof globalSettingsSaving!='undefined')
			{
				if(globalSettingsSaving=='event')
					loader=$('#CalendarLoader');
				else if(globalSettingsSaving=='todo')
					loader=$('#CalendarLoaderTODO');
				else if(globalSettingsSaving=='addressbook')
					loader=$('#AddressbookOverlay');
			}

			if(loader!=null)
			{
				loader.addClass('message_error').children('.loaderInfo').text(localization[globalInterfaceLanguage].errCollectionLoad);
				setTimeout(function(){
					loader.addClass('loader_hidden').removeClass('message_error').children('.loaderInfo').text('');
				}, globalHideInfoMessageAfter);
			}

			globalSettingsSaving='';
			return false;
		},
		success: function(data, textStatus, xml)
		{
			if(isAvaible('Settings')&&isFormSave)
			{
/*						if((isAvaible('CardDavMATE')&&globalCardDAVResourceSync) || (isAvaible('CalDavZAP')&&globalCalDAVResourceSync))
				{
					var myInt = setInterval(function(){
						if((isAvaible('CardDavMATE')&&!globalCardDAVResourceSync) && (isAvaible('CalDavZAP')&&!globalCalDAVResourceSync))
						{
							clearInterval(myInt);
							applySettings(getChangedSettings(globalSettings, inputSettings));
							globalSettings = inputSettings;
						}
					},100);
				}
				else
				{*/
					applySettings(getChangedSettings(globalSettings, inputSettings));
					globalSettings = inputSettings;
//						}
			}
			else if(collectionLoad)
			{
/*						if((isAvaible('CardDavMATE')&&globalCardDAVResourceSync) || (isAvaible('CalDavZAP')&&globalCalDAVResourceSync))
				{
					var myInt = setInterval(function(){
						if((isAvaible('CardDavMATE')&&!globalCardDAVResourceSync) && (isAvaible('CalDavZAP')&&!globalCalDAVResourceSync))
						{
							clearInterval(myInt);
							checkForLoadedCollections(inputSettings);
							globalSettings = inputSettings;
						}
					},100);
				}
				else
				{*/
					checkForLoadedCollections(inputSettings);
					globalSettings = inputSettings;
//						}
			}
		}
	});
}

function deleteVcalendarFromCollection(inputUID,inputForm, putMode)
{
	var tmp=inputUID.match(vCalendar.pre['uidParts']);
	var collection_uid=tmp[1]+tmp[2]+'@'+tmp[3]+tmp[4]+tmp[5];
	var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5]+tmp[6];

	var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
	var resourceCalDAV_user=tmp[2];

	var resourceSettings=null;

	var rid=inputUID.substring(0, inputUID.lastIndexOf('/')+1);
	if(inputForm=='vevent')
		var resources=globalResourceCalDAVList.collections;
	else
		var resources=globalResourceCalDAVList.TodoCollections;

	var rex=vCalendar.pre['accountUidParts'];
	for(var j=0;j<resources.length;j++)
	{
		if(rid==resources[j].uid)
		{
			var tmp=resources[j].accountUID.match(rex);
			var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
			var resourceCalDAV_user=tmp[2];

			// find the original settings for the resource and user
			for(var i=0;i<globalAccountSettings.length;i++)
				if(globalAccountSettings[i].href==resourceCalDAV_href && globalAccountSettings[i].userAuth.userName==resourceCalDAV_user)
					resourceSettings=globalAccountSettings[i];
			break;
		}
	}

	if(resourceSettings==null)
		return false;
	// the begin of each error message
	if(inputForm=='vevent')
		var errBegin=localization[globalInterfaceLanguage].errUnableDeleteBeginCalDAV;
	else
		var errBegin=localization[globalInterfaceLanguage].errUnableDeleteTodoBeginCalDAV;

	var vcalendarList=new Array();
	$.ajax({
		type: 'DELETE',
		url: put_href,
		cache: false,
		crossDomain: true,
		xhrFields: {
			withCredentials: (typeof resourceSettings.withCredentials=='undefined' ? false: resourceSettings.withCredentials)
		},
		timeout: resourceSettings.timeOut,
		beforeSend: function(req)
		{
			if(globalSettings.usejqueryauth.value!=true && resourceSettings.userAuth.userName!='' && resourceSettings.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(resourceSettings.userAuth.userName, resourceSettings.userAuth.userPassword));

			req.setRequestHeader('X-client', globalXClientHeader);
		},
		username: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userPassword : null),
		contentType: 'text/calendar',
		processData: true,
		data: '',
		dataType: 'text',
		error: function(objAJAXRequest, strError){
			console.log("Error: [deleteVcalendarFromCollection: 'DELETE "+put_href+"']: code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
			switch (objAJAXRequest.status)
			{
				case 401:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp401));
					break;
				case 403:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp403));
					break;
				case 405:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp405));
					break;
				case 408:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp408));
					break;
				case 410:
					if(inputForm=='vevent')
						show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].CalDAVerrHttp410));
					else
						show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].CalDAVerrTodoHttp410));
					break;
				case 500:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp500));
					break;
				default:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttpCommon.replace('%%', objAJAXRequest.status)));
					break;
			}
			return false;
		},
		success: function(data, textStatus, xml){
			if(inputForm=='vevent')
				globalEventList.removeOldEvent(inputUID, true, true);
			else if(putMode)
				globalEventList.removeOldEvent(inputUID, true, false);
			if(putMode)
				return true;

			if(inputForm=='vevent')
			{
				show_editor_loader_messageCalendar('vevent', 'message_success', localization[globalInterfaceLanguage].txtAllDeleted, function(a)
				{
					//setTimeout(function()
					//{
						$('#show').val('');
						$('#CAEvent').hide();
						$('#event_details_template').remove();
						$('#CAEvent').append(cleanVcalendarTemplate);
						$('#EventDisabler').fadeOut(globalEditorFadeAnimation, function(){
							$('#timezonePicker').prop('disabled', false);
						});
					//}, a);
				});
			}
			else
			{
				show_editor_loader_messageCalendar('vtodo', 'message_success', localization[globalInterfaceLanguage].txtAllDeletedTodo, function(a)
				{
					//setTimeout(function()
					//{
						$('#showTODO').val('');
						$('#TodoDisabler').fadeOut(globalEditorFadeAnimation, function(){
							$('#timezonePickerTODO').prop('disabled', false);
						});
						globalEventList.removeOldEvent(inputUID, true, false);
					//}, a);
				});
			}
		}
	});
}

function moveVcalendarToCollection(accountUID, inputUID, inputEtag, inputVcalendar, delUID,inputForm,isFormHidden,deleteMode,textArray)
{
	var resultTimestamp=new Date().getTime();
	if(inputForm=='vtodo')
		globalTodoLoaderHide = localization[globalInterfaceLanguage].txtAllSavedTodo;
	var hex=hex_sha256(inputVcalendar+(new Date().getTime()));

	var tmp=delUID.match(vCalendar.pre['uidParts']);
	var tmpDest=inputUID.match(vCalendar.pre['uidParts']);
	var collection_uid=tmpDest[1]+tmpDest[2]+'@'+tmpDest[3]+tmpDest[4]+tmpDest[5];
//console.log(collection_uid)
	// if inputEtag is empty, we have a newly created vevent/vtodo and need to create a .ics file name for it
	var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5]+tmp[6];
	var dest_href=tmpDest[1]+tmpDest[3]+tmpDest[4]+tmpDest[5]+tmpDest[6];

	var put_href_part=tmp[4]+tmp[5]+tmp[6];
	var dest_href_part=tmpDest[4]+tmpDest[5]+tmpDest[6];

	var resourceSettings=null;

	// find the original settings for the resource and user
	var tmp=accountUID.match(vCalendar.pre['accountUidParts']);

	var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
	var resourceCalDAV_user=tmp[2];

	for(var i=0;i<globalAccountSettings.length;i++)
		if(globalAccountSettings[i].href==resourceCalDAV_href && globalAccountSettings[i].userAuth.userName==resourceCalDAV_user)
			resourceSettings=globalAccountSettings[i];

	if(resourceSettings==null)
		return false;

	// the begin of each error message
	if(inputForm=='vevent')
		var errBegin=localization[globalInterfaceLanguage].errUnableSaveBeginCalDAV;
	else
		var errBegin=localization[globalInterfaceLanguage].errUnableSaveTodoBeginCalDAV;
	var collection=globalResourceCalDAVList.getEventCollectionByUID(collection_uid);
	if(collection==null)
		collection=globalResourceCalDAVList.getTodoCollectionByUID(collection_uid);
	var vcalendarList=new Array();
	$.ajax({
		type: 'MOVE',
		url: put_href,
		cache: false,
		crossDomain: (typeof resourceSettings.crossDomain=='undefined' ? true: resourceSettings.crossDomain),
		xhrFields: {
			withCredentials: (typeof resourceSettings.withCredentials=='undefined' ? false: resourceSettings.withCredentials)
		},
		timeout: resourceSettings.timeOut,
		beforeSend: function(req)
		{
			if(globalSettings.usejqueryauth.value!=true && resourceSettings.userAuth.userName!='' && resourceSettings.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(resourceSettings.userAuth.userName, resourceSettings.userAuth.userPassword));

			req.setRequestHeader('X-client', globalXClientHeader);
			req.setRequestHeader('Destination', dest_href);
		},
		username: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userPassword : null),
		contentType: 'text/calendar',
		processData: true,
		data: inputVcalendar,
		dataType: 'text',
		error: function(objAJAXRequest, strError)
		{
			console.log("Error: [moveVcalendarToCollection: 'MOVE from: "+put_href+" to: "+dest_href+"']: code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
			switch (objAJAXRequest.status)
			{
				case 401:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp401));
					break;
				case 403:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp403));
					break;
				case 405:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp405));
					break;
				case 408:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp408));
					break;
				case 412:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp412));
					netLoadCalendar(globalResourceCalDAVList.getCollectionByUID(collection_uid), [{etag: '', href: put_href_part}], (collection.forceSyncPROPFIND==undefined || collection.forceSyncPROPFIND==false ? true : false), false, true, true,true, null, null);
					break;
				case 500:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp500));
					break;
				default:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttpCommon.replace('%%', objAJAXRequest.status)));
					break;
			}
			if(inputForm=='vtodo')
				globalTodoLoaderHide='';
			if(($('#InvitationBoxContent').is(':visible'))&&(inputForm=='vevent'||inputForm=='schedule-inbox'))
			{
				if(!$('#InvitationBoxHeader').find('.invitation_header_item_selected').length)
					$('#InvitationBoxHeader').find('.invitation_header_item').first().trigger('click');
				else
					filterInvitations($('#InvitationBoxHeader').find('.invitation_header_item_selected').attr('data-type'));
			}
			return false;
		},
		success: function(data, textStatus, xml){
			globalRevertFunction=null;
			var isTODO=false;
			globalWindowFocus=false;
			if(inputForm=='vevent' || (inputForm=='schedule-inbox' && $('#CAEvent').is(':visible')))
			{
				var eventSuccessMessage=localization[globalInterfaceLanguage].txtAllSaved;
				if(deleteMode)
					eventSuccessMessage=localization[globalInterfaceLanguage].txtAllDeleted;

				show_editor_loader_messageCalendar(inputForm, 'message_success', eventSuccessMessage, function(a){
					//setTimeout(function(){
						$('#show').val('');
						if(isFormHidden!=true)
						{
							$('#CAEvent').hide();
							$('#calendar').fullCalendar('unselect');
							$('#event_details_template').remove();
							$('#CAEvent').append(cleanVcalendarTemplate);
							$('#EventDisabler').fadeOut(globalEditorFadeAnimation, function(){
								$('#timezonePicker').prop('disabled', false);
							});
						}
					//}, a);
				});
				globalEventList.removeOldEvent(delUID, true, true);
			}
			else if(inputForm=='vtodo')
				globalEventList.removeOldEvent(delUID, true, false);

			if(inputForm=='vevent')
				netLoadCalendar(globalResourceCalDAVList.getEventCollectionByUID(collection_uid), [{etag: '', href: dest_href_part}], (collection.forceSyncPROPFIND==undefined || collection.forceSyncPROPFIND==false ? true : false), false, true,false, true, null, null);
			else if(inputForm=='vtodo')
			{
				$('#showTODO').val(inputUID);
				netLoadCalendar(globalResourceCalDAVList.getTodoCollectionByUID(collection_uid), [{etag: '', href: dest_href_part}], (collection.forceSyncPROPFIND==undefined || collection.forceSyncPROPFIND==false ? true : false), false, true,false, true, null, null);
			}
			globalWindowFocus=true;
		}
	});
}

function putVcalendarToCollection(accountUID, inputUID, inputEtag, inputVcalendar, delUID,inputForm,isFormHidden,deleteMode,textArray)
{
	var resultTimestamp=new Date().getTime();
	if(inputForm=='vtodo')
		globalTodoLoaderHide = localization[globalInterfaceLanguage].txtAllSavedTodo;

	// line folding (RFC2445 - section 4.1) - maximum of 75 octects (and cannot break
	//  multi-octet UTF8-characters) allowed on one line, excluding a line break (CRLF)
	inputVcalendar=vObjectLineFolding(inputVcalendar);

	var hex=hex_sha256(inputVcalendar+(new Date().getTime()));

	var tmp=inputUID.match(vCalendar.pre['uidParts']);
	var collection_uid=tmp[1]+tmp[2]+'@'+tmp[3]+tmp[4]+tmp[5];

	// if inputEtag is empty, we have a newly created vevent/vtodo and need to create a .ics file name for it
	if(inputEtag!='')
	{
		var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5]+tmp[6];
		var put_href_part=tmp[4]+tmp[5]+tmp[6];
	}
	else
	{
		if(inputUID.charAt(inputUID.length-1)!='/')
		{
			var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5]+tmp[6];
			var put_href_part=tmp[4]+tmp[5]+tmp[6];
		}
		else
		{
			var vcalendarFile=hex+'.ics';
			var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5]+vcalendarFile;
			var put_href_part=tmp[4]+tmp[5]+vcalendarFile;
			inputUID+=vcalendarFile;
		}
	}
	var resourceSettings=null;

	// find the original settings for the resource and user
	var tmp=accountUID.match(vCalendar.pre['accountUidParts']);

	var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
	var resourceCalDAV_user=tmp[2];

	for(var i=0;i<globalAccountSettings.length;i++)
		if(globalAccountSettings[i].href==resourceCalDAV_href && globalAccountSettings[i].userAuth.userName==resourceCalDAV_user)
			resourceSettings=globalAccountSettings[i];

	if(resourceSettings==null)
		return false;

	// the begin of each error message
	if(inputForm=='vevent')
		var errBegin=localization[globalInterfaceLanguage].errUnableSaveBeginCalDAV;
	else
		var errBegin=localization[globalInterfaceLanguage].errUnableSaveTodoBeginCalDAV;
	var collection=globalResourceCalDAVList.getEventCollectionByUID(collection_uid);
	if(collection==null)
		collection=globalResourceCalDAVList.getTodoCollectionByUID(collection_uid);
	var vcalendarList=new Array();
	$.ajax({
		type: 'PUT',
		url: put_href,
		cache: false,
		crossDomain: (typeof resourceSettings.crossDomain=='undefined' ? true: resourceSettings.crossDomain),
		xhrFields: {
			withCredentials: (typeof resourceSettings.withCredentials=='undefined' ? false: resourceSettings.withCredentials)
		},
		timeout: resourceSettings.timeOut,
		beforeSend: function(req)
		{
			req.setRequestHeader('Prefer', 'return=representation');
			if(globalSettings.usejqueryauth.value!=true && resourceSettings.userAuth.userName!='' && resourceSettings.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(resourceSettings.userAuth.userName, resourceSettings.userAuth.userPassword));

			req.setRequestHeader('X-client', globalXClientHeader);
			if(inputEtag!='')
				req.setRequestHeader('If-Match', inputEtag);
			else // adding new object
				req.setRequestHeader('If-None-Match', '*');
		},
		username: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userPassword : null),
		contentType: 'text/calendar',
		processData: true,
		data: inputVcalendar,
		dataType: 'text',
		error: function(objAJAXRequest, strError)
		{
			console.log("Error: [putVcalendarToCollection: 'PUT "+put_href+"']: code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
			switch (objAJAXRequest.status)
			{
				case 401:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp401));
					break;
				case 403:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp403));
					break;
				case 405:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp405));
					break;
				case 408:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp408));
					break;
				case 412:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp412));
					netLoadCalendar(globalResourceCalDAVList.getCollectionByUID(collection_uid), [{etag: '', href: put_href_part}], (collection.forceSyncPROPFIND==undefined || collection.forceSyncPROPFIND==false ? true : false), false, true, true,true, null, null);
					break;
				case 500:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttp500));
					break;
				default:
					show_editor_loader_messageCalendar(inputForm, 'message_error', errBegin.replace('%%', localization[globalInterfaceLanguage].errHttpCommon.replace('%%', objAJAXRequest.status)));
					break;
			}
			if(inputForm=='vevent' && globalRevertFunction!=null)
			{
				globalRevertFunction();
				globalRevertFunction=null
			}
			else if(inputForm=='vtodo')
			{
				globalTodoLoaderHide='';
				if(isFormHidden)
					$('#todoList').fullCalendar('allowSelectEvent',true);
			}

			return false;
		},
		success: function(data, textStatus, xml){
			globalRevertFunction=null;
			if(delUID!='')
				deleteVcalendarFromCollection(delUID,inputForm, true);

			if(textArray.length>0)
			{
				var tArr = textArray[0];
				textArray.splice(0,1);
				putVcalendarToCollection(accountUID, inputUID.substring(0, inputUID.lastIndexOf('/')+1), '', tArr, delUID,inputForm,isFormHidden,deleteMode,textArray)
			}
			var newEtag=xml.getResponseHeader('Etag');
			var isTODO=false;
			globalWindowFocus=false;
			if(inputForm=='vevent')
			{
				var eventSuccessMessage=localization[globalInterfaceLanguage].txtAllSaved;
				if(deleteMode)
					eventSuccessMessage=localization[globalInterfaceLanguage].txtAllDeleted;

				show_editor_loader_messageCalendar(inputForm, 'message_success', eventSuccessMessage, function(a){
					//setTimeout(function(){
						$('#show').val('');
						if(isFormHidden!=true)
						{
							$('#CAEvent').hide();
							$('#calendar').fullCalendar('unselect');
							$('#event_details_template').remove();
							$('#CAEvent').append(cleanVcalendarTemplate);
							$('#EventDisabler').fadeOut(globalEditorFadeAnimation, function(){
								$('#timezonePicker').prop('disabled', false);
							});
						}
					//}, a);
				});
			}
			else
			{
				if(newEtag!=null)
				{
					if(deleteMode)
						globalTodoLoaderHide=localization[globalInterfaceLanguage].txtAllDeletedTodo;
					show_editor_loader_messageCalendar(inputForm, 'message_success', globalTodoLoaderHide, function(a){
								globalTodoLoaderHide='';
								if(inputForm=='vtodo'&&isFormHidden!=true)
									$('#showTODO').val('');
								$('#TodoDisabler').fadeOut(globalEditorFadeAnimation, function(){
									$('#timezonePickerTODO').prop('disabled', false);
								});
					});
				}
			}

			if(newEtag!=null)
			{
				var rid=inputUID.substring(0, inputUID.lastIndexOf('/')+1);
				if(inputForm=='vevent')
				{
					var resources=globalResourceCalDAVList.collections;
					for(var j=0;j<resources.length;j++)
					{
						if(rid==resources[j].uid)
						{
							if(inputVcalendar!='')
							{
								var rawVcalendar=inputVcalendar;
								if(xml.getResponseHeader('Preference-Applied')=='return=representation' && xml.responseText)
									rawVcalendar=xml.responseText;

								var vcalendar_clean=vCalendarCleanup(rawVcalendar);
							}
							else
								return true;

							globalEventList.insertEvent(true, resources[j], {isRepeat: false, isTODO: false, untilDate: '', sortStart: '', start: '', end: '', sortkey: '', timestamp: resultTimestamp, accountUID: resources[j].accountUID, uid: inputUID, displayValue: resources[j].displayvalue, etag: newEtag, vcalendar: vcalendar_clean}, true, true,false);
							break;
						}
					}
				}
				else
				{
					var resources=globalResourceCalDAVList.TodoCollections;
					for(var j=0;j<resources.length;j++)
					{
						if(rid==resources[j].uid)
						{
							if(inputVcalendar!='')
							{
								var rawVcalendar=inputVcalendar;
								if(xml.getResponseHeader('Preference-Applied')=='return=representation' && xml.responseText)
									rawVcalendar=xml.responseText;

								var vcalendar_clean=vCalendarCleanup(rawVcalendar);
							}
							else
								return true;

							if(inputForm=='vtodo'&&isFormHidden!=true)
								$('#showTODO').val(inputUID);
							globalEventList.insertEvent(true, resources[j], {isRepeat: false, isTODO: false, untilDate: '', sortStart: '', start: '', end: '', sortkey: '', timestamp: resultTimestamp, accountUID: resources[j].accountUID, uid: inputUID, displayValue: resources[j].displayvalue, etag: newEtag, vcalendar: vcalendar_clean}, true, false,false);
							if(isFormHidden)
								$('#todoList').fullCalendar('allowSelectEvent',true);
							if(inputEtag=='' || isFormHidden)
								$('#todoList').fullCalendar('selectEvent',$('[data-id="'+inputUID+'"]'));
							break;
						}
					}
				}
			}
			else
			{
				if(inputForm=='vevent')
					netLoadCalendar(globalResourceCalDAVList.getEventCollectionByUID(collection_uid), [{etag: '', href: put_href_part}], (collection.forceSyncPROPFIND==undefined || collection.forceSyncPROPFIND==false ? true : false), false, true,false, true, null, null);
				else
				{
					if(isFormHidden)
						$('#todoList').fullCalendar('allowSelectEvent',true);
					if(inputForm=='vtodo'&&isFormHidden!=true)
						$('#showTODO').val(inputUID);
					netLoadCalendar(globalResourceCalDAVList.getTodoCollectionByUID(collection_uid), [{etag: '', href: put_href_part}], (collection.forceSyncPROPFIND==undefined || collection.forceSyncPROPFIND==false ? true : false), false, true,false, true, null, null);
				}
			}
			globalWindowFocus=true;
			return true;
		}
	});
}

/*
Permissions (from the davical wiki):
	all - aggregate of all permissions
	read - grants basic read access to the principal or collection.
	unlock - grants access to write content (i.e. update data) to the collection, or collections of the principal.
	read-acl - grants access to read ACLs on the collection, or collections of the principal.
	read-current-user-privilege-set - grants access to read the current user's privileges on the collection, or collections of the   write-acl-grants access to writing ACLs on the collection, or collections of the principal.
	write - aggregate of write-properties, write-content, bind & unbind
	write-properties - grants access to update properties of the principal or collection. In DAViCal, when granted to a user principal, this will only grant access to update properties of the principal's collections and not the user principal itself. When granted to a group or resource principal this will grant access to update the principal properties.
	write - content-grants access to write content (i.e. update data) to the collection, or collections of the principal.
	bind - grants access to creating resources in the collection, or in collections of the principal. Created resources may be new collections, although it is an error to create collections within calendar collections.
	unbind - grants access to deleting resources (including collections) from the collection, or from collections of the principal.
*/


function CalDAVnetLoadCollection(inputCollection, forceLoad, allSyncMode, recursiveIterator, collections)
{
	if(recursiveIterator>=collections.length)
	{
		setLoadingLimit(forceLoad, allSyncMode);
		if(!globalCalDAVInitLoad && isCalDAVLoaded && allSyncMode)
		{
			$('#SystemCalDavZAP .fc-header-center ').removeClass('r_operate_all');
			loadNextApplication(false);
		}

		return false;
	}
	if(collections.length>0)
	{
		if(inputCollection.uid!=undefined && inputCollection.makeLoaded && inputCollection.newlyAdded && globalSettingsSaving!='')
		{
			updateMainLoaderText(inputCollection.listType);
		}
		if(inputCollection.uid==undefined || inputCollection.subscription || (!inputCollection.newlyAdded && !inputCollection.syncRequired && !forceLoad && allSyncMode) || (!inputCollection.newlyAdded && !inputCollection.someChanged && !globalCalDAVInitLoad &&allSyncMode) || ((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value==null) || (inputCollection.listType=='vevent'&&globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null))&&!inputCollection.syncRequired)
		{
			if(inputCollection.subscription && inputCollection.syncRequired && inputCollection.uid!=undefined)
			{
				netLoadCalendarSubscription(globalAccountSettings[0], inputCollection, recursiveIterator, forceLoad, collections);
			}
			recursiveIterator++;
			if(recursiveIterator>=collections.length && inputCollection.uid!='undefined' && inputCollection.listType=='vevent')
			{
				setLoadingLimit(forceLoad, allSyncMode);
				recursiveIterator=0;
				if((globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null) || allSyncMode)
					CalDAVnetLoadCollection(globalResourceCalDAVList.TodoCollections[0], forceLoad, allSyncMode, 0, globalResourceCalDAVList.TodoCollections);
			}
			else
				CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
			if(inputCollection.uid!=undefined)
			{
				if(!inputCollection.syncRequired && globalCalDAVInitLoad)
				{
					if(inputCollection.listType=='vtodo')
						$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
					else
						$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
					if(((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value==null) || (inputCollection.listType=='vevent'&&globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null))||(globalLimitLoading=='' && globalLimitTodoLoading==''))
					{
							globalAccountSettings[inputCollection.resourceIndex].todoNo--;
							if((globalAccountSettings[inputCollection.resourceIndex].calendarNo==0 && globalAccountSettings[inputCollection.resourceIndex].todoNo==0 && globalCalDAVInitLoad) || !globalCalDAVInitLoad)
								updateMainLoader();
					}
					else if((globalOnlyCalendarNumber>0 && globalOnlyCalendarNumberCount==globalOnlyCalendarNumber) || (globalTodoCalendarNumber>0 && globalOnlyTodoCalendarNumberCount==globalTodoCalendarNumber))
						updateMainLoader(true,inputCollection.listType);
				}
				else if(!globalCalDAVInitLoad && !inputCollection.someChanged)
				{
					if(inputCollection.listType=='vevent')
						$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
					else
						$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
				}
			}
			return false;
		}
	}
	var resourceSettings=null;
	// find the original settings for the resource and user
	var tmp=inputCollection.accountUID.match(vCalendar.pre['accountUidParts']);

	var resourceCalDAV_href=tmp[1]+tmp[3]+tmp[4];
	var resourceCalDAV_user=tmp[2];

	for(var i=0;i<globalAccountSettings.length;i++)
		if(globalAccountSettings[i].href==resourceCalDAV_href && globalAccountSettings[i].userAuth.userName==resourceCalDAV_user)
			resourceSettings=globalAccountSettings[i];

	// POROVNAT S TYM AKO JE TO V CARDDAVMATE
	if(inputCollection.makeLoaded && globalSettingsSaving=='')
		updateMainLoaderText(inputCollection.listType);
	if((globalSettings.eventstartpastlimit.value!=null || globalSettings.eventstartfuturelimit.value!=null )&&!allSyncMode && inputCollection.listType=='vevent')
		$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').addClass('r_operate');

	if(!inputCollection.makeLoaded)
	{
		if(inputCollection.listType == 'vevent')
			$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
		else if(inputCollection.listType == 'vtodo')
			$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
		recursiveIterator++;
		if((globalLimitLoading=='' && globalLimitTodoLoading=='') || ((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value==null) || (inputCollection.listType=='vevent'&&globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null)))
		{
			if(inputCollection.listType == 'vevent')
				globalAccountSettings[inputCollection.resourceIndex].calendarNo--;
			else if(inputCollection.listType == 'vtodo')
			{
				globalAccountSettings[inputCollection.resourceIndex].todoNo--;
			}
			if((globalAccountSettings[inputCollection.resourceIndex].calendarNo==0 && globalAccountSettings[inputCollection.resourceIndex].todoNo==0 && globalCalDAVInitLoad))
			{
				updateMainLoader();
			}
		}
		else if((globalOnlyCalendarNumber>0 && globalOnlyCalendarNumberCount==globalOnlyCalendarNumber) || (globalTodoCalendarNumber>0 && globalOnlyTodoCalendarNumberCount==globalTodoCalendarNumber))
			updateMainLoader(true,inputCollection.listType);
		if(recursiveIterator>=collections.length && inputCollection.uid!='undefined' && inputCollection.listType=='vevent')
		{
			recursiveIterator=0;
			setLoadingLimit(forceLoad, allSyncMode);
			if((globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value == null ) || allSyncMode)
				CalDAVnetLoadCollection(globalResourceCalDAVList.TodoCollections[0], forceLoad, allSyncMode, 0, globalResourceCalDAVList.TodoCollections);
		}
		else
			CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
		return false;
	}

	if(inputCollection.forceSyncPROPFIND!=undefined && inputCollection.forceSyncPROPFIND==true)
		var requestText='<?xml version="1.0" encoding="utf-8"?><D:propfind xmlns:D="DAV:"><D:prop><D:getcontenttype/><D:getetag/></D:prop></D:propfind>';
	else if(((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value==null) || (inputCollection.listType=='vevent'&&globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null)))	// all sync turned off
	{
		var requestText='<?xml version="1.0" encoding="utf-8"?><D:sync-collection xmlns:D="DAV:"><D:prop><D:getcontenttype/><D:getetag/></D:prop><D:sync-level>1</D:sync-level>'+(forceLoad==true || inputCollection.syncToken==undefined || inputCollection.syncToken=='' ? '<D:sync-token/>' : '<D:sync-token>'+inputCollection.syncToken+'</D:sync-token>')+'</D:sync-collection>';
	}
	else // if inputCollection.forceSyncPROPFIND is undefined or false
	{
		var requestText = '';
		if(!forceLoad && !inputCollection.newlyAdded)
			requestText='<?xml version="1.0" encoding="utf-8"?><D:sync-collection xmlns:D="DAV:"><D:prop><D:getcontenttype/><D:getetag/></D:prop><D:sync-level>1</D:sync-level>'+(forceLoad==true || inputCollection.syncToken==undefined || inputCollection.syncToken=='' ? '<D:sync-token/>' : '<D:sync-token>'+inputCollection.syncToken+'</D:sync-token>')+'</D:sync-collection>';
		else
		{
			if(inputCollection.listType=='vevent')
			{
				if(globalCalDAVInitLoad&&allSyncMode)
				{
					if(globalSettings.eventstartpastlimit.value!=null)
					{
						globalLoadedLimit  = new Date();
						globalLoadedLimit.setDate(1);
						globalLoadedLimit.setHours(0);
						globalLoadedLimit.setMinutes(0);
						globalLoadedLimit.setSeconds(0);
						globalLoadedLimit.setMilliseconds(0);
						globalLoadedLimit.setMonth(globalLoadedLimit.getMonth()-globalSettings.eventstartpastlimit.value);
					}
					if(globalSettings.eventstartfuturelimit.value!=null)
					{
						globalToLoadedLimit  = new Date();
						globalToLoadedLimit.setDate(1);
						globalToLoadedLimit.setHours(0);
						globalToLoadedLimit.setMinutes(0);
						globalToLoadedLimit.setSeconds(0);
						globalToLoadedLimit.setMilliseconds(0);
						globalToLoadedLimit.setMonth(globalToLoadedLimit.getMonth()+globalSettings.eventstartfuturelimit.value+1);
					}
				}
				var pastInterval = '', futureInterval = '';
				if(!inputCollection.newlyAdded || globalCalDAVInitLoad)
				{
					if(globalSettings.eventstartpastlimit.value!=null && (allSyncMode || globalLimitLoading=='past'))
					{
						var pastDate = new Date(globalLoadedLimit.getTime());
						pastDate.setDate(pastDate.getDate()-7);
						if(allSyncMode)
							pastInterval = ' start="'+$.fullCalendar.formatDate(pastDate ,"yyyyMMdd'T'HHmmss")+'Z"';
						else
							pastInterval = ' start="'+$.fullCalendar.formatDate(pastDate ,"yyyyMMdd'T'HHmmss")+'Z" end="'+$.fullCalendar.formatDate(globalBeginPast,"yyyyMMdd'T'HHmmss")+'Z"';
						if(recursiveIterator==(collections.length-1))
							globalBeginPast = new Date(pastDate.getTime());
					}
					if(globalSettings.eventstartfuturelimit.value!=null && (allSyncMode || globalLimitLoading=='future'))
					{
						var futureDate = new Date(globalToLoadedLimit.getTime());
						futureDate.setDate(futureDate.getDate()+14);
						if(allSyncMode)
							futureInterval = ' end="'+$.fullCalendar.formatDate(futureDate ,"yyyyMMdd'T'HHmmss")+'Z"';
						else
							futureInterval = ' start="'+$.fullCalendar.formatDate(globalBeginFuture ,"yyyyMMdd'T'HHmmss")+'Z" end="'+$.fullCalendar.formatDate(futureDate,"yyyyMMdd'T'HHmmss")+'Z"';
						if(recursiveIterator==(collections.length-1))
							globalBeginFuture = new Date(futureDate.getTime());
					}
				}
				else
				{
					var pastDate = new Date(globalLoadedLimit.getTime());
					var futureDate = new Date(globalToLoadedLimit.getTime());
					pastInterval = ' start="'+$.fullCalendar.formatDate(pastDate ,"yyyyMMdd'T'HHmmss")+'Z"';
					futureInterval = ' end="'+$.fullCalendar.formatDate(futureDate ,"yyyyMMdd'T'HHmmss")+'Z"';
				}
				if(!allSyncMode)
					requestText='<?xml version="1.0" encoding="UTF-8"?><L:calendar-query xmlns:L="urn:ietf:params:xml:ns:caldav"><D:prop xmlns:D="DAV:"><D:getcontenttype/><D:getetag/><L:calendar-data/></D:prop><L:filter><L:comp-filter name="VCALENDAR"><L:comp-filter name="VEVENT"><L:time-range'+(globalLimitLoading=='past' ? pastInterval : futureInterval)+'/></L:comp-filter></L:comp-filter></L:filter></L:calendar-query>';
				else
					requestText='<?xml version="1.0" encoding="UTF-8"?><L:calendar-query xmlns:L="urn:ietf:params:xml:ns:caldav"><D:prop xmlns:D="DAV:"><D:getcontenttype/><D:getetag/><L:calendar-data/></D:prop><L:filter><L:comp-filter name="VCALENDAR"><L:comp-filter name="VEVENT"><L:time-range'+pastInterval+futureInterval+'/></L:comp-filter></L:comp-filter></L:filter></L:calendar-query>';
			}
			else if(inputCollection.listType=='vtodo')
			{
				if(allSyncMode)
				{
					if(globalSettings.todopastlimit.value!=null)
					{
						globalLoadedLimitTodo  = new Date();
						globalLoadedLimitTodo.setDate(1);
						globalLoadedLimitTodo.setHours(0);
						globalLoadedLimitTodo.setMinutes(0);
						globalLoadedLimitTodo.setSeconds(0);
						globalLoadedLimitTodo.setMilliseconds(0);
						globalLoadedLimitTodo.setMonth(globalLoadedLimitTodo.getMonth()-globalSettings.todopastlimit.value);
					}
					if(globalSettings.eventstartfuturelimit.value!=null)
					{
						globalToLoadedLimitTodo  = new Date();
						globalToLoadedLimitTodo.setDate(1);
						globalToLoadedLimitTodo.setHours(0);
						globalToLoadedLimitTodo.setMinutes(0);
						globalToLoadedLimitTodo.setSeconds(0);
						globalToLoadedLimitTodo.setMilliseconds(0);
						globalToLoadedLimitTodo.setMonth(globalToLoadedLimitTodo.getMonth()+globalSettings.eventstartfuturelimit.value+1);
					}
				}
				var pastInterval = '', futureInterval = '';
				if(!inputCollection.newlyAdded || globalCalDAVInitLoad)
				{
					if(globalSettings.todopastlimit.value!=null && (allSyncMode || globalLimitTodoLoading=='pastTodo'))
					{
						if(allSyncMode)
							pastInterval = ' start="'+$.fullCalendar.formatDate(globalLoadedLimitTodo ,"yyyyMMdd'T'HHmmss")+'Z"';
						else
							pastInterval = ' start="'+$.fullCalendar.formatDate(globalLoadedLimitTodo ,"yyyyMMdd'T'HHmmss")+'Z" end="'+$.fullCalendar.formatDate(new Date(new Date(globalLoadedLimitTodo.getTime()).setMonth(globalLoadedLimitTodo.getMonth()+globalSettings.todopastlimit.value+1)),"yyyyMMdd'T'HHmmss")+'Z"';
					}
				}
				else
					pastInterval = ' start="'+$.fullCalendar.formatDate(globalLoadedLimitTodo ,"yyyyMMdd'T'HHmmss")+'Z"';
				/*if(!globalSettings.appleremindersmode.value && globalSettings.eventstartfuturelimit.value!=null && (allSyncMode || globalLimitLoading=='futureTodo'))
				{
					if(allSyncMode)
						futureInterval = ' end="'+$.fullCalendar.formatDate(globalToLoadedLimitTodo ,"yyyyMMdd'T'HHmmss")+'Z"';
					else
						futureInterval = ' start="'+$.fullCalendar.formatDate(new Date(new Date(globalToLoadedLimitTodo.getTime()).setMonth(globalToLoadedLimitTodo.getMonth()-globalSettings.eventstartfuturelimit.value-1)) ,"yyyyMMdd'T'HHmmss")+'Z" end="'+$.fullCalendar.formatDate(globalToLoadedLimitTodo,"yyyyMMdd'T'HHmmss")+'Z"';
				}*/
				if(!allSyncMode)
					requestText='<?xml version="1.0" encoding="utf-8"?><L:calendar-query xmlns:L="urn:ietf:params:xml:ns:caldav"><D:prop xmlns:D="DAV:"><D:getcontenttype/><D:getetag/><L:calendar-data/></D:prop><L:filter><L:comp-filter name="VCALENDAR"><L:comp-filter name="VTODO"><L:time-range'+(globalLimitTodoLoading=='pastTodo' ? pastInterval : futureInterval)+'/></L:comp-filter></L:comp-filter></L:filter></L:calendar-query>';
				else
					requestText='<?xml version="1.0" encoding="utf-8"?><L:calendar-query xmlns:L="urn:ietf:params:xml:ns:caldav"><D:prop xmlns:D="DAV:"><D:getcontenttype/><D:getetag/><L:calendar-data/></D:prop><L:filter><L:comp-filter name="VCALENDAR"><L:comp-filter name="VTODO"><L:time-range'+pastInterval+futureInterval+'/></L:comp-filter></L:comp-filter></L:filter></L:calendar-query>';
			}
		}
	}

	function ajaxComplete(data, textStatus, xml)
	{
		$('[data-id="'+inputCollection.uid+'"]').removeClass('r_error');
		if(inputCollection.listType=='vevent' && $('#ResourceCalDAVList').find('.r_error').length==0 && isEachResourceLoaded())
			$('#intCaldav').find('.int_error').css('display','none');
		else if(inputCollection.listType=='vtodo' && $('#ResourceCalDAVTODOList').find('.r_error').length==0 && isEachResourceLoaded())
			$('#intCaldavTodo').find('.int_error').css('display','none');
		var prevNew = inputCollection.newlyAdded;
		inputCollection.newlyAdded = false;
		var vcalendarList=new Array();
		var isXMLEmpty=true;
		if(((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value!=null) || (inputCollection.listType=='vevent'&&(globalSettings.eventstartpastlimit.value!=null || globalSettings.eventstartfuturelimit.value!=null))))
		{
			var hrefCounter = 0;
			$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode(new RegExp('^(sync-)?response$')).children().filterNsNode('href').each(function(index, element){
				hrefCounter++;
			});
			globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].collectionLength=hrefCounter;
			globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].counter=0;
			globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].resourceIndex=inputCollection.resourceIndex;
			globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].listType=inputCollection.listType;
			globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].typeList=inputCollection.typeList;
		}
		var re_found = new RegExp('200 OK$');
		var re_not_found = new RegExp('404 Not Found$');
		$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode(new RegExp('^(sync-)?response$')).each(
			function(index, element)
			{
				var hrefVal=$(element).children().filterNsNode('href').text();
				var etagVal=$(element).children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('getetag').text();
				var allowContent=false;
				// checkContentType is undocumented but useful if somebody needs to disable it (wrong server response, etc.)
				if(inputCollection.checkContentType!=false)
				{
					var contenttypeVal=$(element).children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('getcontenttype').text();
					if(contenttypeVal!=undefined)
					{
						contenttypeValArr=contenttypeVal.toLowerCase().replace(vCalendar.pre['spaceRex'],'').split(';');
						if(contenttypeValArr.indexOf('text/calendar')!=-1 || contenttypeValArr.indexOf('text/x-vcalendar')!=-1)
							allowContent=true;
					}
				}
				else
					allowContent=true;
				var result=$(element).find('*').filterNsNode('status').text();	// note for 404 there is no propstat!
				var match=false;
				if(hrefVal[hrefVal.length-1]!='/')	/* Google CalDAV problem with resource URL if content type checking is disabled */
				{
					if(allowContent==true)
					{
						if(result.match(re_found)) // HTTP OK
						{
							vcalendarList[vcalendarList.length]={etag: etagVal, href: hrefVal};
							match=true;
						}
					}
					if(!match && result.match(re_not_found)) // HTTP Not Found
						vcalendarList[vcalendarList.length]={deleted: true, etag: etagVal, href: hrefVal};
				}
				if((forceLoad || prevNew) && ((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value!=null) || (inputCollection.listType=='vevent'&&(globalSettings.eventstartpastlimit.value!=null || globalSettings.eventstartfuturelimit.value!=null))))
				{
					var resultTimestamp=new Date().getTime();
					if($(element).children().filterNsNode('propstat').children().filterNsNode('status').text().match(RegExp('200 OK$'))) // HTTP OK
					{
						var uid=inputCollection.uid+hrefVal.replace(vCalendar.pre['hrefValRex'], '');
						var vcalendar_raw=$(element).children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('calendar-data').text();
						if(vcalendar_raw!='')
						{
							isXMLEmpty=false;
							var vcalendar_clean=vCalendarCleanup(vcalendar_raw);
						}
						else
						{
							checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
							return true;
						}
						if((vcalendar_clean==undefined) || ((check=vcalendar_clean.match(vCalendar.pre['vcalendar']))==null))
						{
							checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
							console.log("Error: '"+uid+"': unable to parse vCalendar");
							return true;
						}

						if((check=vcalendar_clean.match(vCalendar.pre['vevent']))!=null)
						{
							if(inputCollection.typeList.indexOf('vevent')!=-1)
								globalEventList.insertEvent(false,inputCollection, {threadChange: '', isRepeat: false, isDrawn: false, isTODO: false, untilDate: '', sortStart: '', start: '', end: '', sortkey: '', timestamp: resultTimestamp, accountUID: inputCollection.accountUID, uid: uid, displayValue: inputCollection.displayvalue, counter: 0, etag: etagVal, vcalendar: vcalendar_clean}, false, true,true);	// when the inputMode=='sync' we force reload the vevent/vtodo
							else
								checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
						}
						else if((check=vcalendar_clean.match(vCalendar.pre['vtodo']))!=null)
						{
							if(inputCollection.typeList.indexOf('vtodo')!=-1)
								globalEventList.insertEvent(false,inputCollection, {threadChange: '', isRepeat: false, isDrawn: false, isTODO: true, untilDate: '', sortStart: '', start: '', end: '', sortkey: '', timestamp: resultTimestamp, accountUID: inputCollection.accountUID, uid: uid, displayValue: inputCollection.displayvalue, counter: 0, etag: etagVal, vcalendar: vcalendar_clean}, false, false, true);	// when the inputMode=='sync' we force reload the vevent/vtodo
							else
								checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
						}
						else
						{
							console.log("Error: '"+uid+"': unable to parse vEvent or vTodo");
							checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
							return true;
						}
					}
					else
					{
						var uid=inputCollection.uid+hrefVal.replace(vCalendar.pre['hrefValRex'], '');
						console.log("Error: '"+uid+"': unable to parse vEvent or vTodo");
						checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
						return true;
					}
				}
			}
		);

		if(allSyncMode && !forceLoad && !prevNew)
		{
			// store the syncToken
			if(inputCollection.forceSyncPROPFIND==undefined || inputCollection.forceSyncPROPFIND==false)
				inputCollection.syncToken=$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('sync-token').text();
		}
/*			inputCollection.someChanged = false;
		if(globalSettings.eventstartpastlimit.value!=null || globalSettings.eventstartfuturelimit.value!=null)
		{
			inputCollection.oldSyncToken = inputCollection.syncToken;
			inputCollection.someChanged = false;
		}
*/
		//loading of todo calendar when imit is set and we need to make 2 ajax filter requests
		if(((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value!=null) || (inputCollection.listType=='vevent'&&(globalSettings.eventstartpastlimit.value!=null || globalSettings.eventstartfuturelimit.value!=null))) && !isXMLEmpty)
		{
			inputCollection.oldSyncToken = inputCollection.syncToken;
			inputCollection.someChanged = false;
			if(collections.length>0)
			{

				recursiveIterator++;
				if(recursiveIterator>=collections.length && inputCollection.uid!='undefined' && inputCollection.listType=='vevent')
				{
					setLoadingLimit(forceLoad, allSyncMode);
					recursiveIterator=0;
					if(allSyncMode)
						CalDAVnetLoadCollection(globalResourceCalDAVList.TodoCollections[0], forceLoad, allSyncMode, 0, globalResourceCalDAVList.TodoCollections);
				}
				else
					CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
				/*if(globalLimitLoading=='')
				{
						if(inputCollection.listType == 'vevent')
							globalAccountSettings[inputCollection.resourceIndex].calendarNo--;
						else if(inputCollection.listType == 'vtodo')
							globalAccountSettings[inputCollection.resourceIndex].todoNo--;
					if(globalAccountSettings[inputCollection.resourceIndex].calendarNo==0 && globalAccountSettings[inputCollection.resourceIndex].todoNo==0)
						updateMainLoader();
				}*/
				if((globalOnlyCalendarNumber>0 && globalOnlyCalendarNumberCount==globalOnlyCalendarNumber) || (globalTodoCalendarNumber>0 && globalOnlyTodoCalendarNumberCount==globalTodoCalendarNumber))
					updateMainLoader(true,inputCollection.listType);
			}
			return false;
		}
		if(((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value!=null) || (inputCollection.listType=='vevent'&&(globalSettings.eventstartpastlimit.value!=null || globalSettings.eventstartfuturelimit.value!=null))) && ((forceLoad && !allSyncMode)||(prevNew && !globalCalDAVInitLoad)))
			netLoadCalendar(inputCollection, vcalendarList, (inputCollection.forceSyncPROPFIND==undefined || inputCollection.forceSyncPROPFIND==false ? true : false), true, forceLoad,allSyncMode, false, recursiveIterator, collections);
		else
			netLoadCalendar(inputCollection, vcalendarList, (inputCollection.forceSyncPROPFIND==undefined || inputCollection.forceSyncPROPFIND==false ? true : false), true, forceLoad,allSyncMode, false, recursiveIterator, collections);

		vcalendarList=null;
		if(typeof globalParallelAjaxCallCalDAVEnabled!='undefined' && globalParallelAjaxCallCalDAVEnabled!=null && globalParallelAjaxCallCalDAVEnabled)
		{
			if(collections.length>0)
			{
				recursiveIterator++;
				if(recursiveIterator>=collections.length && inputCollection.uid!='undefined' && inputCollection.listType=='vevent')
				{
					recursiveIterator=0;
					if((globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null) || allSyncMode)
						CalDAVnetLoadCollection(globalResourceCalDAVList.TodoCollections[0], forceLoad, allSyncMode, 0, globalResourceCalDAVList.TodoCollections);
				}
				else
					CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
			}
		}
	}

	// first try to process the cached data (if cached results are available in the "auth module" response)
	var tmpCache;
	var component='';
	if(inputCollection.listType=='vtodo')
		component='VTODO';
	else if(inputCollection.listType=='vevent')
		component='VEVENT';
	if(globalXMLCache!=null && (tmpCache=globalXMLCache.children('caldavcalendarquery[request_url="'+jqueryEscapeSelector(inputCollection.url+inputCollection.href)+'"][request_component="'+component+'"]').remove()).length)
	{
		if(typeof globalDebug!='undefined' && globalDebug instanceof Array && globalDebug.indexOf('cache')!=-1)
			console.log('DBG Cache OK: '+arguments.callee.name+' component: '+component+' url: \''+inputCollection.url+inputCollection.href+'\': saved one request!');
		ajaxComplete('', 'success', {responseXML: tmpCache});
	}
	else
	{
		if(typeof globalDebug!='undefined' && globalDebug instanceof Array && globalDebug.indexOf('cache')!=-1)
			console.log('DBG Cache ERROR: '+arguments.callee.name+' url: \''+inputCollection.url+inputCollection.href+'\': spend one request!');
		$.ajax({
			type: (inputCollection.forceSyncPROPFIND!=undefined && inputCollection.forceSyncPROPFIND==true ? 'PROPFIND' : 'REPORT'),
			url: 	inputCollection.url+inputCollection.href,
			cache: false,
			crossDomain: (typeof inputCollection.crossDomain=='undefined' ? true: inputCollection.crossDomain),
			xhrFields: {
				withCredentials: (typeof inputCollection.withCredentials=='undefined' ? false: inputCollection.withCredentials)
			},
			timeout: inputCollection.timeOut,
			beforeSend: function(req){
				if(globalSettings.usejqueryauth.value!=true && inputCollection.userAuth.userName!='' && inputCollection.userAuth.userPassword!='')
					req.setRequestHeader('Authorization', basicAuth(inputCollection.userAuth.userName, inputCollection.userAuth.userPassword));

				req.setRequestHeader('X-client', globalXClientHeader);
				req.setRequestHeader('Depth', '1');
				/* XXX - System display:none changes */
				if(isAvaible('Settings') && $('#SystemSettings').css('visibility')=='visible' && $('.resourceSettings_item_selected').attr('data-type')=='setting_group_password')
				{
					if(collections.length>0)
					{
						recursiveIterator++;
						if(recursiveIterator>=collections.length && inputCollection.uid!='undefined' && inputCollection.listType=='vevent')
						{
							setLoadingLimit(forceLoad, allSyncMode);
							recursiveIterator=0;
							if(allSyncMode || (globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null))
								CalDAVnetLoadCollection(globalResourceCalDAVList.TodoCollections[0], forceLoad, allSyncMode, 0, globalResourceCalDAVList.TodoCollections);
						}
						else
							CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
					}
					return false;
				}
			},
			username: (globalSettings.usejqueryauth.value==true ? inputCollection.userAuth.userName : null),
			password: (globalSettings.usejqueryauth.value==true ? inputCollection.userAuth.userPassword : null),
			contentType: 'text/xml; charset=utf-8',
			processData: true,
			data: requestText,
			dataType: 'xml',
			error: function(objAJAXRequest, strError){
				if(((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value!=null) || (inputCollection.listType=='vevent'&&(globalSettings.eventstartpastlimit.value!=null || globalSettings.eventstartfuturelimit.value!=null))) && objAJAXRequest.responseXML!=null && $(objAJAXRequest.responseXML).children().filterNsNode('C:SUPPORTED-FILTER').length>0)
				{
					if(inputCollection.listType=='vevent')
					{
						globalSettings.eventstartfuturelimit.value = null;
						globalSettings.eventstartpastlimit.value = null;
					}
					else
						globalSettings.todopastlimit.value = null;
					globalCalendarNumberCount--;
					CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
				}
				if((objAJAXRequest.status==400 /* bad request */ || objAJAXRequest.status==403 /* forbidden (for stupid servers) */ || objAJAXRequest.status==501 /* unimplemented */) && inputCollection.forceSyncPROPFIND!=true /* prevent recursion */)
				{
					collections[recursiveIterator].forceSyncPROPFIND=true;
					if(inputCollection.listType=='vevent')
					{
						globalSettings.eventstartfuturelimit.value = null;
						globalSettings.eventstartpastlimit.value = null;
					}
					else
						globalSettings.todopastlimit.value = null;
					globalCalendarNumberCount--;
					CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
					return true;
				}
				else
				{
					if(collections.length>0)
					{
						recursiveIterator++;
						if(recursiveIterator>=collections.length && inputCollection.uid!='undefined' && inputCollection.listType=='vevent')
						{
							recursiveIterator=0;
							setLoadingLimit(forceLoad, allSyncMode);
							if(allSyncMode || (globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null ))
								CalDAVnetLoadCollection(globalResourceCalDAVList.TodoCollections[0], forceLoad, allSyncMode, 0, globalResourceCalDAVList.TodoCollections);
						}
						else
							CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
					}

					if(inputCollection.listType=='vevent')
					{
						$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
						$('#intCaldav').find('.int_error').css('display','block');
					}
					else
					{
						$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
						$('#intCaldavTodo').find('.int_error').css('display','block');
					}
					$('[data-id="'+inputCollection.uid+'"]').addClass('r_error');
					inputCollection.syncToken = inputCollection.oldSyncToken;
					if((globalLimitTodoLoading=='' && globalLimitLoading=='') || ((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value==null) || (inputCollection.listType=='vevent'&&globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null)))
					{
						if(inputCollection.listType == 'vevent')
							globalAccountSettings[inputCollection.resourceIndex].calendarNo--;
						else if(inputCollection.listType == 'vtodo')
						{
							globalAccountSettings[inputCollection.resourceIndex].todoNo--;
						}
						if((globalAccountSettings[inputCollection.resourceIndex].calendarNo==0 && globalAccountSettings[inputCollection.resourceIndex].todoNo==0 && globalCalDAVInitLoad) || !globalCalDAVInitLoad)
						{
							updateMainLoader();
						}
					}
					else if((globalOnlyCalendarNumber>0 && globalOnlyCalendarNumberCount==globalOnlyCalendarNumber) || (globalTodoCalendarNumber>0 && globalOnlyTodoCalendarNumberCount==globalTodoCalendarNumber))
						updateMainLoader(true,inputCollection.listType);
					console.log("Error: [CalDAVnetLoadCollection: '"+(inputCollection.forceSyncPROPFIND!=undefined && inputCollection.forceSyncPROPFIND==true ? 'PROPFIND' : 'REPORT')+" "+inputCollection.url+inputCollection.href+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
					return false;
				}
			},
			success: ajaxComplete
		});
	}
}

function netLoadCalendar(inputCollection, vcalendarList, syncReportSupport,  removeUntouched, forceLoad, allSyncMode, forceCall, recursiveIterator, collections)
{
	var vcalendarChangedList=new Array();
	var rid='';
	var resultTimestamp=new Date().getTime();
	if(!inputCollection.subscription)
	{
		if(syncReportSupport==true)
		{
			if(inputCollection.listType=='vevent')
				var isEvent = true;
			else
				var isEvent = false;
			for(var i=0;i<vcalendarList.length;i++)
				if(vcalendarList[i].deleted==true)
					globalEventList.removeOldEvent(inputCollection.uid+vcalendarList[i].href.replace(vCalendar.pre['hrefValRex'], ''), true, isEvent);
				else
					vcalendarChangedList[vcalendarChangedList.length]=vcalendarList[i].href;
		}
		else	// no sync-collection REPORT supported (we need to delete vevents/vtodos by timestamp comparison)
		{
			for(var i=0;i<vcalendarList.length;i++)
			{
				var uid=inputCollection.uid+vcalendarList[i].href.replace(vCalendar.pre['hrefValRex'],'');
				if(!globalEventList.checkAndTouchIfExists(inputCollection.uid,uid,vcalendarList[i].etag,resultTimestamp))
					vcalendarChangedList[vcalendarChangedList.length]=vcalendarList[i].href;
			}
			if(inputCollection.listType=='vevent')
				var isEvent = true;
			else
				var isEvent = false;
			globalEventList.removeOldEvents(inputCollection.uid, resultTimestamp, isEvent);
		}

		// not loaded vCalendars from the last multiget (if any)
		if(recursiveIterator!=null)
			if(collections[recursiveIterator]!=undefined)
				if(collections[recursiveIterator].pastUnloaded!=undefined && collections[recursiveIterator].pastUnloaded!=null && collections[recursiveIterator].pastUnloaded.length>0)
					vcalendarChangedList=vcalendarChangedList.concat(collections[recursiveIterator].pastUnloaded).sort().unique();

		// if nothing is changed on server return
		if(vcalendarChangedList.length==0)
		{
			inputCollection.someChanged = false;
			inputCollection.oldSyncToken = inputCollection.syncToken;
			if(forceLoad || globalSettingsSaving!='')
			{
				if(inputCollection.listType=='vevent')
					$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
				else
					$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');

				if(((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value==null) || (inputCollection.listType=='vevent'&&globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null)) || (globalLimitLoading=='' && globalLimitTodoLoading==''))
				{
					if(inputCollection.listType=='vevent')
						globalAccountSettings[inputCollection.resourceIndex].calendarNo--;
					else if(inputCollection.listType=='vtodo')
						globalAccountSettings[inputCollection.resourceIndex].todoNo--;
					if(globalAccountSettings[inputCollection.resourceIndex].calendarNo==0 && globalAccountSettings[inputCollection.resourceIndex].todoNo==0  && globalCalDAVInitLoad)
						updateMainLoader();
					else if(globalSettingsSaving!='')
						updateMainLoader(true,inputCollection.listType,inputCollection.uid);
				}
				else if((globalOnlyCalendarNumber>0 && globalOnlyCalendarNumberCount==globalOnlyCalendarNumber) || (globalTodoCalendarNumber>0 && globalOnlyTodoCalendarNumberCount==globalTodoCalendarNumber) || globalSettingsSaving!='')
					updateMainLoader(true,inputCollection.listType);
			}

			if((typeof globalParallelAjaxCallCalDAVEnabled=='undefined' || globalParallelAjaxCallCalDAVEnabled==null || !globalParallelAjaxCallCalDAVEnabled) && collections.length>0)
			{
				recursiveIterator++;
				if(recursiveIterator>=collections.length && inputCollection.uid!='undefined' && inputCollection.listType=='vevent')
				{
					recursiveIterator=0;
					if((globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null) || allSyncMode)
						CalDAVnetLoadCollection(globalResourceCalDAVList.TodoCollections[0], forceLoad, allSyncMode, 0, globalResourceCalDAVList.TodoCollections);
				}
				else
					CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
			}
			return true;
		}
	}
	else
	{
		var evCount=0;
		for(c in vcalendarList)
			if(vcalendarList[c].etag!=undefined && vcalendarList[c].etag!=null)
				evCount++;
		globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].collectionLength=evCount;
		globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].counter=0;
		globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].resourceIndex=inputCollection.resourceIndex;
		globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].listType=inputCollection.listType;
		globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].typeList=inputCollection.typeList;

//		if(inputCollection.listType=='vevent')
//			$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').addClass('r_operate');
//		else
//			$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').addClass('r_operate');

		if($('.r_operate_all').length==0)
			$('#SystemCalDavZAP .fc-header-center ').addClass('r_operate_all');

		for(eventUID in vcalendarList)
		{
			if(vcalendarList[eventUID].etag==undefined || vcalendarList[eventUID]==null)
				continue;
			var etag=vcalendarList[eventUID].etag;
			var uid=vcalendarList[eventUID].href;
			var vcalendar_raw=vcalendarList[eventUID].eventText;
			if(vcalendar_raw!='')
				var vcalendar_clean=vCalendarCleanup(vcalendar_raw);
			else
			{
				checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
				return true;
			}

			if((check=vcalendar_clean.match(vCalendar.pre['vevent']))!=null)
			{
				if(inputCollection.typeList.indexOf('vevent')!=-1)
					globalEventList.insertEvent(forceCall,inputCollection, {threadChange: '', isRepeat: false, isDrawn: false, isTODO: false, untilDate: '', sortStart: '', start: '', end: '', sortkey: '', timestamp: resultTimestamp, accountUID: inputCollection.accountUID, uid: uid, displayValue: inputCollection.displayvalue, counter: 0, etag: etag, vcalendar:  'BEGIN:VCALENDAR'+vcalendar_clean+ 'END:VCALENDAR\r\n'}, false, true,true);	// when the inputMode=='sync' we force reload the vevent/vtodo
				else
				{
					checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
				}
			}
			else if((check=vcalendar_clean.match(vCalendar.pre['vtodo']))!=null)
			{
				if(inputCollection.typeList.indexOf('vtodo')!=-1)
					globalEventList.insertEvent(forceCall, inputCollection, {threadChange: '', isRepeat: false, isDrawn: false, isTODO: false, untilDate: '', sortStart: '', start: '', end: '', sortkey: '', timestamp: resultTimestamp, accountUID: inputCollection.accountUID, uid: uid, displayValue: inputCollection.displayvalue, counter: 0, etag: etag, vcalendar:  'BEGIN:VCALENDAR'+vcalendar_clean+ 'END:VCALENDAR\r\n'}, false, false,true);	// when the inputMode=='sync' we force reload the vevent/vtodo
				else
				{
					checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
				}
			}
			else
			{
				console.log("Error: '"+uid+"': unable to parse vEvent or vTodo");
				checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
			}
		}

		if(evCount==0)
		{
			if(inputCollection.listType=='vevent')
				$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
			else
				$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
			if(allSyncMode && globalLimitLoading=='' && globalLimitTodoLoading=='')
			{
				if(inputCollection.typeList.indexOf('vevent')!=-1)
						globalAccountSettings[inputCollection.resourceIndex].calendarNo--;
				if(inputCollection.typeList.indexOf('vtodo')!=-1)
					globalAccountSettings[inputCollection.resourceIndex].todoNo--;
				if((globalAccountSettings[inputCollection.resourceIndex].calendarNo==0 && globalAccountSettings[inputCollection.resourceIndex].todoNo==0 && globalCalDAVInitLoad))
					updateMainLoader();
				else if(globalSettingsSaving!='')
					updateMainLoader(true,inputCollection.listType,inputCollection.uid);
			}
			else if((globalOnlyCalendarNumber>0 && globalOnlyCalendarNumberCount==globalOnlyCalendarNumber) || (globalTodoCalendarNumber>0 && globalOnlyTodoCalendarNumberCount==globalTodoCalendarNumber))
				updateMainLoader(true,inputCollection.listType);
		}
		return false;
	}
	if($('.r_operate_all').length==0)
		$('#SystemCalDavZAP .fc-header-center ').addClass('r_operate_all');
	multigetData='<?xml version="1.0" encoding="utf-8"?><L:calendar-multiget xmlns:D="DAV:" xmlns:L="urn:ietf:params:xml:ns:caldav"><D:prop><D:getetag/><L:calendar-data/></D:prop><D:href>'+vcalendarChangedList.join('</D:href><D:href>')+'</D:href></L:calendar-multiget>';
	var returnValue=false;
	$.ajax({
		type: 'REPORT',
		url: inputCollection.url+inputCollection.href,
		cache: false,
		crossDomain: (typeof inputCollection.crossDomain=='undefined' ? true: inputCollection.crossDomain),
		xhrFields: {
			withCredentials: (typeof inputCollection.withCredentials=='undefined' ? false: inputCollection.withCredentials)
		},
		timeout: inputCollection.timeOut,
		beforeSend: function(req){
			if(globalSettings.usejqueryauth.value!=true && inputCollection.userAuth.userName!='' && inputCollection.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(inputCollection.userAuth.userName, inputCollection.userAuth.userPassword));

			req.setRequestHeader('X-client', globalXClientHeader);
		},
		username: (globalSettings.usejqueryauth.value==true ? inputCollection.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? inputCollection.userAuth.userPassword : null),
		contentType: 'text/xml',
		processData: true,
		data: multigetData,
		dataType: 'xml',
		error: function(objAJAXRequest, strError) {
			// unable to load vcalendars, try to load them next time
			if(recursiveIterator!=null)
				if(inputCollection.pastUnloaded!=null && inputCollection.pastUnloaded!=undefined)
					inputCollection.pastUnloaded=vcalendarChangedList;

			console.log("Error: [netLoadCalendar: 'REPORT "+inputCollection.url+inputCollection.href+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
			if(inputCollection.listType=='vevent')
			{
				$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
				$('#intCaldav').find('.int_error').css('display','block');
			}
			else
			{
				$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
				$('#intCaldavTodo').find('.int_error').css('display','block');
			}
			$('[data-id="'+inputCollection.uid+'"]').addClass('r_error');
			inputCollection.syncToken = inputCollection.oldSyncToken;

			if(((inputCollection.listType=='vtodo'&&globalSettings.todopastlimit.value==null) || (inputCollection.listType=='vevent'&&globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null)) || (globalLimitLoading=='' && globalLimitTodoLoading==''))
			{
				if(inputCollection.listType.indexOf('vevent')!=-1)
					globalAccountSettings[inputCollection.resourceIndex].calendarNo--;
				else if(inputCollection.listType.indexOf('vtodo')!=-1)
					globalAccountSettings[inputCollection.resourceIndex].todoNo--;
				if((globalAccountSettings[inputCollection.resourceIndex].calendarNo==0 && globalAccountSettings[inputCollection.resourceIndex].todoNo==0 && globalCalDAVInitLoad))
					updateMainLoader();
				else if(globalSettingsSaving!='')
					updateMainLoader(true,inputCollection.listType,inputCollection.uid);
			}
			else if((globalOnlyCalendarNumber>0 && globalOnlyCalendarNumberCount==globalOnlyCalendarNumber) || (globalTodoCalendarNumber>0 && globalOnlyTodoCalendarNumberCount==globalTodoCalendarNumber))
				updateMainLoader(true,inputCollection.listType);
			if((typeof globalParallelAjaxCallCalDAVEnabled=='undefined' || globalParallelAjaxCallCalDAVEnabled==null || !globalParallelAjaxCallCalDAVEnabled) && collections.length>0)
			{
				recursiveIterator++;
				if(recursiveIterator>=collections.length && inputCollection.uid!='undefined' && inputCollection.listType=='vevent')
				{
					recursiveIterator=0;
					if((globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null) || allSyncMode)
						CalDAVnetLoadCollection(globalResourceCalDAVList.TodoCollections[0], forceLoad, allSyncMode,  0, globalResourceCalDAVList.TodoCollections);
				}
				else
					CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
			}
			return false;
		},
		success: function(data, textStatus, xml){
			inputCollection.someChanged = false;
			if(inputCollection.listType=='vevent' && $('#ResourceCalDAVList').find('.r_error').length==0 && isEachResourceLoaded())
				$('#intCaldav').find('.int_error').css('display','none');
			else if(inputCollection.listType=='vtodo' && $('#ResourceCalDAVTODOList').find('.r_error').length==0 && isEachResourceLoaded())
				$('#intCaldavTodo').find('.int_error').css('display','none');
			inputCollection.oldSyncToken = inputCollection.syncToken;
			inputCollection.pastUnloaded='';
			var hrefCounter = 0;
			$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').children().filterNsNode('href').each(function(index, element){
				hrefCounter++;
			});
			globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].collectionLength=hrefCounter;
			globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].counter=0;
			globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].resourceIndex=inputCollection.resourceIndex;
			globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].listType=inputCollection.listType;
			globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType].typeList=inputCollection.typeList;

			var isXMLEmpty=true;
			var re_found = new RegExp('200 OK$');
			$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').each(function(index, element){
				if($(element).children().filterNsNode('propstat').children().filterNsNode('status').text().match(re_found)) // HTTP OK
				{
					isXMLEmpty=false;
					var etag=$(element).children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('getetag').text();
					var uid=inputCollection.uid+$(element).children().filterNsNode('href').text().replace(vCalendar.pre['hrefValRex'], '');
					var vcalendar_raw=$(element).children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('calendar-data').text();
					if(vcalendar_raw!='')
						var vcalendar_clean=vCalendarCleanup(vcalendar_raw);
					else
					{
						checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
						return true;
					}
					if((vcalendar_clean==undefined) || ((check=vcalendar_clean.match(vCalendar.pre['vcalendar']))==null))
					{
						checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
						console.log("Error: '"+uid+"': unable to parse vCalendar");
						return true;
					}

					if((check=vcalendar_clean.match(vCalendar.pre['vevent']))!=null)
					{
						if(inputCollection.typeList.indexOf('vevent')!=-1)
							globalEventList.insertEvent(forceCall,inputCollection, {threadChange: '', isRepeat: false, isDrawn: false, isTODO: false, untilDate: '', sortStart: '', start: '', end: '', sortkey: '', timestamp: resultTimestamp, accountUID: inputCollection.accountUID, uid: uid, displayValue: inputCollection.displayvalue, counter: 0, etag: etag, vcalendar: vcalendar_clean}, false, true,true);	// when the inputMode=='sync' we force reload the vevent/vtodo
						else
							checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
					}
					else if((check=vcalendar_clean.match(vCalendar.pre['vtodo']))!=null)
					{
						if(inputCollection.typeList.indexOf('vtodo')!=-1)
							globalEventList.insertEvent(forceCall,inputCollection, {threadChange: '', isRepeat: false, isDrawn: false, isTODO: false, untilDate: '', sortStart: '', start: '', end: '', sortkey: '', timestamp: resultTimestamp, accountUID: inputCollection.accountUID, uid: uid, displayValue: inputCollection.displayvalue, counter: 0, etag: etag, vcalendar: vcalendar_clean}, false, false, true);	// when the inputMode=='sync' we force reload the vevent/vtodo
						else
							checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
					}
					else
					{
						console.log("Error: '"+uid+"': unable to parse vEvent or vTodo");
						checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
						return true;
					}
				}
				else
				{
					var uid=inputCollection.uid+$(element).children().filterNsNode('href').text().replace(vCalendar.pre['hrefValRex'], '');
					console.log("Error: '"+uid+"': unable to parse vEvent or vTodo");
					checkEventLoader(globalResourceCalDAVList.counterList[inputCollection.uid+' '+inputCollection.listType],false);
					return true;
				}
			});

			if(isXMLEmpty)
			{
				if(inputCollection.listType=='vevent')
					$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
				else
					$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');

				if(globalLimitLoading=='' && globalLimitTodoLoading=='')
				{
					if(inputCollection.typeList.indexOf('vevent')!=-1)
						globalAccountSettings[inputCollection.resourceIndex].calendarNo--;
					else if(inputCollection.typeList.indexOf('vtodo')!=-1)
						globalAccountSettings[inputCollection.resourceIndex].todoNo--;
					if(globalAccountSettings[inputCollection.resourceIndex].calendarNo==0 && globalAccountSettings[inputCollection.resourceIndex].todoNo==0 && globalCalDAVInitLoad)
						updateMainLoader();
					else if(globalSettingsSaving!='')
						updateMainLoader(true,inputCollection.listType,inputCollection.uid);
				}
				else if((globalOnlyCalendarNumber>0 && globalOnlyCalendarNumberCount==globalOnlyCalendarNumber) || (globalTodoCalendarNumber>0 && globalOnlyTodoCalendarNumberCount==globalTodoCalendarNumber))
					updateMainLoader(true,inputCollection.listType);
			}
			if((typeof globalParallelAjaxCallCalDAVEnabled=='undefined' || globalParallelAjaxCallCalDAVEnabled==null || !globalParallelAjaxCallCalDAVEnabled) && collections.length>0)
			{

				recursiveIterator++;
				if(recursiveIterator>=collections.length && inputCollection.uid!='undefined' && inputCollection.listType=='vevent')
				{
					recursiveIterator=0;
					if((globalSettings.eventstartpastlimit.value==null && globalSettings.eventstartfuturelimit.value==null) || allSyncMode)
						CalDAVnetLoadCollection(globalResourceCalDAVList.TodoCollections[0], forceLoad, allSyncMode, 0, globalResourceCalDAVList.TodoCollections);
				}
				else
					CalDAVnetLoadCollection(collections[recursiveIterator], forceLoad, allSyncMode, recursiveIterator, collections);
			}
			if(globalTodoLoaderHide!='')
			{
				show_editor_loader_messageCalendar('vtodo', 'message_success', globalTodoLoaderHide, function(a){
							globalTodoLoaderHide='';
							$('#showTODO').val('');
							$('#TodoDisabler').fadeOut(globalEditorFadeAnimation, function(){
								$('#timezonePickerTODO').prop('disabled', false);
							});
				});
			}
		}
	});
}

function netLoadCalendarSubscription(inputResource, inputCollection, recursiveIterator, forceLoad, collections)
{
	if(!inputCollection.makeLoaded || globalLimitLoading!='' || globalLimitTodoLoading!='')
	{
		if(inputCollection.makeLoaded)
			updateMainLoaderText(inputCollection.listType);
		if(inputCollection.listType=='vevent')
			$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
		else
			$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
		if(globalLimitLoading=='' && globalLimitTodoLoading=='')
		{
			if(inputCollection.typeList.indexOf('vevent')!=-1)
				globalAccountSettings[inputCollection.resourceIndex].calendarNo--;
			else if(inputCollection.typeList.indexOf('vtodo')!=-1)
				globalAccountSettings[inputCollection.resourceIndex].todoNo--;
			if((globalAccountSettings[inputCollection.resourceIndex].calendarNo==0 && globalAccountSettings[inputCollection.resourceIndex].todoNo==0 && globalCalDAVInitLoad) || !globalCalDAVInitLoad)
			updateMainLoader();
		}
		else if(globalLimitLoading!='' || globalLimitTodoLoading!='')
			updateMainLoader();
		return false;
	}
	$.ajax({
		type: 'GET',
		url: inputCollection.href,
		cache: false,
		crossDomain: false,
		timeout: 30000,
		beforeSend: function(req) {
			if(globalSettings.usejqueryauth.value!=true && inputResource.userAuth.userName!='' && inputResource.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(inputResource.userAuth.userName, inputResource.userAuth.userPassword));
		},
		username: (globalSettings.usejqueryauth.value==true ? inputResource.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? inputResource.userAuth.userPassword : null),
		contentType: 'text/plain',
		processData: true,
		data: '',
		dataType: 'text',
		error: function(objAJAXRequest, strError){
			console.log("Error: [netLoadCalendarSubscription: 'GET "+inputCollection.href+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'");
			if(inputCollection.listType=='vevent')
			{
				$('#ResourceCalDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
				$('#intCaldav').find('.int_error').css('display','block');
			}
			else
			{
				$('#ResourceCalDAVTODOList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
				$('#intCaldavTodo').find('.int_error').css('display','block');
			}
				$('[data-id="'+inputCollection.uid+'"]').addClass('r_error');
			if(globalLimitLoading=='' && globalLimitTodoLoading=='')
			{
				if(inputCollection.typeList.indexOf('vevent')!=-1)
					globalAccountSettings[inputCollection.resourceIndex].calendarNo--;
				else if(inputCollection.typeList.indexOf('vtodo')!=-1)
					globalAccountSettings[inputCollection.resourceIndex].todoNo--;
				if((globalAccountSettings[inputCollection.resourceIndex].calendarNo==0 && globalAccountSettings[inputCollection.resourceIndex].todoNo==0 && globalCalDAVInitLoad) || !globalCalDAVInitLoad)
					updateMainLoader();
			}
			return false;
		},
		success: function(data, response, text)
		{
			if(inputCollection.listType=='vevent' && $('#ResourceCalDAVList').find('.r_error').length==0 && isEachResourceLoaded())
				$('#intCaldav').find('.int_error').css('display','none');
			else if(inputCollection.listType=='vtodo' && $('#ResourceCalDAVTODOList').find('.r_error').length==0 && isEachResourceLoaded())
				$('#intCaldavTodo').find('.int_error').css('display','none');
			var vcalendarText = vCalendarCleanup(text.responseText);
			inputCollection.urlArray={};
			inputCollection.newlyAdded = false;
			if(inputCollection.typeList.indexOf('vevent')!=-1)
			{
				var parseCounter=0;
				var isEvent = false;
				if(vcalendarText.match(vCalendar.pre['vevent'])!=null)
					isEvent = true;
				while(vcalendarText.match(vCalendar.pre['vevent'])!=null)
				{
					var partEvent=vcalendarText.substring(vcalendarText.indexOf('BEGIN:VEVENT')-2,vcalendarText.indexOf('END:VEVENT')+'END:VEVENT'.length);
					var realEventUID=partEvent.match(vCalendar.pre['contentline_UID']);

					if(realEventUID!=null)
					{
						realEventUID=realEventUID[0].match(vCalendar.pre['contentline_parse'])[4];
						realEventUID=realEventUID.replace('/','');
					}

					var hex = hex_sha256(partEvent);
					if(inputCollection.urlArray != null)
					{
						if(inputCollection.urlArray[inputCollection.uid+realEventUID+'.ics']!=null && inputCollection.urlArray[inputCollection.uid+realEventUID+'.ics']!=undefined)
							inputCollection.urlArray[inputCollection.uid+realEventUID+'.ics'].eventText+=partEvent+'\r\n';
						else
							inputCollection.urlArray[inputCollection.uid+realEventUID+'.ics'] = {etag: hex, href: inputCollection.uid+realEventUID+'.ics', eventText : partEvent+'\r\n'};
					}
					vcalendarText = vcalendarText.replace(partEvent,'');
					parseCounter++;
				}
				if(parseCounter==0 && isEvent)
				{
					if(typeof realEventUID=='undefined' || realEventUID==null)
						console.log("Error: '"+inputCollection.uid+"': unable to parse subscribed vEvent");
					else
						console.log("Error: '"+inputCollection.uid+realEventUID+'.ics'+"': unable to parse subscribed vEvent");
				}
			}
			if(inputCollection.typeList.indexOf('vtodo')!=-1)
			{
				var parseCounter=0;
				var isTodo = false;
				if(vcalendarText.match(vCalendar.pre['vtodo'])!=null)
					isTodo = true;
				while(vcalendarText.match(vCalendar.pre['vtodo'])!=null)
				{
					var partEvent=vcalendarText.substring(vcalendarText.indexOf('BEGIN:VTODO')-2,vcalendarText.indexOf('END:VTODO')+'END:VTODO'.length);
					var realEventUID=partEvent.match(vCalendar.pre['contentline_UID']);

					if(realEventUID!=null)
					{
						realEventUID=realEventUID[0].match(vCalendar.pre['contentline_parse'])[4];
						realEventUID=realEventUID.replace('/','');
					}

					var hex = hex_sha256(partEvent);
					if(inputCollection.urlArray != null)
					{
						if(inputCollection.urlArray[inputCollection.uid+realEventUID+'.ics']!=null && inputCollection.urlArray[inputCollection.uid+realEventUID+'.ics']!=undefined)
							inputCollection.urlArray[inputCollection.uid+realEventUID+'.ics'].eventText+=partEvent+'\r\n';
						else
							inputCollection.urlArray[inputCollection.uid+realEventUID+'.ics'] = {etag: hex, href: inputCollection.uid+realEventUID+'.ics', eventText : partEvent+'\r\n'};
					}
					vcalendarText = vcalendarText.replace(partEvent,'');
					parseCounter++;
				}
				if(parseCounter==0 && isTodo)
				{
					if(typeof realEventUID=='undefined' || realEventUID==null)
						console.log("Error: '"+inputCollection.uid+"': unable to parse subscribed vTodo");
					else
						console.log("Error: '"+inputCollection.uid+realEventUID+'.ics'+"': unable to parse subscribed vTodo");
				}
			}

				if(typeof globalEventList.events[inputCollection.uid] != 'undefined')
				{
					for(event in globalEventList.events[inputCollection.uid])
					{
						if(inputCollection.urlArray[event] == undefined || inputCollection.urlArray[event] == null)
							globalEventList.removeOldEvent(event, true, true);
					}
				}
				else
				{
					for(event in globalEventList.todos[inputCollection.uid])
						if(inputCollection.urlArray[event] == undefined || inputCollection.urlArray[event] == null)
							globalEventList.removeOldEvent(event, true, false);
				}
			netLoadCalendar(inputCollection, inputCollection.urlArray, (inputCollection.forceSyncPROPFIND==undefined || inputCollection.forceSyncPROPFIND==false ? true : false), true, forceLoad, true, false, recursiveIterator, collections);
		}
	});
}

function unlockCollection(inputContactObj)
{
	var tmp=inputContactObj.uid.match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@([^/]+)(.*/)([^/]+/)([^/]*)','i'));
	var collection_uid=tmp[1]+tmp[2]+'@'+tmp[3]+tmp[4]+tmp[5];

	var lockToken=globalResourceCardDAVList.getCollectionByUID(collection_uid).lockToken;

	// resource not locked, we cannot unlock it
	if(lockToken=='undefined' || lockToken==null)
		return false;

	var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5];
	var put_href_part=tmp[4]+tmp[5];
	var resourceSettings=null;

	// find the original settings for the resource and user
	var tmp=inputContactObj.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];

	if(resourceSettings==null)
		return false;

	// the begin of each error message
	var errBegin=localization[globalInterfaceLanguage].errUnableUnlockBegin;

	$.ajax({
		type: 'UNLOCK',
		url: put_href,
		cache: false,
		crossDomain: (typeof resourceSettings.crossDomain=='undefined' ? true : resourceSettings.crossDomain),
		xhrFields: {
			withCredentials: (typeof resourceSettings.withCredentials=='undefined' ? false : resourceSettings.withCredentials)
		},
		timeout: resourceSettings.timeOut,
		beforeSend: function(req) {
			if(globalSettings.usejqueryauth.value!=true && resourceSettings.userAuth.userName!='' && resourceSettings.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(resourceSettings.userAuth.userName,resourceSettings.userAuth.userPassword));
			req.setRequestHeader('X-client', globalXClientHeader);
			// req.setRequestHeader('Depth', '0');
			if(lockToken!=null)
				req.setRequestHeader('Lock-Token', '<'+lockToken+'>');
		},
		username: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userPassword : null),
		data: '',
		error: function(objAJAXRequest, strError){
			console.log("Error: [unlockCollection: 'UNLOCK "+put_href+"']: code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
			switch(objAJAXRequest.status)
			{
				case 401:
					show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp401),globalHideInfoMessageAfter);
					break;
				case 403:
					show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp403),globalHideInfoMessageAfter);
					break;
				case 405:
					show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp405),globalHideInfoMessageAfter);
					break;
				case 408:
					show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp408),globalHideInfoMessageAfter);
					break;
				case 500:
					show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp500),globalHideInfoMessageAfter);
					break;
				case 501:
					show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp501),globalHideInfoMessageAfter);
					break;
				default:
					show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttpCommon.replace('%%',objAJAXRequest.status)),globalHideInfoMessageAfter);
					break;
			}
			return false;
		},
		success: function(data, textStatus, xml)
		{
			globalResourceCardDAVList.setCollectionFlagByUID(collection_uid, 'lockToken', null);
			return true;
		}
	});
}

function operationPerform(inputPerformOperation, inputContactObj, inputFilterUID)
{
	if(inputPerformOperation=='PUT')
	{
		var tmp=new Array();
		var groupArr=new Array();
//check vcard groups to add
		if(typeof inputContactObj.addToContactGroupUID!='undefined' && inputContactObj.addToContactGroupUID.length>0)
			groupArr=globalAddressbookList.getAddMeToContactGroups(inputContactObj, inputContactObj.addToContactGroupUID);
		else if(typeof inputContactObj.formSave=='undefined')
			groupArr=globalAddressbookList.getAddMeToContactGroups(inputContactObj, inputFilterUID);
		if(groupArr!=null)
			tmp=tmp.concat(groupArr)
//check vcard groups to remove
		groupArr=new Array();
		if(typeof inputContactObj.removeToContactGroupUID!='undefined' && inputContactObj.removeToContactGroupUID.length>0)
			groupArr=globalAddressbookList.getRemoveMeFromContactGroups(inputContactObj.uid, inputContactObj.removeToContactGroupUID);
		else if(typeof inputContactObj.formSave=='undefined')
			groupArr=globalAddressbookList.getRemoveMeFromContactGroups(inputContactObj.uid, null);
		if(groupArr!=null)
			tmp=tmp.concat(groupArr)
		if(tmp.length>0)
			var inputContactObjArr=new Array($.extend({withoutLockTocken: true}, inputContactObj));
		else
			var inputContactObjArr=new Array(inputContactObj);
		inputContactObjArr=inputContactObjArr.concat(tmp);

		putVcardToCollection(inputContactObjArr, inputFilterUID, 'PUT_ALL', null);
	}
	else if(inputPerformOperation=='DELETE')
	{
		var tmp=globalAddressbookList.getRemoveMeFromContactGroups(inputContactObj.uid, null);
		var inputContactObjArr=new Array(inputContactObj);
		inputContactObjArr=tmp.concat(inputContactObjArr);

		if(inputContactObjArr.length==1)
			deleteVcardFromCollection(inputContactObjArr[0], inputFilterUID, 'DELETE_LAST');
		else
			putVcardToCollection(inputContactObjArr, inputFilterUID, 'DELETE_LAST', null);
	}
	else if(inputPerformOperation=='ADD_TO_GROUP')
	{
		var tmp=globalAddressbookList.getAddMeToContactGroups(inputContactObj, [inputContactObj.addToContactGroupUID]);
		tmp[0].uiObjects=inputContactObj.uiObjects
		tmp[0].uidContact = inputContactObj.uid;
		var inputContactObjArr=tmp;

		putVcardToCollection(inputContactObjArr, inputFilterUID, 'ADD_TO_GROUP_LAST', null);
	}
	else if(inputPerformOperation=='DELETE_FROM_GROUP')
	{
		var inputContactObjArr=globalAddressbookList.getRemoveMeFromContactGroups(inputContactObj.uid, [inputFilterUID]);
		putVcardToCollection(inputContactObjArr, inputFilterUID, 'DELETE_FROM_GROUP_LAST', null);
	}
	else if(inputPerformOperation=='IRM_DELETE')
	{
		var tmp=new Array();
		if(typeof inputContactObj.addToContactGroupUID!='undefined' && inputContactObj.addToContactGroupUID.length>0)
			tmp=tmp.concat(globalAddressbookList.getAddMeToContactGroups({vcard:inputContactObj.vcard,uid:inputContactObj.orgUID}, inputContactObj.addToContactGroupUID));

		if(typeof inputContactObj.removeToContactGroupUID!='undefined' && inputContactObj.removeToContactGroupUID.length)
			tmp=tmp.concat(globalAddressbookList.getRemoveMeFromContactGroups(inputContactObj.uid, inputContactObj.removeToContactGroupUID));
		else
			tmp=tmp.concat(globalAddressbookList.getRemoveMeFromContactGroups(inputContactObj.uid, null));

		var inputContactObjArr=new Array($.extend({withoutLockTocken: true}, inputContactObj), inputContactObj);	// first is used for PUT to destination resource (without lock token) and the second for the DELETE
		inputContactObjArr=tmp.concat(inputContactObjArr);

		putVcardToCollection(inputContactObjArr, inputFilterUID, 'IRM_DELETE_LAST', null);
	}
	else if(inputPerformOperation=='MOVE')
	{
		var tmp=globalAddressbookList.getRemoveMeFromContactGroups(inputContactObj.uid, null);
		var inputContactObjArr=new Array(inputContactObj);
		inputContactObjArr=tmp.concat(inputContactObjArr);

		if(inputContactObjArr.length==1)
			moveVcardToCollection(inputContactObjArr[0], inputFilterUID);
		else
			putVcardToCollection(inputContactObjArr, inputFilterUID, 'MOVE_LAST', null);
	}
}

function operationPerformed(inputPerformOperation, inputContactObj, loadContactObj)
{
	var collUID = inputContactObj.uid.replace(RegExp('[^/]*$'),'');
	if(inputPerformOperation=='ADD_TO_GROUP_LAST' && typeof inputContactObj.uiObjects.contact!='undefined')
	{
		// success icon
		setTimeout(function(){
			var resource=$('#ResourceCardDAVList').find('div[data-id="'+jqueryEscapeSelector(inputContactObj.uiObjects.resource)+'"]');
			resource.addClass('r_success');
			resource.removeClass('r_operate');
			setTimeout(function(){
				if($('#ExtendedDest').length>0)
					extendDestSelect();
				checkForVcardGroups(inputContactObj.uidContact);
				inputContactObj.uiObjects.contact.animate({opacity: 1}, 750);
				inputContactObj.uiObjects.contact.draggable('option', 'disabled', false);
				resource.removeClass('r_success');
				resource.droppable('option', 'disabled', false);
			},1200);
		},1000);
	}
	// contact group operation (only one contact group is changed at once)
	else if(inputPerformOperation=='DELETE_FROM_GROUP_LAST')
	{
		// success message
		var duration=show_editor_message('out','message_success',localization[globalInterfaceLanguage].succContactDeletedFromGroup,globalHideInfoMessageAfter);

		// after the success message show the next automatically selected contact
		var animation=400;
		setTimeout(function(){
			$('#ResourceCardDAVListOverlay').fadeOut(animation);
			$('#ABListOverlay').fadeOut(animation,function(){});
			$('#ABContactOverlay').fadeOut(animation,function(){globalRefAddContact.prop('disabled',false);});
		},duration-animation);
	}
	// contact is added but it is hidden due to search filter
	else if(typeof globalAddressbookList.contacts_hash[inputContactObj.uid]!='undefined' && (globalAddressbookList.contacts_hash[inputContactObj.uid].search_hide||!globalAddressbookList.contacts_hash[inputContactObj.uid].show))
	{
		// load the modified contact
		globalAddressbookList.loadContactByUID(loadContactObj.uid);
		// success message
		var duration=show_editor_message('in','message_success',localization[globalInterfaceLanguage].succContactSaved,globalHideInfoMessageAfter);

		// after the success message show the next automatically selected contact
//		setTimeout(function(){
			$('#ResourceCardDAVListOverlay').fadeOut(globalHideInfoMessageAfter);
			$('#ABListOverlay').fadeOut(globalHideInfoMessageAfter,function(){});
			$('#ABContactOverlay').fadeOut(globalHideInfoMessageAfter,function(){globalRefAddContact.prop('disabled',false);});
//		},duration+globalHideInfoMessageAfter);
	}
	else
	{
		if(typeof inputContactObj.newUID!='undefined' && typeof globalAddressbookList.contacts_hash[inputContactObj.newUID]!='undefined' && (globalAddressbookList.contacts_hash[inputContactObj.newUID].search_hide||!globalAddressbookList.contacts_hash[inputContactObj.newUID].show))
			globalDisableAnimationMessageHiding='errContactHidden';
		// load the modified contact
		if(typeof loadContactObj.isInterResource=='undefined' || loadContactObj.isInterResource==null || !loadContactObj.isInterResource)
			globalAddressbookList.loadContactByUID(loadContactObj.uid);

		// success message
		show_editor_message('in','message_success',localization[globalInterfaceLanguage].succContactSaved,globalHideInfoMessageAfter);

		// presunut do jednej funkcie s tym co je vyssie
		$('#ResourceCardDAVListOverlay').fadeOut(globalHideInfoMessageAfter);
		$('#ABListOverlay').fadeOut(globalHideInfoMessageAfter);
		$('#ABContactOverlay').fadeOut(globalHideInfoMessageAfter,function(){globalRefAddContact.prop('disabled',false);});
	}

	unlockCollection(inputContactObj);
}

function lockAndPerformToCollection(inputContactObj, inputFilterUID, inputPerformOperation)
{
	if(typeof(globalContactsExtLockAndPerformOverload)=='function')
	{
		globalContactsExtLockAndPerformOverload();
		return;
	}

	var tmp=inputContactObj.uid.match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@([^/]+)(.*/)([^/]+/)([^/]*)','i'));
	var collection_uid=tmp[1]+tmp[2]+'@'+tmp[3]+tmp[4]+tmp[5];

	// If locking is unsupported or disabled we don't try to LOCK the collection
	if(globalResourceCardDAVList.getCollectionByUID(collection_uid).disableLocking)
	{
		// perform the operation without locking
		operationPerform(inputPerformOperation, inputContactObj, inputFilterUID);
		return true;
	}

	var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5];
	var put_href_part=tmp[4]+tmp[5];
	var resourceSettings=null;

	// find the original settings for the resource and user
	var tmp=inputContactObj.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];

	if(resourceSettings==null)
		return false;

	// the begin of each error message
	var errBegin=localization[globalInterfaceLanguage].errUnableLockBegin;

	$.ajax({
		type: 'LOCK',
		url: put_href,
		cache: false,
		crossDomain: (typeof resourceSettings.crossDomain=='undefined' ? true : resourceSettings.crossDomain),
		xhrFields: {
			withCredentials: (typeof resourceSettings.withCredentials=='undefined' ? false : resourceSettings.withCredentials)
		},
		timeout: resourceSettings.timeOut,
		beforeSend: function(req)
		{
			if(globalSettings.usejqueryauth.value!=true && resourceSettings.userAuth.userName!='' && resourceSettings.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(resourceSettings.userAuth.userName,resourceSettings.userAuth.userPassword));
			req.setRequestHeader('X-client', globalXClientHeader);
			req.setRequestHeader('Depth', '0');
			// we support only one contact group at once + the contact + reserve :)
			req.setRequestHeader('Timeout', 'Second-'+Math.ceil((resourceSettings.lockTimeOut!=undefined ? resourceSettings.lockTimeOut : 10000)/1000));
		},
		username: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userPassword : null),
		contentType: 'text/xml; charset=utf-8',
		processData: false,
		data: '<?xml version="1.0" encoding="utf-8"?><D:lockinfo xmlns:D="DAV:"><D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype><D:owner><D:href>'+escape(collection_uid)+'</D:href></D:owner></D:lockinfo>',
		dataType: 'text',
		error: function(objAJAXRequest, strError)
		{
			// if we tried to LOCK the collection but the server not supports this request we perform
			//  the operation without LOCK (even if it is dangerous and can cause data integrity errors)
			if(objAJAXRequest.status==501)
				operationPerform(inputPerformOperation, inputContactObj, inputFilterUID);
			// if the operation type is 'MOVE' we cannot show error messages, error icon is used instead
			else if(inputPerformOperation!='MOVE')
			{
				console.log("Error: [unlockCollection: 'LOCK "+put_href+"']: code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
				switch(objAJAXRequest.status)
				{
					case 401:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp401),globalHideInfoMessageAfter);
						break;
					case 403:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp403),globalHideInfoMessageAfter);
						break;
					case 405:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp405),globalHideInfoMessageAfter);
						break;
					case 408:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp408),globalHideInfoMessageAfter);
						break;
					case 500:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp500),globalHideInfoMessageAfter);
						break;
					default:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttpCommon.replace('%%',objAJAXRequest.status)),globalHideInfoMessageAfter);
						break;
				}

				// error icon
				setTimeout(function(){
					var resource=$('#ResourceCardDAVList').find('div[data-id="'+jqueryEscapeSelector(inputContactObj.uiObjects.resource)+'"]');
					resource.addClass('r_error');
					resource.removeClass('r_operate');
					setTimeout(function(){
						inputContactObj.uiObjects.contact.animate({opacity: 1}, 1000);
						inputContactObj.uiObjects.contact.draggable('option', 'disabled', false);
						resource.removeClass('r_error');
						resource.droppable('option', 'disabled', false);
					},globalHideInfoMessageAfter);
				},globalHideInfoMessageAfter/10);
			}
			$('#ABContactOverlay').fadeOut(globalEditorFadeAnimation,function(){globalRefAddContact.prop('disabled',false);});

			return false;
		},
		success: function(data, textStatus, xml)
		{
			// workaround for jQuery 2.0.0
			if(xml.responseXML==undefined)
				xml.responseXML=$.parseXML(xml.responseText);

			var lockToken=$(xml.responseXML).children().filterNsNode('prop').children().filterNsNode('lockdiscovery').children().filterNsNode('activelock').children().filterNsNode('locktoken').children().filterNsNode('href').text();
			globalResourceCardDAVList.setCollectionFlagByUID(collection_uid, 'lockToken', (lockToken=='' ? null : lockToken));

			// We have a lock!
			if(lockToken!='')
			{
				// synchronously reload the contact changes (get the latest version of contact group vcards)
				var collection=globalResourceCardDAVList.getCollectionByUID(collection_uid);
				collection.filterUID=inputFilterUID;

				CardDAVnetLoadCollection(collection, false, false, {call: 'operationPerform', args: {performOperation: inputPerformOperation, contactObj: inputContactObj, filterUID: inputFilterUID}}, 0, null, false);
				return true;
			}
			else
			{
				// We assume that empty lockToken means 423 Resource Locked error
				show_editor_message('out','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errResourceLocked),globalHideInfoMessageAfter);

				// error icon
				if(inputContactObj.uiObjects!=undefined)	// only for drag&drop operation
				{
					setTimeout(function(){
						var resource=$('#ResourceCardDAVList').find('div[data-id="'+jqueryEscapeSelector(inputContactObj.uiObjects.resource)+'"]');
						resource.addClass('r_error');
						resource.removeClass('r_operate');
						setTimeout(function(){
							inputContactObj.uiObjects.contact.animate({opacity: 1}, 1000);
							inputContactObj.uiObjects.contact.draggable('option', 'disabled', false);
							resource.removeClass('r_error');
							resource.droppable('option', 'disabled', false);
						},globalHideInfoMessageAfter);
					},globalHideInfoMessageAfter/10);
				}

				$('#ABContactOverlay').fadeOut(globalEditorFadeAnimation,function(){globalRefAddContact.prop('disabled',false);});
			}
			return false;
		}
	});
}

function putVcardToCollectionMain(inputContactObj, inputFilterUID)
{
	if(inputContactObj.etag=='')
	{
		if(inputFilterUID[inputFilterUID.length-1]!='/')	// new contact with vCard group (we must use locking)
		{
			lockAndPerformToCollection(inputContactObj, inputFilterUID, 'PUT');
		}
		else	// new contact without vCard group (no locking required)
			putVcardToCollection(inputContactObj, inputFilterUID, 'PUT_ALL', null);
	}
	else	// existing contact modification (there is no support for contact group modification -> no locking required)
		putVcardToCollection(inputContactObj, inputFilterUID, 'PUT_ALL', null);
}

function putVcardToCollection(inputContactObjArr, inputFilterUID, recursiveMode, loadContactWithUID)
{
	if(!(inputContactObjArr instanceof Array))
		inputContactObjArr=[inputContactObjArr];

	var inputContactObj=inputContactObjArr.splice(0,1);
	inputContactObj=inputContactObj[0];

	// drag & drop inter-resoruce move (we need to change the object parameters)
	if(inputContactObj.newAccountUID!=undefined && inputContactObj.newUid!=undefined)
	{
		inputContactObj.accountUID=inputContactObj.newAccountUID;
		inputContactObj.uid=inputContactObj.newUid;
		inputContactObj.etag='';
	}

	var tmp=inputContactObj.uid.match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@([^/]+)(.*/)([^/]+/)([^/]*)','i'));

	var collection_uid=tmp[1]+tmp[2]+'@'+tmp[3]+tmp[4]+tmp[5];
	var lockToken=globalResourceCardDAVList.getCollectionByUID(collection_uid).lockToken;
	var color=globalResourceCardDAVList.getCollectionByUID(collection_uid).color;

	// if inputContactObj.etag is empty, we have a newly created contact and need to create a .vcf file name for it
	if(inputContactObj.etag!='')	// existing contact
	{
		var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5]+tmp[6];
		var put_href_part=tmp[4]+tmp[5]+tmp[6];
	}
	else	// new contact
	{
		var vcardFile=hex_sha256(inputContactObj.vcard+(new Date().getTime()))+'.vcf';
		var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5]+vcardFile;
		var put_href_part=tmp[4]+tmp[5]+vcardFile;
		inputContactObj.uid+=vcardFile;
	}

	if(loadContactWithUID==null)	// store the first contact (it will be reloaded and marked as active)
		loadContactWithUID=inputContactObj;

	var resourceSettings=null;

	// find the original settings for the resource and user
	var tmp=inputContactObj.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];

	if(resourceSettings==null)
		return false;

	// the begin of each error message
	var errBegin=localization[globalInterfaceLanguage].errUnableSaveBegin;

	var vcardList= new Array();
	$.ajax({
		type: 'PUT',
		url: put_href,
		cache: false,
		crossDomain: (typeof resourceSettings.crossDomain=='undefined' ? true : resourceSettings.crossDomain),
		xhrFields: {
			withCredentials: (typeof resourceSettings.withCredentials=='undefined' ? false : resourceSettings.withCredentials)
		},
		timeout: resourceSettings.timeOut,
		beforeSend: function(req)
		{
			req.setRequestHeader('Prefer', 'return=representation');
			if(globalSettings.usejqueryauth.value!=true && resourceSettings.userAuth.userName!='' && resourceSettings.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(resourceSettings.userAuth.userName,resourceSettings.userAuth.userPassword));
			req.setRequestHeader('X-client', globalXClientHeader);
			if(lockToken!=null && inputContactObj.withoutLockTocken!=true)
				req.setRequestHeader('Lock-Token', '<'+lockToken+'>');
			if(inputContactObj.etag!='')
				req.setRequestHeader('If-Match', inputContactObj.etag);
			else	// adding new contact
				req.setRequestHeader('If-None-Match', '*');
		},
		username: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userPassword : null),
		contentType: 'text/vcard',
		processData: true,
		data: inputContactObj.vcard,
		dataType: 'text',
		error: function(objAJAXRequest, strError)
		{
			if(recursiveMode=='MOVE_LAST' || recursiveMode=='IRM_DELETE_LAST' || recursiveMode=='ADD_TO_GROUP_LAST')
			{
				// error icon
				setTimeout(function(){
					var moveContactObj=inputContactObjArr[inputContactObjArr.length-1];
					var resource=$('#ResourceCardDAVList').find('div[data-id="'+jqueryEscapeSelector(moveContactObj.uiObjects.resource)+'"]');
					resource.addClass('r_error');
					resource.removeClass('r_operate');
					setTimeout(function(){
						moveContactObj.uiObjects.contact.animate({opacity: 1}, 1000);
						moveContactObj.uiObjects.contact.draggable('option', 'disabled', false);
						resource.removeClass('r_error');
						resource.droppable('option', 'disabled', false);
					},1200);
				},1000);
			}
			else
			{
				console.log("Error: [putVcardToCollection: 'PUT "+put_href+"']: code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
				switch(objAJAXRequest.status)
				{
					case 401:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp401),globalHideInfoMessageAfter);
						break;
					case 403:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp403),globalHideInfoMessageAfter);
						break;
					case 405:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp405),globalHideInfoMessageAfter);
						break;
					case 408:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp408),globalHideInfoMessageAfter);
						break;
					case 412:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp412),globalHideInfoMessageAfter);
						break;
					case 500:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp500),globalHideInfoMessageAfter);
						break;
					default:
						show_editor_message('in','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttpCommon.replace('%%',objAJAXRequest.status)),globalHideInfoMessageAfter);
						break;
				}
			}

			// presunut do jednej funkcie s tym co je nizsie pri success
			//$('#ResourceCardDAVListOverlay').fadeOut(1200);
			//$('#ABListOverlay').fadeOut(1200);
			$('#ABContactOverlay').fadeOut(globalEditorFadeAnimation,function(){globalRefAddContact.prop('disabled',false);});

			unlockCollection(inputContactObj);
			return false;
		},
		success: function(data, textStatus, xml)
		{
			if(inputContactObjArr.length==1 && (recursiveMode=='DELETE_LAST' || recursiveMode=='IRM_DELETE_LAST'))
			{
				inputContactObjArr[0].newUID=inputContactObj.uid;
				deleteVcardFromCollection(inputContactObjArr[0], inputFilterUID, recursiveMode);
				return true;
			}
			else if(inputContactObjArr.length==1 && recursiveMode=='MOVE_LAST')
			{
				moveVcardToCollection(inputContactObjArr[0], inputFilterUID);
				return true;
			}

			var newEtag=xml.getResponseHeader('Etag');
			// We get the Etag from the PUT response header instead of new collection sync (if the server supports this feature)
			if(newEtag!=undefined && newEtag!=null && newEtag!='')
			{
				// do not remove the contact group from the interface (if removed there are many GUI animation inconsistencies)
				if(!globalAddressbookList.isContactGroup(inputContactObj.vcard))
					globalAddressbookList.removeContact(inputContactObj.uid,false);

				var rawVcard=inputContactObj.vcard;
				if(xml.getResponseHeader('Preference-Applied')=='return=representation' && xml.responseText)
					rawVcard=additionalRFCFixes(basicRFCFixesAndCleanup(xml.responseText));	// we cannot expect RFC compliant result here
				else
					// remove line folding (added before the PUT operation)
					// by default it is a part of basicRFCFixesAndCleanup but we don't need cleanup here!
					rawVcard=rawVcard.replace(vCard.pre['basicRFCFixesAndCleanup_rnwsp-gm'], '');

				var vcard=normalizeVcard(rawVcard);
				var categories='';
				if((vcard_element=vcard.match(vCard.pre['contentline_CATEGORIES']))!=null)
				{
					// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
					parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
					categories=parsed[4];
				}

				globalAddressbookList.insertContact({timestamp: new Date().getTime(), accountUID: inputContactObj.accountUID, uid: inputContactObj.uid, etag: newEtag, color: color, vcard: vcard, categories: categories, normalized: true}, true, false);
				globalQs.cache();	// update the active search

	// XXX check this
	//						globalAddressbookList.applyABFilter(inputFilterUID, recursiveMode=='DELETE_FROM_GROUP_LAST' || globalRefABListTable.find('[data-id="'+jqueryEscapeSelector(inputContactObj.uid)+'"]').hasClass('search_hide') ? true : false);
				globalAddressbookList.applyABFilter(dataGetChecked('#ResourceCardDAVList'), recursiveMode=='DELETE_FROM_GROUP_LAST' || (typeof globalAddressbookList.contacts_hash[inputContactObj.uid]!='undefined'&&(globalAddressbookList.contacts_hash[inputContactObj.uid].search_hide||!globalAddressbookList.contacts_hash[inputContactObj.uid].show)) ? true : false);
			}
			else	// otherwise mark collection for full sync
				globalResourceCardDAVList.setCollectionFlagByUID(collection_uid, 'forceSync', true);

			if(inputContactObjArr.length>0)
				putVcardToCollection(inputContactObjArr, inputFilterUID, recursiveMode, loadContactWithUID);
			else
			{
				var collection=globalResourceCardDAVList.getCollectionByUID(collection_uid);
				if(collection.forceSync===true)
				{
					globalResourceCardDAVList.setCollectionFlagByUID(collection_uid, 'forceSync', false);
					collection.filterUID=inputFilterUID;

					// for DELETE_FROM_GROUP_LAST we need to force reload the contact (because the editor is in "edit" state = the contact is not loaded automatically)
					CardDAVnetLoadCollection(collection, false, recursiveMode=='DELETE_FROM_GROUP_LAST' ? true : false, {call: 'operationPerformed', args: {mode: recursiveMode, contactObj: inputContactObj, loadContact: loadContactWithUID, forceReload: true}}, 0, null, false);
					return true;
				}
				operationPerformed(recursiveMode, inputContactObj, loadContactWithUID);
			}
			return true;
		}
	});
}

function moveVcardToCollection(inputContactObj, inputFilterUID)
{
	var tmp=inputContactObj.uid.match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@([^/]+)(.*/)([^/]+/)([^/]*)','i'));
	var collection_uid=tmp[1]+tmp[2]+'@'+tmp[3]+tmp[4]+tmp[5];
	var lockToken=globalResourceCardDAVList.getCollectionByUID(collection_uid).lockToken;

	var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5]+tmp[6];
	var put_href_part=tmp[4]+tmp[5]+tmp[6];

	var resourceSettings=null;

	// find the original settings for the resource and user
	var tmp=inputContactObj.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];

	if(resourceSettings==null)
		return false;

	var vcardList= new Array();

	$.ajax({
		type: 'MOVE',
		url: put_href,
		cache: false,
		crossDomain: (typeof resourceSettings.crossDomain=='undefined' ? true : resourceSettings.crossDomain),
		xhrFields: {
			withCredentials: (typeof resourceSettings.withCredentials=='undefined' ? false : resourceSettings.withCredentials)
		},
		timeout: resourceSettings.timeOut,
		beforeSend: function(req)
		{
			if(globalSettings.usejqueryauth.value!=true && resourceSettings.userAuth.userName!='' && resourceSettings.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(resourceSettings.userAuth.userName,resourceSettings.userAuth.userPassword));
			req.setRequestHeader('X-client', globalXClientHeader);
			if(lockToken!=null)
				req.setRequestHeader('Lock-Token', '<'+lockToken+'>');
			req.setRequestHeader('Destination', inputContactObj.moveDest);
		},
		username: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userPassword : null),
		contentType: typeof inputContactObj.finalContactUID!='undefined' ? 'text/vcard' : '',
		processData: typeof inputContactObj.finalContactUID!='undefined' ? true : false,
		data: typeof inputContactObj.finalContactUID!='undefined' ? inputContactObj.vcard : '',
		dataType: typeof inputContactObj.finalContactUID!='undefined' ? 'text' : '',
		error: function(objAJAXRequest, strError)
		{
			// error icon
			setTimeout(function(){
				var resource=$('#ResourceCardDAVList').find('div[data-id="'+jqueryEscapeSelector(inputContactObj.uiObjects.resource)+'"]');
				resource.addClass('r_error');
				resource.removeClass('r_operate');
				setTimeout(function(){
					inputContactObj.uiObjects.contact.animate({opacity: 1}, 1000);
					inputContactObj.uiObjects.contact.draggable('option', 'disabled', false);
					resource.removeClass('r_error');
					resource.droppable('option', 'disabled', false);
				},1200);
			},1000);

			unlockCollection(inputContactObj);
		},
		success: function(data,textStatus,xml)
		{
			// success icon
			setTimeout(function(){
				// move is successfull we can remove the contact (no sync required)
				globalAddressbookList.removeContact(inputContactObj.uid,true);
// XXX check this
//						globalAddressbookList.applyABFilter(inputFilterUID, globalRefABListTable.find('[data-id="'+jqueryEscapeSelector(inputContactObj.uid)+'"]').hasClass('search_hide') ? true : false);
				globalAddressbookList.applyABFilter(dataGetChecked('#ResourceCardDAVList'), (typeof globalAddressbookList.contacts_hash[inputContactObj.uid]!='undefined'&&(globalAddressbookList.contacts_hash[inputContactObj.uid].search_hide||!globalAddressbookList.contacts_hash[inputContactObj.uid].show)) ? true : false);
				if(typeof inputContactObj.finalContactUID=='undefined')
				{
					var resource=$('#ResourceCardDAVList').find('div[data-id="'+jqueryEscapeSelector(inputContactObj.uiObjects.resource)+'"]');
					resource.addClass('r_success');
					resource.removeClass('r_operate');
					setTimeout(function(){
						resource.removeClass('r_success');
						resource.droppable('option', 'disabled', false);
					},1200);
				}
				else
					operationPerformed('PUT_ALL', inputContactObj, {uid:inputContactObj.finalContactUID});
			},1000);

			unlockCollection(inputContactObj);

			// if the destination addressbook is already loaded re-sync it (to get the moved contact immediately)
			var collection=globalResourceCardDAVList.getCollectionByUID(inputContactObj.moveDestUID);
			CardDAVnetLoadCollection(collection, false, false, null, 0, null, false);
		}
	});
}

function deleteVcardFromCollection(inputContactObj, inputFilterUID, recursiveMode)
{
	var tmp=inputContactObj.uid.match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@([^/]+)(.*/)([^/]+/)([^/]*)','i'));

	var collection_uid=tmp[1]+tmp[2]+'@'+tmp[3]+tmp[4]+tmp[5];
	var lockToken=globalResourceCardDAVList.getCollectionByUID(collection_uid).lockToken;
	var put_href=tmp[1]+tmp[3]+tmp[4]+tmp[5]+tmp[6];
	var resourceSettings=null;

	// find the original settings for the resource and user
	var tmp=inputContactObj.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];

	if(resourceSettings==null)
		return false;

	// the begin of each error message
	var errBegin=localization[globalInterfaceLanguage].errUnableDeleteBegin;

	$.ajax({
		type: 'DELETE',
		url: put_href,
		cache: false,
		crossDomain: (typeof resourceSettings.crossDomain=='undefined' ? true : resourceSettings.crossDomain),
		xhrFields: {
			withCredentials: (typeof resourceSettings.withCredentials=='undefined' ? false : resourceSettings.withCredentials)
		},
		timeout: resourceSettings.timeOut,
		beforeSend: function(req) {
			if(globalSettings.usejqueryauth.value!=true && resourceSettings.userAuth.userName!='' && resourceSettings.userAuth.userPassword!='')
				req.setRequestHeader('Authorization', basicAuth(resourceSettings.userAuth.userName,resourceSettings.userAuth.userPassword));
			req.setRequestHeader('X-client', globalXClientHeader);
			if(lockToken!=null)
				req.setRequestHeader('Lock-Token', '<'+lockToken+'>');
		},
		username: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userName : null),
		password: (globalSettings.usejqueryauth.value==true ? resourceSettings.userAuth.userPassword : null),
		data: '',
		error: function(objAJAXRequest, strError)
		{
			// if the DELETE is performed as a part of inter-resource move operation (drag&drop)
			if(recursiveMode=='IRM_DELETE_LAST' && typeof inputContactObj.finalContactUID=='undefined')
			{
				// error icon
				setTimeout(function(){
					if(typeof inputContactObj.finalContactUID=='undefined')
					{
						var resource=$('#ResourceCardDAVList').find('div[data-id="'+jqueryEscapeSelector(inputContactObj.uiObjects.resource)+'"]');
						resource.addClass('r_error');
						resource.removeClass('r_operate');
						setTimeout(function(){
							inputContactObj.uiObjects.contact.animate({opacity: 1}, 1000);
							inputContactObj.uiObjects.contact.draggable('option', 'disabled', false);
							resource.removeClass('r_error');
							resource.droppable('option', 'disabled', false);
						},1200);
					}
					else
						operationPerformed('PUT_ALL', inputContactObj, {uid:inputContactObj.uid, isInterResource:true});
				},1000);
			}
			else
			{
				console.log("Error: [deleteVcardFromCollection: 'DELETE "+put_href+"']: code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
				switch(objAJAXRequest.status)
				{
					case 401:
						show_editor_message('out','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp401),globalHideInfoMessageAfter);
						break;
					case 403:
						show_editor_message('out','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp403),globalHideInfoMessageAfter);
						break;
					case 405:
						show_editor_message('out','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp405),globalHideInfoMessageAfter);
						break;
					case 408:
						show_editor_message('out','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp408),globalHideInfoMessageAfter);
						break;
					case 410:
						show_editor_message('out','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp410),globalHideInfoMessageAfter);
						break;
					case 500:
						show_editor_message('out','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttp500),globalHideInfoMessageAfter);
						break;
					default:
						show_editor_message('out','message_error',errBegin.replace('%%',localization[globalInterfaceLanguage].errHttpCommon.replace('%%',objAJAXRequest.status)),globalHideInfoMessageAfter);
						break;
				}
			}

			// presunut do jednej funkcie s tym co je nizsie pri success
			$('#ResourceCardDAVListOverlay').fadeOut(globalEditorFadeAnimation);
			$('#ABListOverlay').fadeOut(globalEditorFadeAnimation);
			$('#ABContactOverlay').fadeOut(globalEditorFadeAnimation,function(){globalRefAddContact.prop('disabled',false);});

			unlockCollection(inputContactObj);
		},
		success: function(data,textStatus,xml)
		{
			if(recursiveMode=='IRM_DELETE_LAST')
			{
				// success icon
				setTimeout(function(){
					// move is successfull we can remove the contact (no sync required)
					globalAddressbookList.removeContact(inputContactObj.uid,true,true);
					if(typeof inputContactObj.finalContactUID=='undefined')
					{
						var resource=$('#ResourceCardDAVList').find('div[data-id="'+jqueryEscapeSelector(inputContactObj.uiObjects.resource)+'"]');
						resource.addClass('r_success');
						resource.removeClass('r_operate');
						setTimeout(function(){
							resource.removeClass('r_success');
							resource.droppable('option', 'disabled', false);
						},1200);
					}
					else
						operationPerformed('PUT_ALL', inputContactObj, {newUID:inputContactObj.newUID,uid:inputContactObj.uid, isInterResource:true});
				},1000);
			}
			else
			{
				// success message
				var duration=show_editor_message('out','message_success',localization[globalInterfaceLanguage].succContactDeleted,globalHideInfoMessageAfter);
				var prevConSearchHide = false;
				if(typeof globalAddressbookList.contacts_hash[inputContactObj.uid]!='undefined'&&(globalAddressbookList.contacts_hash[inputContactObj.uid].search_hide||!globalAddressbookList.contacts_hash[inputContactObj.uid].show))
					prevConSearchHide = true;
				globalAddressbookList.removeContact(inputContactObj.uid,true);
	// XXX check this
	//						globalAddressbookList.applyABFilter(inputFilterUID, globalRefABListTable.find('[data-id="'+jqueryEscapeSelector(inputContactObj.uid)+'"]').hasClass('search_hide') ? true : false);
				globalAddressbookList.applyABFilter(dataGetChecked('#ResourceCardDAVList'), prevConSearchHide ? true : false);
				var animation=400;
				// after the success message show the next automatically selected contact
				setTimeout(function(){
					// presunut do jednej funkcie s tym co je vyssie
					$('#ResourceCardDAVListOverlay').fadeOut(animation);
					$('#ABListOverlay').fadeOut(animation);
					$('#ABContactOverlay').fadeOut(animation,function(){globalRefAddContact.prop('disabled',false);});
				},duration-animation);
			}
			unlockCollection(inputContactObj);

			// if the destination addressbook is already loaded re-sync it (to get the moved contact immediately)
			if(recursiveMode=='IRM_DELETE_LAST')
			{
				var collection=globalResourceCardDAVList.getCollectionByUID(inputContactObj.newUid);
				CardDAVnetLoadCollection(collection, false, false, null, 0, null, false);
			}
		}
	});
}

/*
iCloud auth (without this we have no access to iCloud photos)

function netiCloudAuth(inputResource)
{
	var re=new RegExp('^(https?://)([^/]+)','i');
	var tmp=inputResource.href.match(re);

	var uidBase=tmp[1]+inputResource.userAuth.userName+'@'+tmp[2];

	$.ajax({
		type: 'POST',
		url: 'https://setup.icloud.com/setup/ws/1/login',
		cache: false,
		crossDomain: (typeof inputResource.crossDomain=='undefined' ? true : inputResource.crossDomain),
		xhrFields: {
			withCredentials: (typeof inputResource.withCredentials=='undefined' ? false : inputResource.withCredentials)
		},
		timeout: inputResource.timeOut,
		error: function(objAJAXRequest, strError){
			console.log("Error: [netiCloudAuth: '"+uidBase+"'] code: '"+objAJAXRequest.status+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
			return false;
		},
		beforeSend: function(req) {
			req.setRequestHeader('Origin', 'https://www.icloud.com');
		},
		contentType: 'text/plain',
		processData: false,
		data: '{"apple_id":"'+inputResource.userAuth.userName+'","password":"'+inputResource.userAuth.userPassword+'","extended_login":false}',
		complete: function(xml, textStatus)
		{
			// iCloud cookie not set (no photo access)
			if(textStatus!='success')
				return false;
		}
	});
}
*/

/*
Permissions (from the DAViCal wiki):
	all - aggregate of all permissions
	read - grants basic read access to the principal or collection.
	unlock - grants access to write content (i.e. update data) to the collection, or collections of the principal.
	read-acl - grants access to read ACLs on the collection, or collections of the principal.
	read-current-user-privilege-set - grants access to read the current user's privileges on the collection, or collections of the write-acl - grants access to writing ACLs on the collection, or collections of the principal.
	write - aggregate of write-properties, write-content, bind & unbind
	write-properties - Grants access to update properties of the principal or collection. In DAViCal, when granted to a user principal, this will only grant access to update properties of the principal's collections and not the user principal itself. When granted to a group or resource principal this will grant access to update the principal properties.
	write-content - grants access to write content (i.e. update data) to the collection, or collections of the principal.
	bind - grants access to creating resources in the collection, or in collections of the principal. Created resources may be new collections, although it is an error to create collections within calendar collections.
	unbind - grants access to deleting resources (including collections) from the collection, or from collections of the principal.
*/

function CardDAVnetLoadCollection(inputCollection, forceLoad, forceLoadNextContact, innerOperationData, recursiveIterator, collections, recursiveMode)
{
	if(recursiveMode)
	{
		if(recursiveIterator>=collections.length)
		{
			if(!globalCardDAVInitLoad && isCardDAVLoaded)
				loadNextApplication(false);

			return false;
		}

		if((collections.length>0 && inputCollection.uid==undefined) || (!inputCollection.newlyAdded && !inputCollection.someChanged && !globalCardDAVInitLoad))
		{
			recursiveIterator++;
			CardDAVnetLoadCollection(collections[recursiveIterator], forceLoad, forceLoadNextContact, innerOperationData, recursiveIterator, collections, recursiveMode);

			if(globalCardDAVInitLoad)
				$('#ResourceCardDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');

			return false;
		}
	}

	if(inputCollection.forceSyncPROPFIND!=undefined && inputCollection.forceSyncPROPFIND==true)
		var requestText='<?xml version="1.0" encoding="utf-8"?><D:propfind xmlns:D="DAV:"><D:prop><D:getcontenttype/><D:getetag/></D:prop></D:propfind>';
	else	// if inputCollection.forceSyncPROPFIND is undefined or false
		var requestText='<?xml version="1.0" encoding="utf-8"?><D:sync-collection xmlns:D="DAV:"><D:prop><D:getcontenttype/><D:getetag/></D:prop><D:sync-level>1</D:sync-level>'+(forceLoad==true || inputCollection.syncToken==undefined || inputCollection.syncToken=='' || inputCollection.newlyAdded ? '<D:sync-token/>' : '<D:sync-token>'+inputCollection.syncToken+'</D:sync-token>')+'</D:sync-collection>';

	if(!inputCollection.makeLoaded)
	{
		if(globalSettingsSaving!='addressbook')
			CardDAVUpdateMainLoader(inputCollection);
		recursiveIterator++;
		CardDAVnetLoadCollection(collections[recursiveIterator], forceLoad, forceLoadNextContact, innerOperationData, recursiveIterator, collections, recursiveMode);
		return false;
	}

	function ajaxComplete(data, textStatus, xml)
	{
		$('[data-id="'+inputCollection.uid+'"]').removeClass('er_error');
		if($('#ResourceCardDAVList').find('.er_error').length==0 && isEachResourceLoaded())
			$('#intCarddav').find('.int_error').css('display','none');
		var vcardList=new Array();
		$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode(new RegExp('^(sync-)?response$')).each(
			function(index, element)
			{
				var hrefVal=$(element).children().filterNsNode('href').text();
				var etagVal=$(element).children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('getetag').text();

				var allowContent=false;
				// checkContentType is undocumented but useful if somebody needs to disable it (wrong server response, etc.)
				if(inputCollection.checkContentType!=false)
				{
					var contenttypeVal=$(element).children().filterNsNode('propstat').children().filterNsNode('prop').children().filterNsNode('getcontenttype').text();
					if(contenttypeVal!=undefined)
					{
						contenttypeValArr=contenttypeVal.toLowerCase().replace(RegExp(' ','g'),'').split(';');
						if(contenttypeValArr.indexOf('text/vcard')!=-1 || contenttypeValArr.indexOf('text/x-vcard')!=-1)
							allowContent=true;
					}
				}
				else
					allowContent=true;

				var result=$(element).find('*').filterNsNode('status').text();	// note for 404 there is no propstat!
				var match=false;
				if(hrefVal[hrefVal.length-1]!='/')	/* Google CardDAV problem with resource URL if content type checking is disabled */
				{
					if(allowContent==true)
					{
						if(result.match(RegExp('200 OK$')))	// HTTP OK
						{
							vcardList[vcardList.length]={etag: etagVal, href: hrefVal};
							match=true;
						}
					}
					if(!match && result.match(RegExp('404 Not Found$')))	// HTTP Not Found
						vcardList[vcardList.length]={deleted: true, etag: etagVal, href: hrefVal};
				}
			}
		);

		// store the syncToken
		if(inputCollection.forceSyncPROPFIND==undefined || inputCollection.forceSyncPROPFIND==false)
			inputCollection.syncToken=$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('sync-token').text();

		// we must call the netLoadAddressbook even if we get empty vcardList
		netLoadAddressbook(inputCollection, vcardList, (inputCollection.forceSyncPROPFIND==undefined || inputCollection.forceSyncPROPFIND==false ? true : false), forceLoadNextContact, innerOperationData, forceLoad, recursiveIterator, collections, recursiveMode);
		if(typeof globalParallelAjaxCallCardDAVEnabled!='undefined' && globalParallelAjaxCallCardDAVEnabled!=null && globalParallelAjaxCallCardDAVEnabled && recursiveMode && collections.length>0)
		{
			recursiveIterator++;
			CardDAVnetLoadCollection(collections[recursiveIterator], forceLoad, forceLoadNextContact, innerOperationData, recursiveIterator, collections, true);
		}
	}
	// first try to process the cached data (if cached results are available in the "auth module" response)
	var tmpCache;
	if(globalXMLCache!=null && (tmpCache=globalXMLCache.children('carddavsynccollection[request_url="'+jqueryEscapeSelector(inputCollection.url+inputCollection.href)+'"]').remove()).length)
	{
		if(typeof globalDebug!='undefined' && globalDebug instanceof Array && globalDebug.indexOf('cache')!=-1)
			console.log('DBG Cache OK: '+arguments.callee.name+' url: \''+inputCollection.url+inputCollection.href+'\': saved one request!');
		ajaxComplete('', 'success', {responseXML: tmpCache});
	}
	else
	{
		if(typeof globalDebug!='undefined' && globalDebug instanceof Array && globalDebug.indexOf('cache')!=-1)
			console.log('DBG Cache ERROR: '+arguments.callee.name+' url: \''+inputCollection.url+inputCollection.href+'\': spend one request!');
		$.ajax({
			type: (inputCollection.forceSyncPROPFIND!=undefined && inputCollection.forceSyncPROPFIND==true ? 'PROPFIND' : 'REPORT'),
			url: inputCollection.url+inputCollection.href,
			cache: false,
			crossDomain: (typeof inputCollection.crossDomain=='undefined' ? true : inputCollection.crossDomain),
			xhrFields: {
				withCredentials: (typeof inputCollection.withCredentials=='undefined' ? false : inputCollection.withCredentials)
			},
			timeout: inputCollection.timeOut,
			beforeSend: function(req) {
				if(globalSettings.usejqueryauth.value!=true && inputCollection.userAuth.userName!='' && inputCollection.userAuth.userPassword!='')
					req.setRequestHeader('Authorization', basicAuth(inputCollection.userAuth.userName,inputCollection.userAuth.userPassword));
				req.setRequestHeader('X-client', globalXClientHeader);
				req.setRequestHeader('Depth', '1');
				/* XXX - System display:none changes */
				if(isAvaible('Settings') && $('#SystemSettings').css('visibility')=='visible' && $('.resourceSettings_item_selected').attr('data-type')=='setting_group_password')
				{
					if(recursiveMode && collections.length>0)
					{
						recursiveIterator++;
						CardDAVnetLoadCollection(collections[recursiveIterator], forceLoad, forceLoadNextContact, innerOperationData, recursiveIterator, collections, recursiveMode);
					}
					return false;
				}
			},
			username: (globalSettings.usejqueryauth.value==true ? inputCollection.userAuth.userName : null),
			password: (globalSettings.usejqueryauth.value==true ? inputCollection.userAuth.userPassword : null),
			contentType: 'text/xml; charset=utf-8',
			processData: true,
			data: requestText,
			dataType: 'xml',
			error: function(objAJAXRequest, strError){
				// POROVNAT S TYM AKO JE TO V CALDAVZAP
				$('#intCarddav').find('.int_error').css('display','block');
				if((objAJAXRequest.status==400 /* bad request */ || objAJAXRequest.status==403 /* forbidden (for stupid servers) */ || objAJAXRequest.status==501 /* unimplemented */) && inputCollection.forceSyncPROPFIND!=true /* prevent recursion */)
				{
					collections[recursiveIterator].forceSyncPROPFIND=true;
					CardDAVnetLoadCollection(collections[recursiveIterator], forceLoad, forceLoadNextContact, innerOperationData, recursiveIterator, collections, recursiveMode);
					return true;
				}
				else
				{
					globalAddressbookNumberCount--;
					if(globalCardDAVInitLoad || globalSettingsSaving!='')
						CardDAVUpdateMainLoader(inputCollection);
					if(recursiveMode && collections.length>0)
					{
						recursiveIterator++;
						CardDAVnetLoadCollection(collections[recursiveIterator], forceLoad, forceLoadNextContact, innerOperationData, recursiveIterator, collections, recursiveMode);
					}
					$('#ResourceCardDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
					$('[data-id="'+inputCollection.uid+'"]').addClass('er_error');
					inputCollection.syncToken = inputCollection.oldSyncToken;
					console.log("Error: [CardDAVnetLoadCollection: '"+(inputCollection.forceSyncPROPFIND!=undefined && inputCollection.forceSyncPROPFIND==true ? 'PROPFIND' : 'REPORT')+" "+inputCollection.url+inputCollection.href+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
					return false;
				}
			},
			success: ajaxComplete
		});
	}
}

function netLoadAddressbook(inputCollection, vcardList, syncReportSupport, forceLoadNext, innerOperationData, forceLoadCollection, recursiveIterator, collections, recursiveMode)
{
	var vcardChangedList=new Array();
	var resultTimestamp=new Date().getTime();
	if(syncReportSupport==true)
	{
		for(var i=0;i<vcardList.length;i++)
			if(vcardList[i].deleted!=undefined && vcardList[i].deleted==true)
				globalAddressbookList.removeContact(inputCollection.uid+vcardList[i].href.replace(RegExp('.*/',''),''),true);
			else
				vcardChangedList[vcardChangedList.length]=vcardList[i].href;
	}
	else	// no sync-collection REPORT supported (we need to delete contacts by timestamp comparison)
	{
		for(var i=0;i<vcardList.length;i++)
		{
			var uid=inputCollection.uid+vcardList[i].href.replace(RegExp('.*/',''),'');
			if(!globalAddressbookList.checkAndTouchIfExists(uid,vcardList[i].etag,resultTimestamp))
				vcardChangedList[vcardChangedList.length]=vcardList[i].href;
		}
		globalAddressbookList.removeOldContacts(inputCollection.uid, resultTimestamp);
	}

	// not loaded vCards from the last multiget (if any)
	if(inputCollection.pastUnloaded!=undefined && inputCollection.pastUnloaded.length>0)
		vcardChangedList=vcardChangedList.concat(inputCollection.pastUnloaded).sort().unique();

	// if nothing is changed on the server return
	if(vcardChangedList.length==0)
	{
		inputCollection.newlyAdded = false;
		inputCollection.someChanged = false;
		inputCollection.oldSyncToken = inputCollection.syncToken;
		if(forceLoadCollection)
			$('#ResourceCardDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
		if(innerOperationData!=null)
		{
			if(innerOperationData.call=='operationPerform')
				operationPerform(innerOperationData.args.performOperation, innerOperationData.args.contactObj, innerOperationData.args.filterUID);
			else if(innerOperationData.call=='operationPerformed')
				operationPerformed(innerOperationData.args.mode, innerOperationData.args.contactObj, innerOperationData.args.loadContact);
		}
		CardDAVUpdateMainLoader(inputCollection);

		if((typeof globalParallelAjaxCallCardDAVEnabled=='undefined' || globalParallelAjaxCallCardDAVEnabled==null || !globalParallelAjaxCallCardDAVEnabled) && recursiveMode && collections.length>0)
		{
			recursiveIterator++;
			CardDAVnetLoadCollection(collections[recursiveIterator], forceLoadCollection, false, null, recursiveIterator, collections, recursiveMode);
		}
		return true;
	}
	var multigetData='<?xml version="1.0" encoding="utf-8"?><R:addressbook-multiget xmlns:D="DAV:" xmlns:R="urn:ietf:params:xml:ns:carddav"><D:prop><D:getetag/><R:address-data/></D:prop><D:href>'+vcardChangedList.join('</D:href><D:href>')+'</D:href></R:addressbook-multiget>';
	function ajaxComplete(data, textStatus, xml)
	{
		var isXMLEmpty=true;
		inputCollection.newlyAdded = false;
		inputCollection.someChanged = false;
		inputCollection.oldSyncToken = inputCollection.syncToken;
		$('[data-id="'+inputCollection.uid+'"]').removeClass('er_error');
		if($('#ResourceCardDAVList').find('.er_error').length==0 && isEachResourceLoaded())
			$('#intCarddav').find('.int_error').css('display','none');
		inputCollection.pastUnloaded=[];	// all vCards loaded
		$(xml.responseXML).children().filterNsNode('multistatus').children().filterNsNode('response').each(
			function(index, element)
			{
				var tmpRef=$(element).children();
				var tmpPropstatRef=tmpRef.filterNsNode('propstat').children();
				var tmpPropstatPropRef=tmpPropstatRef.filterNsNode('prop').children();

				if(tmpPropstatRef.filterNsNode('status').text().match(RegExp('200 OK$')))	// HTTP OK
				{
					isXMLEmpty=false;
					var etag=tmpPropstatPropRef.filterNsNode('getetag').text();
					var uid=inputCollection.uid+tmpRef.filterNsNode('href').text().replace(RegExp('.*/',''),'');

					var vcard_raw=tmpPropstatPropRef.filterNsNode('address-data').text();

					if(vcard_raw!='')
					{
						var result=basicRFCFixesAndCleanup(vcard_raw);
						var normalized=false;
						if(typeof globalCardDavPreNormalize!='undefined' && globalCardDavPreNormalize==true) /* pre-normalization is disabled by default */
						{
							result.vcard=normalizeVcard(additionalRFCFixes(result.vcard));
							normalized=true;
						}
					}
					else
						return true;	// continue for jQuery

					// check the vCard validity here
					// ...
					// ...
					globalAddressbookList.insertContact({timestamp: resultTimestamp, accountUID: inputCollection.accountUID, uid: uid, etag: etag, color: inputCollection.color, vcard: result.vcard, categories: result.categories, normalized: normalized}, (innerOperationData!=null && ((innerOperationData.call=='operationPerformed' && innerOperationData.args.mode=='DELETE_FROM_GROUP_LAST') || innerOperationData.args.forceReload==true)), !isCardDAVLoaded);	// if inner operation is DELETE_FROM_GROUP_LAST we force reload the contact
				}
			}
		);
		CardDAVUpdateMainLoader(inputCollection);
		// update the active search
		if(globalQs!=null)
			globalQs.cache();
		if(typeof globalContactExtSyncEnd=='function')
			globalContactExtSyncEnd();

		// if no "concurrent" write in progress we need to update the group filter
		if(globalRefAddContact.attr('data-url')==inputCollection.uid && inputCollection.filterUID!=undefined)
// XXX check this
//					globalAddressbookList.applyABFilter(inputCollection.filterUID, forceLoadNext);
			globalAddressbookList.applyABFilter(dataGetChecked('#ResourceCardDAVList'), forceLoadNext);

		if(innerOperationData!=null)
		{
			if(innerOperationData.call=='operationPerform')
				operationPerform(innerOperationData.args.performOperation, innerOperationData.args.contactObj, innerOperationData.args.filterUID);
			else if(innerOperationData.call=='operationPerformed')
				operationPerformed(innerOperationData.args.mode, innerOperationData.args.contactObj, innerOperationData.args.loadContact);
		}

		if(isXMLEmpty)
			$('#ResourceCardDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');

		if((typeof globalParallelAjaxCallCardDAVEnabled=='undefined' || globalParallelAjaxCallCardDAVEnabled==null || !globalParallelAjaxCallCardDAVEnabled) && recursiveMode && collections.length>0)
		{
			recursiveIterator++;
			CardDAVnetLoadCollection(collections[recursiveIterator], forceLoadCollection, false, null, recursiveIterator, collections, recursiveMode);
		}
		return true;
	}
	// first try to process the cached data (if cached results are available in the "auth module" response)
	var tmpCache;
	if(globalXMLCache!=null && (tmpCache=globalXMLCache.children('carddavaddressbookmultiget[request_url="'+jqueryEscapeSelector(inputCollection.url+inputCollection.href)+'"]').remove()).length)
	{
		if(typeof globalDebug!='undefined' && globalDebug instanceof Array && globalDebug.indexOf('cache')!=-1)
			console.log('DBG Cache OK: '+arguments.callee.name+' url: \''+inputCollection.url+inputCollection.href+'\': saved one request!');
		ajaxComplete('', 'success', {responseXML: tmpCache});
	}
	else
	{
		if(typeof globalDebug!='undefined' && globalDebug instanceof Array && globalDebug.indexOf('cache')!=-1)
			console.log('DBG Cache ERROR: '+arguments.callee.name+' url: \''+inputCollection.url+inputCollection.href+'\': spend one request!');
		$.ajax({
			type: 'REPORT',
			url: inputCollection.url+inputCollection.href,
			cache: false,
			crossDomain: (typeof inputCollection.crossDomain=='undefined' ? true : inputCollection.crossDomain),
			xhrFields: {
				withCredentials: (typeof inputCollection.withCredentials=='undefined' ? false : inputCollection.withCredentials)
			},
			timeout: inputCollection.timeOut,
			beforeSend: function(req) {
				if(globalSettings.usejqueryauth.value!=true && inputCollection.userAuth.userName!='' && inputCollection.userAuth.userPassword!='')
					req.setRequestHeader('Authorization', basicAuth(inputCollection.userAuth.userName,inputCollection.userAuth.userPassword));
				req.setRequestHeader('X-client', globalXClientHeader);
				req.setRequestHeader('Depth', '0');
			},
			username: (globalSettings.usejqueryauth.value==true ? inputCollection.userAuth.userName : null),
			password: (globalSettings.usejqueryauth.value==true ? inputCollection.userAuth.userPassword : null),
			contentType: 'text/xml; charset=utf-8',
			processData: true,
			data: multigetData,
			dataType: 'xml',
			error: function(objAJAXRequest, strError){
				// unable to load vCards, try to load them next time
				inputCollection.pastUnloaded=vcardChangedList;
				$('[data-id="'+inputCollection.uid+'"]').addClass('er_error');
				$('#intCarddav').find('.int_error').css('display','block');
				inputCollection.syncToken = inputCollection.oldSyncToken;
				console.log("Error: [netLoadAddressbook: 'REPORT "+inputCollection.url+inputCollection.href+"'] code: '"+objAJAXRequest.status+"' status: '"+strError+"'"+(objAJAXRequest.status==0 ? ' - see https://www.inf-it.com/'+globalAppName.toLowerCase()+'/readme.txt (cross-domain setup)' : ''));
				$('#ResourceCardDAVList [data-id="'+inputCollection.uid+'"]').removeClass('r_operate');
				if(innerOperationData!=null && innerOperationData.call=='operationPerform')
				{
					show_editor_message('out','message_error',localization[globalInterfaceLanguage].errUnableSync,globalHideInfoMessageAfter);

					// error icon
					setTimeout(function(){
						var resource=$('#ResourceCardDAVList').find('div[data-id="'+jqueryEscapeSelector(inputContactObj.uiObjects.resource)+'"]');
						resource.addClass('r_error');
						resource.removeClass('r_operate');
						setTimeout(function(){
							inputContactObj.uiObjects.contact.animate({opacity: 1}, 1000);
							inputContactObj.uiObjects.contact.draggable('option', 'disabled', false);
							resource.removeClass('r_error');
							resource.droppable('option', 'disabled', false);
						},globalHideInfoMessageAfter);
					},globalHideInfoMessageAfter/10);
					$('#ABContactOverlay').fadeOut(globalEditorFadeAnimation,function(){globalRefAddContact.prop('disabled',false);});
				}

				if(globalCardDAVInitLoad || globalSettingsSaving!='')
					CardDAVUpdateMainLoader(inputCollection);

				if((typeof globalParallelAjaxCallCardDAVEnabled=='undefined' || globalParallelAjaxCallCardDAVEnabled==null || !globalParallelAjaxCallCardDAVEnabled) && recursiveMode && collections.length>0)
				{
					recursiveIterator++;
					CardDAVnetLoadCollection(collections[recursiveIterator], forceLoadCollection, false, null, recursiveIterator, collections, recursiveMode);
				}
				return false;
			},
			success: ajaxComplete
		});
	}
}