FR.UI.reloadStatusBar = function() {
	if (!User.perms.space_quota_max) {return false;}
	FR.UI.quotaIndicator.getEl().mask();
	Ext.Ajax.request({
		url: FR.baseURL+'/?module=fileman&section=utils&page=status_bar',
		success: function(req) {
			FR.UI.quotaIndicator.getEl().unmask();
			try {
				var rs = Ext.util.JSON.decode(req.responseText);
			} catch (er){return false;}
			if (rs) {
				User.perms = Ext.apply(User.perms, rs);
				FR.UI.updateQuotaStatus();
			}
		}
	});
};
FR.UI.updateQuotaStatus = function() {
	FR.UI.quotaIndicator.update('%1 used (%2%)'.replace('%1', User.perms.space_quota_used).replace('%2', User.perms.space_quota_percent_used).replace('%3', User.perms.space_quota_max_formated));
};

FR.UI.feedback = function(text) {
	if (!text) {return false;}
	if (Ext.util.Format.stripTags(text).length > 100) {
		new Ext.Window({width: 350, height: 160, layout: 'fit', items: {bodyStyle: 'padding:5px', html: text, autoScroll: true}}).show();
		return false;
	}
	var delay = Math.max(text.length/15, 2);
	if (!FR.UI.feedbackCt) {
		FR.UI.feedbackCt = Ext.DomHelper.append(document.body, {style:'width:300px;z-index:9999999'}, true);
	}
	var m = Ext.DomHelper.append(FR.UI.feedbackCt, {html:'<div class="fr-feedback-msg">'+text+'</div>'}, true);
	FR.UI.feedbackCt.alignTo(Ext.getBody(), 'tr-tr', [-300, 7]);
	//m.on('dblclick', function(e, node) {Ext.get(node).parent('.fr-feedback-msg').ghost('t', {remove: true});});
	m.slideIn('t').pause(delay).ghost('b', {remove: true});
};
FR.UI.popupCount = 0;
FR.UI.popup = function(args) {
	var id = 'popups_'+(++this.popupCount);
	var windowId = args.id || id+'_window';
	args.src = args.src+'&_popup_id='+windowId;
	var dialog = new Ext.Window({
		id: windowId,
		stateful: false,
		autoDestroy: args.autoDestroy,
		closeAction: (args.autoDestroy ? 'close' : 'hide'),
		constrainHeader: true,
		layout: 'fit',
		width: args.width, height: args.height,
		title: args.title || false,
		tools: args.tools || false,
		resizable: args.resizable || false,
		collapsible: args.collapsible || false,
		maximizable: args.maximizable || false,
		maximized: args.maximized || false,
		constrain: args.constrain || false,
		iconCls: args.iconCls || false,
		closable: true, plain: false, modal: args.modal || false,
		html: '<div style="background-color:white;height:100%;"><iframe src="'+(args.post ? 'about:blank' : args.src)+'" style="width:100%;height:100%;position:relative" marginheight="0" marginwidth="0" frameborder="0" id="'+id+'" name="'+id+'"></iframe></div>'
	});
	dialog.frameId = id;
	args.centerTo = args.centerTo || false;
	dialog.show(args.centerTo);
	if (args.align) {
		if (args.align == 'next2tree') {
			args.align = {'el': FR.UI.gridPanel.getEl(), 'pos':'tl', 'offset':[5, 5]};
		}
		dialog.alignTo(args.align.el, args.align.pos, args.align.offset);
	}
	if (args.loadingMsg) {
		Ext.get(dialog.getLayout().container.body.dom).mask(FR.T(args.loadingMsg));
		Ext.get(dialog.frameId).on('load', function() {
			Ext.get(dialog.getLayout().container.body.dom).unmask();
		});
	}
	FR.UI.popups[windowId] = dialog;
	if (args.autoDestroy) {
		dialog.on('afterhide', function(dlg){
			dlg.destroy(true);
			delete FR.UI.popups[dlg.id];
		});
	}
	if (args.post) {
		var frm = document.createElement('FORM');
		frm.action = args.src;
		frm.method = 'POST';
		frm.target = id;
		Ext.each(args.post, function(param) {
			inpt = document.createElement('INPUT');
			inpt.type = 'hidden';
			inpt.name = param.name;
			inpt.value = encodeURIComponent(param.value);
			frm.appendChild(inpt);
		});
		Ext.get('theBODY').appendChild(frm);
		frm.submit();
		Ext.get(frm).remove();
	}
	return dialog;
};


FR.UI.openInTab = function(args) {
	var id = 'fr-tabs-'+Ext.id();
	var frameId = id+'-frame';
	args.src = args.src+'&_tab_id='+id;
	var bsize = Ext.getBody().getSize();
	var w = Math.floor(bsize.width-10/100*bsize.width);
	var h = Math.floor(bsize.height-10/100*bsize.height);
	var panel = new Ext.Window({
		id: id, stateful: false, layout: 'fit', title: args.title, width: w, height: h,
		iconCls: args.iconCls || false, closable: true, modal: true,
		html: '<div style="background-color:white;height:100%;"><iframe src="'+(args.post ? 'about:blank' : args.src)+'" style="width:100%;height:100%;position:relative" marginheight="0" marginwidth="0" frameborder="0" id="'+frameId+'" name="'+frameId+'"></iframe></div>'
	});
	panel.show();
	panel.frameId = frameId;
	if (args.loadingMsg) {
		Ext.get(panel.getLayout().container.body.dom).mask(FR.T(args.loadingMsg));
		Ext.get(frameId).on('load', function() {
			Ext.get(panel.getLayout().container.body.dom).unmask();
		});
	}
	if (args.post) {
		FR.UI.postToTarget(args, frameId);
	}
	FR.UI.tabs[id] = panel;
	return panel;
};

FR.UI.openInPopup = function(args) {
	var id = 'fr-tabs-'+Ext.id();
	var frameId = id+'-frame';
	args.src = args.src+'&_tab_id='+id;

	var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : screen.left;
	var dualScreenTop = window.screenTop != undefined ? window.screenTop : screen.top;
	var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
	var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
	var w = Math.round(width-15/100*width);
	var h = Math.round(height-15/100*height);
	var left = ((width / 2) - (w / 2)) + dualScreenLeft;
	var top = ((height / 2) - (h / 2)) + dualScreenTop;
	var win = window.open(args.src, frameId, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
	if (args.post) {
		FR.UI.postToTarget(args, frameId);
	}
	return win;
};

FR.UI.postToTarget = function(args, target) {
	var frm = document.createElement('FORM');
	frm.action = args.src;
	frm.method = 'POST';
	frm.target = target;
	Ext.each(args.post, function(param) {
		inpt = document.createElement('INPUT');
		inpt.type = 'hidden';
		inpt.name = param.name;
		inpt.value = encodeURIComponent(param.value);
		frm.appendChild(inpt);
	});
	Ext.get('theBODY').appendChild(frm);
	frm.submit();
	Ext.get(frm).remove();
};


FR.UI.showUploadForm = function(type) {
	if (FR.currentFolderPerms && !FR.currentFolderPerms.upload) {
		FR.UI.feedback(FR.T("You are not allowed to upload files in this folder."));
		return false;
	}
	var useFlow = false;

	if (type == 'folder' && FlowUtils.browserSupport.folders) {
		useFlow = true;
	} else if (type == 'files') {
		if (FlowUtils.browserSupport.files) {
			useFlow = true;
		}
	}
	if (FR.utils.currentFolderAllowsUpload()) {
		var targetTreeNode = FR.UI.tree.currentSelectedNode;
	} else {
		var targetTreeNode = FR.UI.tree.homeFolderNode;
	}
	var targetPath = targetTreeNode.getPath('pathname');
	var title = FR.T('Upload to "%1"').replace('%1', targetTreeNode.text);
	if (useFlow) {
		FlowUtils.browseFiles({
			entireFolder: (type == 'folder'),
			onSelect: function(files, e) {
				if (files.length > 0) {
					var up = new FR.components.uploadPanel({
						closable: false, targetPath: targetPath, files: files
					});
					FR.UI.uploadWindow(title, up);
				}
			}, scope: this
		});
		return false;
	} else {
		if (!FR.UI.uploadDialog) {
			FR.UI.uploadDialog = new FR.components.oldUploadWindow({title: title});
		}
		FR.UI.uploadDialog.setTitle(title);
		FR.UI.uploadDialog.customShow(type);
	}
};
FR.UI.uploadWindow = function(title, uploader) {
	var bsize = Ext.getBody().getSize();
	var h = Math.floor(bsize.height-20/100*bsize.height);
	var w = new Ext.Window({
		title: FR.T('Upload to "%1"').replace('%1', FR.UI.tree.currentSelectedNode.text),
		items: uploader, width: 800, height: h, closable: false, modal: true, layout: 'fit'
	});
	uploader.window = w;
	w.show();
};
FR.UI.persistentWindow = function(args) {
	var win = FR.UI.popups[args.id];
	if (!win) {
		win = FR.UI.popup(args);
		Ext.get(win.getLayout().container.body.dom).mask(args.initMsg);
	} else {
		win.setTitle(args.title);
		win.syncSize();
		win.show();
		Ext.get(win.frameId).dom.contentWindow.FR.update(args);
	}
};
FR.UI.showLoading = function(msg, onlyTreePane) {
	if (onlyTreePane) {
		FR.UI.tree.panel.el.mask(msg);
	} else {
		FR.UI.window.getEl().mask(msg);
	}
};
FR.UI.doneLoading = function() {
	FR.UI.tree.panel.el.unmask();
	FR.UI.window.getEl().unmask();
};
FR.UI.tooltip = function(html) {
	return function() {
		new Ext.ToolTip({
			target: this.getEl(), showDelay: 250,
			html: html, anchor: 'top',
			baseCls: 'headerTbar-btn-tooltip'
		});
	}
};
FR.UI.getTextLogo = function(text) {
	if (Ext.isIE && !Ext.isIE10 && !Ext.isIE11) {
		var logoCls = 'logo3d logoIE9';
	} else {
		var logoCls = 'logo3d';
	}
	if (Settings.ui_logo_link_url) {
		text = '<a href="'+Settings.ui_logo_link_url+'" draggable="false">'+text+'</a>';
	} else {
		logoCls += ' unselectable';
	}
	return '<div class="'+logoCls+'" unselectable="on">'+text+'</div>';
};
FR.UI.getImageLogo = function(URL) {
	var html = '<img src="'+URL+'" border="0" alt="" draggable="false" />';
	var cls = '';
	if (Settings.ui_logo_link_url) {
		html = '<a href="'+Settings.ui_logo_link_url+'" draggable="false">'+html+'</a>';
	} else {
		cls = 'unselectable';
	}
	return '<div id="logoContainer" class="'+cls+'" draggable="false">'+html+'</div>';
};

FR.components.SearchBox = Ext.extend(Ext.form.ComboBox, {
	searchParams: {},
	initComponent: function() {
		Ext.apply(this, {
			cls:'search-field', minChars: 2, queryParam: 'keyword',
			emptyText: FR.T('Search')+' '+FR.T('My Files'), itemSelector: 'div.fr-search-field-item',
			listClass: 'fr-search-list', hideTrigger: true, tpl: new Ext.XTemplate(
				'<tpl for=".">' +
					'<div class="fr-search-field-item" title="{path}">' +
					'<div style="float:left;">' +
					'{[this.getIcon(values)]} ' +
					'<div class="filename">{filename}</div>' +
					'</div>' +
					'<div class="size">{nice_filesize}</div><div style="clear:both;"></div>' +
					'</div>' +
				'</tpl>', {
				getIcon: function(values) {
					if (values.isFolder) {
						return '<i class="fa fa-fw fa-folder fa-2x colorGray"></i>';
					} else {
						if (values.hasThumb) {
							var url = FR.UI.getThumbURL({path: values.path+'/'+values.filename, extra: 'width=50&height=50&exactSize=1'});
						} else {
							var url = 'images/fico/'+values.icon;
						}
						return '<img src="'+url+'" width="32" height="32" align="absmiddle" />';
					}
				}}),
			store: new Ext.data.JsonStore({
				searchBox: this,
				url: FR.baseURL+'/?module=search&section=ajax&page=quicksearch',
				root: 'files', idProperty: 'id',
					fields: [
					{name: 'id', mapping: 'id'},
					{name: 'filename', mapping: 'n'},
					{name: 'isFolder', mapping: 'dir'},
					{name: 'hasThumb', mapping: 'th'},
					{name: 'path', mapping: 'p'},
					{name: 'nice_filesize', mapping: 'ns'},
					{name: 'icon', mapping: 'i'}
				],
				listeners: {
					'beforeload': function() {this.searchBox.showMoreBtn.hide();},
					'load': function() {
						var msg = '';
						var count = this.getCount();
						if (count == 10) {
							this.searchBox.showMoreBtn.show();
						}
					}
				}
			}),
			valueField: 'n', displayField: 'n',
			listeners: {
				select: function(c, r) {FR.utils.locateItem(r.data.path, r.data.filename);},
				render: function() {this.el.removeClass('x-form-text');}
			}}
		);
		FR.components.SearchBox.superclass.initComponent.apply(this, arguments);
	},
	doSearch: function() {
		this.searchParams.keyword = this.getRawValue();
		FR.UI.gridPanel.loadParams = this.searchParams;
		var title = FR.T('Search results');
		if (this.searchParams.keyword) {
			title += ' ('+this.searchParams.keyword+')';
		}
		FR.UI.tree.searchResultsNode.setText(title);
		if (FR.currentSection == 'search') {
			FR.utils.reloadGrid();
		} else {
			FR.UI.tree.searchResultsNode.select();
		}
		this.reset();
		this.clearValue();
		this.lastQuery = false;
		this.hasFocus = false;
		this.postBlur();
	},
	initList: function() {
		FR.components.SearchBox.superclass.initList.apply(this, arguments);
		this.extr = this.list.createChild({});
		this.showMoreBtn = new Ext.Toolbar.Button({
			text: FR.T('Show more...'), hidden: true, cls:'fr-btn-smaller',
			handler: function(){this.searchParams.searchType = 'filename';this.doSearch();}, scope: this
		});
		new Ext.Toolbar({
			renderTo: this.extr, height: 26,
			items: ['&nbsp;', '->', this.showMoreBtn]
		});
		this.assetHeight += this.extr.getHeight();
	}
});
FR.UI.getThumbURL = function(itemData) {
	var path = (itemData.path || FR.currentPath+'/'+itemData.filename);
	//append &v=2 when the thumb image style changes
	var url = FR.baseURL+'/t.php?sn=1&p='+encodeURIComponent(path);
	if (itemData.filesize) {
		url += '&s='+itemData.filesize;
	}
	if (itemData.modified) {
		var timestamp = new Date(itemData.modified).getTime()/1000;
		url += '&t='+timestamp;
	}
	if (itemData.extra) {
		url += '&'+itemData.extra;
	}
	return url;
};



FR.components.oldUploadWindow = Ext.extend(Ext.Window, {
	closeAction: 'hide',
	minimized: false,
	lastType: false,
	initComponent: function() {
		Ext.apply(this, {
			activeItem: 0, layout:'card',
			width: 400, height: 356, constrainHeader: true,
			resizable: false, collapsible: false, closeAction: 'hide',
			tools: [
				{
					id: 'minimize', qtip: FR.T('Minimize'),
					handler: function (event, toolEl, win) {
						win.minimized = true;
						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.minimized = false;
						win.getTool('minimize').show();
						win.getTool('restore').hide();
						win.setSize(400, 356).clearAnchor().expand(false).center();
					}
				}
			],
			defaults: {html: '', border: false, layout: 'fit'},
			items: [{ref: 'pluploadcard'}, {ref: 'javacard'}],
			listeners: {
				'hide': function() {
					this.resetUploader();
				}
			}
		});
		FR.components.cartPanel.superclass.initComponent.apply(this, arguments);
	},
	onRender: function() {
		FR.components.cartPanel.superclass.onRender.apply(this, arguments);
	},
	customShow: function(type) {
		this.show();
		this.loadUI(type);
		if (this.minimized) {
			this.getTool('minimize').show();
			this.getTool('restore').hide();
			this.setSize(400, 356).clearAnchor().expand(false);
		}
		this.center();
	},
	loadUI: function(type) {
		if (this.lastType != false && this.lastType != type) {
			this.resetUploader();
		}
		this.lastType = type;
		if (type == 'folder') {
			if (!this.javaIframe) {
				this.javacard.el.mask(FR.T('Loading...'));
				this.javacard.update('');
				this.javaIframe = Ext.DomHelper.insertFirst(this.javacard.el, {tag: 'iframe', frameBorder: 0, src: URLRoot+'/?module=fileman_myfiles&section=ajax&page=upload_java', style: 'width:100%;height:324px;'});
			} else {
				try {
					this.javaIframe.contentWindow.insertApplet();
				} catch (er) {}
			}
			this.getLayout().setActiveItem(1);
		} else {
			FR.UI.feedback('For an improved experience, we recommend you to use a <a href="%1" target="_blank">modern web browser</a>.'.replace('%1', 'http://whatbrowser.org'));
			if (!this.pluploadIframe) {
				this.pluploadIframe = Ext.DomHelper.insertFirst(this.pluploadcard.el, {
					tag: 'iframe', frameBorder: 0,
					src: URLRoot + '/?module=fileman_myfiles&section=ajax&page=upload_regular',
					style: 'width:100%;height:324px;'
				});
			}
			this.getLayout().setActiveItem(0);
		}
	},
	resetUploader: function() {
		try {
			var pu = this.pluploadIframe.contentWindow.Ext.getCmp('PluploadPanel');
			pu.onCancel();
			pu.onDeleteAll();
		} catch(er) {}
	}
});