/**
 * 
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 * 
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 * 
 * Copyright (C) 2004-2010 Open-Xchange, Inc.
 * Mail: info@open-xchange.com 
 * 
 * @author Markus Wagner <markus.wagner@open-xchange.com>
 * 
 */

  ////////////////////
 //  Participants  //
////////////////////

/**
 * Constructor for the participants dialog
 * 
 * @param {String} attachpoint The id of the div where the big livegrid should be inserted
 * @param {function} cbFunction A callback function which is called when you close the participants search window
 * @param {boolean} showUser show or don't show users in the participants search window
 * @param {boolean} showGroup show or don't show groups in the participants search window
 * @param {boolean} showResource show or don't show resources in the participants search window
 * @param {boolean} showFolder enable od disable the possibility to switch the folder. When false is given, only internal user are shown
 * @param {String} title The title of the participants search window
 * @param {Number} id The id of the user which should be initial be inserted into participants
 */
 
function Participants(attachpoint, cbFunction, showUser, showGroup, showResource, showFolder, title, id, singleFolderSearch){
	/**
	 * @private
	 */
	this.attachpoint = attachpoint;
	/**
	 * @private
	 */
	this.setFullParticipants = true;
	/**
	 * @private
	 */
	this.selGroups = [];
	/**
	 * @private
	 */
	this.selContacts = [];
	/**
	 * @private
	 */
	this.selResources = [];
	/**
	 * @private
	 */
	this.internalStorage;
	/**
	 * @private
	 */
	this.showUser = showUser || true;
	/**
	* @private
	*/
	this.showGroup = showGroup || false;

	/**
	* @private
	*/
	this.showResource = showResource || false;
	/**
	* @private
	*/
	this.showFolder = showFolder || false;
	/**
	* @private
	*/
	this.cbFunction = cbFunction;
	/**
	* @private
	*/
	this.title = title || null;		
	/**
	* @private
	*/
	this.id = id || null;		
	/**
	 * @private
	 */
	this.internalStorage2 = new Storage(0, [], "", 0, 0,  null, 
			function(x){ 
				return x[0] + "." + x[1] + "." + x[8] || 0;
			}
	);
	/**
	 * @private
	 */
	this.selectedParticipants = new Array();
	/**
	 * @private
	 */
	this.selectionObject = new Selection();	
	/**
	 * @private
	 */
	this.selectedResource = new Array();
	/**
	 * @private
	 */
	this.participantsGridBig;
	/**
	 * @private
	 */
	this.enabled = false;
	/**
	 * @private
	 */
	this.userData;
	/**
	 * @private
	 */
	this.changedParticipants;
	/**
	 * @private
	 */
	this.contact2user = [];
	/**
	 * @private
	 */
	this.initalFilled;		
	/**
	 * @private
	 */

	this.selPartsStorage  = null;
	this.selRessStorage = null;
	this.groupMemberLiveGrid = null;
	this.groupResolution = new Object();
	
	this.bUserHead = false;
	this.participantsGridSmall;
	this.smallParticipantsInit = false;
	this.singleFolderSearch = singleFolderSearch || false;
	
	var treeVisible = false;
	
	this.getHTML();
	this.emptySearchText = _("Please enter your search");
	this.searchField=$("searchpattern_participants");
    this.searchpattern="";
    this.blurTimer;
	var Self = this;
	
	register("OX_Object_Add_Participant", function(){ Self.openAddParticipantsWindow(); });
	register("OX_Object_Add_Ressource", function(){ Self.openAddParticipantsWindow(); });	
	register("closeParticipantsWindowOK", function(){ if(Self.enabled) Self.closeParticipantsWindowOK(); });
	register("closeParticipantsWindowCancel", function(){ if(Self.enabled) Self.closeParticipantsWindowCancel(); });
	register("addToParticipantsList", function(){ if(Self.enabled) Self.addToParticipantsList(); });
	register("addToResourceList", function(){ if(Self.enabled) Self.addToResourceList(); });
	register("searchParticipants", function(){ if(Self.enabled) Self.searchParticipants(); });
	register("OX_Object_Participant_Delete", function(){ Self.deleteParticipants(); });
	
	register("delParticipantsList", function(){ Self.delSelParticipants(); });	
	register("delResourceList", function(){ Self.delSelRessources(); });		
	
	addOnClose($("floatingdivParticipants"), function() { 
		  if (Self.enabled) Self.closeParticipantsWindowCancel(); 
		});
	
	if(!this.showResource){
		$("selectedResourceTr").style.display = "none";
	}
	
    // remove dom events first
    if (Participants.inE) {
        removeDOMEvent(Self.searchField, "keypress", Participants.inE);
        removeDOMEvent(Self.searchField, "click", Participants.inE);
    }
    if (Participants.inB) {
        removeDOMEvent(Self.searchField, "blur", Participants.inB);
    }
	// wrapper functions for key and click events on search field
	Participants.inE = function(e) {
		if (Self.blurTimer != undefined) {
			clearTimeout(Self.blurTimer);
			delete(Self.blurTimer);
		}
		Self.searchParticipantsEnter(e, Self);
	}
    Participants.inB = function(e) {
        Self.blurTimer = setTimeout(function() { Self.searchParticipantsBlur(e, Self); },100);
    }
    // re-add dom events
	addDOMEvent(Self.searchField, "keypress", Participants.inE); 
    addDOMEvent(Self.searchField, "click", Participants.inE);
    addDOMEvent(Self.searchField, "blur", Participants.inB); 
}

function ParticipantsSmall(attachpoint, cbFunction, showUser, showGroup, showResource, showFolder, 
											title,id,bUserHead,bUserMember, singleFolderSearch){
	/**
	 * @private
	 */
	this.showUser = showUser || false;
	/**
	* @private
	*/
	this.showGroup = showGroup || false;
	/**
	* @private
	*/
	this.showResource = showResource || false;
	/**
	* @private
	*/
	this.showFolder = showFolder || false;
	/**
	 * @private
	 */
	this.attachpoint = attachpoint;
	/**
	 * @private
	 */
	this.setFullParticipants = false;
	/**
	 * @private
	 */
	this.selGroups = [];
	/**
	 * @private
	 */
	this.selContacts = [];
	/**
	 * @private
	 */
	this.selResources = [];
	/**
	 * @private
	 */
	this.internalStorage;
	/**
	 * @private
	 */
	this.internalStorage2 = new Storage(0, [], "", 0, 0,  null, 
			function(x){ 
				return x[0] + "." + x[1] + "." + x[8] || 0;
			}
	);
	/**
	 * @private
	 */
	this.selectedParticipants = new Array();
	/**
	 * @private
	 */
	this.selectedResource = new Array();	
	/**
	 * @private
	 */
	this.cbFunction = cbFunction;
	/**
	* @private
	*/
	this.title = title || null;	
	/**
	 * @private
	 */
	this.enabled = false;	
	/**
	 * @private
	 */
	this.changedParticipants;
	/**
	 * @private
	 */
	this.contact2user = [];
	/**
	 * @private
	 */
	this.initalFilled;				
	/**
	 * @private
	 */
	this.bUserHead = bUserHead;
	this.bUserMember = bUserMember;
	
	this.groupResolution = new Object();
	this.groupMemberLiveGrid = null;
	this.selectedParticipantsGrid = null;
	this.selectedRessourcesGrid = null;
	this.singleFolderSearch = singleFolderSearch || false;

	this.selPartsStorage  = null;
	this.selRessStorage = null;
	this.participantsGridSmall;
	this.smallParticipantsInit = false;
	this.emptySearchText = _("Please enter your search");
	this.searchField=$("searchpattern_participants");
	this.searchpattern="";
	this.blurTimer;
	this.allEmailAddresses = false;
	this.getHTML(); 
	var Self = this;

	register("closeParticipantsWindowOK", function() { if (Self.enabled) Self.closeParticipantsWindowOK(); });
	register("closeParticipantsWindowCancel", function(){ if(Self.enabled) Self.closeParticipantsWindowCancel(); });
	register("addToParticipantsList", function(){ if(Self.enabled) Self.addToParticipantsList(); });
	register("addToResourceList", function(){ if(Self.enabled) Self.addToResourceList(); });
	
	register("delParticipantsList", function(){ if(Self.enabled) Self.delSelParticipants(); });	
	register("delResourceList", function(){if(Self.enabled) Self.delSelRessources(); });			
	
	register("searchParticipants", function(){ if(Self.enabled) Self.searchParticipants(); });
	if (!this.showResource) $("selectedResourceTr").style.display = "none";
	
	addOnClose($("floatingdivParticipants"), function(){ if(Self.enabled) Self.closeParticipantsWindowCancel(); });
	
    // remove dom events first
    if (Participants.inE) {
        removeDOMEvent(Self.searchField, "keypress", Participants.inE);
        removeDOMEvent(Self.searchField, "click", Participants.inE);
    }
    if (Participants.inB) {
        removeDOMEvent(Self.searchField, "blur", Participants.inB);
    }
    // wrapper functions for key and click events on search field
    Participants.inE = function(e) {
        if (Self.blurTimer != undefined) {
            clearTimeout(Self.blurTimer);
            delete(Self.blurTimer);
        }
        Self.searchParticipantsEnter(e, Self);
    }
    Participants.inB = function(e) {
        Self.blurTimer = setTimeout(function() { Self.searchParticipantsBlur(e, Self); },100);
    }
    // re-add dom events
    addDOMEvent(Self.searchField, "keypress", Participants.inE); 
    addDOMEvent(Self.searchField, "click", Participants.inE);
    addDOMEvent(Self.searchField, "blur", Participants.inB); 
}



Participants.prototype = {
		
	// helper for event handling
	f_addParticipant: function(e) { triggerEvent('addToParticipantsList'); },
	f_deleteParticipant: function(e) { triggerEvent('delParticipantsList'); },
	f_addResource: function(e) { triggerEvent('addToResourceList'); },
	f_deleteResource: function(e) { triggerEvent('delResourceList'); },
	// helper: enable button
	f_enableButton: function(nodeId, handler) {
		$(nodeId+"-button").className = "fakeButtonBottomRight";
		$(nodeId).style.cursor = "pointer";
		addDOMEvent($(nodeId), "click", handler);
	},
	// helper: disable button
	f_disableButton: function(nodeId, handler) {
		$(nodeId+"-button").className = "fakeButtonBottomRight font-color-disabled";
		$(nodeId).style.cursor = "default";
		removeDOMEvent($(nodeId), "click", handler);
	},
	// helper: toggle button (via boolean flag)
	f_toggleButton: function(flag, nodeId, handler) {
		var Self = this;
		if (flag) {
			Self.f_enableButton(nodeId, handler);
		} else {
			Self.f_disableButton(nodeId, handler);
		}
	},
	
	getHTML: function() {
		var Self=this;
		if (this.setFullParticipants) {
			var sel = this.selectionObject;

			sel.toggle2 = sel.toggle;
			sel.select2 = sel.select;
			
			sel.toggle = function(index){
				if(this.storage.groups[index]){
					return this.select2(index - this.storage.groups[index].before,  index + this.storage.groups[index].after + 1);
				} else {
					return this.toggle2(index);
				}
			}
			
			sel.select = function(from, to){
				for(var i = from; i < to; i++){
					if(this.storage.groups[i]){
						this.select2(i - this.storage.groups[i].before,  i + this.storage.groups[i].after + 1);
						i += this.storage.groups[i].after;
					} else {
						this.toggle2(i);
					}
				}
			}
			
			sel.changed_cb2 = sel.changed_cb;
			sel.changed_cb = function(from, to) {
				if (sel.storage.groups)
					filterArray(sel.storage.groups,
						function(group, i) { return !sel.get(1); }, from);
				sel.changed_cb2(from, to);
			};

			this.participantsGridBig = new LiveGrid([
			  {	
					text: "",
					sortable: true,
					width: "16px",
					style: {padding: 0},
					set: function(div,text) {
						switch (text[6]) {
							case "contact":
								var userImgSrc = (text[7]) ? getFullImgSrc("img/calendar/user.gif") : getFullImgSrc("img/calendar/user_extern.gif");
								if(div.firstChild.src)
									div.firstChild.src = userImgSrc;
								else{
									removeChildNodes(div);
									div.appendChild(newnode("img", 0, {src: userImgSrc, alt: "User", align: "absmiddle"}));
								}
								break;
							case "group":
								if(div.firstChild.src)
									div.firstChild.src = getFullImgSrc("img/calendar/group.gif");
								else{
									removeChildNodes(div);
									div.appendChild(newnode("img", 0, {src: getFullImgSrc("img/calendar/group.gif"), alt: "Group", align: "absmiddle"}));
								}
								break;
							case "resource":
								if(div.firstChild.src)
									div.firstChild.src = getFullImgSrc("img/calendar/ressourcen.gif");
								else{
									removeChildNodes(div);
									div.appendChild(newnode("img", 0, {src: getFullImgSrc("img/calendar/ressourcen.gif"), alt: "Resource", align: "absmiddle"}));
								}
								break;								
							default:
								if(div.firstChild.src)
									div.firstChild.src = getFullImgSrc("img/empty16x16.gif");
								else{
									removeChildNodes(div);
									div.appendChild(newnode("img", 0, {src: getFullImgSrc("img/empty16x16.gif"), alt: "Group Member", align: "absmiddle"}));
								}
								break;
						}
					},
					clear: LiveGrid.makeClear("...")
				},	{	
					text: ((this.showUser || this.showGroup) && this.showResource)? "Participants/Resources":/*i18n*/
																				    "Participants", /*i18n*/
					i18n: true,
					sortable: true,
					width: "30%",
					set: function(div, text){					
						removeChildNodes(div);
						var dn = text[2] || text[5] || _("unknown"); /*i18n*/
						if(text[6] == "groupMember"){
							div.appendChild(newnode("img", 0, {src: getFullImgSrc("img/calendar/user.gif"), alt: _("Group Member"), title: _("Group Member"), align: "absmiddle"}));
							div.appendChild(document.createTextNode("\u00a0" + dn));
						} else {
							div.appendChild(document.createTextNode(dn));
						}
					},
					clear: LiveGrid.makeClear("...")
				}, {
					text: "Status", /*i18n*/
					i18n: true,
					sortable: true,
					width: "20%",
					set: function(div, text){
						if(text[6] == "groupMember"){
							removeChildNodes(div);
							div.appendChild(document.createTextNode("\u00a0\u00a0\u00a0\u00a0" + text[3]));
						} else {
							removeChildNodes(div);
							div.appendChild(document.createTextNode(text[3]));
						}
					},
					clear: LiveGrid.makeClear("...")
				}, {
					text: "Comment", /*i18n*/
					i18n: true,
					/* sortable: true, */
					set: function(div, text){
						if(text[6] == "groupMember"){
							removeChildNodes(div);
							div.appendChild(document.createTextNode("\u00a0\u00a0\u00a0\u00a0" + text[4]));
						} else {
							removeChildNodes(div);
							div.appendChild(document.createTextNode(text[4]));
						}
					},
					clear: LiveGrid.makeClear("...")
				}
			], this.selectionObject);
			$(this.attachpoint + "Header").appendChild(this.participantsGridBig.getHeader());
			this.participantsGridBig.getTable($(this.attachpoint));
			
			this.participantsGridBig.events.register("Selected", function(ids){
				triggerEvent("SubSelected", Self.participantsGridBig.selection.count);
                ox.ToolBarController.processSelection("participants", false,
                    Self.participantsGridBig.selection.getSelected(), true);
			});
			this.participantsGridBig.events.register("Activated", function(ids){
				if(ids[0] && ids[0].split('_')[0]=="group")
				{
					if(Self.groupResolution[ids[0].split('.')[0]])
						Self.openGroupMembersPopup(Self.groupResolution[ids[0].split('.')[0]],ids[0]);	
				}
			});
				
		}
		
		if(!this.smallParticipantsInit) {
			var sel_ = new Selection();
			sel_.oldToggle = sel_.toggle;
			function getTyp(id){ return id.substring(0, id.indexOf("_")); }
			sel_.selectable = function(index) {
				var data = this.storage.data.get(this.storage.getSID(index));
				if(getTyp(data[0]) == "group")
					return Boolean(data[4] != "m_mail")
				else
					return Boolean(data[3] || (getTyp(data[0]) != "contact" && getTyp(data[0]) != "user"));
			}
			sel_.toggle = function(index) {
				return this.selectable(index) && this.oldToggle(index);
			};
			sel_.select = function(from, to) {
				for (var i = from; i < to; i++)
					if (!this.get(i) && this.selectable(i)) this.oldToggle(i);
			}
			
			// live grid in popup
			this.participantsGridSmall = new LiveGrid([
				{	
					text: "&#160;",
					sortable: true,
					width: "20px",
					style: {padding: 0},
					set: function(div, text) {
							var color = "";							
							var item_type = getTyp(text[0]);
							switch (item_type) {
								case "contact":
									// nobreak
								case "user":
									// different icons for contacts/users
									var img = item_type == "user" ? "user.gif" : "user_extern.gif";
									// has email?
									if (!text[3]) {
										color = "silver"; 
										img = "user_d.gif";
									}
									// draw node
									if(div.firstChild.src)
										div.firstChild.src = getFullImgSrc("img/calendar/" + img);
									else{
										removeChildNodes(div);
										div.appendChild(newnode("img", 0, {src: getFullImgSrc("img/calendar/" + img), alt: _("User"), title: _("User"), align: "absmiddle"}));
									}
									break;
								case "group":
									color = (Self.bDisableG== -1 || text[4] == "m_mail")?"silver":""; 
									if(div.firstChild.src)								
										div.firstChild.src = (Self.bDisableG!= -1)?getFullImgSrc("img/calendar/group.gif"):getFullImgSrc("img/calendar/user_d.gif");
									else{
										removeChildNodes(div);
										div.appendChild(newnode("img", 0, {src: getFullImgSrc("img/calendar/group.gif"), alt: _("Group"), title: _("Group")}));
									}
									break;
								case "resource":
									if(div.firstChild.src)
										div.firstChild.src = getFullImgSrc("img/calendar/ressourcen.gif");
									else{
										removeChildNodes(div);
										div.appendChild(newnode("img", 0, {src: getFullImgSrc("img/calendar/ressourcen.gif"), alt: "User"}));
									}
									break;								
								default:
									if(div.firstChild)
										div.firstChild.src = getFullImgSrc("img/empty16x16.gif");
									else
										div.appendChild(newnode("img", 0, {src: getFullImgSrc("img/empty16x16.gif"), alt: ""}));
									break;
							}
							div.parentNode.style.color = color;
						},
					clear: LiveGrid.makeClear("...")
				}, {	
					text: "Name", /*i18n*/
					/* sortable: true, */
					width: "40%",
					//set: LiveGrid.defaultSet,
					//index:2
					set: function(div, data) {
						removeChildNodes(div);
						div.appendChild(document.createTextNode(data[2] || data[3] || _("unknown")));
					},
					clear: LiveGrid.makeClear("...")
				}, {
					text: "E-Mail", /*i18n*/
					/* sortable: true, */
					set: LiveGrid.defaultSet,
					clear: LiveGrid.makeClear("..."),
					index:3
				}
			], sel_);			
			
			this.participantsGridSmall.events.register("Selected", function(ids) {
				// flags
				var canAddParticipant = false;
				var canAddResource = false;
				// current selection
				var items = Self.participantsGridSmall.selection.getSelected();
				// loop selection
				for (i = 0; i < items.length; i++) {
					// get type (e.g. contact, resource, group)
					var type = items[i].split('_')[0];
					switch(type) {
						case "user":
							// internal contacts (users) can be a resource
							canAddParticipant = true;
							canAddResource = true; 
							break;
						case "contact":
							// external contacts cannot be a resource
							canAddParticipant = true;
							break;
						case "group": 
							canAddParticipant = true;
							break;
						case "resource": 
							canAddResource = true;
							break;
					}
				}
				
				// participant(s) selected?
				Self.f_toggleButton(canAddParticipant, "buttonAddToParticipantsList", Self.f_addParticipant);
				// resource(s) selected?
				Self.f_toggleButton(canAddResource, "buttonAddToResourcesList", Self.f_addResource);
			});

			this.participantsGridSmall.events.register("Activated", function(ids) {				
				if (ids[0] == undefined && Self.bDisableG == -1 && 
						ids[0].split('_')[0] == 'group') {
					return;
				}
				Self.participantsGridSmall.selection.select(ids[0]);
								
				if (ids[0].split('_')[0] == 'resource')
					triggerEvent('addToResourceList');				
				else	
					triggerEvent('addToParticipantsList');				

			});					
			this.attach_lg_header = newnode("div", { display: "none" },
                { className: "innerTableContainerAddAddresseesHeader" });
            this.attach_lg = newnode("div", { display: "none" },
                { className: "innerTableContainerAddAddressees" });
            $("tableContainerAddParticipants").appendChild(this.attach_lg_header);
            $("tableContainerAddParticipants").appendChild(this.attach_lg);
            this.attach_lg_header.appendChild(this.temp_storage_head = this.participantsGridSmall.getHeader());
			this.participantsGridSmall.getTable(this.attach_lg);
			this.smallParticipantsInit = true;
		}
		if(this.showFolder){
			$("newParticipant_folder").style.display = ""; 
		}
		else{
			$("newParticipant_folder").style.display = "none";		
		}
        
        if (!configGetKey("modules.contacts.singleFolderSearch") && !this.singleFolderSearch) {
            var setDisabled = classNameSetter("font-color-disabled");
            var checkbox = $("participants-search-all-folders");
            checkbox.parentNode.parentNode.parentNode.style.display = "";
            checkbox.checked = true;
            setDisabled($("participants-folder-button"), true);
            checkbox.onclick = function() {
                setDisabled($("participants-folder-button"), checkbox.checked);
            };
        }
	},
	openGroupMembersPopup: function (memberArray,group_id) {
		var sGroupIdSplitDot = group_id.split(".")[0];
		internalCache.getGroups([sGroupIdSplitDot.split('_')[1]],function (res){
            //#. %s is the name of a group.
		    //#, c-format
		    $('memberPopup-h-c').innerHTML = format(_("Members of %s"), /*i18n*/
                res[sGroupIdSplitDot.split('_')[1]].display_name);			
        });

		var Self = this;
		if(typeof memberArray != "object")
			return;
		centerPopupWindow($("memberPopup"));
		$("memberPopup").style.display = "block";
		internalCache.getUsers(memberArray, function(cbObj){
			if(Self.groupMemberLiveGrid == null)
			{	
				Self.groupMemberLiveGrid = new LiveGrid([ 
					{
						text:"",
						index: 1,
						width: "20px",	
						set: function (div, content){
							if (!div.firstChild)
								div.appendChild(newnode("img", null, {src: getFullImgSrc("img/mail/noattachment.gif"), align: "absmiddle", width: "16", height: "16"}));
							switch(content)
							{
								 case "contact": 	
								 		div.firstChild.src = getFullImgSrc("img/calendar/user.gif")
								 		break;
								 case "group": 	
								 		div.firstChild.src = getFullImgSrc("img/calendar/group.gif")
								 		break;							 					
								 case "resource": 
								 		div.firstChild.src = getFullImgSrc("img/calendar/ressourcen.gif")
								 		break;							 												 					
							}
						},
						clear: function(div) {
							if (!div.firstChild)
								div.appendChild(newnode("img", null, {src: getFullImgSrc("img/mail/noattachment.gif"), align: "absmiddle", width: "16", height: "16"}));
						}
					}, {
						text:_("Group Members"),				
						index: 2,	
						set: LiveGrid.defaultSet,					
						clear: LiveGrid.makeClear("")
					}
				],new Selection());

				Self.groupMemberLiveGrid.emptylivegridtext =_("No Members");
				Self.groupMemberLiveGrid.getHeader();		
				Self.groupMemberLiveGrid.getTable($("member_lg"));
			}					
			var showMember = new Array();

			for(var nId in cbObj)
			{
				showMember.push(["contact_" + cbObj[nId].id,"contact",cbObj[nId].display_name]);
			}	
			var memberStorage = new Storage(0, []);		
			showMember.sort(function(a,b){
				if (a[2] && b[2])
					return a[2].toUpperCase() < b[2].toUpperCase() ? -1 : 1;
				else
					return -1;
			});			
			memberStorage.append(showMember);
			Self.groupMemberLiveGrid.enable(memberStorage);
		});
	},
	openAddParticipantsWindow: function(bDisableG) {

		if (this.opened)	return;

		var Self = this; //bind
		
		// disable all buttons now
		Self.f_disableButton("buttonAddToParticipantsList", Self.f_addParticipant);
		Self.f_disableButton("buttonAddToResourcesList", Self.f_addResource);
		Self.f_disableButton("buttonDeleteFromParticipantsList", Self.f_deleteParticipant);
		Self.f_disableButton("buttonDeleteFromResourcesList", Self.f_deleteResource);

		$("tableContainerAddParticipants").style.display = "block";
		this.attach_lg_header.style.display = "block";
		this.attach_lg.style.display = "block";		
		this.opened = true;
		//clear search
		this.bDisableG = bDisableG;
		$("searchpattern_participants").value = "";
		if(this.bUserMember) {
			$("headerSelPartAndRes").style.display ="none";
			$("headerSelUser").style.display ="none";						
			$("headerSelPart").style.display ="none";		
			$("headerSelPart2").style.display ="none";	
			$("headerSelUser2").style.display ="none";
			$("headerSelMember").style.display ="";
			$("headerSelMember2").style.display ="";
		}
		else if((this.showUser || this.showGroup) && this.showResource)
		{
			$("headerSelPartAndRes").style.display ="";
			$("headerSelUser").style.display ="none";						
			$("headerSelPart").style.display ="none";		
			$("headerSelPart2").style.display ="";	
			$("headerSelUser2").style.display ="none";	
			$("headerSelMember").style.display ="none";
			$("headerSelMember2").style.display ="none";
		}
		else if((this.showUser || this.showGroup) && this.bUserHead)
		{
			$("headerSelUser").style.display =""			
			$("headerSelPartAndRes").style.display ="none";						
			$("headerSelPart").style.display ="none";			
			$("headerSelPart2").style.display ="none";	
			$("headerSelUser2").style.display ="";
			$("headerSelMember").style.display ="none";
			$("headerSelMember2").style.display ="none";							
		}
		else if(this.showUser || this.showGroup)
		{
			$("headerSelPart").style.display =""			
			$("headerSelPartAndRes").style.display ="none";						
			$("headerSelUser").style.display ="none";			
			$("headerSelPart2").style.display ="";	
			$("headerSelUser2").style.display ="none";
			$("headerSelMember").style.display ="none";
			$("headerSelMember2").style.display ="none";										
		}
        if ($("modal-dialog")) {
            ox.api.setModal(true);
//            showNode("modal-dialog");
//            $("modal-dialog").style.display = "block";
        }
		showNode("floatingdivParticipants");
		centerPopupWindow($("floatingdivParticipants"));
		$("floatingdivParticipants").style.display = "block";	
		if(this.internalStorage){
			this.enable_small_grid(this.internalStorage);
		}
		if(this.title)
			$("floatingdivParticipants-h-c").firstChild.data = this.title.toString();
		this.selectedParticipants = new Array();
		this.selectedResource = new Array();
		this.enabled = true;
		this.changedParticipants = new Array();
        this.changedResources = [];
		if (!this.internalStorage2.groups) {
			this.internalStorage2.groups = new Array();
		}
		removeChildNodes($("selectedParticipants"));
		removeChildNodes($("selectedResource"));
		triggerEvent("searchParticipants");
		this.selPartsStorage = new Storage(0, []);		
		this.selRessStorage = new Storage(0, []);		
		this.selectedParticipantsGrid = null;		
		this.selectedRessourcesGrid = null;		
	},
	
	attachpoint: function() {
		
	},
	
	getParticipants: function(onlyInternal) {
		if(!onlyInternal) {
			onlyInternal = false;
		}
		var parts = [];
		if (this.internalStorage2.data.data){
			for(i in this.internalStorage2.data.data){
				if (!onlyInternal || this.internalStorage2.data.data[i][4] != null) {
				    var part = this.internalStorage2.data.data[i];
					var tmpObj = { id: getID(part[0]) };
					if (part[2]) tmpObj.display_name = part[2];
					switch (getTyp(part[0])) {
						case "contact":
							if(part[1] == 6){
								tmpObj.type = 1;
								tmpObj.id = part[7];
							}
							else {
								tmpObj.type = 5;
								tmpObj.mail = part[5];
							}
							break;
						case "group":
							tmpObj.type = 2;
							break;
						case "resource":
							tmpObj.type = 3;
							break;
						default:
							break;
					}
					if (!parts[0])
						parts.push(tmpObj);
					else if(tmpObj.id != parts[0].id && tmpObj.type){
						if(tmpObj.type == 5){
							tmpObj.id = 0;
							parts.push(tmpObj);
						} else
							parts.push(tmpObj);
					}
				}
			}
		}
		//we need empty participants array!!!
		//if(parts.length > 0) 		
		return parts;
		
		function getID(id){ return id = id.substring(id.indexOf("_")+1); }
		function getTyp(id){ return id = id.substring(0, id.indexOf("_")); }
	},
	
	getChangedParticipants: function() {
		return this.changedParticipants;
	},
	
	containsParticipants: function() {
		if(this.userData)
			return true;
		if(this.internalStorage2 && this.internalStorage2.data.data) {
			for (i in this.internalStorage2.data.data) {
				return true;
			} 
		}
		return false;
	},
	
    searchParticipantsBlur : function(event, Self) {
        if (trimStr(Self.searchField.value).length == 0) {
            Self.searchField.value=Self.emptySearchText;
            Self.searchField.style.color="silver";
        }
    },
    
    searchParticipantsEnter: function (event, Self){
        if (Self.searchField.value == Self.emptySearchText) {
            Self.searchField.value="";
            Self.searchField.style.color="";
        } else if (event.keyCode == 13) {
            Self.searchpattern = Self.searchField.value;            
            triggerEvent("searchParticipants");
            //$(liveGridDivResult).focus();
        }
    },
    
    displayError: function(msg) {
    	$("participantsSearchError").style.display="";
    	$("participantsSearchError").getElementsByTagName("DIV")[0].firstChild.data=msg;
    },
	
	/**
	 * @private
	 */	
	searchParticipants: function() {
		var Self = this; // bind
		this.searchpattern="";
        var inVal=this.searchField.value;
        if (trimStr(inVal).length == 0 ||
            inVal == this.emptySearchText) {
            this.searchField.value=this.emptySearchText;
            setTimeout(function() {
                Self.searchField.style.color="silver";
            },0);
            if (configContainsKey("participants.autoSearch") &&
                configGetKey("participants.autoSearch") == false) {
                this.searchpattern = "";
                //if(this.enabled) this.resetGrid();
                return; 
            } else if (configContainsKey("minimumSearchCharacters") &&
                configGetKey("minimumSearchCharacters") != 0) {
            	this.displayError(
            	   //#. %s is the number of characters.
            	   //#, c-format
            	   format(_("The search pattern requires at least %s characters."), 
            	       configGetKey("minimumSearchCharacters")));
            	return;
            } else {
                this.searchstring="";
            }
        } else if (configContainsKey("minimumSearchCharacters") &&
            trimStr(inVal).length < configGetKey("minimumSearchCharacters")) {
            this.displayError(
                //#. %s is the number of characters.
                //#, c-format
                format(_("The search pattern requires at least %s characters."), 
                    configGetKey("minimumSearchCharacters")));
            return;
        } else {
            this.searchField.style.color="";
            this.searchpattern=inVal;
        }
        
		//if no folder set, use the default
        if(clickedItemParticipant == null || clickedItemParticipant == "") {
            clickedItemParticipant = defaultParticipantFolder;
        }
        var pattern = trimStr(this.searchpattern) ? this.searchpattern : "*";
        var patternObj = { pattern: pattern };
        var userPatternObj = { display_name: pattern, email1: pattern,
            email2: pattern, email3: pattern, last_name: pattern,
            first_name: pattern, orSearch: true };
        if (!$("participants-search-all-folders").checked) {
            patternObj.folder = clickedItemParticipant;
            userPatternObj.folder = clickedItemParticipant;
        }
		
		this.internalStorage = new Storage(0, [], "", 0, 0,  null, 
				function(x){ 
					return x[0] + "." + x[1] + "." + x[5] || 0;
				}
		);		
		
		var oObj;
		var aRequests = new Array();
		var oRequestObj = new Object();

		if(this.showUser){
			oRequestObj['module'] = "contacts";
			oRequestObj['action'] = "search";	
			oRequestObj['columns'] = "1,20,500,555,602,524,556,557,501,502";	
			oRequestObj['sort'] = "500";
			oRequestObj['order'] = "asc";
			oRequestObj['data'] = userPatternObj;
			aRequests.push(oRequestObj);
		}
		if (this.showGroup && clickedItemParticipant == defaultParticipantFolder){		
			var oRequestObj = new Object();		
			oRequestObj['module'] = "group";
			oRequestObj['action'] = "search";		
			oRequestObj['data'] = patternObj;
			aRequests.push(oRequestObj);
		}
		if (this.showResource  && clickedItemParticipant == defaultParticipantFolder){
			var oRequestObj = new Object();		
			oRequestObj['module'] = "resource";
			oRequestObj['action'] = "search";		
			oRequestObj['data'] = patternObj;
			aRequests.push(oRequestObj);		
		}

		// disable for concurrent searches, see bug #17194
		var buton = $("participants_button_go");
		buton.style.color = "#c0c0c0";
		buton.onclick = null;
        removeDOMEvent(Self.searchField, "keypress", Participants.inE);
		
		json.put(AjaxRoot + "/multiple?" + "session=" + session,aRequests,null,function (arg){
			for(var indx=0;indx<aRequests.length;indx++) {
				switch (aRequests[indx].module){
					case "contacts": 
						var tmpArray = new Array();
						for (var i=0; i<arg[indx].data.length; i++){
							// Add a user only when it is not a Distributionlist
							// and either the user has a mail address or admin enabled
							// displaying of participants without email.
							var cb = arg[indx].data[i];
							
							// ignore distribution list
							if (cb[4]) {
								continue; 
							}
							
							var displayname = "";
							if (cb[2]) {
								displayname = cb[2];
							} else if (cb[8] || cb[9]) {
								displayname = (cb[9] || "") + ", " + (cb[8] || ""); 
							} else {
								displayname = cb[3];
							}
							
							if (!cb[3] && !cb[6] && !cb[7] && configGetKey("participants.showWithoutEmail")) {
								// contact do not have any e-mail address but config says show it anyway
								// but we just want to have it once								
								tmpArray.push(["contact_" + cb[0], cb[1], displayname, null, cb[5], 0]);
							} else {
								function isUser(user) {
									return user && user > 0;
								}
							
								// iterate through addresses
								for (var ia=0; ia<3; ia++) {
									var mailaddr = cb[[ 3, 6, 7][ia]];
									// do not add if noaddress available
									if (!mailaddr) continue; 
									
									tmpArray.push([( isUser(cb[5]) ? "user_" : "contact_") + cb[0], cb[1], displayname, mailaddr, cb[5], ia]);
									// we don't want all of the users addresses so we
									// break after adding the first one
									if (!Self.allEmailAddresses) break;
								}		
							}
							
							// remember contact-user-relation of any seen contact
							Self.contact2user[cb[0]] = cb[5];							
						}							
						Self.internalStorage.append(tmpArray);
						break;
					case "group": 
						var tmpArray = new Array();		
						for(var i = 0; i< arg[indx].data.length; i++){
							var cb = arg[indx];		
							var foldertype = (("comboboxProps" in window) && comboboxProps && (comboboxProps.getKey() == "m_mail")) ?	"m_mail" : "";									
							tmpArray[i] = ["group_" + cb.data[i].id, 0, cb.data[i].display_name, "", foldertype, 0];
						}
						tmpArray.sort(function(a,b){
							if (a[2] && b[2]) 
								return a[2].toUpperCase() < b[2].toUpperCase() ? -1 : 1;
							else
								return -1;
						});				
						Self.internalStorage.append(tmpArray);					
						break;							
					case "resource": 
						var tmpArray = new Array();							
						for(var i = 0; i< arg[indx].data.length; i++){
							var cb = arg[indx];			
							tmpArray[i] = ["resource_" + cb.data[i].id, 0, cb.data[i].display_name, "", 0, 0];
						}
						tmpArray.sort(function(a,b){
							if (a[2] && b[2])
								return a[2].toUpperCase() < b[2].toUpperCase() ? -1 : 1;
							else
								return -1;
						});
						Self.internalStorage.append(tmpArray);								
						break;														
				}
			}
			//removeChildNodes($("addParticipantsTableHeader"));
			Self.enable_small_grid(Self.internalStorage);
		}, function(){
			// reenable button if error occures
			var buton = $("participants_button_go");
			buton.style.color = "";
			buton.onclick=function(e) {
				triggerEvent('searchParticipants');
			     
	    	};
	    	addDOMEvent(Self.searchField, "keypress", Participants.inE);
		});
	},
	
	enable_small_grid : function (storage){
		this.participantsGridSmall.enable(storage);		
		if (this.participantsGridSmall && this.participantsGridSmall.selection) {
			this.participantsGridSmall.selection.reset();
		}
		var buton = $("participants_button_go");
		buton.style.color = "";
		buton.onclick=function(e) {
			triggerEvent('searchParticipants');
    	};
    	addDOMEvent(this.searchField, "keypress", Participants.inE);
	},
	
	disable_small_grid : function (){
		this.participantsGridSmall.disable();		
	},
	
	/**
	 * @private
	 */	
	closeParticipantsWindowOK: function() {
		var Self = this; // bind
		this.opened = false;
		
        if ($("modal-dialog")) {
        	var childs = $("modal-dialog").childNodes;
        	var closeall=true;
		    for (var i=0;i<childs.length;i++) {
		        if(childs[i].tagName && childs[i].tagName == "DIV") {
		            if(childs[i].style.display && childs[i].style.display != "none") {
		                closeall=false;
		            }
		        }
		    }
		    if (closeall) {
		        ox.api.setModal(false);
//                hideNode("modal-dialog");
//                $("modal-dialog").style.display = "none";
		    }
        }
		hideNode("floatingdivParticipants");
		$("floatingdivParticipants").style.display = "none";
		this.attach_lg_header.style.display = "none";
		this.attach_lg.style.display = "none";		
		this.disable_small_grid();
		if(this.selectedParticipantsGrid)
			this.selectedParticipantsGrid.disable();
		if(this.selectedRessourcesGrid)
			this.selectedRessourcesGrid.disable();			
		
		// clear
		this.selGroups = []; this.selContacts = []; this.selResources = [];		
		this.changedParticipants =  new Array();
		
		// copy selected contacts, groups, and resources
		// resources first (higher priority)
		
		if (this.selectedResource && this.selectedResource.length > 0) {
			// loop selected resources
			for(var i = 0; i < this.selectedResource.length; i++) {
				var resource = parseItem(this.selectedResource[i]);
				// distinguish type
				switch (resource.type) {
					case "user":
						var user_as_contact = parseItem(
							"contact_" + resource.id + "." + resource.folder + ".0"
							);
						var contact_as_resource = parseItem(
							"resource_" + this.contact2user[resource.id] + ".0.0"
							);
						// not in grid?
						if ( !inGrid(contact_as_resource.key) ) {
							// in grid as contact?
							if ( inGrid(user_as_contact.key) ) {
								// remove as contact
								this.internalStorage2.removeIDs([user_as_contact.key]);
							}
							// add contact as resource
							this.selResources.push({
								id: contact_as_resource.id,
								folder: contact_as_resource.folder,
								key: contact_as_resource.key
							});
						}
						break;
					case "resource":
						// not in grid?
						if ( ! inGrid(resource.key) ) {
							// add resource
							this.selResources.push({ 
								id: resource.id,
								folder: 0,
								key: resource.key
							});
						}
						break;
				}
			}
		}
		
		// for cache request
		var collection_contact = { 
				objects: [],
				columns: ["display_name", "email1", "email2", "email3", "internal_userid"]
			};
		
		this.enabled = false;
		
		// fill grid now
		
		// join three callbacks
		var joint = new Join(function() {
			// callback
			Self.cbFunction(Self.changedParticipants);
			// enable grid
			if(Self.setFullParticipants) {
				Self.participantsGridBig.enable(Self.internalStorage2);
			}
		});
		
		var cb_resources = joint.add(function(items) {
			var tmpArray = new Array();
			// loop resources
			for (key in items) {
				var item = items[key];
				tmpArray.push([
				               "resource_" + item.id, 0, item.display_name, 
				               _("not sent"), "", "", "resource", 0, 0
				               ]);
				// add as changed
				Self.changedParticipants.push({
					"id": item.id, "display_name": item.display_name,
					"type": 3
				});
			}				
			// add to grid
			Self.internalStorage2.append(tmpArray);
			
			// contacts / groups in second run
	        if (Self.selectedParticipants && Self.selectedParticipants.length > 0) {
	            // loop selected contacts
	            for (var i = 0; i < Self.selectedParticipants.length; i++) {
	                var participant = parseItem(Self.selectedParticipants[i]);
	                // distinguish type
	                switch (participant.type) {
	                    case "user":
	                        // no conflict with resource?
	                        var contact_as_resource = parseItem(
	                                "resource_" + Self.contact2user[participant.id] + ".0.0"
	                                );
	                        // not in grid?
	                        var user_as_contact = parseItem(
	                                "contact_" + participant.id + "." + participant.folder + "." + participant.recurrence
	                                );
	                        if ( inGrid(contact_as_resource.key) || inGrid(user_as_contact.key) ) break;
	                        // nobreak
	                    case "contact":
	                        // not in grid (neither as contact nor as resource)
	                        if ( !inGrid(participant.key) ) {
	                            // add contact
	                            Self.selContacts.push({
	                                id: participant.id,
	                                folder: participant.folder,
	                                recurrence: participant.recurrence,
	                                email: participant.email
	                            });
	                            collection_contact.objects.push({
	                                module: "contacts",
	                                id: participant.id,
	                                folder_id: participant.folder,
	                                recurrence: participant.recurrence,
	                                email: participant.email
	                            });
	                        }
	                        break;
	                    case "group":
	                        // not in grid?         
	                        if ( !inGrid(participant.key) ) {
	                            // add group
	                            Self.selGroups.push({ 
	                                id: participant.id
	                            });
	                        }
	                        break;
	                }
	            }
	        }
			
			// fetch contacts via cache
	        corewindow.OXCache.newRequest(
	            null, "contacts", 
	            corewindow.clone(collection_contact, window), // don't ask (IE7)
	            null, cb_fetch_contacts
	        );
		});
		
		var cb_fetch_contacts = joint.add(function(data) {
			var tmpArray = new Array();
			// loop objects
			for(i = 0; i < data.objects.length; i++) {				
				// shortcut
				var item = data.objects[i];
							
				// needed later to map email addresses
				var map_item = collection_contact.objects[i];				
				
				// look for email address
				item.email = item.email1 || item.email2 || item.email3;
				
				// setting a valid display name, if not given (bug #
				if (!item.display_name) {
					if (item.last_name || item.first_name) {
						item.display_name = (item.last_name || "") + ", " + (item.first_name || "");
					} else {
						item.display_name = item.email;
					}
				}
				
				// add
				tmpArray.push([
						        "contact_" + item.id, item.folder_id,
					            item.display_name, _("not sent"), "",
					            item.email, "contact", item.internal_userid,
					            (map_item.recurrence || 0)
					            ]);
				
				var recurrence = 0, mail = item.email;
				// really bad hack to provide ALL email addresses of a user
				// recurrence is the number of the email [email1, email2 or email3]
				if ( Self.allEmailAddresses ) {
					recurrence = map_item.recurrence ? map_item.recurrence : 0;					
					if (map_item.recurrence != 0) {
						mail = item["email" + (parseInt(map_item.recurrence)+1)];
					}
				}
				
				// add as changed
				var participant = {
                    "contactID": item.id, 
                    "display_name": item.display_name,
                    "mail": mail, "type": 5, "recurrence": recurrence 
                };
                if ( item.internal_userid && item.internal_userid > 0 ) {
                    participant.type = 1;
                    participant.id = item.internal_userid;
                }
                Self.changedParticipants.push(participant);
			}
			// add to grid (via storage)
			Self.internalStorage2.append(tmpArray);
			
			// fetch groups via cache
	        internalCache.getGroups(flattenIds(Self.selGroups), cb_fetch_groups);
		});
		
		var cb_fetch_groups = joint.add(function(items) {
			var tmpArray = new Array();
			// loop resources
			for (key in items) {
				var item = items[key];
				tmpArray.push([
				               "group_" + item.id, 0, item.display_name, 
				               _("not sent"), "", "", "group"
				               ]);
				// add as changed
				Self.changedParticipants.push({
					"id": item.id, "display_name": item.display_name, 
					"type": 2
				});
			}
			// add to grid
			Self.internalStorage2.append(tmpArray);
		});
		
		// fetch resources via cache
		internalCache.getResources(flattenIds(this.selResources), cb_resources);
		
		function flattenIds(objects) {
			var ids = new Array();
			for (i = 0; i < objects.length; i++) { ids.push(objects[i].id); }
			return ids;
		}
		
		function inGrid(key) {
			// either in small mode (i.e., someone else takes care of duplicates)
			// or actually not in grid)
			if (!Self.setFullParticipants) {
				return false;
			} else {
				return typeof(Self.internalStorage2.indices[key]) != "undefined";
			}
		}
		
		function parseItem(str) {
			// use regular expression
			var reg = /^([^\_]+)\_(\w+)\.(\w+)\.(\w+)$/;
			var matches = reg.exec(str);
			return { key: matches[0], type: matches[1], id: matches[2], folder: matches[3], recurrence: matches[4] };
		}
	},
	
	initalFillBigGrid: function(obj, callback) {

		if(this.initalFilled)
			this.internalStorage2 = new Storage(0, [], "", 0, 0,  null, 
					function(x) {
						return x[0] + "." + x[1] + ".0";
					}
		);
		if(!this.internalStorage2.groups)
			this.internalStorage2.groups = new Array();
			
		this.part = obj.participants;
		if(obj.users)
			this.users = obj.users;
		else
			this.users = [];
		this.stati = ["waiting"/*i18n*/, "accepted"/*i18n*/,
		              "declined"/*i18n*/, "tentative"/*i18n*/];

		var Self = this;
		
		this.userToReq = new Array();
		this.groupToReq = new Array();
		this.resourceToReq = new Array();
		var externalUser = new Array();
		
		this.tmpArrayContact = new Array();
		this.tmpArrayGroup = new Array();
		this.tmpArrayResource = new Array();			
		
		for(var k = 0; k < this.part.length; k++) {
			switch(this.part[k].type){
				case 1:
					this.userToReq.push({id : this.part[k].id, type : 1});
					break;
				case 2:
					this.groupToReq.push({id : this.part[k].id, type : 2});
					break;
				case 3:
					this.resourceToReq.push({id : this.part[k].id, type : 3});
					break;
				case 5:
					externalUser.push({id : this.part[k].mail, type : 5, display_name : this.part[k].display_name, mail:this.part[k].mail})
					break;
				default:
					break;
			}
		}
		
		var joint = new Join(function() {
		    // mark as filled
		    Self.initalFilled = true;
		    // call back
		    if (callback) callback();
		});
		
		var outerJoin = joint.add(emptyFunction);
        
		// users
		if(Self.userToReq.length > 0 ) {
		    // define callback
		    var user2reqCB = joint.add(function(cb) {
	            var count = 0;
	            for(i in cb){
	                var userstatus = "";
	                var message = ""
	                var folder = 0;
	                for(var j = 0; j < Self.users.length; j++){
	                    if(Self.users[j].id == i){
	                        folder = 6;
	                        if(Self.users[j].confirmation > -1 && Self.users[j].confirmation < 4)
	                            userstatus = _(Self.stati[Self.users[j].confirmation]);
	                        if(Self.users[j].confirmmessage)
	                            message = Self.users[j].confirmmessage;
	                        break;
	                    }
	                }
	                Self.tmpArrayContact[count++] = ["contact_" + cb[i].user_id, folder, cb[i].display_name, userstatus, message, "", "contact", i, 0];
	                Self.internalStorage2.groups.push(false);
	            }
	            Self.tmpArrayContact.sort(function(a,b){
	                if (a[2] && b[2])
	                    return a[2] < b[2] ? -1 : 1;
	                else
	                    return -1;
	            });
	            Self.internalStorage2.append(Self.tmpArrayContact);
	        });
		    // go!
			internalCache.getObjects(Self.userToReq, user2reqCB);
		}
		
		// groups
		if(Self.groupToReq.length > 0) {
		    // define callback
	        var groupToReqCB = joint.add(function(cb) {

	            var count = 0;
	            var tmpArray = new Array();
	            var toGetTmp = new Array();
	            for(i in cb){
	                for(k in cb[i].members){
	                    toGetTmp[cb[i].members[k]] = cb[i].members[k];
	                }
	            }
	            var toGet = new Array();
	            for(var ho = 0; ho < toGetTmp.length; ho++){
	                if(toGetTmp[ho])
	                    toGet.push({id : toGetTmp[ho], type : 1});
	            }
	            
	            internalCache.getObjects(toGet, function(cbObj){
	                for(t in cb){
	                    Self.tmpArrayGroup.push(["group_" + cb[t].id, 6, cb[t].display_name, "", "", "", "group"]);
	                }

	                Self.internalStorage2.append(Self.tmpArrayGroup);
	            });
	        });
	        // go!
			internalCache.getObjects(Self.groupToReq, groupToReqCB);
		}

        // resources
		if (Self.resourceToReq.length > 0){
		    // define callback
	        var resourceToReqCB = joint.add(function(cb) {
	            var count = 0;
	            for(i in cb){
	                Self.tmpArrayResource[count++] = ["resource_" + i, 6, cb[i].display_name, "", "", "", "resource"];
	                Self.internalStorage2.groups.push(false);
	            }
	            Self.internalStorage2.append(Self.tmpArrayResource);
	        });
	        // go!
			internalCache.getObjects(Self.resourceToReq, resourceToReqCB);
		}
		
		if(externalUser.length > 0){
			var tmpArrayExternal = new Array();
			var count = 0;
			var confirmations = {};
			for (var i in obj.confirmations) {
			    var confirmation = obj.confirmations[i];
			    confirmations[confirmation.mail] = confirmation;
			}
			for(i in externalUser){
			    var confirmation = confirmations[externalUser[i].mail] ||
                    { status: 0, message: "" };
				tmpArrayExternal[count++] = [
				    "contact_" + externalUser[i].id, 0,
				    externalUser[i].display_name,
				    _(this.stati[confirmation.status || 0]),
				    confirmation.message || "",
				    externalUser[i].mail, "contact"];
				Self.internalStorage2.groups.push(false);
			}
			Self.internalStorage2.append(tmpArrayExternal);
		}
		
		// complete join
		outerJoin();
	},
	
	enableTheGrid: function(){
		this.participantsGridBig.enable(this.internalStorage2);		
	},
	
	disableTheGrid: function(){
		this.participantsGridBig.disable();
	},
	
	/**
	 * @private
	 */	
	closeParticipantsWindowCancel: function() {	
		this.opened = false;
		var Self = this;
        if ($("modal-dialog")) {
            var childs = $("modal-dialog").childNodes;
            var closeall=true;
            for(var i=0;i<childs.length;i++) {
                if(childs[i].tagName && childs[i].tagName == "DIV") {
                    if(childs[i].style.display && childs[i].style.display != "none") {
                        closeall=false;
                    }
                }
            }
            if (closeall) {
                ox.api.setModal(false);
//                hideNode("modal-dialog");
//                $("modal-dialog").style.display = "none";
            }
        }
		hideNode("floatingdivParticipants");
		$("floatingdivParticipants").style.display = "none";
		this.attach_lg_header.style.display = "none";
		this.attach_lg.style.display = "none";		
		$("selectedParticipants").value = "";
		Self.enabled = false;
		Self.disable_small_grid();
		if(Self.selectedParticipantsGrid)
			Self.selectedParticipantsGrid.disable();
		if(Self.selectedRessourcesGrid)
			Self.selectedRessourcesGrid.disable();			
	},
	
	/**
	 * @private
	 */		
	addToParticipantsList: function() {
		var Self = this; // bind
		var tmpSelected = this.participantsGridSmall.selection.getSelected();
		var currAdded = new Array();
		
		for(var i = 0; i < tmpSelected.length; i++){
			var drin = false;
			if(this.selectedParticipants){
				for(var j = 0; j < this.selectedParticipants.length; j++){
					if(tmpSelected[i] == this.selectedParticipants[j]){
						drin = true;
						break;
					}
				}
			}
			if(!drin && this.selectedParticipants){
				currAdded.push(tmpSelected[i]);
				this.selectedParticipants.push(tmpSelected[i]);
				this.changedParticipants.push(tmpSelected[i]);
			}
		}
	
		var selPartData = new Array();
		if(this.selectedParticipantsGrid == null)
		{
			this.selectedParticipantsGrid = new LiveGrid([ 
				{
					text: "",
					width: "20px",
					set: function (div, content){
						if (!div.firstChild)
							div.appendChild(newnode("img",null,{src: getFullImgSrc("img/mail/noattachment.gif"), align: "absmiddle", width: "16", height: "16" }));
							
						switch(content[1])
						{
							 case "contact":
							 		div.firstChild.src = (content[4] && content[4] > 0 ) ? getFullImgSrc("img/calendar/user.gif") : getFullImgSrc("img/calendar/user_extern.gif");
							 		break;
							 case "group": 		
							 		div.firstChild.src = getFullImgSrc("img/calendar/group.gif")
							 		break;							 					
							 case "resource": 	
							 		div.firstChild.src = getFullImgSrc("img/calendar/ressourcen.gif")
							 		break;							 												 					
						}
					},
					clear: function(div) {
						if (!div.firstChild)
							div.appendChild(newnode("img",null,{src: getFullImgSrc("img/mail/noattachment.gif"), align: "absmiddle", width: "16", height: "16" }));
					}
				}, {
					text:"",				
					//index: 2,	
					//set: LiveGrid.defaultSet,
					set: function(div,data) {
						removeChildNodes(div);
						div.appendChild(document.createTextNode(data[2] || data[3] || _("unknown")));
					},
					clear: LiveGrid.makeClear("")
				}
			],new Selection());		
			
			// enable/disable delete button?
			this.selectedParticipantsGrid.events.register("Selected", function(count) {
				// at least one item selected?				
				Self.f_toggleButton(count > 0, "buttonDeleteFromParticipantsList", Self.f_deleteParticipant);
			});

			var select = $("selectedParticipants");
			this.selectedParticipantsGrid.emptylivegridtext ="";
			this.selectedParticipantsGrid.getHeader();		
			this.selectedParticipantsGrid.getTable(select);
			this.selectedParticipantsGrid.enable(this.selPartsStorage);	
		}
		
		// add
		var tmpSel = new Array();
		// loop through current selection
		for(var i = 0; i< currAdded.length; i++) {
			// get type
			var typ = currAdded[i].substring(0, currAdded[i].indexOf("_"));			
			tmpSel.push(this.selectedParticipantsGrid.storage.ids.length+i);
			switch(typ) {
				case "group":
					selPartData.push([
					                  currAdded[i], "group",
					                  this.internalStorage.data.data[currAdded[i]][2]
					                                                               ]);
					break;
				case "user":
					// nobreak
				case "contact":
					selPartData.push([
					                  currAdded[i], "contact",
					                  this.internalStorage.data.data[currAdded[i]][2],
					                  this.internalStorage.data.data[currAdded[i]][3],
					                  this.internalStorage.data.data[currAdded[i]][4]
					                                                               ]);
					break;
			}
		}
		this.selPartsStorage.append(selPartData);						
		this.selectIDs(this.selectedParticipantsGrid, tmpSel);
		
	},
		
	deleteParticipants: function(){
		with (this.participantsGridBig) deleteIDs(selection.getSelected());
		if ($("countParticipantsNewAppointment"))
			$("countParticipantsNewAppointment").firstChild.data = this.getParticipants().length;
		if ($("partCounterTasksNew"))
			$("partCounterTasksNew").firstChild.data = this.getParticipants().length;			
	},
	
	 /**
	 * @private
	 */		
	addToResourceList: function() {
		var Self = this; // bind
		var tmpSelected = this.participantsGridSmall.selection.getSelected();
		var currAdded = new Array();
		for(var i = 0; i < tmpSelected.length; i++){
			var drin = false;
			if(this.selectedResource){
				for(var j = 0; j < this.selectedResource.length; j++){
					if(tmpSelected[i] == this.selectedResource[j]){
						drin = true;
						break;
					}
				}
			}
			if(!drin && this.selectedResource){
				currAdded.push(tmpSelected[i]);
				this.selectedResource.push(tmpSelected[i]);
                this.changedResources.push(tmpSelected[i]);          
			}
		}


		var selRessData = new Array();
		if(this.selectedRessourcesGrid == null)
		{	
			this.selectedRessourcesGrid = new LiveGrid([ 
				{
                    text: "",
					index: 1,
					width: "20px",						
					set: function (div, content){						
						if (!div.firstChild)
							div.appendChild(newnode("img",null,{src: getFullImgSrc("img/mail/noattachment.gif"), align: "absmiddle", width: "16", height: "16" }));
						switch(content)
						{
							 case "user":
							 		div.firstChild.src = getFullImgSrc("img/calendar/user.gif")
							 		break;
							 case "group": 		
									div.firstChild.src = getFullImgSrc("img/calendar/group.gif")
							 		break;							 					
							 case "resource": 	
							 		div.firstChild.src = getFullImgSrc("img/calendar/ressourcen.gif")
							 		break;							 												 					
						}
					},
					clear: function(div) {
						if (!div.firstChild)
							div.appendChild(newnode("img",null,{src: getFullImgSrc("img/mail/noattachment.gif"), align: "absmiddle", width: "16", height: "16" }));
					}
				}, {			
					text: "",
                    //index: 2,	
					//set: LiveGrid.defaultSet,		
					set: function(div,data) {
						removeChildNodes(div);
						div.appendChild(document.createTextNode(data[2] || data[3] || _("unknown")));
					},			
					clear: LiveGrid.makeClear("")					
				}
			],new Selection());
			
			// enable/disable delete button?
			this.selectedRessourcesGrid.events.register("Selected", function(count) {
				// at least one item selected?				
				Self.f_toggleButton(count > 0, "buttonDeleteFromResourcesList", Self.f_deleteResource);
			});
			
			var select = $("selectedResource");			
			this.selectedRessourcesGrid.emptylivegridtext ="";
			this.selectedRessourcesGrid.getHeader();		
			this.selectedRessourcesGrid.getTable(select);
			this.selectedRessourcesGrid.enable(this.selRessStorage);	
		}
		
		// add
		var tmpSel = new Array();
		// loop through selected items
		for(var i = 0; i< currAdded.length; i++){
			var typ = currAdded[i].substring(0, currAdded[i].indexOf("_"));
			tmpSel.push(this.selectedRessourcesGrid.storage.ids.length+i);
			if(typ == "user" || typ == "resource"){
				selRessData.push([currAdded[i], typ,
						this.internalStorage.data.data[currAdded[i]][2],
						this.internalStorage.data.data[currAdded[i]][3]]);
			}
		}
		this.selRessStorage.append(selRessData);		
		this.selectIDs(this.selectedRessourcesGrid, tmpSel);	
		
	},
	delSelParticipants: function (){
		//if nothing selected
		if(this.selectedParticipantsGrid == null)
			return;
		var aItemsToDelete = this.selectedParticipantsGrid.selection.getSelected();
		var aNewPartArr = new Array();		
		var aNewChPartArr = new Array();			
		for(var j = 0; j < this.selectedParticipants.length; j++){
			var bFound = false;
			for( var indx in aItemsToDelete)
			{
				if(this.selectedParticipants[j] == aItemsToDelete[indx])
				{
					var bFound = true;					
					break;
				}				
			}
			if(!bFound){
				aNewPartArr.push(this.selectedParticipants[j]);			
				aNewChPartArr.push(this.selectedParticipants[j]);			
			}			
		}
//		this.selectedParticipantsGrid.selection.removeSelected();
		this.selectedParticipantsGrid.selection.storage.removeIDs(this.selectedParticipantsGrid.selection.getSelected());

		this.changedParticipants = aNewChPartArr;
		this.selectedParticipants = aNewPartArr;		
	},
	delSelRessources: function (){
		//if nothing selected
		if(this.selectedRessourcesGrid == null)
			return;		
		var aItemsToDelete = this.selectedRessourcesGrid.selection.getSelected();
		var aNewRessArr = new Array();
        var aNewChRessArr = [];
		for(var j = 0; j < this.selectedResource.length; j++){
			var bFound = false;
			for( var indx in aItemsToDelete)
			{
				if(this.selectedResource[j] == aItemsToDelete[indx])
				{
					var bFound = true;					
					break;
				}				
			}
			if(!bFound){
				aNewRessArr.push(this.selectedResource[j]);
                aNewChRessArr.push(this.selectedResource[j]);
			}			
		}
		
		this.selectedResource = aNewRessArr;
        this.changedResources = aNewChRessArr;
//		this.selectedRessourcesGrid.selection.removeSelected();
		this.selectedRessourcesGrid.selection.storage.removeIDs(this.selectedRessourcesGrid.selection.getSelected());
	},
	selectIDs: function(grid, sids) {
		grid.selection.reset();
		for (var ia = 0; ia < sids.length; ia++) {
			grid.selection.toggle(sids[ia]);
			if (ia == sids.length-1) {
				grid.focus = sids[ia];
				grid.showFocus();
			}
		}
	}	
}

ParticipantsSmall.prototype = Participants.prototype;

/*
 * 
 * Search in Addressbook (Recources, Groups)
 * Participant
 * 
 */

var contactAddressbookTreeParticipantLoaded = false;
var currentDivIdForAddressbook = "";
var defaultParticipantFolder = corewindow.defaultParticipantFolder || 6;
var clickedItemParticipant = corewindow.clickedItemParticipant;
register("OX_Configuration_Loaded_Complete", function() {
    ox.api.folder.exists({
        folder: "6", 
        success: function (GAL) {
            defaultParticipantFolder = GAL ? 6 : configGetKey("folder.contacts");
            if (clickedItemParticipant === undefined) {
                clickedItemParticipant = defaultParticipantFolder;
            }
        }
    });
});


function initParticipantContent() {
	setTimeout('participantsFolderPath()',100);
}


function hideAddressbookParticipantsTree(divId){
	$("treeDialogNewParticitpantList").style.display = "none";
}

/*
function toggleAddressbookParticipantsTree(divId){
	currentDivIdForAddressbook = divId;
	if($(divId).style.display == "none"){
		$(divId).style.display = "block";
	} else{
		$(divId).style.display = "none";
	}
}
*/

function toggleAddressbookParticipantsTree(){
	if($("treeDialogNewParticitpantList").style.display === "none"){
		centerPopupWindow($("treeDialogNewParticitpantList"));
		$("treeDialogNewParticitpantList").style.display = "block";
		$("treeDialogNewParticitpantList").style.top = "50px";
		//$("treeDialogNewParticitpantList").style.left = "70px";

	}
	else{
		$("treeDialogNewParticitpantList").style.display = "none";
	}
}

function participantsFolderPath() {
	var folderViewSettingsNewContact = new Object();
	var folderViewSettingsNewContactById = new Object();
	//Disable Email... 
	folderViewSettingsNewContactById["default"] = 4;
	folderViewSettingsNewContact["contacts"] = 8;
	folderViewSettingsNewContact["calendar"] = 4;
	folderViewSettingsNewContact["tasks"] = 4;
	folderViewSettingsNewContact["infostore"] = 4;
//	if(corewindow)
//		var oLocalState = corewindow.optFolderState.getState('folderAddressbookParticipant_tree_info');
//	else
//	var oLocalState = new Object();
	
	ox.api.ui.selectFolder({
    	type: "contacts",
    	id: "select-folder-popup-contacts",
    	callback: folderParticipantAction,
    	node: $('folderAddressbookParticipantTreeInfo')
    });			

	if(!contactAddressbookTreeParticipantLoaded)
	{
		contactAddressbookTreeParticipantLoaded = true;	
	}
	
	ox.api.folder.getPathString({
	    folder: clickedItemParticipant,
	    success: cb_AddressbookGetpath
	});
}

function cb_AddressbookGetpath(sPath)
{
	var tmpSlash = sPath.substr(sPath.length-1);
	
	if(tmpSlash == "/")
		sPath = sPath.substr(0, sPath.length-1);
	
	var tmpIndex = sPath.lastIndexOf("/") + 1;
	var finalFolderName = sPath.substr(tmpIndex);
	
	$('newParticipant_folderText').value = finalFolderName;
}

function folderParticipantAction(data) {
	hideAddressbookParticipantTree(currentDivIdForAddressbook);
	clickedItemParticipant = data.id;
	ox.api.folder.getPathString({
	    folder: clickedItemParticipant,
	    success: cb_AddressbookGetpath
	});
	triggerEvent("searchParticipants");
}
/*
function cb_AddressbookGetpath(sPath)
{
	var tmpSlash = sPath.substr(sPath.length-1);
	
	if(tmpSlash == "/")
		sPath = sPath.substr(0, sPath.length-1);
	
	var tmpIndex = sPath.lastIndexOf("/") + 1;
	var finalFolderName = sPath.substr(tmpIndex);
	
	document.getElementsByName('newParticipant_folder')[0].value = finalFolderName;
}
*/
function hideAddressbookParticipantTree(divId){
	$("treeDialogNewParticitpantList").style.display = "none";	
	treeAddressbookVisible = false;
}
fileloaded();