/**
 * 

 * 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) Open-Xchange Inc., 2006-2011
 * Mail: info@open-xchange.com 
 * 
 * @author Suphi Basdemir <suphi.basdemir@open-xchange.com>
 * 
 */

/**
 * Search for Contacts in different Addressbooks
 * makes a liveGrid for Searchresult, an append the selected to a LiveGrid or
 * in a Input field
 * @param {String} searchstring for pattern in the database
 * @param {String} Id of the main search dialog div
 * @param {String} Id of the div for the Livegrid, in the search dialog
 * @param {String} optional: for appending the Contacts in a LiveGrid of the page
 * @param {String} Id from div, for the selected Contacts in the search dialog
 * @param {String} Id from div, for clearing the search string in the search dialog
 * @param {Array} optional: if suffix of each Inputfield (example: 'to' and 'cc' for newmail_btn_add_to, newmail_btn_add_cc)
 * 
 * the DOM Event as parameter.
 */

function SearchListAddressBook(searchstring, floatingpopupdiv, liveGridDivSearch, liveGridDivResult, divAddContact, searchField, moreFields)
{
	var Self = this;
	this.emptySearchText = _("Please enter your search");
	this.searchField = searchField;
	this.blurTimer;
	addressbookFolderPath();
	this.divAddContact = divAddContact;
	this.liveGridDivResult = liveGridDivResult;
	this.liveGridDivSearch = liveGridDivSearch;
	this.floatingpopupdiv = floatingpopupdiv;
	this.searchstring = searchstring;
	this.resulObject = {};
	this.arrayWhithDistrContact = new Array();
	this.numberOfSelection = 0;
	this.findContactForDistrList = null;
	this.buildContactForDistrList = new Array();
	this.tmpIdsForSave = new Array();
	this.contactsForBigGrid = {};
	this.tmpCountAppendet = 0;
	this.tmpCountSearchAppendet = 0;
	this.contactsForBigGrid.data = new Array();
	this.internalStorage = new Storage(0, []);
	this.internalResultStorage = new Storage(0, []);
	//this.internalResultStorage = new Storage(0, [], "", 0, 0,  null, function(x){ return x[0] + "." + x[1];});
	this.setAdding = "";
	this.distrids = new Array();
	this.myAddedContacts = new AddedSearchContacts();
	this.updateList = false;
	this.tmpDistId = 210000000;
	this.moreFields = new Array();
	
	if(moreFields)
	this.moreFields = moreFields;
	this.method = "";
	this.aFindedAddressboks = new Array();
	this.recipientType = "to";	
	$(this.searchField).value = this.emptySearchText;
	this.enabled = false;
	
    Self.clickOnCombobox = function (e) {
    	if (Self.blurTimer != undefined) {
            clearTimeout(Self.blurTimer);
            delete(Self.blurTimer);
        }
        if ($(searchField).value == Self.emptySearchText) {
            $(searchField).value="";
            $(Self.searchField).style.color="";
        } else if (e.keyCode == 13) {
            Self.searchstring = $(searchField).value;            
            Self.getResult();
            //$(liveGridDivResult).focus();
        }
    };
    Self.enterInput = function(e) {
    	Self.blurTimer = setTimeout(function() {
	        if (trimStr($(searchField).value).length == 0) {
	            $(searchField).value=Self.emptySearchText;
	            $(Self.searchField).style.color="silver";
	        }
        }, 100);
    }; 
    
    addDOMEvent($(this.searchField), "keypress", Self.clickOnCombobox); 
    addDOMEvent($(this.searchField), "click", Self.clickOnCombobox);
    addDOMEvent($(this.searchField), "blur", Self.enterInput); 
	
	register("searchContacts", function(){ if(Self.enabled) Self.getResult(); });
}

SearchListAddressBook.prototype = {

    setAllFolders: function(checkbox, folder_button) {
        if (configGetKey("modules.contacts.singleFolderSearch")) return;
        var setDisabled = classNameSetter("font-color-disabled");
        checkbox.parentNode.parentNode.parentNode.style.display = "";
        checkbox.checked = true;
        setDisabled(folder_button, true);
        checkbox.onclick = function() {
            setDisabled(folder_button, checkbox.checked);
        };
        this.allFoldersCheckbox = checkbox;
    },

	displayError: function(msg) {
        $(this.floatingpopupdiv+"SearchError").style.display="";
        $(this.floatingpopupdiv+"SearchError").getElementsByTagName("DIV")[0].firstChild.data=msg;
    },
	getResult: function() {	        
		var Self = this;
        this.searchstring="";
        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("modules.contacts.mailAddressAutoSearch") &&
                configGetKey("modules.contacts.mailAddressAutoSearch") == false) {
            	this.searchstring = "";
                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 {
    	   $(Self.searchField).style.color="";
    	   this.searchstring=inVal;
        }
		var pattern = trimStr(this.searchstring) ? this.searchstring : "*";
        this.searchObject = {
            display_name: pattern, first_name: pattern, last_name: pattern,
            email1: pattern, email2: pattern, email3: pattern, orSearch: true
        };
        if (configGetKey("language") == "ja_JP") {
            this.searchObject.yomiFirstName = pattern;
            this.searchObject.yomiLastName = pattern;
        }
        if (!this.allFoldersCheckbox || !this.allFoldersCheckbox.checked) { 
            this.searchObject.folder = clickedItem;
        }
		
		if(!json)
		var json = new JSON();
		this.distrids = [];
		json.put(AjaxRoot + "/contacts?action=search&session=" + corewindow.session + "&columns=1,500,555,556,557,524,602,592,501,502,20",
			Self.searchObject,
			null,
			function(findContactForDistrList) {	
				/*
		         * 0 = id               (1)
		         * 1 = display_name     (500)
				 * 2 = email1           (555)
				 * 3 = email2           (556)
				 * 4 = email3           (557)
				 * 5 = internal_userid  (524)
				 * 6 = mark_as_distri.  (602)
				 * 7 = distribution_l.  (592)
				 * 8 = first name
				 * 9 = last name
				 * 10 = folder_id       (20)
				 */
				
				/* click on "Go" for search in the Addressbook */
				Self.findContactForDistrList = findContactForDistrList;
				Self.findContactForDistrList.events = new Events();	
				Self.buildContactForDistrList = [];
				var tmpLaufIndex = Self.findContactForDistrList.data.length;
				for(i=0; i<tmpLaufIndex; i++) {	
                    Self.findContactForDistrList.data[i][0] += "\x01" +
                        Self.findContactForDistrList.data[i][10];
					(function() {
						if(Self.findContactForDistrList.data[i][6]) {
							/* the finded "contact" is a distribution list */
							if((Self.method && Self.method == "mail") || (Self.moreFields && Self.moreFields.length > 0)) {
								var tmpDistArray = new Array();
								tmpDistArray[0] = Self.findContactForDistrList.data[i][0];
								tmpDistArray[1] = Self.findContactForDistrList.data[i][1];
								tmpDistArray[2] = "";
								tmpDistArray[3] = "true";
								var tmpString = "";
								if(Self.findContactForDistrList.data[i][7]) {
									for(var t=0; t<Self.findContactForDistrList.data[i][7].length;t++) {
										if(t==0) {
											tmpString = Self.findContactForDistrList.data[i][7][t].mail;
										} else {
											tmpString += ", "+Self.findContactForDistrList.data[i][7][t].mail;
										}
									}
									tmpDistArray[4] = tmpString;
									Self.buildContactForDistrList.push(tmpDistArray);
									Self.myAddedContacts.setAllFinded(
													tmpDistArray[0],
													tmpDistArray[4]
										);	
								}
							}
						} else {
							/* the flag in [index 6] is false, so this contact is not a distribution list  */
							var displayName = "";
							if (Self.findContactForDistrList.data[i][1]) {
								displayName = Self.findContactForDistrList.data[i][1];
							} else if (Self.findContactForDistrList.data[i][8] || Self.findContactForDistrList.data[i][9]) {
								displayName = (Self.findContactForDistrList.data[i][9] || "") + ", " 
									+ (Self.findContactForDistrList.data[i][8] || "");
							}
							
                            var findEmails = 0;
							if(Self.findContactForDistrList.data[i][2]) {
								var tmpDistArray = new Array();
								tmpDistArray[0] = Self.findContactForDistrList.data[i][0];
								tmpDistArray[1] = displayName;
								tmpDistArray[2] = Self.findContactForDistrList.data[i][2];
								Self.buildContactForDistrList.push(tmpDistArray);
								findEmails = 1;		
								Self.distrids.push(tmpDistArray[0]);
								Self.myAddedContacts.setAllFinded(tmpDistArray[0], tmpDistArray[2]);				
							}
							
							if(Self.findContactForDistrList.data[i][3]) {
								var tmpDistArray = new Array();
								tmpDistArray[1] = displayName;
								tmpDistArray[2] = Self.findContactForDistrList.data[i][3];
								
								Self.buildContactForDistrList.push(tmpDistArray);
								if(findEmails == 0) {
									tmpDistArray[0] = Self.findContactForDistrList.data[i][0];
								} else {
									tmpDistArray[0] = Self.tmpDistId;
									Self.findContactForDistrList.data.push(tmpDistArray);
									Self.tmpDistId++;
								}
								findEmails = 1;		
								
								Self.distrids.push(tmpDistArray[0]);
								Self.myAddedContacts.setAllFinded(tmpDistArray[0], tmpDistArray[2]);					
							}
							
							if(Self.findContactForDistrList.data[i][4]) {
								var tmpDistArray = new Array();
								tmpDistArray[1] = displayName;
								tmpDistArray[2] = Self.findContactForDistrList.data[i][4];
								if(findEmails == 0) {
									tmpDistArray[0] = Self.findContactForDistrList.data[i][0];
								} else {
									tmpDistArray[0] = Self.tmpDistId;
									Self.findContactForDistrList.data.push(tmpDistArray);
									Self.tmpDistId++;
								}
								
								Self.distrids.push(tmpDistArray[0]);
								Self.buildContactForDistrList.push(tmpDistArray);
								findEmails = 1;		
								
								Self.myAddedContacts.setAllFinded(tmpDistArray[0], tmpDistArray[2]);					
							}
						}
					})();
				}
				Self.internalStorage.remove(0,Self.tmpCountSearchAppendet);
				Self.internalStorage.append(Self.buildContactForDistrList);	
				Self.aFindedAddressboks.push(Self.buildContactForDistrList);
				/* 
				 * Self.buildContactForDistrList 
				 * is an array with Object with the ids and tmpIds
				 * all finded valid Contact are inside 
				 * */
				distruGrid.enable(Self.internalStorage); 
				Self.tmpCountSearchAppendet = Self.buildContactForDistrList.length;
			}
		);
	},
	
	/*
	 * result view for Modules with Livegrid
	 */   	
	showResult: function(insertDistribution) {		
		this.insertDistribution = insertDistribution;
		
		if (this.insertDistribution == "extern" && myDistrListExternEmails.storage.ids.length != 0) { //external email
		  	for (i = 0; i < myDistrListExternEmails.storage.ids.length; i++) {		  		
		  		var extObj = myDistrListExternEmails.storage.data.data[i];
		  		if (!this.myAddedContacts.exist(extObj.displayName + extObj.email)) {
		  			this.contactsForBigGrid.data[this.contactsForBigGrid.data.length] = [ this.tmpDistId++, extObj.displayName, extObj.email ] ;
		  			this.myAddedContacts.set(extObj.displayName + extObj.email, true);
                    this.updateList = true;
		  		}
		  	}
		
		} else if (this.insertDistribution == "db") {
			if(this.findContactForDistrList) { //internal email
			    /* this is the function after clicking to "Ok" in the bottom, to accept the selected data or contacts */
					for(i=0; i< this.findContactForDistrList.data.length; i++){
						for(j=0; j< this.tmpIdsForSave.length; j++) {
							if(this.tmpIdsForSave[j] == this.findContactForDistrList.data[i][0]) {
								
								if(this.findContactForDistrList.data[i][0] == 0 || typeof this.findContactForDistrList.data[i][0] == "undefined") {
									this.findContactForDistrList.data[i][0] = this.tmpDistId;
									this.tmpDistId++;
								}
								if(!this.myAddedContacts.exist(this.findContactForDistrList.data[i][2]+this.findContactForDistrList.data[i][3])) {
									this.contactsForBigGrid.data[this.contactsForBigGrid.data.length] = 
																			this.findContactForDistrList.data[i];
									
				
									this.myAddedContacts.set(
										this.findContactForDistrList.data[i][2]+this.findContactForDistrList.data[i][3],
										true
									);										
								}						
							}			
						}
					}
					
					this.tmpIdsForSave = [];
				}
			} else {
				if(this.aFindedAddressboks) { //internal email
			    /* this is the function after clicking to "Ok" in the bottom, to accept the selected data or contacts */
					for(i=0; i< this.aFindedAddressboks.length; i++){
						/* through each addressbook from the search result  */
						for(k=0; k< this.aFindedAddressboks[i].length; k++){
							/* the arrays in the addressbook (index 0 = id, index 1 = display name, index 2 = mail address)  */
							for(j=0; j< this.tmpIdsForSave.length; j++) {
								if(this.tmpIdsForSave[j] == this.aFindedAddressboks[i][k][0]) {
									
									if(this.aFindedAddressboks[i][k][0] == 0 || typeof this.aFindedAddressboks[i][k][0] == "undefined") {
										this.aFindedAddressboks[i][k][0] = this.tmpDistId;
										this.tmpDistId++;
									}
									if(!this.myAddedContacts.exist(this.aFindedAddressboks[i][k][1]+this.aFindedAddressboks[i][k][2])) {
										this.contactsForBigGrid.data[this.contactsForBigGrid.data.length] = 
																				this.aFindedAddressboks[i][k];
										
										this.myAddedContacts.set(
													this.aFindedAddressboks[i][k][1]+this.aFindedAddressboks[i][k][2],
													true
										);										
									}						
								}			
							}
						}
					}
					
					this.tmpIdsForSave = [];
				}
			}
			
			
			var Self = this;
			Self.internalResultStorage.remove(0,Self.tmpCountAppendet);
			Self.internalResultStorage.append(Self.contactsForBigGrid.data);
			
			if(Self.internalResultStorage.ids.length > 0)
			distruBigGrid.enable(Self.internalResultStorage);
			
			
			/*if(this.arrayWhithDistrContact.length != 0) {
				distruBigGrid.enable(this.internalResultStorage);
				
			} else {
				//distruBigGrid.disable();
			}*/
			this.tmpCountAppendet = this.contactsForBigGrid.data.length;
	},
	
	showResultInInput: function(insertDistribution) {	
		/*
		 * result view for Mail Module
		 * */
		if(this.moreFields && this.moreFields.length > 0) {
			var valueToInputArray = new Array();
			for (var i = 0; i < this.moreFields.length; i++) {
				valueToInputArray[i] = $(this.divAddContact + "_" + this.moreFields[i]).value;
				if (!valueToInputArray[i] || valueToInputArray[i].length == 0) continue;
				$(this.moreFields[i]).value += this.setSemicolon(valueToInputArray[i], this.moreFields[i]);
				oMailFunctionsNew.showAdditionalHeaderField(this.moreFields[i], true);
			}
		} else {
			var valueToInput = $(this.divAddContact).value;
			if(valueToInput != '') {
				$(this.recipientAs).value += this.setSemicolon(valueToInput, this.recipientAs);
			}
		}		
		this.closeDiv();	
	},
	
	setSemicolon: function(value, divRecipientId) {
		if(value == "") return "";
		var valueToInput = value;
		var valueInitToInput = $(divRecipientId).value;
		var indexOfSemicolon = valueInitToInput.lastIndexOf(',');
		var lengthOfString = valueInitToInput.length - 2;
		if(valueInitToInput != '' && indexOfSemicolon == (lengthOfString + 1 )) {
			//the last char is a semicolon, whitout space
			valueToInput = " " + valueToInput;
		} else if(valueInitToInput != '' && indexOfSemicolon < lengthOfString) {
			//the last char is not a semicolon
			valueToInput = ", " + valueToInput;			
		} else {
			//input field is empty
		}
		return valueToInput;
	}, 
	
	addToList: function(setAdding, fieldSuffix){
		this.setAdding = setAdding;
				
		//mySelectedDistrContacts = 3405.name, 3333.name
		if(distruGrid.storage) {			
			var mySelectedDistrContacts = distruGrid.selection.getSelected();
			if((mySelectedDistrContacts.length > 0 && this.setAdding == "bySelection") || this.setAdding == "all") {	
				var myTmpArray = new Array();
				if(this.setAdding == "bySelection") {
					mySelectedDistrContacts = mySelectedDistrContacts.toString();
					myTmpArray = mySelectedDistrContacts.split(",");	
				} else {
					myTmpArray = distruGrid.storage.ids;
				}				
				
				for(i=0; i<myTmpArray.length;i++) {
					if(myTmpArray[i] in this.arrayWhithDistrContact) {
						//alert("already in list");
					} else {							
						this.updateList = true;
						this.arrayWhithDistrContact[myTmpArray[i]] = this.myAddedContacts.getFromAll(myTmpArray[i]);
					}	
				}
				
				if(fieldSuffix) {
					var tmpArrayWhithNames = $(this.divAddContact + '_' + fieldSuffix).value;
					this.recipientType = fieldSuffix;
				} else {
					var tmpArrayWhithNames = "";
				}
				for(i in this.arrayWhithDistrContact) {
					if(tmpArrayWhithNames == "") {
						tmpArrayWhithNames = this.arrayWhithDistrContact[i];
					}
					else {
						tmpArrayWhithNames += ", " + this.arrayWhithDistrContact[i];
					}
					this.tmpIdsForSave[this.tmpIdsForSave.length] = i;
				}
				if(fieldSuffix) {
					$(this.divAddContact + '_' + fieldSuffix).value = tmpArrayWhithNames;
					this.arrayWhithDistrContact = [];
				} else {
					$(this.divAddContact).value = tmpArrayWhithNames;
				}
				
				
			} else {
				newConfirm(_("Select a contact"),_("Please select a contact to add"),AlertPopup.OK,null,null,null,null);		
			} 
		} /* else {
			triggerEvent("OX_New_Error", 4, "Please search to add Contact");
		}*/
	},
	deleteSelected: function(callbak) {	
		var mySelectedDistrContacts = distruBigGrid.selection.getSelected(distruBigGrid.storage);
		for (i=0; i< mySelectedDistrContacts.length; i++) {
			for(t=0; t< this.contactsForBigGrid.data.length; t++) {
				if(this.contactsForBigGrid.data[t][0] == mySelectedDistrContacts[i]) {
					var hashKey = this.contactsForBigGrid.data[t][1]+this.contactsForBigGrid.data[t][2];
					for(value in this.myAddedContacts.addContacts) {
						if(value == hashKey)
							this.myAddedContacts.addContacts[value] = false;
					}
					this.contactsForBigGrid.data.splice(t,1);	
					this.updateList = true;		
				}
			}
		}	
		if(callbak) callbak();
		//distruBigGrid.deleteSelected();	
	},
	clearList: function(){
		this.arrayWhithDistrContact = [];	
		this.tmpIdsForSave = [];
		if(this.moreFields && this.moreFields.length > 0) {
			for(var i = 0; i < this.moreFields.length; i++) {
				$(this.divAddContact + "_" + this.moreFields[i]).value = "";
			}
		} else {
			$(this.divAddContact).value = "";
		}
	},
	resetView: function() {
		this.clearList();
		this.tmpIdsForSave = [];
		if(distruGrid.storage) {
			distruGrid.storage.remove(0,this.tmpCountSearchAppendet);
		}
		//$(this.searchField).value = "";
	},
	resetGrid: function() {		
        if(distruGrid && distruGrid.storage) {
        	distruGrid.disable();        	
            this.internalStorage = new Storage(0, []);            
            this.makeGrid();
        }
	},	
	makeGrid: function() {
		var list = $(this.liveGridDivSearch);
		var listHeader = $(this.liveGridDivSearch + "Header");
		if (distruGrid) 
		{
			removeChildNodes(listHeader);
			list.innerHTML = "";
			distruGrid = null;
		}
		
		distruGrid = new LiveGrid([
			{
				text: "&#xa0;",
				sortable: true,
				width: "20px",
				style: {padding: 0},
				set: function(div,text) {
					var divIcons = "";
					if (div) {
						if (text) {
							divIcons = "<img src='"+getFullImgSrc("img/menu/distributionlist.gif")+"' alt='Distribution List' />"; 
						} else {
							divIcons = "<img src='"+getFullImgSrc("img/folder/contacts.gif")+"' alt='Contact' />"; 
						}
						
					}
						div.innerHTML = divIcons;
				},
				clear: LiveGrid.makeClear("..."),
				index:3
			},{	
				text: _("Name"),
				sortable: true,
				width: "40%",
				set: LiveGrid.defaultSet,
				clear: LiveGrid.makeClear("..."),
				index:1
			}, {
				text: _("E-Mail"),
				/* sortable: true, */
				set: LiveGrid.defaultSet,
				clear: LiveGrid.makeClear("..."),
				index:2
			}
		], new Selection());
		listHeader.appendChild(distruGrid.getHeader());
		distruGrid.getTable(list);
		
		var Self = this;
		distruGrid.events.register("Activated", 
			function(ids){
				if(Self.moreFields && Self.moreFields.length > 0)
					Self.addToList('bySelection', Self.recipientType);		
				else
					Self.addToList('bySelection');				
			}
		);	
	},
	makeBigGrid: function() {
		var list = $(this.liveGridDivResult);
		var listHeader = $(this.liveGridDivResult + "Header");
		if (distruBigGrid) 
		{
			list.innerHTML = "";
			distruBigGrid = null;
		}
		
		distruBigGrid = new LiveGrid([
			{	
				text: _("Name"),
				sortable: true,
				width: "50%",
				set: LiveGrid.defaultSet,
				clear: LiveGrid.makeClear("..."),
				index:1
			}, {
				text: _("E-Mail"),
				sortable: true,
				set: LiveGrid.defaultSet,
				clear: LiveGrid.makeClear("..."),
				index:2
			}
		], new Selection());
		
		distruBigGrid.emptylivegridtext = "No recipients have been added";/*i18n*/
		
		listHeader.appendChild(distruBigGrid.getHeader());
		distruBigGrid.getTable(list);
		
		
		distruBigGrid.events.register("Selected", 
			function(ids){
				triggerEvent("SubSelected",distruBigGrid.getSelectedIDs().length);				
			}
		);		
			
	},
	
	buildFloatingDiv: function(style) {
		this.enabled = true;
		$(this.floatingpopupdiv).style.display = style;
		this.makeGrid();
		
		//clear values
		this.arrayWhithDistrContact = [];
		if(this.moreFields && this.moreFields.length > 0) {
			for(var i = 0; i < this.moreFields.length; i++) {
				$(this.divAddContact + "_" + this.moreFields[i]).value = "";
			}
		} else {
			$(this.divAddContact).value = "";
		} 		
	},
	
	closeDiv: function() {
		this.disableActiveGrids();
		$(this.floatingpopupdiv).style.display = 'none';
	},
	
	disableActiveGrids : function() {		
		if(distruGrid && distruGrid.storage) {
			distruGrid.storage.remove(0,this.tmpCountSearchAppendet);
			window.setTimeout(function() {
					distruGrid.disable();
			}, 0);
		}
	}
};


function AddedSearchContacts() {
	this.addContacts = new Array();
	this.allFindedContacts = new Array();
}

AddedSearchContacts.prototype = {
	
	set : function(key,value) {
		this.addContacts[key] = value;
	},
	
	setAllFinded : function(key,value) {
		this.allFindedContacts[key] = value;
	},
	
	getFromAll : function(key) {
		var myItem = this.allFindedContacts[key];
		return (myItem) ? myItem : false;
	},
	
	exist: function(key) {
		var tmpItem = this.addContacts[key];
		return (tmpItem) ? true : false;
	}
	
};

var contactAddressbookTreeLoaded = false;
var treeAddressbookVisible = false;
var clickedItem = "";
var currentDivIdForAddressbook = "";

function addressbookFolderPath() {
	ox.api.folder.exists({
	    folder: "6",
	    success: function (GAL) {
            clickedItem = GAL ? 6 : corewindow.configGetKey("folder.contacts");
        	session = corewindow.session;
        	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 || window.parent)
//        		var oLocalState = corewindow.optFolderState.getState('folderAddressbook_tree_info');
//        	else
//        		var oLocalState = new Object();	
        	if(!contactAddressbookTreeLoaded){
            			
        			ox.api.ui.selectFolder({
        		    	type: "contacts",
        		    	id: "select-folder-popup-contacts",
        		    	callback: folderAction,
        		    	node: $('folderAddressbook_tree_info')
        		    });
        			
        			contactAddressbookTreeLoaded = true;
        	}
    		    
        	ox.api.folder.get({ folder: clickedItem, success: cb_AddressbookGetpath});
	    }
	});
}
	

function cb_AddressbookGetpath(data)
{
	/*
	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);
	*/
	var vb = document.getElementsByName('newcontact_folder')[0].value = data.title;
}

function folderAction(data) {
	hideAddressbookTree(currentDivIdForAddressbook);
	clickedItem = data.id;
	ox.api.folder.get({ folder: clickedItem, success: cb_AddressbookGetpath });
    triggerEvent('searchContacts');
}

function hideAddressbookTree(divId){
	$(divId).style.display = "none";	
	treeAddressbookVisible = false;
}

function toggleAddressbookTree(divId){
	currentDivIdForAddressbook = divId;
	if(!treeAddressbookVisible){
		$(divId).style.display = "block";
		treeAddressbookVisible = true;
	}
	else{
		$(divId).style.display = "none";
		treeAddressbookVisible = false;
	}
}
