FR.initTree = function() {
	var t = new Ext.tree.TreePanel({
		id: 'FR-Tree-Panel', region: 'center',
		enableDD: !User.perms.read_only, ddGroup: 'TreeDD', dropConfig: {appendOnly:true}, bodyStyle: 'padding-top:1px;padding-bottom:30px;',
		animate: true, autoScroll: true, rootVisible: false, lines: false, useArrows: true
	});
	FR.UI.tree.panel = t;

	var r = new Ext.tree.TreeNode({pathname: 'ROOT', allowDrag: false, allowDrop: false});
	t.setRootNode(r);
	FR.UI.tree.root = r;
	
	t.getSelectionModel().on('selectionchange', function(selectionModel, treeNode) {
		FR.UI.tree.onSelectionChange(selectionModel, treeNode);
	});
	t.getSelectionModel().on('beforeselect', function(selectionModel, treeNode) {
		if (treeNode.attributes.section == 'userWithShares') {treeNode.expand();return false;}
		if (!treeNode.attributes.pathname) {return false;}
	});
	FR.UI.tree.loader = new Ext.tree.TreeLoader({
		dataUrl: this.myfilesBaseURL+'&page=tree',
		baseAttrs: {uiProvider: FR.components.TreeNodeCustomUI},
		listeners: {'beforeload': function(loader, node){loader.baseParams.path = node.getPath('pathname');}}
	});

	FR.UI.tree.homeFolderNode = new Ext.tree.AsyncTreeNode({
		text: FR.T('My Files'), pathname: 'HOME', section: 'myfiles',
		iconCls: 'fa-folder', homefolder: true,
		allowDrag: false, allowDrop: !User.perms.read_only,
		custom: FR.homeFolderCfg.customAttr,
		loader: FR.UI.tree.loader,
		uiProvider: FR.components.TreeNodeCustomUI
	});
	r.appendChild(FR.UI.tree.homeFolderNode);

	FR.UI.tree.sharesLoader = new Ext.tree.TreeLoader({
		dataUrl:FR.myfilesBaseURL+'&page=tree_shares&nocache=1',
		baseAttrs: {uiProvider: FR.components.TreeNodeCustomUI},
		listeners: {'beforeload': function(loader, node){loader.baseParams.path = node.getPath('pathname');}}
	});
	Ext.each(AnonShares, function(fld) {
		r.appendChild(new Ext.tree.AsyncTreeNode(Ext.apply(fld, {
			readonly: true, allowDrag: false, allowDrop: fld.perms.upload,
			loader: FR.UI.tree.sharesLoader, section: 'sharedFolder', uiProvider: FR.components.TreeNodeCustomUI
		})));
	});
	FR.UI.tree.starredNode = new Ext.tree.TreeNode({
		text: FR.T('Starred'), readonly: true, uiProvider: FR.components.TreeNodeCustomUI,
		leaf: false, allowDrag: false, allowDrop: true, hidden: (!(User.perms.read_comments && User.perms.write_comments)),
		iconCls: 'fa-star icon-gray', pathname: 'STARRED', section: 'starred'
	});
	r.appendChild(FR.UI.tree.starredNode);
	FR.UI.tree.webLinksNode = new Ext.tree.TreeNode({
		text: FR.T('Shared links'), readonly: true, uiProvider: FR.components.TreeNodeCustomUI,
		leaf: false, allowDrag: false, allowDrop: false, hidden: !User.perms.weblink,
		iconCls: 'fa-link icon-gray', pathname: 'WLINKED', section: 'webLinked'
	});
	r.appendChild(FR.UI.tree.webLinksNode);
	FR.UI.tree.searchResultsNode = new Ext.tree.TreeNode({
		text: FR.T('Search Results'), readonly: true, uiProvider: FR.components.TreeNodeCustomUI,
		leaf: false, allowDrag: false, allowDrop: true, hidden: true,
		iconCls: 'fa-search icon-gray', pathname: 'SEARCH', section: 'search'
	});
	r.appendChild(FR.UI.tree.searchResultsNode);
	FR.UI.tree.trashNode = new Ext.tree.TreeNode({
		text: FR.T('Trash'), readonly: true, uiProvider: FR.components.TreeNodeCustomUI,
		leaf: false, allowDrag: false, allowDrop: true,
		iconCls: 'fa-trash icon-gray', pathname: 'TRASH', section: 'trash'
	});
	r.appendChild(FR.UI.tree.trashNode);
	if (!User.trashCount || User.perms.read_only) {
		FR.UI.tree.trashNode.getUI().hide();
	}
	
	Ext.each(Sharing, function(usr) {
		r.appendChild(new Ext.tree.AsyncTreeNode({
			text: usr.name, pathname: usr.id, section: 'userWithShares',
			iconCls: 'fa-user icon-gray', allowDrag: false, allowDrop: false,
			loader: FR.UI.tree.sharesLoader, uiProvider: FR.components.TreeNodeCustomUI
		}));
	});

	FR.UI.tree.getCurrentPath = function() {
		return this.currentSelectedNode.getPath('pathname');
	};

	FR.UI.tree.onSelectionChange = function(selectionModel, treeNode) {
		FR.UI.tree.currentSelectedNode = treeNode;
		if (!treeNode) {return false;}
		var path = treeNode.getPath('pathname');
		if (path != FR.currentPath) {
            var section = treeNode.attributes.section;
			FR.UI.explorerPanel.setTitle(treeNode.text);
			FR.UI.gridPanel.load(path);
			FR.currentFolderPerms = treeNode.attributes.perms ? treeNode.attributes.perms : false;
			FR.currentSection = treeNode.attributes.section;
			if (section == 'myfiles' || section == "sharedFolder") {
				treeNode.expand();
			}
			if (section == 'search') {
				FR.UI.tree.searchResultsNode.getUI().show();
			} else {
				FR.UI.tree.searchResultsNode.getUI().hide();
			}
			/*
			if (section == 'myfiles' || section == 'search') {
				FR.UI.actions.searchField.show();
			} else {
				FR.UI.actions.searchField.hide();
			}
			*/
			var gridCM = FR.UI.gridPanel.getColumnModel();
			if (section == 'trash') {
				gridCM.setHidden(gridCM.getIndexById('trash_deleted_from'), false);
				gridCM.setHidden(gridCM.getIndexById('path'), true);
			} else {
				if (FR.UI.gridPanel.changeViewTo) {
					FR.UI.gridPanel.toggleView(true);
					FR.UI.gridPanel.changeViewTo = false;
				}
				gridCM.setHidden(gridCM.getIndexById('trash_deleted_from'), true);
				FR.UI.actions.toggleViewList.show();
				if (treeNode.attributes.section == 'starred') {
					gridCM.setHidden(gridCM.getIndexById('path'), false);
				} else {
					gridCM.setHidden(gridCM.getIndexById('path'), true);
				}
			}
		}
	}
};

FR.initTreeDD = function() {
	FR.UI.tree.panel.on('nodedragover', function(e){
		if (FR.currentSection == 'trash' || FR.currentSection == 'starred' || FR.currentSection == 'search' || FR.currentSection == 'webLinked' ||
		(e.dropNode && e.dropNode.attributes.readonly) || 
		(e.target.attributes.perms && (!e.target.attributes.perms.alter && !e.target.attributes.perms.upload)) ||
		(FR.currentPath == e.target.getPath('pathname'))
		) {
			e.cancel = true;
			return false;
		}
	});
	
	FR.UI.tree.panel.on('beforenodedrop', function(drop){
		var sourceType = drop.data.grid ? 'grid' : 'tree';
		if (sourceType == 'grid') {
			FR.UI.tree.onDrop2Tree(drop);
		} else {
			FR.UI.tree.moveNodeParent = drop.dropNode.parentNode;
			FR.UI.tree.onTreeDrop(drop);
		}
		return false;
	});

	FR.UI.tree.onTreeDrop = function(drop) {
		if (drop.target.attributes.section == 'trash') {
			FR.actions.deleteFolder(true, drop.dropNode);
		} else if (drop.target.attributes.section == 'starred') {
			/*
			Todo: add stars to dropped items
			*/
		} else {
			FR.actions.moveFolder(drop);
		}
	};

	FR.UI.tree.onDrop2Tree = function(drop) {
		if (drop.target.attributes.section == 'trash') {
			FR.actions.deleteSelected(true);
		} else if (drop.target.attributes.section == 'starred') {
			FR.actions.star('add');
		} else {
			FR.actions.moveFiles(drop);
		}
	}
};

FR.UI.tree.reloadNode = function(treeNode) {
	treeNode.loaded = false;
	treeNode.collapse();
	treeNode.expand();
};

FR.UI.tree.updateIcon = function(treeNode) {
	treeNode.getUI().updateIcons();
};

FR.UI.tree.initContextMenu = function() {
	var cm = {options:{}};
	cm.menu = new Ext.menu.Menu({
	    id: 'myfiles-tree-contextmenu',
	    items: FR.UI.tree.arrayActions
	});
	cm.menu.on('hide', function(menu) {
		FR.UI.tree.contextMenuVisible = false;
		if (FR.UI.tree.contextMenuSelectedNode) {
			Ext.get(FR.UI.tree.contextMenuSelectedNode.getUI().elNode).removeClass('highlighted-tree-node');
		}
	});
	this.contextMenu = cm;
	this.updateActions = function(treeNode) {
		var ta = this.actions;

		var showNotifications = Settings.allow_folder_notifications;
		var showBTSync = true;
		var showLink = true;
		var showEmail = User.perms.email;
		var showShareInternal = true;
		var showShare = false;
		var showAddStar = false;
		var showRemoveStar = false;
		var showZip = true;
		var showDownload = true;
		var showNewFolder = true;
		var showPaste = true;
		var showCopy = true;
		var showPasteFolder = true;
		var showRenameDelete = true;
		var showProp = User.isAdmin;
		
		if (User.perms.read_only) {
			showShareInternal = false;
			showBTSync = false;
			showZip = false;
			showCopy = false;
			showNewFolder = false;
			showPaste = false;
			showPasteFolder = false;
			showRenameDelete = false;
		} else {
			if (treeNode.attributes.section == 'sharedFolder'){
				showShareInternal = false;
				showBTSync = false;
				if (FR.currentSection == 'sharedFolder') {
					if (!this.currentSelectedNode.attributes.perms.upload) {
						showZip = false;
					}
				}
				showPaste = treeNode.attributes.perms.upload;
				if (!treeNode.attributes.perms.download) {
					showLink = false;
					showEmail = false;
					showZip = false;
					showDownload = false;
					showCopy = false;
				}
				if (!treeNode.attributes.perms.alter) {
					showRenameDelete = false;
					showPasteFolder = false;
					if (!treeNode.attributes.perms.upload) {
						showNewFolder = false;
					}
				} else {
					showRenameDelete = true;
					showNewFolder = true;
					showPasteFolder = true;
				}
				if (treeNode.attributes.readonly) {
					showPasteFolder = false;
					showRenameDelete = false;
				}
			} else {
				if (treeNode.attributes.homefolder) {
					showShareInternal = false;
					showLink = false;
					showEmail = false;
					showRenameDelete = false;
					showCopy = false;
				}
			}
			if (!treeNode.attributes.homefolder) {
				if (treeNode.attributes.custom && treeNode.attributes.custom.star) {
					showRemoveStar = true;
				} else {
					showAddStar = true;
				}
			}
			if (treeNode == FR.copyingFolderNode) {
				showCopy = false;
				showPasteFolder = false;
			}
		}
		if (FR.copyingFiles && showPaste) {
			ta.pasteFiles.show();
		} else {
			ta.pasteFiles.hide();
		}
		if (FR.copyingFolder && showPasteFolder) {
			ta.pasteFolder.show();
		} else {
			ta.pasteFolder.hide();
		}
		if (!User.perms.btsync || !User.perms.download) {
			showBTSync = false;
		}
		if (!User.perms.weblink || !User.perms.download) {
			showLink = false;
		}
		if (!User.perms.share) {showShareInternal = false;}
		if (showShareInternal || showLink || showBTSync) {showShare = true;}

		if (showRenameDelete) {ta.rename.show();ta.deleteFolder.show();ta.sep3.show();} else {ta.rename.hide();ta.deleteFolder.hide();ta.sep3.hide();}
		if (showShareInternal) {ta.shareInternal.show();} else {ta.shareInternal.hide();}
		if (showLink) {ta.weblink.show();} else {ta.weblink.hide();}
		if (showEmail) {ta.email.show();} else {ta.email.hide();}
		if (showBTSync) {ta.btsync.show();} else {ta.btsync.hide();}
		if (showShare) {ta.share.show();} else {ta.share.hide();}

		if (showNotifications) {ta.notifications.show();} else {ta.notifications.hide();}
		if (showNewFolder) {ta.newFolder.show();ta.sep1.show();} else {ta.newFolder.hide();ta.sep1.hide();}
		if (showProp) {ta.properties.show();} else {ta.properties.hide();}
		if (showZip && User.perms.download_folders) {ta.zip.show();} else {ta.zip.hide();}
		if (User.perms.download && User.perms.download_folders && showDownload) {ta.download.show();ta.sep2.show();} else {ta.download.hide();ta.sep2.hide();}
		if (showCopy) {ta.copy.show();} else {ta.copy.hide();}
		if (!showZip && !showCopy && !showNotifications && !showProp) {ta.more.hide();} else {ta.more.show();}

		if (!showAddStar) {ta.addStar.hide();} else {ta.addStar.show();}
		if (!showRemoveStar) {ta.removeStar.hide();} else {ta.removeStar.show();}
	};
	this.panel.on('contextmenu', function(node, e) {FR.UI.tree.showContextMenu(node,e);});
	this.showContextMenu = function(node, e) {
		if (node.attributes.section == 'myfiles' || node.attributes.section == 'sharedFolder') {
			this.contextMenuSelectedNode = node;
			this.updateActions(node);
			Ext.get(node.getUI().elNode).addClass('highlighted-tree-node');
			FR.UI.tree.contextMenuVisible = true;
			this.contextMenu.menu.showAt([FR.UI.xy[0]+5, FR.UI.xy[1]+5]);
			if (e) {
				e.stopEvent();
			}
		    return false;
		}
	}
};



FR.components.TreeNodeCustomUI = Ext.extend(Ext.tree.TreeNodeUI, {
	getIcons: function() {
		var n = this.node;
		var icons = '';
		if (n.attributes.custom) {
			if (n.attributes.custom.share) {
				icons += ' <i class="fa fa-user-plus"></i>';
			}
			if (n.attributes.custom.weblink) {
				icons += ' <i class="fa fa-link"></i>';
			}
			if (n.attributes.custom.sync) {
				icons += ' <i class="fa fa-retweet"></i>';
			}
			if (n.attributes.custom.notInfo) {
				icons += ' <i class="fa fa-bell-o"></i>';
			}
			if (n.attributes.custom.star) {
				icons += ' <i class="fa fa-star-o"></i>';
			}
		}
		if (n.attributes['new']) {
			icons += ' <i class="fa fa-asterisk icon-red"></i>';
		}
		return icons;
	},
	updateIcons: function() {
		this.frIconsNodeEl.update(this.getIcons());
	},
	renderElements : function(n, a, targetNode, bulkRender){
		this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
		var showMenuTrigger = (n.attributes.section == 'myfiles' || n.attributes.section == 'sharedFolder');
		var icons = this.getIcons();
		var nel,
			buf =
			'<li class="x-tree-node">' +
				'<div ext:tree-node-id="'+n.id+'" class="x-tree-node-el x-tree-node-leaf x-unselectable '+(a.cls || '')+'" unselectable="on">' +
					'<span class="x-tree-node-indent">'+this.indentMarkup+"</span>"+
					'<img alt="" src="'+this.emptyIcon+'" class="x-tree-ec-icon x-tree-elbow" />'+
					'<i class="x-tree-node-icon fa fa-lg fa-fw icon-silver '+(a.iconCls || "fa-folder")+'" unselectable="on"></i>'+
					'<a hidefocus="on" class="x-tree-node-anchor">' +
						'<span unselectable="on">'+n.text+"</span>" +
						'<span class="x-tree-node-fr-icons" style="color:silver">'+ icons + '</span>' +
					"</a>" +
				(showMenuTrigger ? '<div class="nodeMenu"><div class="triangle"></div></div>':'') +
				'</div>'+
				'<ul class="x-tree-node-ct" style="display:none;"></ul>'+
			'</li>';

		if(bulkRender !== true && n.nextSibling && (nel = n.nextSibling.ui.getEl())){
			this.wrap = Ext.DomHelper.insertHtml("beforeBegin", nel, buf);
		}else{
			this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf);
		}
		this.elNode = this.wrap.childNodes[0];
		this.ctNode = this.wrap.childNodes[1];
		var cs = this.elNode.childNodes;
		this.indentNode = cs[0];
		this.ecNode = cs[1];
		this.iconNode = cs[2];
		this.iconNodeEl = Ext.get(this.iconNode);
		this.anchor = cs[3];
		this.textNode = cs[3].firstChild;
		this.frIconsNodeEl = Ext.get(cs[3].lastChild);
		if (showMenuTrigger) {
			this.menuTriggerNode = cs[4];
			Ext.get(this.menuTriggerNode).on('click', function(e) {
				FR.UI.tree.showContextMenu(n, e);
				e.stopEvent();
			});
		}
	},
	beforeLoad : function(){
		this.iconNodeEl.removeClass("fa-folder").addClass('fa-refresh').addClass('fa-spin');
	},
	afterLoad : function(){
		this.iconNodeEl.removeClass('fa-refresh').removeClass('fa-spin').addClass('fa-folder');
	}
});