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 
/*
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/>.
*/

// AddressbookList Class
function AddressbookList()
{
	this.contacts=new Array();
	this.contacts_hash=new Object();
	this.contacts_hash_uidattr=new Object();
	this.companies=new Array();
	this.companies_hash=new Object();
	this.companies_hash_uidattr=new Object();
	this.vcard_groups=new Object();
	this.contact_categories=new Object();
	this.contact_companies=new Object();
	this.contactLoaded=null;
	this.contactToReload=null;
	this.vcardGroupLoaded=null;

	this.reset=function()
	{
		this.contacts.splice(0,this.contacts.length);
		this.contacts_hash=new Object();
		this.contacts_hash_uidattr=new Object();
		this.companies.splice(0,this.companies.length);
		this.companies_hash=new Object();
		this.companies_hash_uidattr=new Object();
		this.vcard_groups=new Object();	// these are not removed from the interface (it's OK)
		this.contact_categories=new Object();
		this.contact_companies=new Object();
		this.contactLoaded=null;
		this.contactToReload=null;
		this.vcardGroupLoaded=null;
	};

	this.getNewUID=function()
	{
		// we count with uniqueness of generated hash string
		var newUID=null;
		newUID=generateUID();
		return newUID;
	};

	this.getLoadedContactUID=function()
	{
		if(this.contactLoaded!=null)
			return this.contactLoaded.uid;
		else
			return '';
	};

	this.getSortKey=function(inputContact, inputSettings, inputMode)	// inputMode (0=sort, 1=display)
	{
		var vcard_element=('\r\n'+inputContact.vcard).match(vCard.pre['contentline_N']);
		if(vcard_element===null || vcard_element.length!==1)	// if the N attribute is not present exactly once, vCard is considered invalid
			return false;

		var sortKeyCompanyPart='';
		if(typeof (getCRMSortKey)== 'function' && inputMode==0)
		{
			sortKeyCompanyPart=getCRMSortKey(inputContact);
			if(inputContact.isCompany!=undefined && inputContact.isCompany)
				return sortKeyCompanyPart;	// for company contact we can return here
		}
		else if(typeof globalGroupContactsByCompanies!='undefined' && globalGroupContactsByCompanies==true)
		{
			var sortKeyCompanyPart='\u0009';
			var vcard_orgname=('\r\n'+inputContact.vcard).match(vCard.pre['contentline_ORG']);
			if(vcard_orgname!=null && vcard_orgname.length>0)	// if more than one ORG is present, use the first one
			{
				// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
				var parsed=vcard_orgname[0].match(vCard.pre['contentline_parse']);
				var parsed_value=vcardSplitValue(parsed[4], ';');

				sortKeyCompanyPart=parsed_value[0]+'\u0009'+(parsed_value[1]!=undefined ? parsed_value[1] : '')+'\u0009';

				if(inputMode==0 && inputContact.isCompany!=undefined && inputContact.isCompany)
					return sortKeyCompanyPart;	// for company contact we can return here
			}
		}

		var tmp = [];
		var isGroup = this.isContactGroup(inputContact.vcard);
		/* backward compatibility for stupid users (remove it in future) */
		if(typeof inputSettings==='string')
			tmp = inputSettings.replace(RegExp(',','g'), ', ').split(',');
		else if($.isArray(inputSettings))	/* new configuration options (arrays) */
			tmp = inputSettings.slice();	// copy the configuration array

		// display settings for non-group contacts need some flattening
		if(inputMode===1 && !isGroup) {
			tmp = $.map(tmp, function(el) {
				if($.isPlainObject(el.value)) {
					return el.value;
				}
				else {
					return [el.value];
				}

			});
		}

		// now flatten the array completely to a company / personal version
		tmp = $.map(tmp, function(el) {
			if($.isPlainObject(el)) {
				if(inputContact.isCompany && el.hasOwnProperty('company')) {
					return [el.company];
				}
				else if(!inputContact.isCompany && el.hasOwnProperty('personal')) {
					return [el.personal];
				}

				return [];
			}

			return [el];
		});

		for(var i=0; i<tmp.length; i++) {
			tmp[i] = getContactDataColumn(inputContact, tmp[i]);
		}

		sort_value = tmp.join(' ').trim();

		if(sort_value==='' && isGroup)	// if we didn't get a proper sort value for group contacts, use FN
		{
			var vcard_element2=('\r\n'+inputContact.vcard).match(vCard.pre['contentline_FN']);
			if(vcard_element2!=null && vcard_element2.length==1)	// if the FN attribute is not present exactly once, vCard is considered invalid
			{
				// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
				var parsed=vcard_element2[0].match(vCard.pre['contentline_parse']);
				var sort_value=parsed[4];
			}
		}

		return (inputMode===0 ? sortKeyCompanyPart+sort_value : sort_value);
	};

	this.isContactGroup=function(inputVcard)
	{
		var vcard_element=null;
		if((vcard_element=('\r\n'+inputVcard).match(vCard.pre['X-ADDRESSBOOKSERVER-KIND']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			var parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
			if(parsed[4].toLowerCase()=='group')
				return true;
		}
		return false;
	};

	this.getMyContactGroups=function(inputUid)
	{
		if(this.contacts_hash[inputUid]!=undefined)
		{
			var myContactGroups=new Array();

			if((vcard_element=this.contacts_hash[inputUid].vcard.match(vCard.pre['contentline_UID']))!=null)
			{
				// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
				parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

				for(var j=0;j<this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')].length;j++)
				{
					if(this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')][j].vcard.match(RegExp('\r\nX-ADDRESSBOOKSERVER-MEMBER:urn:uuid:'+parsed[4]+'\r\n','mi')))
						myContactGroups[myContactGroups.length]=this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')][j].uid;
				}
			}
			return myContactGroups;
		}
		else
			return null;
	};

	this.getRemoveMeFromContactGroups=function(inputUid, inputContactGroupsUidArr)
	{
		if(this.contacts_hash[inputUid]!=undefined)
		{
			var changedContactGroups=new Array();

			if((vcard_element=this.contacts_hash[inputUid].vcard.match(vCard.pre['contentline_UID']))!=null)
			{
				// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
				parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

				for(var j=0;j<this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')].length;j++)
				{
					if(inputContactGroupsUidArr!=null)
					{
						var skipThis=true;
						for(var k=0;k<inputContactGroupsUidArr.length;k++)
							if(inputContactGroupsUidArr[k]==this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')][j].uid)
							{
								skipThis=false;
								break;
							}

						if(skipThis==true)
							continue;
					}

					var vcard=this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')][j].vcard;

					var changedVcard=null;
					if(vcard!=(changedVcard=vcard.replaceAll('\r\nX-ADDRESSBOOKSERVER-MEMBER:urn:uuid:'+parsed[4]+'\r\n','\r\n')))
					{
						// update the revision in the group vcard
						var d = new Date();
						utc=d.getUTCFullYear()+(d.getUTCMonth()+1<10 ? '0':'')+(d.getUTCMonth()+1)+(d.getUTCDate()<10 ? '0':'')+d.getUTCDate()+'T'+(d.getUTCHours()<10 ? '0':'')+d.getUTCHours()+(d.getUTCMinutes()<10 ? '0':'')+d.getUTCMinutes()+(d.getUTCSeconds()<10 ? '0':'')+d.getUTCSeconds()+'Z';
						changedVcard=changedVcard.replace(RegExp('\r\nREV:.*\r\n','mi'),'\r\nREV:'+utc+'\r\n');

						// "copy" of the original object
						changedContactGroups[changedContactGroups.length]=$.extend({},this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')][j]);
						// new modified vcard group
						changedContactGroups[changedContactGroups.length-1].vcard=changedVcard;
					}
				}
			}
			return changedContactGroups;
		}
		else
			return null;
	};

	this.getAddMeToContactGroups=function(inputContactObj, inputContactGroupsUidArr)
	{
		if(!(inputContactGroupsUidArr instanceof Array))
			inputContactGroupsUidArr=[inputContactGroupsUidArr];

		vcard_element=inputContactObj.vcard.match(vCard.pre['contentline_UID']);

		// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
		parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

		var changedContactGroups=new Array();

		for(var j=0;j<this.vcard_groups[inputContactObj.uid.replace(RegExp('/[^/]*$',''),'/')].length;j++)
			for(var k=0;k<inputContactGroupsUidArr.length;k++)
				if(this.vcard_groups[inputContactObj.uid.replace(RegExp('/[^/]*$',''),'/')][j].uid==inputContactGroupsUidArr[k])
				{
					// if the uuid is already a member we remove it from contact-group to avoid duplicate membership
					var vcard=this.vcard_groups[inputContactObj.uid.replace(RegExp('/[^/]*$',''),'/')][j].vcard.replaceAll('\r\nX-ADDRESSBOOKSERVER-MEMBER:urn:uuid:'+parsed[4]+'\r\n','\r\n');
					var tmp=vcard.split('\r\n');
					tmp.splice(tmp.length-2,0,'X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:'+parsed[4]);
					var changedVcard=tmp.join('\r\n');

					var d = new Date();
					utc=d.getUTCFullYear()+(d.getUTCMonth()+1<10 ? '0':'')+(d.getUTCMonth()+1)+(d.getUTCDate()<10 ? '0':'')+d.getUTCDate()+'T'+(d.getUTCHours()<10 ? '0':'')+d.getUTCHours()+(d.getUTCMinutes()<10 ? '0':'')+d.getUTCMinutes()+(d.getUTCSeconds()<10 ? '0':'')+d.getUTCSeconds()+'Z';
					changedVcard=changedVcard.replace(RegExp('\r\nREV:.*\r\n','mi'),'\r\nREV:'+utc+'\r\n');

					// "copy" of the original object
					changedContactGroups[changedContactGroups.length]=$.extend({},this.vcard_groups[inputContactObj.uid.replace(RegExp('/[^/]*$',''),'/')][j]);
					// new modified vcard group	(normalisation is added to fix basic errors in invalid vCard)
					changedContactGroups[changedContactGroups.length-1].vcard=normalizeVcard(changedVcard);
				}
		return changedContactGroups;
	};

	// Contact group list is not sorted, instead "insert sort" is performed
	this.insertContactGroup=function(inputContact, forceReload, forceReinsert)
	{
		if((inputContact.sortkey=this.getSortKey(inputContact, [['{LastName}']], 0))===false || (inputContact.displayvalue=this.getSortKey(inputContact, [['{LastName}']], 1))===false)
			return false;	//invalid vcard

		var makeActive=null;
		var makeChecked=null;

		// do not insert entry with duplicate UID
		for(var i=0;i<this.vcard_groups[inputContact.uid.replace(RegExp('/[^/]*$',''),'/')].length;i++)
			if(this.vcard_groups[inputContact.uid.replace(RegExp('/[^/]*$',''),'/')][i].uid==inputContact.uid)
			{
				if(forceReinsert==false && this.vcard_groups[inputContact.uid.replace(RegExp('/[^/]*$',''),'/')][i].displayvalue==inputContact.displayvalue)
				{
					this.vcard_groups[inputContact.uid.replace(RegExp('/[^/]*$',''),'/')][i]=inputContact;
					return 0;
				}
				else
				{
					if($('#ResourceCardDAVList').find('[data-id='+jqueryEscapeSelector(inputContact.uid)+']').hasClass('resourceCardDAV_selected'))
						makeActive=inputContact.uid;

					if(dataGetChecked('#ResourceCardDAVList').indexOf(inputContact.uid)!=-1 || dataGetChecked('#ResourceCardDAVList').indexOf(inputContact.uid.replace(RegExp('/[^/]*$',''),'/'))!=-1)
						makeChecked=inputContact.uid;

					// the contact group name is changed and must be moved to correct place (we first remove it and then reinsert)
					this.removeContactGroup(inputContact.uid, false);
					break;
				}
			}

		// find the index where to insert the new contact group

		var insertIndex=this.vcard_groups[inputContact.uid.replace(RegExp('/[^/]*$',''),'/')].length;
		for(var i=0;i<this.vcard_groups[inputContact.uid.replace(RegExp('/[^/]*$',''),'/')].length;i++)
			if(this.vcard_groups[inputContact.uid.replace(RegExp('/[^/]*$',''),'/')][i].sortkey.customCompare(inputContact.sortkey,globalSortAlphabet,1,false)==1)
			{
				insertIndex=i;
				break;
			}

		// insert the contact group
		this.vcard_groups[inputContact.uid.replace(RegExp('/[^/]*$',''),'/')].splice(insertIndex, 0, inputContact);

		// insert the contact group to interface
		var newElement=globalTranslCardDAVListItem.find('.contact_group').find('.group').clone();
		// the onclick event is disabled until the last drag&drop operation is completed
		newElement.click(function(e){
			if(globalAddressbookCollectionsLoading)
				return true;
			if(e.shiftKey) {
				var uid = $(this).attr('data-id');
				$('#ResourceCardDAVList').find('.resourceCardDAV:visible').children('input[type="checkbox"]').each(function(){
					var currentUid = $(this).attr('data-id');
					$(this).prop({'checked':false, 'indeterminate':false}).attr('data-ind', 'true');
					collectionChBoxClick(this, '#ResourceCardDAVList', '.resourceCardDAV_header', '.resourceCardDAV', '.contact_group', false);
				});
				var checkbox = $(this).children('input[type="checkbox"]');
				checkbox.prop({'checked':true, 'indeterminate':false});
				groupChBoxClick(checkbox.get(0), '#ResourceCardDAVList', '.resourceCardDAV_header', '.resourceCardDAV', '.contact_group', false);
				globalAddressbookList.applyABFilter([uid], false);
			}
			globalResourceCardDAVList.resourceOrGroupClick(this.getAttribute('data-id'));
		});
		newElement.attr('data-id',inputContact.uid);
		newElement.find('.resourceCardDAVGroupColor').css('background-color', inputContact.color);

		// note: we need to check the group if the parent collection is checked (and we need to use .attr() instead of .prop() because the element is not in the DOM)
		var tmp_check=false;
		if($('#ResourceCardDAVList').find('[data-id='+jqueryEscapeSelector(inputContact.uid.replace(RegExp('[^/]*$',''),''))+']').find('input[type=checkbox]').prop('checked')==true && $('#ResourceCardDAVList').find('[data-id='+jqueryEscapeSelector(inputContact.uid.replace(RegExp('[^/]*$',''),''))+']').find('input[type=checkbox]').prop('indeterminate')==false)
			tmp_check=true;
		newElement.find('input[type=checkbox]').attr('checked', tmp_check).attr({'data-id': inputContact.uid, 'onclick': 'var evt=arguments[0]; evt.stopPropagation(); if($(this).parents(\':eq(2)\').find(\'[class^="r_"]\').length>0) return false; else globalAddressbookList.applyABFilter(groupChBoxClick(this, \'#ResourceCardDAVList\', \'.resourceCardDAV_header\', \'.resourceCardDAV\', \'.contact_group\', true), false);'});

		newElement.append(vcardUnescapeValue(inputContact.displayvalue));
		newElement.css('display','');
		if($('#ResourceCardDAVList').find('[data-id="'+jqueryEscapeSelector(inputContact.uid.replace(RegExp('/[^/]*$',''),'/'))+'"]').next('.contact_group').find('[data-id="'+jqueryEscapeSelector(inputContact.uid)+'"]').length==0)
			$('#ResourceCardDAVList').find('[data-id="'+jqueryEscapeSelector(inputContact.uid.replace(RegExp('/[^/]*$',''),'/'))+'"]').next('.contact_group').children().eq(insertIndex).after(newElement);

		// make the area droppable if the collection is not read-only
		if(globalResourceCardDAVList.getCollectionPrivByUID(inputContact.uid.replace(RegExp('[^/]*$',''),''))==false && (typeof globalDisableDragAndDrop=='undefined' || globalDisableDragAndDrop!=true))
			$('#ResourceCardDAVList').find('[data-id="'+jqueryEscapeSelector(inputContact.uid.replace(RegExp('[^/]*$',''),''))+'"]').parent().find('.contact_group').children().eq(insertIndex+1).droppable({
				accept: '.ablist_item',
				tolerance: 'pointer',
				hoverClass: 'group_dropped_to',
				drop: function(event, ui){
					// animate the clone of the dropped (draggable) element
					var tmp=ui.helper.clone();
					tmp.appendTo('body')
					.animate({opacity: 0, color: 'transparent', height: 0, width: 0, fontSize: 0, lineHeight: 0, paddingLeft: 0, paddingRight: 0},750,function(){tmp.remove()});

					// disallow to drag the original dropped element until the processing is finished
					ui.draggable.draggable('option', 'disabled', true);

					// animate the original dropped element
					ui.draggable.animate({opacity: 0.3}, 750);

					// disallow to drop any new element until the processing is finished
					$(this).droppable('option', 'disabled', true);

					// show the loader icon
					$(this).addClass('r_operate');

					var tmp2=globalAddressbookList.getContactByUID(ui.draggable.attr('data-id'));
					tmp2.addToContactGroupUID='';
					tmp2.removeToContactGroupUID=new Array();
					tmp2.addToContactGroupUID=$(this).attr('data-id');
					tmp2.uiObjects={contact: ui.draggable, resource: $(this).attr('data-id')};

					lockAndPerformToCollection(tmp2, globalRefAddContact.attr('data-filter-url'), 'ADD_TO_GROUP');
				}
			});

		// if no new makeActive but forceReload is true then reload the current contact group
		if(makeActive==null && forceReload==true)
			makeActive=globalRefAddContact.attr('data-filter-url');

		// load the contact group if it was selected
		if(makeActive!=null)
		{
			$('#ResourceCardDAVList').find('.resourceCardDAV_item').find('.resourceCardDAV_selected').removeClass('resourceCardDAV_selected');
			$('#ResourceCardDAVList').find('[data-id='+jqueryEscapeSelector(makeActive.replace(RegExp('[^/]*$',''),''))+']').addClass('resourceCardDAV_selected');
			$('#ResourceCardDAVList').find('[data-id='+jqueryEscapeSelector(makeActive)+']').addClass('resourceCardDAV_selected');
		}
		if(makeChecked!=null)
		{
			$('#ResourceCardDAVList').find('[data-id='+jqueryEscapeSelector(makeChecked)+']').find('input[type=checkbox]').prop('checked',true);
			this.applyABFilter(dataGetChecked('#ResourceCardDAVList'), false);
		}
	};

	this.removeContactGroup=function(inputUid, loadNext)
	{
		for(var i=this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')].length-1;i>=0;i--)
			if(this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')][i].uid==inputUid)
			{
				var uidRemoved=this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')][i].uid;
				var item=$('#ResourceCardDAVList').find('[data-id^="'+jqueryEscapeSelector(this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')][i].uid)+'"]');

				// remove the item
				item.remove();
				this.vcard_groups[inputUid.replace(RegExp('/[^/]*$',''),'/')].splice(i,1);

// vcardGroupLoaded bolo zrusene, pozriet co s tym
				if(loadNext && this.vcardGroupLoaded!=null && this.vcardGroupLoaded.uid==inputUid)
				{
					this.vcardGroupLoaded=null;

					// set the whole collection as active
					var tmp=uidRemoved.match(RegExp('(^.*/)'),'');
// XXX it is no longer needed
//					globalResourceCardDAVList.loadAddressbookByUID(tmp[1]);
				}
				break;
			}
	};

	// hide/show contacts in the interface according to contactGroupOrResourceUid or search filter in the interface (contactGroupOrResourceUid==false)
	this.applyABFilter=function(contactGroupOrResourceUid, inputForceLoadNext)
	{
		if(globalCardDAVInitLoad)
			return false;

// XXX docasne, potom dame prec
		if(!(contactGroupOrResourceUid instanceof Array))
			return false;

		var vcardGroupOrCollection=[];
		for(var i=0;i<contactGroupOrResourceUid.length;i++)
		{
			if(contactGroupOrResourceUid[i][contactGroupOrResourceUid[i].length-1]=='/')
				vcardGroupOrCollection.push({uid: contactGroupOrResourceUid[i]});
			else		// remember the loaded contact group
			{
				// required only if we want so support collection unloading

				for(var j=0;j<this.vcard_groups[contactGroupOrResourceUid[i].replace(RegExp('/[^/]*$',''),'/')].length;j++)
					if(this.vcard_groups[contactGroupOrResourceUid[i].replace(RegExp('/[^/]*$',''),'/')][j].uid==contactGroupOrResourceUid[i])
					{
// vcardGroupLoaded bolo zrusene, pozriet co s tym
//						vcardGroupOrCollection=this.vcardGroupLoaded=this.vcard_groups[contactGroupOrResourceUid.replace(RegExp('/[^/]*$',''),'/')][j];
						vcardGroupOrCollection.push(this.vcard_groups[contactGroupOrResourceUid[i].replace(RegExp('/[^/]*$',''),'/')][j]);
					}
			}
		}

		var previousActiveIndex=null;	// used to find the nearest contact and set it as selected

		if(this.contactLoaded!=null)
			var previousActiveUID=this.contactLoaded.uid;

		// set all contacts as inactive
		for(var i=0;i<this.contacts.length;i++)
			if(this.contacts[i].headerOnly==undefined)
			{
				if(this.contacts[i].uid==previousActiveUID)
					previousActiveIndex=i;

				this.contacts_hash[this.contacts[i].uid].show=false
				this.contacts[i].show=false;	// XXX zmenit s5 na false
			}

		for(var i=0;i<vcardGroupOrCollection.length;i++)
		{
			if((vcard=vcardGroupOrCollection[i].vcard)==undefined)	// collection
			{
				for(var j=0;j<this.contacts.length;j++)
					if(this.contacts[j].headerOnly==undefined)
					{
							if(this.contacts[j].uid.indexOf(vcardGroupOrCollection[i].uid)==0 && this.contacts[j].search_hide==false)
							{
								this.contacts[j].show=true;
								this.contacts_hash[this.contacts[j].uid].show=true
							}
					}
			}
			else	// vcard group
			{
				var vcardUIDList=new Array();
				// get the members of the array group
				while((vcard_element=vcard.match(vCard.pre['X-ADDRESSBOOKSERVER-MEMBER']))!=null)
				{
					// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
					parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
					vcardUIDList[vcardUIDList.length]=parsed[4].replace('urn:uuid:','');
					// remove the processed parameter
					vcard=vcard.replace(vcard_element[0],'\r\n');
				}

				// update the contacts' "show" attribute
				for(var j=0;j<vcardUIDList.length;j++)
					for(var k=0;k<this.contacts.length;k++)
						if(this.contacts[k].headerOnly==undefined)
						{
							vcard_element=this.contacts[k].vcard.match(vCard.pre['contentline_UID']);

							if(vcard_element!=null)	// only for contacts with UID (non-RFC contacts not contains UID)
							{
								// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
								parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

								if(vcardUIDList[j]==parsed[4] && this.contacts[k].search_hide==false)
								{
									this.contacts[k].show=true;
									this.contacts_hash[this.contacts[k].uid].show=true
								}
							}
						}
			}
		}

		var lastActive=null;
		var prevHeader=null;
		var lastContactForHeader=this.contacts.length-1;
		// performance
		var tmpListRefChildren=globalRefABListTable.children();
		// init displayed columns text length cache
		var columnLengths = [];
		for(var i=0; i<getDataColumnCount(); i++) {
			columnLengths.push([]);
		}

		// the show attribute is now set, we can make changes in the interface
		for(var i=this.contacts.length-1;i>=0;i--)
		{
			if(this.contacts[i].headerOnly==undefined)
			{
				// find the previous header index
				for(var j=i-1;j>=0;j--)
					if(this.contacts[j].headerOnly!=undefined && this.contacts[j].headerOnly==true)
					{
						prevHeader=j;
						break;
					}

				// performance
				var tmpListRefChildren_i=tmpListRefChildren.eq(i);
				var tmpListRefChildren_prev=tmpListRefChildren.eq(prevHeader);

				var coll_tmp=this.contacts[i].uid.match(RegExp('^(https?://)([^@/]+(?:@[^@/]+)?)@([^/]+)(.*/)([^/]+/)([^/]*)','i'));
				var collection_uid=coll_tmp[1]+coll_tmp[2]+'@'+coll_tmp[3]+coll_tmp[4]+coll_tmp[5];
				var coll_color=globalResourceCardDAVList.getCollectionByUID(collection_uid).color;
				this.contacts[i].color = coll_color;
				tmpListRefChildren_i.find('.ablist_item_color').css('background-color', coll_color);
				switch(this.contacts[i].show)
				{
					case false:
						tmpListRefChildren_i.css('display','none');
						if(tmpListRefChildren_i.hasClass('ablist_item_selected'))
							lastActive=i;

						var hideHeader=true;
						for(j=prevHeader+1;j<=lastContactForHeader;j++)
							if(this.contacts[j].show==true)
							{
								hideHeader=false;
								break;
							}

						if(hideHeader)
							tmpListRefChildren_prev.css('display','none');

						break;
					case true:
						// set the contact header to visible
						tmpListRefChildren_prev.css('display','');

						// set the contact to visible
						tmpListRefChildren_i.css('display','');

						// save column text length into cache
						tmpListRefChildren_i.children().slice(globalFixedContactDataColumnsCount).each(function(ind) {
							columnLengths[ind].push($(this).text().length);
						});

						break;
					default:
						break;
				}
			}
			else
				lastContactForHeader=i-1;
		}

		setDataColumnsWidth(columnLengths);

		// the previously loaded contact is hidden or not exists we need to select a new one
		if(inputForceLoadNext==true || $('#vCardEditor').attr('data-editor-state')!='edit' && (lastActive!=null || globalRefABListTable.children('.ablist_item_selected').length==0))
		{
			var nextCandidateToLoad=null;
			// get the nearest candidate to load
			//  if we can go forward
			if(this.contactToReload!=null)
				nextCandidateToLoad=this.contactToReload;
			else
			{
				for(j=(previousActiveIndex==null ? 0 : previousActiveIndex);j<this.contacts.length;j++)
					if((this.contacts[j].headerOnly==undefined || this.contacts[j].headerOnly==false) && (this.contacts[j].show==true))
					{
						nextCandidateToLoad=this.contacts[j];
						break;
					}
				//  we must go backwards
				if(nextCandidateToLoad==null && previousActiveIndex!=null)
				{
					for(j=previousActiveIndex-1;j>=0;j--)
						if((this.contacts[j].headerOnly==undefined || this.contacts[j].headerOnly==false) && (this.contacts[j].show==true))
						{
							nextCandidateToLoad=this.contacts[j];
							break;
						}
				}
			}
			// make the contact active
			globalRefABListTable.children('.ablist_item.ablist_item_selected').removeClass('ablist_item_selected');
			if(nextCandidateToLoad!=null)
			{
				// prevent re-loading the contact if it is already loaded
				if((this.contactToReload!=null||$('#vCardEditor').attr('data-url')!=nextCandidateToLoad.uid) && !globalCardDAVInitLoad)
				{
					this.loadContactByUID(nextCandidateToLoad.uid);
				}
				else	// because the collection click unselects the active contact we need to re-select it
				{
					// Make the selected contact active
					globalRefABListTable.children('.ablist_item.ablist_item_selected').removeClass('ablist_item_selected');
					globalRefABListTable.children('[data-id='+jqueryEscapeSelector(nextCandidateToLoad.uid)+']').addClass('ablist_item_selected');
				}
				// move scrollbar to ensure that the contact is visible in the interface
				if((selected_contact=globalRefABListTable.children('.ablist_item_selected')).length==1)
					globalRefABList.scrollTop(globalRefABList.scrollTop()+selected_contact.offset().top-globalRefABList.offset().top-globalRefABList.height()*globalKBNavigationPaddingRate);
			}
			else
			{
				this.contactLoaded=null;
				$('#ABContactColor').css('background-color', '');
				$('#ABContact').html('');
			}
		}
		if(this.contactToReload!=null&& (selected_contact=globalRefABListTable.find('[data-id="'+this.contactToReload.uid+'"]')).length==1)
		{
			selected_contact.addClass('ablist_item_selected');
			globalRefABList.scrollTop(globalRefABList.scrollTop()+selected_contact.offset().top-globalRefABList.offset().top-globalRefABList.height()*globalKBNavigationPaddingRate);

		}
	}

	this.getABCategories=function(returnSorted)
	{
		var categoriesArr=[];

		for(var category in this.contact_categories)
			categoriesArr.push(category);

		if(returnSorted)
			return categoriesArr.sort(function(x,y){return x.customCompare(y,globalSortAlphabet,1,false)});
		else
			return categoriesArr;
	}

	this.getABCompanies=function(returnSorted)
	{
		var companiesArr=[];

		for(var company in this.contact_companies)
			companiesArr.push(company);

		if(returnSorted)
			return companiesArr.sort(function(x,y){return x.customCompare(y,globalSortAlphabet,1,false)});
		else
			return companiesArr;
	}

	this.getABCompanyDepartments=function(inputCompany)
	{
		var departmentsArr=[];

		if(this.contact_companies[inputCompany]!=undefined)
			departmentsArr=this.contact_companies[inputCompany].departments.slice();

		return departmentsArr.sort(function(x,y){return x.customCompare(y,globalSortAlphabet,1,false)});
	}

	// Contact list is not sorted, instead "insert sort" is performed
	this.insertContact=function(inputContact, forceReload, disableDOM)
	{
		// Apple "group" vCards
		if(this.isContactGroup(inputContact.vcard))
			return this.insertContactGroup(inputContact, forceReload, false);

		// check for company contact
		inputContact.isCompany=false;
		var vcard_element=inputContact.vcard.match(vCard.pre['X-ABShowAs']);
		if(vcard_element!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
			if(vcardUnescapeValue(parsed[4]).match(RegExp('^company$','i')))
				inputContact.isCompany=true;
		}

		// check for company contact
		if((typeof globalContactsExtVcardToData)=='function')
		{
			inputContact.isLegacy=false;
			var vcard_element=inputContact.vcard.match(RegExp('\r\nX-IsLegacy:.*\r\n', 'mi'));
			if(vcard_element!=null)
			{
				// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
				var parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
				if(vcardUnescapeValue(parsed[4]).match(RegExp('^(?:yes|1|true)$', 'i')))
					inputContact.isLegacy=true;
			}
		}

		// contact UID attr
		var vcard_element=inputContact.vcard.match(vCard.pre['contentline_UID']);
		if(vcard_element!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
			inputContact.uidattr=vcardUnescapeValue(parsed[4]);
		}
		else	// UID attr is REQUIRED
			return false;	// invalud vcard

		var this_destination=this.contacts;
		var this_destination_hash=this.contacts_hash;
		var this_destination_hash_uidattr=this.contacts_hash_uidattr;

		// search plugin requirement
		inputContact.search_hide=false;

		// CATEGORIES suggestion
		var categoriesArr=(inputContact.categories=='' ? [] : vcardSplitValue(inputContact.categories,','));
		var allCategoriesArr=this.getABCategories(false);

		// The search funcionality uses this ASCII value (you can add additional data here)

		// ORG attribute
		var tmp=inputContact.vcard;
		var orgArr=[];
		var depArr=[];
		var tmpCurrentCompany='';
		var tmpCurrentDepartment='';
		while((vcard_element=tmp.match(vCard.pre['contentline_ORG']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			var parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
			var parsed_valArr=vcardSplitValue(parsed[4], ';');

			if(isDataColumnDefined('COMPANY')) {
				setContactDataColumn(inputContact, 'COMPANY', vcardUnescapeValue(parsed_valArr[0]));
			}

			if(isDataColumnDefined('DEPARTMENT')) {
				setContactDataColumn(inputContact, 'DEPARTMENT', vcardUnescapeValue(parsed_valArr[1]));
			}

			tmpCurrentCompany=(parsed_valArr[0]==undefined || parsed_valArr[0]=='' ? '' : parsed_valArr[0]);
			tmpCurrentDepartment=(parsed_valArr[1]==undefined || parsed_valArr[1]=='' ? '' : parsed_valArr[1]);

			if(tmpCurrentCompany!='')
				orgArr[orgArr.length]=vcardUnescapeValue(tmpCurrentCompany);

			if(tmpCurrentDepartment)
				depArr[depArr.length]=vcardUnescapeValue(tmpCurrentDepartment);

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}
		var allOrgArr=this.getABCompanies(false);

		// N attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_N']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			var parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
			var parsed_valArr=vcardSplitValue(parsed[4],';');

			if(isDataColumnDefined('LASTNAME')) {
				setContactDataColumn(inputContact, 'LASTNAME', vcardUnescapeValue(parsed_valArr[0]));
			}

			if(isDataColumnDefined('FIRSTNAME')) {
				setContactDataColumn(inputContact, 'FIRSTNAME', vcardUnescapeValue(parsed_valArr[1]));
			}

			if(isDataColumnDefined('MIDDLENAME')) {
				setContactDataColumn(inputContact, 'MIDDLENAME', vcardUnescapeValue(parsed_valArr[2]));
			}

			if(isDataColumnDefined('PREFIX')) {
				setContactDataColumn(inputContact, 'PREFIX', vcardUnescapeValue(parsed_valArr[3]));
			}

			if(isDataColumnDefined('SUFFIX')) {
				setContactDataColumn(inputContact, 'SUFFIX', vcardUnescapeValue(parsed_valArr[4]));
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// NICKNAME attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_NICKNAME']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('NICKNAME')) {
				setContactDataColumn(inputContact, 'NICKNAME', parsed[4]);
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// X-PHONETIC-LAST-NAME attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_X-PHONETIC-LAST-NAME']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('PHONETICLASTNAME')) {
				setContactDataColumn(inputContact, 'PHONETICLASTNAME', parsed[4]);
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// X-PHONETIC-FIRST-NAME attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_X-PHONETIC-FIRST-NAME']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('PHONETICFIRSTNAME')) {
				setContactDataColumn(inputContact, 'PHONETICFIRSTNAME', parsed[4]);
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// BDAY attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_BDAY']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('BIRTHDAY')) {
				var bday = null;
				try {
					bday = $.datepicker.parseDate('yy-mm-dd', parsed[4]);
				}
				catch(e) {

				}

				if(bday) {
					setContactDataColumn(inputContact, 'BIRTHDAY', $.datepicker.formatDate(globalSettings.datepickerformat.value, bday));
				}
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// TITLE attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_TITLE']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('JOBTITLE')) {
				setContactDataColumn(inputContact, 'JOBTITLE', vcardUnescapeValue(parsed[4]));
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// NOTE attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_NOTE']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('NOTETEXT')) {
				setContactDataColumn(inputContact, 'NOTETEXT', vcardUnescapeValue(parsed[4]));
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// ADR attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_ADR']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			var parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
			var parsed_valArr=vcardSplitValue(parsed[4],';');

			if(isDataColumnDefined('ADDRESS')) {
				var unescapedArr = $.map(parsed_valArr, function(el) {
					if(el) {
						return vcardUnescapeValue(el);
					}
				});

				setContactDataColumn(inputContact, 'ADDRESS', unescapedArr.join(' '), {'TYPE': getParamsFromContentlineParse(tmp, parsed, 'TYPE', 'X-ABLabel', 'address_type_store_as')});
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// TEL attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_TEL']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('PHONE')) {
				setContactDataColumn(inputContact, 'PHONE', parsed[4], {'TYPE': getParamsFromContentlineParse(tmp, parsed, 'TYPE', 'X-ABLabel', 'phone_type_store_as')});
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// EMAIL attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_EMAIL']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('EMAIL')) {
				setContactDataColumn(inputContact, 'EMAIL', parsed[4], {'TYPE': getParamsFromContentlineParse(tmp, parsed, 'TYPE', 'X-ABLabel', 'email_type_store_as')});
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// URL attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_URL']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('URL')) {
				setContactDataColumn(inputContact, 'URL', parsed[4], {'TYPE': getParamsFromContentlineParse(tmp, parsed, 'TYPE', 'X-ABLabel', 'url_type_store_as')});
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// X-ABDATE attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_X-ABDATE']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('DATES')) {
				var abdate = null;
				try {
					abdate = $.datepicker.parseDate('yy-mm-dd', parsed[4]);
				}
				catch(e) {

				}

				if(abdate) {
					setContactDataColumn(inputContact, 'DATES', $.datepicker.formatDate(globalSettings.datepickerformat.value, abdate), {'TYPE': getParamsFromContentlineParse(tmp, parsed, 'TYPE', 'X-ABLabel', 'date_store_as')});
				}
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// X-ABRELATEDNAMES attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_X-ABRELATEDNAMES']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('RELATED')) {
				setContactDataColumn(inputContact, 'RELATED', parsed[4], {'TYPE': getParamsFromContentlineParse(tmp, parsed, 'TYPE', 'X-ABLabel', 'person_type_store_as')});
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// X-SOCIALPROFILE attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_X-SOCIALPROFILE']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);

			if(isDataColumnDefined('PROFILE')) {
				setContactDataColumn(inputContact, 'PROFILE', getParamsFromContentlineParse(tmp, parsed, 'X-USER', null, null, true)[0], {'TYPE': getParamsFromContentlineParse(tmp, parsed, 'TYPE', 'X-ABLabel', 'profile_type_store_as')});
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// IMPP attribute
		while((vcard_element=tmp.match(vCard.pre['contentline_IMPP']))!=null)
		{
			// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
			parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
			if(isDataColumnDefined('IM')) {
				setContactDataColumn(inputContact, 'IM', parsed[4].replace(vCard.pre['vcardToData_before_val'], ''), {
					'TYPE': getParamsFromContentlineParse(tmp, parsed, 'TYPE', 'X-ABLabel', 'im_type_store_as'),
					'SERVICE-TYPE': getParamsFromContentlineParse(tmp, parsed, 'X-SERVICE-TYPE', null, 'im_service_type_store_as')
				});
			}

			// remove the processed parameter
			tmp=tmp.replace(vcard_element[0],'\r\n');
		}

		// CATEGORIES attribute (preparsed)
		if(isDataColumnDefined('CATEGORIES')) {
			setContactDataColumn(inputContact, 'CATEGORIES', inputContact.categories.splitCustom(','));
		}

		if((inputContact.sortkey=this.getSortKey(inputContact, globalSettings.collectionsort.value || $.map(globalSettings.collectiondisplay.value, function(el) {if($.isPlainObject(el.value)) {return el.value;} else {return [el.value];}}), 0))===false || (inputContact.displayvalue=this.getSortKey(inputContact, globalSettings.collectiondisplay.value, 1))===false)
			return false;	//invalid vcard

		// if company headers are used add also the header to the searchvalue
		var companyHeader='';
		if(typeof globalGroupContactsByCompanies!='undefined' && globalGroupContactsByCompanies==true)
		{
			if(tmpCurrentCompany!='' || tmpCurrentDepartment!='')
			{
				if(typeof (getCRMSortKey)=='function')
					companyHeader=getCRMSortKey(inputContact);
				else
					companyHeader=tmpCurrentCompany+'\u0009'+tmpCurrentDepartment+'\u0009';
			}
		}

		inputContact.searchvalue=(companyHeader+inputContact.displayvalue).multiReplace(globalSearchTransformAlphabet);

		// CATEGORIES suggestion
		for(var i=0;i<allCategoriesArr.length;i++)	// if a contact is changed remove it from previous categories
			if(categoriesArr.indexOf(allCategoriesArr[i])==-1)
			{
				var index=this.contact_categories[allCategoriesArr[i]].indexOf(inputContact.uid);
				if(index!=-1)
				{
					this.contact_categories[allCategoriesArr[i]].splice(index,1);

					if(this.contact_categories[allCategoriesArr[i]].length==0)
						delete this.contact_categories[allCategoriesArr[i]];
				}
			}
		for(var i=0;i<categoriesArr.length;i++)	// add contact to it's categories
			this.contact_categories[categoriesArr[i]]=(this.contact_categories[categoriesArr[i]]==undefined ? [] : this.contact_categories[categoriesArr[i]]).concat(inputContact.uid).sort().unique();

		// ORG suggestion
		for(var i=0;i<allOrgArr.length;i++)	// if a contact is changed remove it from previous companies
			if(orgArr.indexOf(allOrgArr[i])==-1)
			{
				var index=this.contact_companies[allOrgArr[i]].uids.indexOf(inputContact.uid);
				if(index!=-1)
				{
					this.contact_companies[allOrgArr[i]].uids.splice(index,1);

					if(this.contact_companies[allOrgArr[i]].uids.length==0)
						delete this.contact_companies[allOrgArr[i]];
				}
			}

		for(var i=0;i<orgArr.length;i++)	// add contact to it's companies
			this.contact_companies[orgArr[i]]={uids: (this.contact_companies[orgArr[i]]==undefined ? [] : this.contact_companies[orgArr[i]].uids).concat(inputContact.uid).sort().unique(), departments: (this.contact_companies[orgArr[i]]==undefined ? [] : this.contact_companies[orgArr[i]].departments).concat(depArr).sort().unique()};

		var makeActive=null;

		// do not insert entry with duplicate UID
		if(this_destination_hash[inputContact.uid]!=undefined)
		{
			var beforeSortKeyChar='';
			if(typeof globalGroupContactsByCompanies!='undefined' && globalGroupContactsByCompanies==true && tmpCurrentCompany=='' && tmpCurrentDepartment=='')
				beforeSortKeyChar='\u0009';

			if(this_destination_hash[inputContact.uid].displayvalue==inputContact.displayvalue && this_destination_hash[inputContact.uid].sortkey==(beforeSortKeyChar+inputContact.sortkey) && this_destination_hash[inputContact.uid].isCompany==inputContact.isCompany && this_destination_hash[inputContact.uid].isLegacy==inputContact.isLegacy)
			{
				// we perform the normalization here, because we need to check whether the vCard is changed or not
				//  normalize the vCard when it's loaded first time
				if(inputContact.normalized==false)
				{
					inputContact.normalized=true;
					inputContact.vcard=normalizeVcard(additionalRFCFixes(inputContact.vcard));
				}
				this_destination_hash[inputContact.uid]=inputContact;
				this_destination_hash_uidattr[inputContact.uidattr]=inputContact;	// hash by UID attr

				// if the contact is loaded and the editor is in 'show' state, reload it
				if(this.contactLoaded!=null && this.contactLoaded.uid==inputContact.uid && this.contactLoaded.vcard!=inputContact.vcard && $('#vCardEditor').attr('data-editor-state')=='show')
				{
					this.loadContactByUID(inputContact.uid);
					show_editor_message('in', 'message_success', localization[globalInterfaceLanguage].contactConcurrentChange,globalHideInfoMessageAfter);
					return 0;
				}
				else	// we are editing the contact or it is not active
					return -1;
			}
			else
			{
				if(this.contactLoaded!=null && this.contactLoaded.uid==inputContact.uid && forceReload==true)
						makeActive=inputContact.uid;
				if($('#vCardEditor').attr('data-url')==inputContact.uid)
					this.contactToReload=this.contactLoaded;
				else
					this.contactToReload=null;
				// the contact name is changed and must be moved to correct place (we first remove it and then reinsert)
				this.removeContact(inputContact.uid,false);
			}
		}

		if(typeof globalGroupContactsByCompanies!='undefined' && globalGroupContactsByCompanies==true)
		{
			if(tmpCurrentCompany=='' && tmpCurrentDepartment=='')
			{
				headerValue=headerSortKey='\u0009';
				inputContact.sortkey='\u0009'+inputContact.sortkey;
			}
			else
			{
				headerValue=vcardUnescapeValue(tmpCurrentCompany)+(tmpCurrentDepartment=='' ? '' : ' ['+vcardUnescapeValue(tmpCurrentDepartment)+']');
				if(typeof (getCRMSortKey)== 'function')
					headerSortKey=getCRMSortKey(inputContact);
				else
					headerSortKey=tmpCurrentCompany+'\u0009'+tmpCurrentDepartment+'\u0009';
			}
		}
		else
		{
			var headerValue='';
			// key value for most common non-alphabet characters is defined as '#'
			if(inputContact.sortkey[0]!=undefined)
			{
				var unicodeValue=inputContact.sortkey.charCodeAt(0);
				if(unicodeValue<65 || (unicodeValue>90 && unicodeValue<97) || (unicodeValue>122 && unicodeValue<127))
				{
					headerValue='#';
					inputContact.sortkey='#'+inputContact.sortkey;
				}
				else
					headerValue=inputContact.sortkey.charAt(0).toUpperCase();
			}
			else
			{
				headerValue='#';
				inputContact.sortkey='#';
			}

			headerSortKey=headerValue;
		}

		// create the header
		var headerObject={headerOnly: true, sortkey: headerSortKey, displayvalue: headerValue};

		// find the index where to insert the new contact O(n*log(n))
		insertIndex=0;
		low=0;
		high=this_destination.length-1;
		if(this_destination.length>0)
			while(low<high)
			{
				insertIndex=low+Math.round((high-low)/2);
				result=(cmp_str=this_destination[insertIndex].sortkey).customCompare(inputContact.sortkey,globalSortAlphabet, 1, false);

				if(result==-1)
				{
					if(insertIndex+1==this_destination.length-1 && typeof this_destination[insertIndex+1]!='undefined' && (cmp_str=this_destination[insertIndex+1].sortkey).customCompare(inputContact.sortkey, globalSortAlphabet, 1, false)==-1)
					{
						insertIndex+=2;
						break;
					}
					else
						low=++insertIndex;
				}
				else if(result==1)
				{
					if((cmp_str=this_destination[insertIndex-1].sortkey).customCompare(inputContact.sortkey, globalSortAlphabet, 1, false)==-1)
						break;
					else
						high=--insertIndex;
				}
			}

		// check for header existence
		var headerMiss=1;
		for(var i=0;i<this_destination.length;i++)
			if(this_destination[i].headerOnly!=undefined && this_destination[i].headerOnly==true && this_destination[i].displayvalue==headerObject.displayvalue)
				{headerMiss=0; break;}

		// insert the header if not exists
		if(headerMiss)
			this_destination.splice(insertIndex,0,headerObject);
		// insert the contact
		this_destination.splice(insertIndex+headerMiss,0,inputContact);
		// insert reference to the contact into hash for much faster search by UID and UID attr
		this_destination_hash[inputContact.uid]=this_destination[insertIndex+headerMiss];
		this_destination_hash_uidattr[inputContact.uidattr]=this_destination[insertIndex+headerMiss];

		// DOM processing can be disabled for performance (then we use mass DOM operations)
		if(!disableDOM)
		{
			// insert header to interface if not exists
			if(headerMiss)
			{
				var newElement=globalOrigABListHeader.clone();
				newElement.children().text(headerObject.displayvalue);
				if(globalRefABListTable.children().eq(insertIndex).length==0)	// if a tbody is completely empty we cannot search using index
					globalRefABListTable.append(newElement);
				else
					globalRefABListTable.children().eq(insertIndex).before(newElement);
			}

			// insert the contact to interface
			var newElement=globalOrigABListItem.clone();
			if(typeof inputContact.isLegacy!='undefined' && inputContact.isLegacy)
				newElement.css('text-decoration','line-through');
			else
				newElement.css('text-decoration','none');

			newElement.attr('data-id', inputContact.uid);
			newElement.children('.ablist_item_color').css('background-color', inputContact.color);

			var columns = getContactDataColumns(inputContact.isCompany);
			for(var i=0; i<columns.length; i++) {
				$('<td>').text(getContactDataColumn(inputContact, columns[i])).appendTo(newElement);
			}

			newElement.click(function() {
				if($(this).hasClass('ablist_item_selected') || globalObjectLoading)
					return false;
				else
					globalAddressbookList.loadContactByUID(this.getAttribute('data-id'));
			});

			// set the company icon
			if(inputContact.isCompany==true)
				newElement.addClass('company');

			if(typeof globalDisableDragAndDrop=='undefined' || globalDisableDragAndDrop!=true)
				newElement.draggable({
					delay: 250,
					revert: 'invalid',
					scroll: false,
					opacity: 0.8,
					stack: '#SystemCardDavMATE',
					containment: '#SystemCardDavMATE',
					appendTo: 'body',
					start: function( event, ui ){
						// disallow on read-only collection
						if(globalResourceCardDAVList.getCollectionPrivByUID($(this).attr('data-id').replace(RegExp('[^/]*$'),''))==true)
							return false;
					},
					helper: function(){
						$('#ResourceCardDAVList').find('.resourceCardDAV.ui-droppable').droppable( 'option', 'accept', false);
						$('#ResourceCardDAVList').find('.group.ui-droppable').droppable( 'option', 'accept', false);

						$('#ResourceCardDAVList').find('.resourceCardDAV[data-id!='+jqueryEscapeSelector($(this).attr('data-id').replace(RegExp('[^/]+$'),''))+'].ui-droppable').droppable( 'option', 'accept', '.ablist_item');
						var myContactGroups=globalAddressbookList.getMyContactGroups($(this).attr('data-id'));
						$('#ResourceCardDAVList').find('.group[data-id^='+jqueryEscapeSelector($(this).attr('data-id').replace(RegExp('[^/]+$'),''))+'].ui-droppable').each(function(index, element){
							if(myContactGroups.indexOf($(element).attr('data-id'))==-1)
								$(element).droppable( 'option', 'accept', '.ablist_item');
						});

						var tmp=$(this).clone();
						tmp.addClass('ablist_item_dragged');
						// we cannot use .css() here, because we need to add !important (problem with Gecko based browsers)
						var tmp_style='max-width: '+$(this).outerWidth()+'px;';
						if($(this).css('background-image')!='none')
							tmp_style+='background-image: url(images/company_s_w.svg) !important;';
						tmp.attr('style', tmp_style);

						return tmp;
					}
				});

			globalRefABListTable.children().eq(insertIndex+headerMiss-1).after(newElement);

			if($('#vCardEditor').attr('data-editor-state')=='edit')
			{
				if((selected_contact=globalRefABListTable.children('.ablist_item_selected')).length==1)
					globalRefABList.scrollTop(globalRefABList.scrollTop()+selected_contact.offset().top-globalRefABList.offset().top-globalRefABList.height()*globalKBNavigationPaddingRate);
			}
// toto tu asi nahradit zavolanim trigger('click') co vyrazne sprehladni kod
// =>
			// load the updated contact (because we first deleted it, we need to set it active)
			if(makeActive!=null)
			{
				// make the contact active
				globalRefABListTable.children('.ablist_item.ablist_item_selected').removeClass('ablist_item_selected');
				globalRefABListTable.children().eq(insertIndex+headerMiss).addClass('ablist_item_selected');
				this.loadContactByUID(makeActive);
			}
		}
	}

	this.renderContacs=function()
	{
		var this_destination=this.contacts;
		var this_destination_hash=this.contacts_hash;

		var tmpResultObject=[];

		for(var i=0;i<this_destination.length;i++)
		{
			if(this_destination[i].headerOnly!=undefined && this_destination[i].headerOnly==true)
			{
				var newElement=globalOrigABListHeader.clone();
				newElement.children().text(this_destination[i].displayvalue);
			}
			else
			{
				// insert the contact to interface
				var newElement=globalOrigABListItem.clone();
				if(typeof this_destination[i].isLegacy!='undefined' && this_destination[i].isLegacy)
					newElement.css('text-decoration','line-through');
				else
					newElement.css('text-decoration','none');

				newElement.attr('data-id', this_destination[i].uid);
				newElement.find('.ablist_item_color').css('background-color', this_destination[i].color);

				var columns = getContactDataColumns(this_destination[i].isCompany);
				for(var j=0; j<columns.length; j++) {
					$('<td>').text(getContactDataColumn(this_destination[i], columns[j])).appendTo(newElement);
				}
				for(; j<getDataColumnCount(); j++) {
					$('<td>').appendTo(newElement);
				}

				newElement.click(function() {
					if($(this).hasClass('ablist_item_selected') || globalObjectLoading)
						return false;
					else
						globalAddressbookList.loadContactByUID(this.getAttribute('data-id'));
				});

				// set the company icon
				if(this_destination[i].isCompany==true)
					newElement.addClass('company');

				if(typeof globalDisableDragAndDrop=='undefined' || globalDisableDragAndDrop!=true)
					newElement.draggable({
						delay: 250,
						revert: 'invalid',
						scroll: false,
						opacity: 0.8,
						stack: '#SystemCardDavMATE',
						containment: '#SystemCardDavMATE',
						appendTo: 'body',
						start: function( event, ui ){
							// disallow on read-only collection
							if(globalResourceCardDAVList.getCollectionPrivByUID($(this).attr('data-id').replace(RegExp('[^/]*$'),''))==true)
								return false;
						},
						helper: function(){
							$('#ResourceCardDAVList').find('.resourceCardDAV.ui-droppable').droppable( 'option', 'accept', false);
							$('#ResourceCardDAVList').find('.group.ui-droppable').droppable( 'option', 'accept', false);

							$('#ResourceCardDAVList').find('.resourceCardDAV[data-id!='+jqueryEscapeSelector($(this).attr('data-id').replace(RegExp('[^/]+$'),''))+'].ui-droppable').droppable( 'option', 'accept', '.ablist_item');
							var myContactGroups=globalAddressbookList.getMyContactGroups($(this).attr('data-id'));
							$('#ResourceCardDAVList').find('.group[data-id^='+jqueryEscapeSelector($(this).attr('data-id').replace(RegExp('[^/]+$'),''))+'].ui-droppable').each(function(index, element){
								if(myContactGroups.indexOf($(element).attr('data-id'))==-1)
									$(element).droppable( 'option', 'accept', '.ablist_item');
							});

							var tmp=$(this).clone();
							tmp.addClass('ablist_item_dragged');
							// we cannot use .css() here, because we need to add !important (problem with Gecko based browsers)
							var tmp_style='max-width: '+$(this).outerWidth()+'px;';
							if($(this).css('background-image')!='none')
								tmp_style+='background-image: url(images/company_s_w.svg) !important;';
							tmp.attr('style', tmp_style);

							return tmp;
						}
					});
			}
			tmpResultObject.push(newElement);
		}

		globalRefABListTable.empty().append(tmpResultObject);
	}

	this.removeContact=function(inputUid, loadNext, isFromPUT)
	{
		if(!(inputUid instanceof Array))
			inputUid=[inputUid];
		var tmpRex=new RegExp('/[^/]*$','');

		// Apple "group" vCards
		for(var i=inputUid.length-1;i>=0;i--)
			for(var j=this.vcard_groups[inputUid[i].replace(tmpRex,'/')].length-1;j>=0;j--)
				if(inputUid.indexOf(this.vcard_groups[inputUid[i].replace(tmpRex,'/')][j].uid)!=-1)
					return this.removeContactGroup(inputUid[i], loadNext);

		for(var i=this.contacts.length-1;i>=0;i--)
			if(this.contacts[i]!=undefined&&inputUid.indexOf(this.contacts[i].uid)!=-1)
			{
				var inUID=this.contacts[i].uid;
				// CATEGORIES suggestion
				var categoriesArr=vcardSplitValue(this.contacts[i].categories,',');
				for(var j=0;j<categoriesArr.length;j++)
					if(this.contact_categories[categoriesArr[j]]!=undefined)
					{
						var index=this.contact_categories[categoriesArr[j]].indexOf(this.contacts[i].uid);
						if(index!=-1)
						{
							this.contact_categories[categoriesArr[j]].splice(index,1);

							if(this.contact_categories[categoriesArr[j]].length==0)
								delete this.contact_categories[categoriesArr[j]];
						}
					}

				// ORG suggestion
				var tmp=this.contacts[i].vcard;
				var orgArr=[];
				while((vcard_element=tmp.match(vCard.pre['contentline_ORG']))!=null)
				{
					// parsed (contentline_parse) = [1]->"group.", [2]->"name", [3]->";param;param", [4]->"value"
					parsed=vcard_element[0].match(vCard.pre['contentline_parse']);
					orgArr[orgArr.length]=vcardUnescapeValue(vcardSplitValue(parsed[4],';')[0]);

					// remove the processed parameter
					tmp=tmp.replace(vcard_element[0],'\r\n');
				}
				for(var j=0;j<orgArr.length;j++)
					if(this.contact_companies[orgArr[j]]!=undefined /* there is no suggestion for '' company */ && this.contact_companies[orgArr[j]].uids!=undefined)
					{
						var index=this.contact_companies[orgArr[j]].uids.indexOf(this.contacts[i].uid);
						if(index!=-1)
						{
							this.contact_companies[orgArr[j]].uids.splice(index,1);

							if(this.contact_companies[orgArr[j]].uids.length==0)
								delete this.contact_companies[orgArr[j]];
						}
					}

				var nextCandidateToLoad=null;
				var item=globalRefABListTable.find('[data-id^="'+jqueryEscapeSelector(this.contacts[i].uid)+'"]');

				// get the nearest candidate to load
				//  if we can go forward
				for(j=i+1;j<this.contacts.length;j++)
					if(this.contacts[j].headerOnly!=true && (typeof isFromPUT!='undefined' || this.contacts[j].show==true))
					{
						nextCandidateToLoad=this.contacts[j];
						break;
					}
				//  we must go backwards
				if(nextCandidateToLoad==null)
				{
					for(j=i-1;j>=0;j--)
						if(this.contacts[j].headerOnly!=true && this.contacts[j].show==true)
						{
							nextCandidateToLoad=this.contacts[j];
							break;
						}
				}

				// remove the item
				item.remove();
				this.contacts.splice(i,1);
				if(this.contacts_hash[inUID]!=undefined)
				{
					delete this.contacts_hash_uidattr[this.contacts_hash[inUID].uidattr];
					delete this.contacts_hash[inUID];
				}
				else if(this.companies_hash[inUID]!=undefined)
				{
					delete this.companies_hash_uidattr[this.contacts_hash[inUID].uidattr];
					delete this.companies_hash[inUID];
				}

				// remove the header if there is no more contact
				var removeHeader=true;
				var prevHeader=null;
				// find the previous header index
				for(var j=i-1;j>=0;j--)
					if(this.contacts[j].headerOnly!=undefined && this.contacts[j].headerOnly==true)
					{
						prevHeader=j;
						break;
					}

				// check for contact existence for the found header
				if((prevHeader+1)<this.contacts.length && (this.contacts[prevHeader+1].headerOnly==undefined || this.contacts[prevHeader+1].headerOnly!=true))
					removeHeader=false;

				// remove the header
				if(removeHeader==true)
				{
					globalRefABListTable.children().eq(prevHeader).remove();
					this.contacts.splice(prevHeader,1);
				}

				// hide header if there is no more visible contacts
				var hideHeader=true;
				for(j=prevHeader+1;j<this.contacts.length && (this.contacts[j].headerOnly==undefined || this.contacts[j].headerOnly!=true);j++)
					if(this.contacts[j].show==true)
					{
						hideHeader=false;
						break;
					}

				if(hideHeader)
					globalRefABListTable.children().eq(prevHeader).css('display','none');

				// update the active search
				if(globalQs!=null)
					globalQs.cache();

				// load next contact
				if(loadNext && this.contactLoaded!=null)
				{
					if(nextCandidateToLoad!=null)
						this.loadContactByUID(nextCandidateToLoad.uid);
					else
					{
						this.contactLoaded=null;
						$('#ABContactColor').css('background-color', '');
						$('#ABContact').html('');
					}
				}
			}
	}

	this.checkAndTouchIfExists=function(inputUID,inputEtag,inputTimestamp)
	{
		if(this.contacts_hash[inputUID]!=undefined)
		{
			this.contacts_hash[inputUID].timestamp=inputTimestamp;

			if(this.contacts_hash[inputUID].etag==inputEtag)
				return true;
			else
				return false;
		}
		else
			return false;
	}

	this.removeOldContacts=function(inputUidBase, inputTimestamp)
	{
		for(var i=this.contacts.length-1;i>=0;i--)
			if(this.contacts[i]!=undefined /* because the header can be deleted with the contact */ && this.contacts[i].timestamp!=undefined && this.contacts[i].uid.indexOf(inputUidBase)==0 && this.contacts[i].timestamp<inputTimestamp)
				this.removeContact(this.contacts[i].uid, true);
	}

	this.loadContactByUID=function(inputUID)
	{
		// find the inputUID contact
		if(this.contacts_hash[inputUID]!=undefined)
		{
			globalObjectLoading=true;	// temporary disable keyboard navigation

			// normalize the vCard when it's loaded first time
			if(this.contacts_hash[inputUID].normalized==false)
			{
				this.contacts_hash[inputUID].normalized=true;
				this.contacts_hash[inputUID].vcard=normalizeVcard(additionalRFCFixes(this.contacts_hash[inputUID].vcard));
			}

			var is_readonly=globalResourceCardDAVList.getCollectionPrivByUID(this.contacts_hash[inputUID].uid.replace(RegExp('[^/]*$'),''));
			var loadContact=this.contactLoaded=this.contacts_hash[inputUID];

//			CardDAVeditor_cleanup(false, this.contacts_hash[inputUID].isCompany);	// editor initialization

			if(vcardToData(loadContact, is_readonly, this.contacts_hash[inputUID].isCompany, 'hide', []))
				$('#EditorBox').fadeTo(0, 1, function(){	/* 0 => no animation */
					globalObjectLoading=false;	// re-enable keyboard navigation
				});
			else
			{
				$('#ABContactColor').css('background-color', '');
				$('#ABContact').empty();
				globalDisableAnimationMessageHiding='contactRfcNotCompliant';
				var tmpTime=show_editor_message('out','message_error', localization[globalInterfaceLanguage].contactRfcNotCompliant, globalHideInfoMessageAfter);
				setTimeout(function(){globalObjectLoading=false;}, tmpTime);	// re-enable keyboard navigation
			}
			// Make the selected contact active
			globalRefABListTable.children('.ablist_item.ablist_item_selected').removeClass('ablist_item_selected');
			globalRefABListTable.children('[data-id='+jqueryEscapeSelector(this.contacts_hash[inputUID].uid)+']').addClass('ablist_item_selected');
			this.contactToReload=null;
			if(globalRefABListTable.children('[data-id='+jqueryEscapeSelector(this.contacts_hash[inputUID].uid)+']:visible').length>0&&$('#ABInMessageEditBox').css('display')!='none')
			{
				animate_message('#ABInMessageEditBox', '#ABInMessageTextEditBox', 0, '-=');
				$('#ABInMessageEditBox').css('display','');

			}
			else if(globalRefABListTable.children('[data-id='+jqueryEscapeSelector(this.contacts_hash[inputUID].uid)+']:visible').length==0&&$('#ABInMessageEditBox').css('display')=='none')
			{
				this.contactToReload=this.contacts_hash[inputUID];
				globalDisableAnimationMessageHiding='errContactHidden';
				$('#ABInMessageEditBox').css('display','block');
				$('#ABInMessageTextEditBox').attr('class','message_success');
				$('#ABInMessageTextEditBox').text(localization[globalInterfaceLanguage][globalDisableAnimationMessageHiding]);
				animate_message('#ABInMessageEditBox', '#ABInMessageTextEditBox', globalHideInfoMessageAfter);
			}
			if($('#ResourceCardDAVListOverlay').is(':visible'))
			{
				if($('#ABContactOverlay').is(':visible'))
				{
					var animation = 400;
					var duration = globalHideInfoMessageAfter + 2*animation;
					setTimeout(function(){
						$('#ResourceCardDAVListOverlay').fadeOut(animation);
						$('#ABListOverlay').fadeOut(animation,function(){});
						$('#ABContactOverlay').fadeOut(animation,function(){globalRefAddContact.prop('disabled',false);});
					},duration-animation);
				}
				else
				{
					$('#ResourceCardDAVListOverlay').fadeOut(globalEditorFadeAnimation);
					$('#ABListOverlay').fadeOut(globalEditorFadeAnimation,function(){});
				}
			}
		}
		else
		{
			$('#ABContactColor').css('background-color', '');
			$('#ABContact').empty();
//			CardDAVeditor_cleanup(false, false);	// editor initialization
		}
		checkContactFormScrollBar();
	}

	this.loadContactByVcard=function(vcard, color, isCompany, inputEditorMode, inputEditorLockedEntries)
	{
// sem callback pre index.html a v pripade ak pridavame usera (nie firmu) pridat do vcard prislusny atribut
		if(typeof(globalContactsExtLoadByVcardBefore)=='function')
			vcard=globalContactsExtLoadByVcardBefore(vcard, isCompany);

		var loadContact=new Object();
		loadContact.vcard=vcard;
		loadContact.isCompany=isCompany;
		loadContact.color=color;

		globalObjectLoading=true;			// temporary disable keyboard navigation
		if(vcardToData(loadContact, false /* XXX check this */, isCompany, inputEditorMode, inputEditorLockedEntries))
			$('#EditorBox').fadeTo(0, 1, function(){	/* 0 => no animation */
				// append the UID of previous contact into "data-id" for "cancel" functionality
				$('#vCardEditor').find('[data-type="cancel"]').attr('data-id', globalAddressbookList.getLoadedContactUID());
				this.contactLoaded=null;	// do not do this earlier
				globalObjectLoading=false;	// re-enable keyboard navigation
			});
		else
		{
			// todo: replace with icon or text in the editor div
			globalDisableAnimationMessageHiding='contactRfcNotCompliant';
			show_editor_message('out', 'message_error', localization[globalInterfaceLanguage].contactRfcNotCompliant, globalHideInfoMessageAfter);
			this.contactLoaded=null;	// do not do this earlier
			globalObjectLoading=false;	// re-enable keyboard navigation
		}
		checkContactFormScrollBar();
	}

	// DONE
	this.getContactByUID=function(inputUID)
	{
		// find the inputUID contact
		if(this.contacts_hash[inputUID]!=undefined)
			return this.contacts_hash[inputUID];
		else
			return null;
	}

	// DONE
	this.getContactGroupByUID=function(inputUID)
	{
		var collectionUID=inputUID.replace(RegExp('[^/]*$'),'');
		for(var i=0;i<this.vcard_groups[collectionUID].length;i++)
		{
			if(this.vcard_groups[collectionUID][i].uid==inputUID)
				return this.vcard_groups[collectionUID][i];
		}
		return null;
	}
}