FR.utils = {
	currentFolderAllowsUpload: function() {
		if (User.perms.upload) {
			if (!FR.UI.tree.currentSelectedNode) {return false;}
			var section = FR.UI.tree.currentSelectedNode.attributes.section;
			if (section == 'myfiles') {
				return true;
			} else {
				if (section == 'sharedFolder') {
					if (FR.currentFolderPerms && FR.currentFolderPerms.upload) {
						return true;
					}
				}
			}
		}
		return false;
	},
	canAddComments: function() {
		if (User.perms.write_comments) {
			var currentFolderPerms = FR.UI.tree.currentSelectedNode.attributes.perms;
			if (currentFolderPerms) {
				if (currentFolderPerms.comment) {return true;}
			} else {
				return true;
			}
		}
	},
	reloadGrid: function(highlightOnDisplay) {
		if (highlightOnDisplay) {
			FR.UI.gridPanel.highlightOnDisplay = highlightOnDisplay;
		}
		FR.UI.gridPanel.load(FR.currentPath);
	},
	pathInfo: function (path) {
		var s = path.split('/');
		return {basename: s.pop(), dirname: s.join('/')};
	},
	getFileExtension: function(filename) {
		var dotpos = filename.lastIndexOf(".");
		if (dotpos == -1) {return '';}
		return filename.substr(dotpos + 1).toLowerCase();
	},
	stripFileExtension: function(filename) {
		var dotpos = filename.lastIndexOf(".");
		if (dotpos == -1) {return filename;}
		if (dotpos == 0) {return '';}
		return filename.substr(0, dotpos);
	},
	dimExt: function(filename) {
		var dot = filename.lastIndexOf(".");
		if (dot == -1) {return filename;}
		var name = filename.substr(0, dot);
		var name = filename.substr(0, dot);
		var ext = filename.substr(dot);
		return name+'<span class="gray">'+ext+'<span>';
	},
	humanFilePath: function(str) {
		str = str.replace('/ROOT/HOME', FR.T('My Files'));
		str = str.replace('/ROOT/TRASH', FR.T('Trash'));
		return str;
	},
	showPreview: function(item) {
		if ((FR.currentFolderPerms && !FR.currentFolderPerms.download) || !User.perms.download) {
			FR.UI.feedback(FR.T("You are not allowed to download or preview files."));
			return false;
		}
		if (!item) {
			var item = FR.UI.gridPanel.getOneSel();
		}
		var path = item.data.path ? item.data.path: FR.currentPath+'/'+item.data.filename;
		var icon = item.data.icon;

		var ext = FR.utils.getFileExtension(item.data.filename);
		FR.previewData = {path: path, filename: item.data.filename};

		if (!item.data.isFolder && item.data.thumb && ext != 'pdf' && item.data.filetype != 'wvideo') {
			FR.UI.imagePreview.init(item);
			return true;
		}

		var opts = {
			title: item.data.filename,
			autoDestroy: true, resizable: true,
			icon: 'images/fico/small/'+icon,
			src: FR.baseURL+'/?module=fileman&section=utils&page=file_preview',
			post: [
				{name: 'path', value: path}
			]
		};
		if (ext != 'pdf') {
			opts.loadingMsg = FR.T('Loading...');
		}
		if (ext.length > 0 && 'mp3,ogg,wav,m3u,m3u8,pls,m4a'.indexOf(ext) != -1) {
			opts.width = 400;
			opts.height = 300;
			opts.tools = [{
			    id: 'minimize', qtip: FR.T('Minimize'),
			    handler: function(event, toolEl, win){
					win.getTool('restore').show();
					win.getTool('minimize').hide();
					win.setSize(180, 5).collapse(false).anchorTo(FR.UI.window.el, 'bl-bl', [10,-40]);
			    }
			},
			{
				id: 'restore', qtip: FR.T('Restore'), hidden: true,
				handler: function(event, toolEl, win){
					win.getTool('minimize').show();
					win.getTool('restore').hide();
					win.setSize(400, 400).clearAnchor().expand(false).center();
				 }
			}];
			FR.UI.popup(opts);
		} else {
			FR.UI.openInTab(opts);
		}
		return true;
	},
	locateSelected: function() {
		var s = FR.UI.gridPanel.getOneSel().data;
		if (s.isFolder) {
			FR.utils.locateItem(s.path);
		} else {
			FR.utils.locateItem(FR.utils.pathInfo(s.path).dirname, s.filename);
		}
	},
	locateItem: function(path, filename) {
		//todo: locate inside anonymously shared folders
		if (path != FR.currentPath) {
			FR.UI.tree.panel.selectPath(path, 'pathname', function(success, selNode) {
				if (success && selNode) {selNode.ui.elNode.scrollIntoView();}
				if (filename){FR.UI.gridPanel.highlightOnDisplay = filename;}
			});
		} else {FR.UI.gridPanel.highlight(filename);}
	}
};

FR.actions.downloadFolderZip = function() {
	if (FR.UI.tree.contextMenuVisible) {
		var treeNode = FR.UI.tree.contextMenuSelectedNode;
	} else {
		var treeNode = FR.UI.tree.currentSelectedNode;
	}
	var path = treeNode.getPath('pathname');
	var renameTo = FR.T(treeNode.attributes.text+'.zip');
	FR.UI.feedback(FR.T('Please wait while the selected folder is being zipped...'));
	FR.actions.zipSelectedFolder(path, renameTo, 'forDownload=1', function(response) {
		if (response.rs) {
			FR.UI.feedback(response.msg+'<br>'+FR.T('Downloading zip file...'));
			FR.actions.downloadOneFile(FR.currentPath, renameTo, false, false, false, renameTo, 'afterZip=1');
		}
	});
}
FR.actions.downloadSelectedFolder = function() {
	if (FR.UI.tree.contextMenuVisible) {
		var treeNode = FR.UI.tree.contextMenuSelectedNode;
	} else {
		var treeNode = FR.UI.tree.currentSelectedNode;
	}
	var path = treeNode.getPath('pathname');
	var folderName = treeNode.attributes.pathname;
	FR.actions.download([path]);
}
FR.actions.downloadSelectedFiles = function() {
	var paths = [];
	var sel = FR.UI.gridPanel.getSelectedFiles();
	if (sel.length > 1) {
		if (!FR.UI.cart) {
			FR.UI.cart = new FR.components.cartPanel();
		}
	}
	Ext.each(sel, function (s) {
		var path = (s.path || FR.currentPath + '/' + s.filename);
		if (sel.length > 1) {
			FR.UI.cart.addItem(path, s.filename, s.icon, s.nice_filesize);
		} else {
			paths.push(path);
		}
	});
	if (sel.length > 1) {
		FR.UI.cart.show();
	} else {
		FR.actions.download(paths);
	}
}
FR.actions.download = function(paths) {
	if (!User.perms.download) {return false;}
	var frm = document.createElement('FORM');
	frm.action = FR.myfilesBaseURL+'&page=download';
	frm.method = 'POST';
	frm.target = '_blank';
	Ext.each(paths, function(p) {
		inpt = document.createElement('INPUT');
		inpt.type = 'hidden';
		inpt.name = 'paths[]';
		inpt.value = encodeURIComponent(p);
		frm.appendChild(inpt);
	});
	Ext.get('theBODY').appendChild(frm);
	frm.submit();
	Ext.get(frm).remove();
}
FR.actions.openFileInBrowser = function(path) {
	var downloadURL = FR.myfilesBaseURL+'&page=download&open_in_browser=1&paths[]='+encodeURIComponent(path);
	FR.UI.feedback(FR.T('Opening popup window... <br>Click <a href="%1" target="_blank">here</a> if the browser prevents it from opening.').replace('%1', downloadURL));
	window.setTimeout(function() {window.open(downloadURL);}, 50);
}
FR.actions.comments = function(path) {
	if (!path) {
		var item = FR.UI.gridPanel.getOneSel();
		var path = item.data.path ? item.data.path : FR.currentPath+'/'+item.data.filename;
	}
	FR.UI.commentsPanel.show();
	FR.UI.commentsPanel.setItem(path);
}
FR.actions.openAccountSettings = function() {
	FR.UI.popup({
		id: 'accountSettings', title: FR.T('Account settings'),
		src: FR.baseURL+'/?module=fileman&section=profile',
		width: 450, height: 420, autoDestroy: true, modal: true
	});
};
FR.actions.openActivityLog = function(filename, path) {
	var filename = filename ? filename : FR.UI.gridPanel.getOneSel().data.filename;
	var path = path ? path : FR.currentPath;
	var tmp = FR.UI.openInTab({
		loadingMsg: FR.T('Loading the file\'s activity log...'),
		src:FR.baseURL+'/?module=filelog&section=default&page=default',
		post: [
			{name: 'path', value: path},
			{name: 'filename', value: filename}
		],
		title: FR.T('Activity log')+': "'+filename+'"'
	});
}
FR.actions.clearActivityLog = function(path) {
	FR.UI.showLoading(FR.T('Clearing activity log...'));
	Ext.Ajax.request({
		url: FR.baseURL+'/?module=filelog&section=default&page=clear_log',
		method: 'post',
		params: 'path='+encodeURIComponent(path),
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.msg) {FR.UI.feedback(rs.msg);}
		}
	});
}
FR.actions.deleteSelected = function() {
	var s = FR.UI.gridPanel.getSelectedFiles();
	FR.deletingFiles = s;
	var permanent = false;
	var pars = '';
	var url;
	if (FR.currentSection == 'trash') {
		Ext.each(s, function(i) {
			pars += '&ids[]='+encodeURIComponent(i.uniqid);
		});
		url = FR.baseURL+'/?module=trash&section=ajax&page=grid_action_delete';
	} else {
		pars = 'path='+encodeURIComponent(FR.currentPath);
		Ext.each(s, function(i) {
			pars += '&filenames[]='+encodeURIComponent(i.filename);
		});
		url = FR.myfilesBaseURL+'&page=grid_action_delete';
	}
	FR.UI.showLoading(FR.T('Deleting file(s)...'));
	Ext.Ajax.request({
		url: url, method: 'post', params: pars,
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.rs) {
				Ext.each(FR.deletingFiles, function(aItem) {
					var store = FR.UI.gridPanel.getStore();
					store.remove(store.getById(aItem.id));
				});
				if (FR.currentSection != 'trash' && !permanent) {
					FR.UI.tree.trashNode.getUI().show();
				} else {
					if (rs.trashCount < 1) {
						FR.UI.tree.homeFolderNode.select();
						FR.UI.tree.trashNode.getUI().hide();
					}
				}
				FR.deletingFiles = false;
				FR.UI.reloadStatusBar();
			}
			FR.UI.feedback(rs.msg);
		}
	});
}

FR.actions.restoreSelectedFromTrash = function() {
	var s = FR.UI.gridPanel.getSelectedFiles();
	FR.restoringFiles = s;
	var pars = '';
	Ext.each(s, function(i) {
		pars += '&ids[]='+encodeURIComponent(i.uniqid);
	});
	FR.UI.showLoading(FR.T('Restoring file(s)...'));
	var url = FR.baseURL+'/?module=trash&section=ajax&page=grid_action_restore';
	Ext.Ajax.request({
		url: url,
		method: 'post',
		params: pars,
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.rs) {
				Ext.each(FR.restoringFiles, function(aItem) {
					var store = FR.UI.gridPanel.getStore();
					store.remove(store.getById(aItem.id));
				});
				if (rs.trashCount < 1) {
					FR.UI.tree.trashNode.getUI().hide();
					if (FR.currentSection == 'trash') {
						FR.UI.tree.homeFolderNode.select();
					}
				}
				FR.UI.tree.root.eachChild(function(node) {if (node.loaded && node.expanded) {FR.UI.tree.reloadNode(node);}})
				FR.restoringFiles = false;
			}
			FR.UI.feedback(rs.msg);
		}
	});
	return true;
}

FR.actions.copySelected = function(folder) {
	if (folder) {
		if (FR.UI.tree.contextMenuVisible) {
			var treeNode = FR.UI.tree.contextMenuSelectedNode;
		} else {
			var treeNode = FR.UI.tree.currentSelectedNode;
		}
		FR.copyingFolderNode = treeNode;
		FR.copyingFolder = treeNode.getPath('pathname');
		FR.copyingFiles = false;
	} else {
		FR.copyingFilesFrom = FR.currentPath;
		FR.copyingFiles = FR.UI.gridPanel.getSelectedFiles();
		FR.copyingFolder = false;
		FR.copyingFolderNode = false;
	}
	FR.UI.feedback(FR.T('Right-click the destination folder for pasting the copied item'));
	return true;
}
FR.actions.pasteCopied = function(treePath, folder) {
	if (!treePath) {
		if (FR.UI.tree.contextMenuVisible) {
			var treePath = FR.UI.tree.contextMenuSelectedNode.getPath('pathname');
			FR.copyToFolderNode = FR.UI.tree.contextMenuSelectedNode;
		} else {
			FR.copyToFolderNode = FR.UI.tree.currentSelectedNode;
			var treePath = FR.currentPath;
		}
	}
	var pars = 'path_to='+encodeURIComponent(treePath);
	if (folder) {
		pars += '&path_from='+encodeURIComponent(FR.copyingFolder);
		FR.UI.showLoading(FR.T('Copying folder...'), 1);
		var url = FR.myfilesBaseURL+'&page=tree_action_copy';
	} else {
		pars += '&path_from='+encodeURIComponent(FR.copyingFilesFrom);
		for (var i = 0, len = FR.copyingFiles.length; i < len; i++){
			var filename = FR.copyingFiles[i].filename;
			pars += '&filenames[]='+encodeURIComponent(filename);
		}
		FR.UI.showLoading(FR.T('Copying file(s)...'));
		var url = FR.myfilesBaseURL+'&page=grid_action_copy';
	}
	Ext.Ajax.request({
		url: url,
		method: 'post',
		params: pars,
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			var folder = FR.copyingFolder;
			var treeNode = FR.copyToFolderNode;
			FR.copyingFolder = false;
			FR.copyingFolderNode = false;
			FR.copyingFiles = false;
			FR.copyToFolderNode = false;
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){
				alert('Error: '+req.responseText);
				return false;
			}
			if (rs.rs) {
				if (folder) {
					FR.UI.tree.reloadNode(treeNode);
				} else {
					if (rs.path == FR.currentPath) {
						FR.utils.reloadGrid();
					}
				}
				FR.UI.reloadStatusBar();
			}
			FR.UI.feedback(rs.msg);
		}
	});
	return true;
}
FR.actions.moveFolder = function(drop, cnfirm) {
	if (!cnfirm) {
		new Ext.ux.prompt({
			text: FR.T('Are you sure you want to move the folder?'),
			confirmHandler: function() {
				FR.actions.moveFolder(drop, true);
			}
		});
		return true;
	}
	var url = FR.myfilesBaseURL+'&page=tree_action_move';
	var pars = '';
	pars += 'from_path='+encodeURIComponent(drop.dropNode.parentNode.getPath('pathname'));
	pars += '&to_path='+encodeURIComponent(drop.target.getPath('pathname'));
	pars += '&filename='+encodeURIComponent(drop.dropNode.attributes.pathname);
	FR.UI.tree.movingNode = drop.dropNode;
	FR.UI.tree.moveTarget = drop.target;
	FR.UI.showLoading(FR.T('Moving folder...'));
	Ext.Ajax.request({
		url:url, method: 'post', params: pars,
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			FR.UI.tree.homeFolderNode.select();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.rs) {
				var node = FR.UI.tree.movingNode;
				node.parentNode.removeChild(node);
				FR.UI.tree.reloadNode(FR.UI.tree.moveTarget);
			} else {
				FR.UI.tree.reloadNode(FR.UI.tree.homeFolderNode);
			}
			FR.UI.tree.movingNode = false;
			FR.UI.tree.moveTarget = false;
			FR.UI.feedback(rs.msg);
		}
	});
}
FR.actions.moveFiles = function(drop) {
	if (FR.currentSection == 'userWithShares') {
		FR.actions.copySelected();
		FR.actions.pasteCopied(drop.target.getPath('pathname'));
	} else {
		var s = drop.data.selections;
		FR.currentlyMovingFiles = [];
		var pars = 'from_path='+encodeURIComponent(FR.currentPath);
		pars += '&to_path='+encodeURIComponent(drop.target.getPath('pathname'));
		for(var i = 0, len = s.length; i < len; i++){
			var filename = s[i].data.filename;
			pars += '&filenames[]='+encodeURIComponent(filename);
			FR.currentlyMovingFiles.push(s[i]);
		}
		var url = FR.myfilesBaseURL+'&page=grid_action_move';

		FR.UI.showLoading(FR.T('Moving file(s)...'));
		Ext.Ajax.request({
			url: url, method: 'post', params: pars,
			callback: function(opts, succ, req) {
				FR.UI.doneLoading();
				try {
					var rs = Ext.util.JSON.decode(req.responseText);
				} catch (er){return false;}
				if (rs.rs) {
					Ext.each(FR.currentlyMovingFiles, function(gridRow) {
						gridRow.store.remove(gridRow);
					});
				}
				FR.UI.feedback(rs.msg);
			}
		});
	}
}
FR.actions.deleteFolder = function(cnfirm, treeNode) {
	if (!treeNode) {
		if (FR.UI.tree.contextMenuVisible) {
			var treeNode = FR.UI.tree.contextMenuSelectedNode;
		} else {
			var treeNode = FR.UI.tree.currentSelectedNode;
		}
	}
	FR.deletingTreeNode = treeNode;
	if (!cnfirm) {
		if (!FR.UI.folderDelConfirmWin) {
			FR.UI.folderDelConfirmWin = new Ext.Window({
				title: '&nbsp;',
				layout : 'table', constrain: true,
				width: 430,	height: 170, modal: true,
				closable : false, resizable: false, closeAction: 'close', stateful: false,
				html : '<div style="font-size:12px;margin:5px;margin-top:10px;" align="center">'+FR.T('Are you sure you want to delete the selected folder and all its contents?')+'</div><table style="margin-top:5px;margin-bottom:5px;font-size:11px;color:gray" align="center"><tr><td><input type="checkbox" value="1" id="folderDelConfWinPerm"></td><td><label for="folderDelConfWinPerm">'+FR.T('Permanent deletion')+'</label></td></tr></table>',
				buttonAlign: 'center',
				buttons: [{
					text : FR.T('Yes'), cls: 'fr-btn-default fr-btn-primary',
					handler: function() {
						FR.UI.folderDelConfirmWin.hide();
						FR.actions.deleteFolder(true, FR.deletingTreeNode);
					}
				}, {
					text : FR.T('No'), cls: 'fr-btn-default',
					handler : function() {
						FR.UI.folderDelConfirmWin.hide();
					}
				}]
			});
		}
		FR.UI.folderDelConfirmWin.setTitle(FR.T('Delete "%1"?').replace('%1', treeNode.text));
		FR.UI.folderDelConfirmWin.show();
		Ext.get('folderDelConfWinPerm').dom.checked = false;
		return true;
	}
	var pars = 'path='+encodeURIComponent(FR.deletingTreeNode.getPath('pathname'));
	var url = FR.myfilesBaseURL+'&page=tree_action_delete';
	var permanent = false;
	if (Ext.get('folderDelConfWinPerm')) {
		if (Ext.get('folderDelConfWinPerm').dom.checked) {
			url += '&permanent=true';
			permanent = true;
		}
	}
	FR.UI.showLoading(FR.T('Deleting...'));
	Ext.Ajax.request({
		url: url,
		method: 'post',
		params: pars,
		callback: function(opts, succ, req) {	
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.rs) {
				var node = FR.deletingTreeNode;
				if (node == FR.UI.tree.currentSelectedNode || node == FR.UI.tree.currentSelectedNode.parentNode) {
					FR.UI.tree.homeFolderNode.select();
				}
				if (node.attributes.section == 'myfiles') {
					FR.UI.reloadStatusBar();
				}
				if (FR.currentSection != 'trash' && !permanent) {
					FR.UI.tree.trashNode.getUI().show();
				}
				node.parentNode.removeChild(node);
				FR.deletingTreeNode = false;
			}
			FR.UI.feedback(rs.msg);
		}
	});
}
FR.actions.renameSelected = function(originalValue, newValue) {
	var pars = 'path='+encodeURIComponent(FR.currentPath);
	pars += '&oldfilename='+encodeURIComponent(originalValue);
	pars += '&newfilename='+encodeURIComponent(newValue);
	FR.UI.showLoading(FR.T('Renaming file...'));
	Ext.Ajax.request({
		url: FR.myfilesBaseURL+'&page=grid_action_rename',
		method: 'post',
		params: pars,
		callback: function(opts, succ, req) {						
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			FR.UI.gridPanel.load(FR.currentPath);
			if (rs.msg) {
				FR.UI.feedback(rs.msg);
			}
		}
	});
}
FR.actions.newFolder = function(treeNode, folderName) {
	var pars = 'path='+encodeURIComponent(treeNode.getPath('pathname'));
	pars += '&newfilename='+encodeURIComponent(folderName);
	pars += '&new_folder=1';
	FR.UI.showLoading(FR.T('Creating new folder...'));
	Ext.Ajax.request({
		url: FR.myfilesBaseURL+'&page=tree_action_rename',
		method: 'post',
		params: pars,
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			FR.UI.tree.panel.getEl().unmask();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.rs) {
				FR.UI.tree.editNode.reload();
			}
			if (rs.msg) {FR.UI.feedback(rs.msg);}
		}
	});
}
FR.actions.renameFolder = function(node, newName) {
	var pars = 'path='+encodeURIComponent(node.getPath('pathname'));
	pars += '&newfilename='+encodeURIComponent(newName);
	pars += '&new_folder=0';
	FR.UI.showLoading(FR.T('Renaming folder...'));
	Ext.Ajax.request({
		url: FR.myfilesBaseURL+'&page=tree_action_rename',
		method: 'post',
		params: pars,
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			FR.UI.tree.panel.getEl().unmask();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.rs) {
				FR.UI.tree.editNode.setText(newName);
				FR.UI.tree.editNode.attributes.pathname = newName;
			}
			if (rs.msg) {FR.UI.feedback(rs.msg);}
		}
	});
}
FR.actions.changeLocking = function(lock) {
	FR.currentlyLockingItem = FR.UI.gridPanel.getOneSel();
	var pars = 'path='+encodeURIComponent(FR.currentPath);
	pars += '&filename='+encodeURIComponent(FR.currentlyLockingItem.data.filename);
	FR.UI.showLoading(FR.T(lock?'Locking file...':'Unlocking file...'));
	Ext.Ajax.request({
		url: FR.baseURL+'/?module=versioning&section=ajax&page=locking&action='+(lock?'lock':'unlock'),
		method: 'post',
		params: pars,
		callback: function(opts, succ, req) {	
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.msg) {
				FR.UI.feedback(rs.msg);
			}
			if (rs.rs) {
				if (FR.currentlyLockingItem) {
					FR.currentlyLockingItem.data.lockInfo = rs.status;
					FR.UI.gridPanel.getView().refresh();
				}
			}
		}
	});
}
FR.actions.zipSelected = function(zipName, additionalParameters, callback) {
	var s = FR.UI.gridPanel.getSelectedFiles();
	if (!zipName) {
		if (s.length == 1) {
			zipName = FR.utils.stripFileExtension(s[0].filename)+'.zip';
		} else {
			zipName = FR.T('New Archive.zip');
		}
		new Ext.ux.prompt({
			title: FR.T('Add to zip'),
			text: FR.T('Please type a name for the zip file:'),
			defaultValue: zipName,
			confirmHandler: function(text) {
				if (text) {
					FR.actions.zipSelected(text, additionalParameters, callback);
				}
			}
		});
		return true;
	}
	var pars = 'path='+encodeURIComponent(FR.currentPath);
	for (var i = 0, len = s.length; i < len; i++){
		var filename = s[i].filename;
		pars += '&filenames[]='+encodeURIComponent(filename);
	}
	FR.actions.abstractZip(zipName, pars, additionalParameters, callback);
}
FR.actions.zipSelectedFolder = function(path, zipName, additionalParameters, callback) {
	if (!path) {
		if (FR.UI.tree.contextMenuVisible) {
			path = FR.UI.tree.contextMenuSelectedNode.getPath('pathname');
		} else {
			path = FR.currentPath;
		}
	}
	if (!zipName) {
		new Ext.ux.prompt({
			title: FR.T('Add to zip'),
			text: FR.T('Please type a name for the zip file:'),
			defaultValue: FR.T('New Archive.zip'),
			confirmHandler: function(text) {
				if (text) {
					FR.actions.zipSelectedFolder(path, text, additionalParameters, callback);
				}
			}
		});
		return true;
	}
	var pars = 'path='+encodeURIComponent(FR.currentPath);
	pars += '&folder='+encodeURIComponent(path);
	FR.actions.abstractZip(zipName, pars, additionalParameters, callback);
}
FR.actions.abstractZip = function(zipName, pars, additionalParameters, callback)  {
	pars += '&zipName='+encodeURIComponent(zipName);
	if (additionalParameters && additionalParameters.length > 0) {
		pars += '&'+additionalParameters;
	}
	FR.zipCallback = callback;
	FR.UI.showLoading(FR.T('Zipping file(s)...'));
	Ext.Ajax.request({
		url: FR.myfilesBaseURL+'&page=zip',
		method: 'post',
		params: pars,
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.rs) {
				if (FR.zipCallback) {
					return FR.zipCallback(rs);
				}
				FR.utils.reloadGrid();
				FR.UI.reloadStatusBar();
			}
			FR.UI.feedback(rs.msg);
			FR.zipCallback = false;
		}
	});
}
FR.actions.extractSelected = function(folderName) {
    var fileName = FR.UI.gridPanel.getOneSel().data.filename;
    var exts = ['zip', 'tar', 'tar.gz', 'tgz', 'tar.bz2', 'tbz', 'jar', 'gz'];
    var suggestedFolderName = FR.T('Extracted Files');
    Ext.each(exts, function(x){
        if (fileName.substring(fileName.length-x.length).toLowerCase() == x) {
            suggestedFolderName = fileName.substring(0, fileName.length-(x.length+1));
            return false;
        }
    });
	if (!folderName) {
		new Ext.ux.prompt({
			title: FR.T('Extract archive'),
			text: FR.T('Please type a folder name for the archive contents:'),
			defaultValue: suggestedFolderName, confirmHandler: function(text) {
				FR.actions.extractSelected(text);
			}
		});
		return true;
	}
	var pars = 'path='+encodeURIComponent(FR.currentPath);
	pars += '&filename='+encodeURIComponent(fileName);
	pars += '&folderName='+encodeURIComponent(folderName);
	FR.UI.showLoading(FR.T('Extracting archive contents...'));
	Ext.Ajax.request({
		url: FR.myfilesBaseURL+'&page=extract_archive',
		method: 'post',
		params: pars,
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.rs) {
				FR.UI.tree.reloadNode(FR.UI.tree.currentSelectedNode);
				FR.UI.reloadStatusBar();
			}
			FR.UI.feedback(rs.msg);
		}
	});
	return true;
}

FR.actions.share = function() {
	if (FR.UI.tree.contextMenuVisible) {
		var treeNode = FR.UI.tree.contextMenuSelectedNode;
	} else {
		var treeNode = FR.UI.tree.currentSelectedNode;
	}
	var path = treeNode.getPath('pathname');
	FR.sharing = {
		path: path,
		folderName: treeNode.attributes.pathname
	}
	FR.UI.tree.sharingNode = treeNode;
	FR.UI.persistentWindow({
		id: 'folderShare',
		src:FR.baseURL+'/?module=fileman_myfiles_share',
		post: [{name:'path', value: path}], modal: true,
		width:500, height:350, title: FR.T('Sharing')+': "'+treeNode.text+'"',
		initMsg: FR.T('Initializing sharing panel...')
	});
}
FR.actions.folderOptions = function() {
	if (FR.UI.tree.contextMenuVisible) {
		var treeNode = FR.UI.tree.contextMenuSelectedNode;
	} else {
		var treeNode = FR.UI.tree.currentSelectedNode;
	}
	var path = treeNode.getPath('pathname');
	FR.UI.popup({
		src:FR.baseURL+'/?module=folder_options',
		post: [{name:'path', value: path}], align: 'next2tree',
		width:300, height:300, title: FR.T('Properties')+': "'+treeNode.attributes.text+'"',
		initMsg: FR.T('Loading...')
	});
}
FR.actions.emailFiles = function(items, sendLinks) {
	FR.sendingByEmail = {items: items, sendLinks: sendLinks};
	FR.UI.persistentWindow({
		id: 'emailFiles',
		src: FR.baseURL+'/?module=email',
		width: 440, height: 450,
		title: FR.T('E-mail Files'), modal: true,
		initMsg: FR.T('Initializing e-mail panel...')
	});
}
FR.actions.BTSync = function() {
	if (FR.UI.tree.contextMenuVisible) {
		var item = FR.UI.tree.contextMenuSelectedNode;
	} else {
		var item = FR.UI.tree.currentSelectedNode;
	}
	var path = item.getPath('pathname');
	var itemTitle = item.text;
	FR.BTSync = {itemTitle: itemTitle, item: item, path: path};
	FR.UI.persistentWindow({
		id: 'BTSync',
		title: FR.T('BitTorrent Sync'),
		src: FR.baseURL+'/?module=btsync',
		width:380, height:360, modal: true,
		initMsg: FR.T('Initializing BitTorrent Sync panel...')
	});
}
FR.actions.WebLink = function(itemTitle, itemType, item, path) {
	FR.WebLinking = {itemTitle: itemTitle, itemType: itemType, item: item, path: path};
	FR.UI.persistentWindow({
		id: 'webLink',
		src: FR.baseURL+'/?module=weblinks',
		width: 400, height: 310,
		title: FR.T('Web Link'), modal: true,
		initMsg: FR.T('Initializing WebLink panel...')
	});
}
FR.actions.UnWebLink = function() {
	var params = '';
	Ext.each(FR.UI.gridPanel.getSelectedFiles(), function(item) {
		params += '&paths[]='+encodeURIComponent((item.path || FR.currentPath+'/'+item.filename));
	});
	FR.UI.showLoading(FR.T('Removing weblinks...'));
	Ext.Ajax.request({
		url: FR.baseURL+'/?module=weblinks&section=ajax&page=remove_multiple',
		method: 'post',
		params: params,
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			FR.utils.reloadGrid();
			if (rs && rs.msg) {
				FR.UI.feedback(rs.msg);
			}
		}
	});
}
FR.actions.openVersions = function() {
	FR.UI.popup({
		title: FR.T('File Versions'),
		width: 350,	height: 270,
		src: FR.baseURL+'/?module=versioning',
		post: [
			{name: 'filename', value: FR.UI.gridPanel.getOneSel().data.filename},
			{name: 'path', value: FR.currentPath}
		],
		autoDestroy: true
	});
}
FR.actions.openMetadata = function() {
	var pars = '&filename='+encodeURIComponent(FR.UI.gridPanel.getOneSel().data.filename)+'&path='+encodeURIComponent(FR.currentPath);
	FR.UI.popup({
		title: FR.T('Metadata'),
		width: 400, height: 330,
		src: FR.baseURL+'/?module=metadata'+pars,
		autoDestroy: true
	});
}
FR.actions.setLabel = function(label) {
	var params = 'label='+encodeURIComponent(label);
	Ext.each(FR.UI.gridPanel.getSelectedFiles(), function(item) {
		params += '&paths[]='+encodeURIComponent(FR.currentPath+'/'+item.filename);
	});
	FR.UI.showLoading(FR.T('Setting label...'));
	Ext.Ajax.request({
		url: FR.baseURL+'/?module=labels&page=set',
		method: 'post',
		params: params,
		callback: function(opts, succ, req) {
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			FR.UI.gridPanel.load(FR.currentPath);
			if (rs.msg) {
				FR.UI.feedback(rs.msg);
			}
		}
	});
}
FR.actions.star = function(action) {
	var params = 'action='+action;
	if (FR.UI.tree.contextMenuVisible) {
		var treeNode = FR.UI.tree.contextMenuSelectedNode;
		params += '&paths[]='+encodeURIComponent(treeNode.getPath('pathname'));
	} else {
		Ext.each(FR.UI.gridPanel.getSelectedFiles(), function(item) {
			params += '&paths[]=';
			if (item.path) {
				params += encodeURIComponent(item.path);
			} else {
				params += encodeURIComponent(FR.currentPath+'/'+item.filename);
			}
		});
	}
	Ext.Ajax.request({
		url: FR.baseURL+'/?module=stars&page=set',
		method: 'post',
		params: params,
		callback: function(opts, succ, req) {
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.msg) {FR.UI.feedback(rs.msg);}
			if (FR.currentSection == 'starred') {
				FR.UI.gridPanel.load(FR.currentPath);
			} else {
				if (rs.updates) {FR.UI.gridPanel.applyUpdates(rs.updates);}
			}
		}
	});
}
FR.actions.customAction = function(opt, path, filename) {
	if (opt.popup) {
		if (path) {
			var postData = [{name:'path', value: path}];
		} else {
			var sel = FR.UI.gridPanel.getSelectionModel().getSelections();
			if (sel.length == 1) {
				var filename = sel[0].data.filename;
				var postData = [{name:'path', value: sel[0].data.path ? sel[0].data.path : FR.currentPath+'/'+sel[0].data.filename}];
			} else {
				var filename = FR.T('[multiple files]');
				var postData = [];
				Ext.each(sel, function(item) {
					postData.push({name:'paths[]', value: item.data.path ? item.data.path : FR.currentPath+'/'+item.data.filename});
				});
			}
		}
		var url = FR.baseURL+'/?module=custom_actions&action='+opt.actionName;
		var popOpts = {
			title: FR.T(opt.title)+': '+filename,
			loadingMsg: opt.loadingMsg || false,
			src: url, icon: opt.icon,
			post: postData
		};
		if (opt.external) {
			FR.UI.openInPopup(popOpts);
		} else {
			FR.UI.openInTab(popOpts);
		}
	} else {
		if (opt.handler) {
			opt.handler();
		} else {
			eval(opt.fn);
		}
	}
	return true;
}
FR.actions.createNew = function(action, filename) {
	if (!filename) {
		var filename = FR.T(action.createNew.defaultFileName);
	}
	new Ext.ux.prompt({text: FR.T('Please type a file name:'), defaultValue: filename, confirmHandler: function(val) {
		var url = FR.baseURL+'/?module=custom_actions&action='+action.actionName+'&method=createBlankFile';
		FR.UI.showLoading(FR.T('Creating blank file...'));
		if (FR.utils.currentFolderAllowsUpload()) {
			var path = FR.currentPath+'/'+val;
		} else {
			var path = '/ROOT/HOME/'+val;
		}
		Ext.Ajax.request({
			url: url,
			method: 'post',
			params: {path: path},
			callback: function(opts, succ, req) {
				FR.UI.doneLoading();
				try {
					var rs = Ext.util.JSON.decode(req.responseText);
				} catch (er){return false;}
				if (rs.rs) {
					FR.actions.customAction(action, rs.path, rs.filename);
					FR.utils.reloadGrid();
				}
				FR.UI.feedback(rs.msg);
			}
		});
	}});
}

FR.actions.saveNotifications = function(settings) {
	if (FR.UI.tree.contextMenuVisible) {
		selectedTreeNode = FR.UI.tree.contextMenuSelectedNode;
	} else {
		selectedTreeNode = FR.UI.tree.currentSelectedNode;
	}
	if (!selectedTreeNode) {return false;}
	var r = settings[1]?1:0;
	var w = settings[0]?1:0;
	if (!selectedTreeNode.attributes.custom) {selectedTreeNode.attributes.custom = {};}
	selectedTreeNode.attributes.custom.notInfo = (r || w)? {w: w, r: r} : 0;
	var url = FR.baseURL+'/?module=folder_options&section=ajax&page=save_notifications';
	var pars = {
		path: selectedTreeNode.getPath('pathname'),
		notifyWrite: w, notifyRead: r
	};
	FR.UI.showLoading(FR.T('Saving notification settings...'));
	Ext.Ajax.request({
		url: url,
		method: 'post',
		params: pars,
		callback: function(opts, succ, req) {	
			FR.UI.doneLoading();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs.rs) {
				FR.UI.tree.updateIcon(selectedTreeNode);
			}
			FR.UI.feedback(rs.msg);
		}
	});
	return true;
}

FR.actions.quickLinks = {
	webLink: function(id) {
		var item = FR.UI.gridPanel.getStore().getById(id);
		var path = item.data.path ? item.data.path : FR.currentPath+'/'+item.data.filename;
		FR.actions.WebLink(item.data.filename, 'file', item, path);
	},
	activityLog: function(id) {
		var data = FR.UI.gridPanel.getStore().getById(id).data;
		FR.actions.openActivityLog(data.filename, (data.path || false));
	},
	comments: function(id) {
		var data = FR.UI.gridPanel.getStore().getById(id).data;
		var path = data.path ? data.path : FR.currentPath+'/'+data.filename;
		FR.actions.comments(path);
	}
}

FR.actions.pasteImage = function(e) {
	if (!FR.utils.currentFolderAllowsUpload()) {return false;}
	for (var i = 0 ; i < e.browserEvent.clipboardData.items.length ; i++) {
		var item = e.browserEvent.clipboardData.items[i];
		if (item.type.indexOf("image") != -1) {
			var blob = item.getAsFile();

			var reader = new FileReader();
			reader.onload = function(event){
				var imageObj = new Image();
				imageObj.src = event.target.result;
				imageObj.width = '500';
				imageObj.onload = function() {
					var w = new Ext.Window({
						title: FR.T('Uploading pasted image...'),
						contentEl: this
					});
					w.show();

					var fileName = FR.T('Pasted image')+' '+Ext.util.Format.date(new Date(), 'Y-m-d H-i-s')+'.png';
					blob.fileName = fileName;

					var upload = new Flow({
						target: '?module=fileman_myfiles&section=ajax&page=up',
						validateChunkResponse: function(status, message) {
							if (status != '200') {return 'retry';}
							try {var rs = Ext.util.JSON.decode(message);} catch (er){return 'retry';}
							if (rs) {if (rs.success) {return 'success';} else {return 'error';}}
						}, validateChunkResponseScope: this,
						query: {path: FR.currentPath}
					});
					upload.on('fileSuccess', function() {
						w.close();
						FR.UI.feedback('Pasted image successfully uploaded');
						FR.actions.WebLink(fileName, 'file', false, FR.currentPath+'/'+fileName);
						FR.utils.reloadGrid(fileName);
					});
					upload.on('progress', function(flow) {
						var percent = Math.floor(flow.getProgress()*100);
						w.setTitle(FR.T('Uploading pasted image...')+' '+percent+'%');
					});
					upload.addFile(blob);
					upload.start();
				}
			}
			reader.readAsDataURL(blob);
			break;
		}
	}
}