/*
 * Copyright 2005 - 2009  Zarafa B.V.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3, 
 * as published by the Free Software Foundation with the following additional 
 * term according to sec. 7:
 *  
 * According to sec. 7 of the GNU Affero General Public License, version
 * 3, the terms of the AGPL are supplemented with the following terms:
 * 
 * "Zarafa" is a registered trademark of Zarafa B.V. The licensing of
 * the Program under the AGPL does not imply a trademark license.
 * Therefore any rights, title and interest in our trademarks remain
 * entirely with us.
 * 
 * However, if you propagate an unmodified version of the Program you are
 * allowed to use the term "Zarafa" to indicate that you distribute the
 * Program. Furthermore you may use our trademarks where it is necessary
 * to indicate the intended purpose of a product or service provided you
 * use it in accordance with honest practices in industrial or commercial
 * matters.  If you want to propagate modified versions of the Program
 * under the name "Zarafa" or "Zarafa Server", you may only do so if you
 * have a written permission by Zarafa B.V. (to acquire a permission
 * please contact Zarafa at trademark@zarafa.com).
 * 
 * The interactive user interface of the software displays an attribution
 * notice containing the term "Zarafa" and/or the logo of Zarafa.
 * Interactive user interfaces of unmodified and modified versions must
 * display Appropriate Legal Notices according to sec. 5 of the GNU
 * Affero General Public License, version 3, when you propagate
 * unmodified or modified versions of the Program. In accordance with
 * sec. 7 b) of the GNU Affero General Public License, version 3, these
 * Appropriate Legal Notices must retain the logo of Zarafa or display
 * the words "Initial Development by Zarafa" if the display of the logo
 * is not reasonably feasible for technical reasons."
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *  
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

function onOpenItem(entryid)
{
	if(fields.length < 1) {
		// In anonymous-select, double-clicking the item just
		// selects the single item, and closes the window
		addressBookSubmit();
		window.close();
	} else {
		// Otherwise, only add the selected contact(s)
		addSelectedContacts();
	}
}

/**
* This function will add the selected contacts to the view
*/
function addSelectedContacts(destId)
{
	// when no destination is given, we use the default for that view
	if (!destId){
		destId = module.dest;
	}

	var destElem = dhtml.getElementById(destId);

	if(destElem) {
		var selectedMessages = module.getSelectedMessages();
		var selectedEntryid = null;
		
		if(selectedMessages.length >= 1) {
			for(var i=0;i<selectedMessages.length;i++){
				var element = dhtml.getElementById(selectedMessages[i]);
				
				var addName = false;
				selectedEntryid = module.entryids[selectedMessages[i]];
				var props = module.itemProps[selectedEntryid];
				
				// TODO:	This whole switch structure can be removed when we alter all code that is calling the addressbook,
				//			because all properties are returned in callbackdata. Only thing to check is when we need to expand dist lists or not.
				//			For now we assume that when type=fullemail we want to expand. Else we just give the item.
				switch(module.type){
					case "username":
					case "username_single":
						if (props["fileas"] && props["fileas"].trim()!=""){
							addName = props["fileas"].trim();
						}
						break;
					case "displayname":
					case "displayname_single":
						if (props["display_name"] && props["display_name"].trim()!=""){
							addName = props["display_name"].trim();
						}
						break;
					case "all_single":
					case "email_single":
						if (props["email_address"] && props["email_address"].trim()!=""){
							addName = props["email_address"].trim();
						}
						if (props["smtp_address"] && props["smtp_address"].trim()!=""){
							addName = props["smtp_address"].trim();
						}
						break;
					case "fullemail":
					default:
						if (props["email_address"] && props["email_address"].trim()!=""){
							switch (props["message_class"]){
								case "IPM.DistList.Organization":
								case "IPM.DistList":
									addName = mergeABItems(props["members"]);
									break;
								case "IPM.Contact":
								default:
									addName = props["email_address"];
									if(props["smtp_address"])
    									addName = props["smtp_address"];
									if (props["display_name"] && props["display_name"].trim()!=""){
										addName = props["display_name"] + " <"+addName+">";
									}
							}
						}
						break;
				}

				if (addName!=false){
					// fix entryid for contacts with multiple addressess
					if (props.entryid && props.entryid.indexOf("_")>0){
						props.entryid = props.entryid.substr(0,props.entryid.indexOf("_"));
					}

					if (module.type.indexOf("_single") > 0){
						destElem.value = addName;
						destElem.props = props;
					}else{
						// add email separator
						if (destElem.value.length > 0 && destElem.value.trim().substr(-1,1)!=";"){
							destElem.value  += "; ";
						}
						destElem.value += addName;
						if (typeof destElem.props == "undefined"){
							destElem.props = new Object;
						}
						destElem.props["multiple"] = true;
						destElem.props[props.entryid] = props;
						destElem.props[props.entryid].value = addName;
					}
					destElem.value = destElem.value.trim();
				}
			}
		} else if(destElem.id != "anonymous") {
			alert(_("Please select a contact"));
		}
	}
}

function addressBookSearchKeyInput(moduleObj, element, event)
{
	if (event.keyCode == 13){
		searchAddressBook();
	}
}

function addressBookSubmit()
{
	var result;

	if(fields.length > 0) {
		result = new Array();
		for(var i = 0; i < fields.length; i++) {
			var props = dhtml.getElementById(fields[i]).props;
			if (typeof props != "undefined"){
				result[fields[i]] = props
			}else{
				result[fields[i]] = new Object;
			}
			result[fields[i]].value = dhtml.getElementById(fields[i]).value;
		}
	} else {
		addSelectedContacts();

		// No fields given, return a single entry with entryid
		result = dhtml.getElementById("anonymous").props;
		if(result) {
			result.value = dhtml.getElementById("anonymous").value;
		} else {
			return false;
		}
	}
			
	return window.resultCallBack(result, window.callBackData);
}

function mergeABItems(items)
{
	var result = "";
	if (items["member"]){
		items = items["member"];
	}

	if (!items.length){
		items = new Array(items);
	}
	for(var i=0;i<items.length;i++){
		if (items[i].email_address){
			var email = items[i].email_address;
			if(items[i].smtp_address)
			    email = items[i].smtp_address;

			if (items[i].display_name){
				email = items[i].display_name + " <" + email + ">";
			}else if (items[i].fileas){
				email = items[i].fileas + " <" + email + ">";
			}

			result += email +"; ";
		}
	}
	return result;
}


function changeAddressBookFolder(folders)
{
	var folder;
	if (typeof(folders)=="undefined" || folders.options.length==0){
		folder = new Object;
		folder.folderType = webclient.settings.get("addressbook/default/foldertype","gab");
		folder.value = webclient.settings.get("addressbook/default/entryid","");
		folder.storeid = webclient.settings.get("addressbook/default/storeid","");
	}else{
		folder = folders.options[folders.selectedIndex];
	}

	var sortSaveList = new Object();
	
	// Get sorting data from the settings.
	var sortData = module.loadSortSettings();
	/**
	 * If folder is changed to contact from GAB then change sorting column on email_address
	 * If folder is changed to GAB from contact then change sorting column on smtp_address
	 */
	if(sortData)
	{
		if(folder.folderType == "contacts" && (sortData[0]["_content"] == "smtp_address" || sortData[0]["_content"] == "email_address")) {
			sortSaveList["email_address"] = sortData[0]["attributes"]["direction"];
			module.saveSortSettings(sortSaveList);
		} else if(sortData[0]["_content"] == "email_address") {
			sortSaveList["smtp_address"] = sortData[0]["attributes"]["direction"];
			module.saveSortSettings(sortSaveList);
		}
	}

	if (module.source=="gab" && folder.folderType && folder.folderType!="gab"){
		// when default ab folder is not from GAB and we request only from GAB: force to use GAB
		module.entryid = "";
		module.list("globaladdressbook");
	}else if(!folder.folderType || folder.folderType=="gab") {
		module.entryid = folder.value;
		module.list("globaladdressbook");
	} else {
		module.storeid = folder.storeid;
		module.entryid = folder.value;
		module.list("contacts");
	}
}

function searchAddressBook()
{
	var name = dhtml.getElementById("name");
	if(name) {
		module.list(false, false, name.value);
	}
}

function getAddressBookRecipients(recipients)
{
	var parentwindow = window.opener;
	if(!parentwindow) {
		if(window.dialogArguments) {
			parentwindow = window.dialogArguments.parentWindow;
		}
	}

	switch (typeof recipients){
		case "string":
			recipients = new Array(recipients);
			break;
		case "undefined":
			recipients = new Array("to", "cc", "bcc");
			break;
	}
	
	for(var i = 0; i < recipients.length; i++)
	{
		var type = parentwindow.dhtml.getElementById(recipients[i]);
		if(type) {	
			dhtml.getElementById(recipients[i]).value = type.value;
		}
	}
}

function setAddressBookRecipients(recipients)
{
	var parentwindow = window.opener;
	if(!parentwindow) {
		if(window.dialogArguments) {
			parentwindow = window.dialogArguments.parentWindow;
		}
	}
	
	switch (typeof recipients){
		case "string":
			recipients = new Array(recipients);
			break;
		case "undefined":
			recipients = new Array("to", "cc", "bcc");
			break;
	}

	for(var i = 0; i < recipients.length; i++)
	{
		var type = parentwindow.dhtml.getElementById(recipients[i]);
		if(type) {
			var el = dhtml.getElementById(recipients[i]);
			type.value = el.value;
			if (el.entryid){
				type.entryid = el.entryid;
			}
		}	
	}
	
	// call addressbook handler of calling module if exists
	if (parentwindow && parentwindow.module && parentwindow.module.abHandler){
		parentwindow.setTimeout(parentwindow.module.abHandler, 10);
	}
}
