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

hierarchyselectmodule.prototype = new Module;
hierarchyselectmodule.prototype.constructor = hierarchyselectmodule;
hierarchyselectmodule.superclass = Module.prototype;

function hierarchyselectmodule(id, element)
{
	if(arguments.length > 0) {
		this.init(id, element);
	}
}

/* Creates a hierarchy-select module on the position of 'element', identified
 * by module ID 'id'. The 'storeonly' optional value is TRUE if only full
 * stores should be shown (so shared folders are NOT shown)
 */
hierarchyselectmodule.prototype.init = function(id, element, storeonly)
{
	hierarchyselectmodule.superclass.init.call(this, id, element);
	
	this.defaultstore = false;
	this.stores = new Array();
	this.selectedFolder = false;
	this.selectedFolderStoreId = false;

	if(storeonly)
	    this.storeonly = true;
    else
        this.storeonly = false;

	this.folderEvents = new Object();
	this.folderEvents["click"] = eventHierarchyCopyMoveSelectFolder;
	
	this.treeEvents = new Object();
	this.treeEvents["ShowBranch"] = eventTreeShowBranch;
	this.treeEvents["SwapFolder"] = eventTreeSwapFolder;

	this.contentElement = this.element;	
}

hierarchyselectmodule.prototype.execute = function(type, action)
{
	switch(type)
	{
		case "list":
			var stores = action.getElementsByTagName("store");

			for(var j = 0; j < stores.length; j++)
			{
				var store = new Object();

				var attributes = stores[j].attributes;
				for(var i = 0; i < attributes.length; i++)
				{
					var item = attributes.item(i);
					
					switch(item.nodeName)
					{
						case "id":
							store["id"] = item.nodeValue;
							break;
						case "subtree":
							store["subtree_entryid"] = item.nodeValue;
							break;
						case "name":
							store["name"] = item.nodeValue;
							break;
						case "type":
							store["type"] = item.nodeValue;
							if (store["type"] == "default"){
								this.defaultstore = store;
							}
							break;
						case "foldertype":
							store["foldertype"] = item.nodeValue;
							break;
					}
				}

				var defaultfolders = stores[j].getElementsByTagName("defaultfolders")[0];
				store["defaultfolders"] = new Object();
				if (defaultfolders && defaultfolders.childNodes){	
					for(var i = 0; i < defaultfolders.childNodes.length; i++)
					{
						var folder = defaultfolders.childNodes[i];
						
						if(folder.firstChild) {
							store["defaultfolders"][folder.nodeName] = folder.firstChild.nodeValue;
						}
					}
				}
				
				var folders = stores[j].getElementsByTagName("folder");
				store["folders"] = new Array();
				
				for(var i = 0; i < folders.length; i++)
				{
					var folder = this.setFolder(folders[i]);
					
					if(folder) {
						if(folder["entryid"] == store["subtree_entryid"]) {
							folder["display_name"] = store["name"];
							store["root"] = folder;
						} else {
							store["folders"].push(folder);
						}
					}
				}
				
				this.stores.push(store);
			}
			
			// sorting storelist
			this.stores.sort(this.sortStores);
			
			this.createHierarchyList();
			
			if(this.selectedFolder)
				this.selectFolder(this.selectedFolder);
				
			break;
	}
}

hierarchyselectmodule.prototype.setFolder = function(folderobject)
{
	var folder = false;
	
	if(folderobject) {
		var entryid = folderobject.getElementsByTagName("entryid")[0];
		var parent_entryid = folderobject.getElementsByTagName("parent_entryid")[0];
		var display_name = folderobject.getElementsByTagName("display_name")[0];
		var subfolders = folderobject.getElementsByTagName("subfolders")[0];
		var content_count = folderobject.getElementsByTagName("content_count")[0];
		var content_unread = folderobject.getElementsByTagName("content_unread")[0];
		var container_class = folderobject.getElementsByTagName("container_class")[0];
		
		if(entryid.firstChild && parent_entryid.firstChild && display_name.firstChild) {
			folder = new Object();
			folder["entryid"] = entryid.firstChild.nodeValue;
			folder["parent_entryid"] = parent_entryid.firstChild.nodeValue;
			folder["display_name"] = display_name.firstChild.nodeValue;
			folder["subfolders"] = subfolders.firstChild.nodeValue;
			folder["content_count"] = content_count.firstChild.nodeValue;
			folder["content_unread"] = content_unread.firstChild.nodeValue;
			folder["container_class"] = container_class.firstChild.nodeValue;
		}
	}
	
	return folder;
}

hierarchyselectmodule.prototype.createHierarchyList = function(load)
{
	this.deleteLoadMessage();
	
	// Loop through all stores
	for(var i = 0; i < this.stores.length; i++)
	{
		var store = this.stores[i];
		var tree = new Tree(this.id, this.contentElement, this.treeEvents);
		
		// If required, skip shared folders
		if(store["foldertype"] != "all" && this.storeonly)
		    continue;
		
		store["tree"] = tree;

		var attributes = new Object;
		attributes.storeid = store["id"];
		attributes.displayname = store["root"]["display_name"];

		tree.createNode(store["root"]["parent_entryid"], store["root"]["entryid"], true, store["root"]["display_name"], "store", store["root"]["subfolders"], (store["root"]["entryid"] == this.defaultstore["root"]["entryid"]?true:false), this.folderEvents, null, attributes);
		
		// Loop through all folders in the store
		for(var j = 0; j < store["folders"].length; j++)
		{
			var folder = store["folders"][j];
			var iconClass = false;
			
			// Handle special folders
			for(var folderType in store["defaultfolders"])
			{
				if(store["defaultfolders"][folderType] == folder["entryid"]) {
					iconClass = folderType;
				}
			}
			
			if(!iconClass) {
				switch(folder["container_class"])
				{
					case "IPF.Appointment":
						iconClass = "calendar";
						break;
					case "IPF.Contact":
						iconClass = "contact";
						break;
					case "IPF.Task":
						iconClass = "task";
						break;
					case "IPF.StickyNote":
						iconClass = "note";
						break;
					default:
						iconClass = "mail";
						break;
				}
			}
		
			attributes = new Object;
			attributes.storeid = store["id"];
			attributes.displayname = folder["display_name"];
			
			// Create the actial node in the tree 
			tree.createNode(folder["parent_entryid"], folder["entryid"], false, folder["display_name"], iconClass, folder["subfolders"], false, this.folderEvents, null, attributes);
		}
		//to check weather the parent folders of selected folder is open or not.
		if(this.selectedFolder){
			var selectedNode = tree.getNode(this.selectedFolder);
			if (selectedNode && selectedNode.attributes.storeid == store.id) {
				var parentNode	= tree.getNode(selectedNode["parentid"]);
				while((parentNode != false) && (parentNode["id"] != store.root["entryid"])){
					parentNode["open"] =(parentNode["hasChildNodes"]=="1")? true: false;
					selectedNode = parentNode;
					parentNode = tree.getNode(selectedNode["parentid"]);
				}
			}
		}
		tree.buildTree();
	}

}

hierarchyselectmodule.prototype.list = function()
{
	webclient.xmlrequest.addData(this, "list");
	webclient.xmlrequest.sendRequest();
	this.loadMessage();
}

hierarchyselectmodule.prototype.selectFolder = function(entryid)
{
	var element = dhtml.getElementById(entryid);
	if (element){
		var folderName = element.getElementsByTagName("div")[1];
		if(folderName) {
			dhtml.executeEvent(folderName, "click");
		} else {
			eventHierarchyCopyMoveSelectFolder(this, folderName, false);
		}
		this.selectedFolderStoreId = element.storeid;
	}

	this.selectedFolder = entryid;
}

/**
* grab sortStores function from hierarchymodule
*/
if (typeof hierarchymodule != "undefined")
	hierarchyselectmodule.prototype.sortStores = hierarchymodule.prototype.sortStores;



function eventHierarchyCopyMoveSelectFolder(moduleObject, element, event)
{
	if(!event) {
		event = new Object();
	}

	if(event.button == 0 || event.button == 1 || !event.button) {
		if(moduleObject.selectedFolder) {
			var folder = dhtml.getElementById(moduleObject.selectedFolder);
			if(folder) {
				var folderIcon = folder.getElementsByTagName("div")[1];
				var folderName = folderIcon.getElementsByTagName("span")[0];
				folderName.className = "folder_title";
			}
		}
		
		moduleObject.selectedFolder = element.parentNode.id;
		moduleObject.selectedFolderStoreId = element.parentNode.storeid;
		var folderName = element.getElementsByTagName("span")[0];
		folderName.className = "folder_title_selected";
	}
}
