FR.initLayout = function() {
	
	Ext.get('theBODY').on('mousemove', function(e){
		FR.UI.xy = e.getXY();
	});

	var bottomToolbar = [];
	bottomToolbar.push({
		text: FR.T('Logout'),
		handler:function(){document.location.href = FR.logoutURL;},
		icon: FR.baseURL+'/images/fileman/interface/icons/door_out.gif', cls: 'x-btn-text-icon'
	});
	if (Settings.allowUserToChangePass) {
		bottomToolbar.push({
			text: FR.T('Change password'),
			handler:function(){
				if (!FR.UI.changePassWindow) {
					FR.UI.changePassWindow = FR.UI.popup({
						title: FR.T('Change password'),
						src: FR.baseURL+'/?module=fileman&section=utils&page=change_password',
						width: 300, height: 160
					});
				} else {
					FR.UI.changePassWindow.show();
				}
			},
			icon: FR.baseURL+'/images/fileman/interface/icons/textfield_key.gif', cls: 'x-btn-text-icon'
		});
	}
	if (User.isAdmin) {
		bottomToolbar.push({
			text: FR.T('Control Panel'),
			handler:function(){
			FR.UI.popup({
				src: FR.baseURL+'/?module=admin&page=index',
				width: 680, height: 540,
				constrain: true, maximizable: true
			});
			},
			icon: FR.baseURL+'/images/fileman/interface/icons/monitor.gif', cls: 'x-btn-text-icon'
		});
	}
	bottomToolbar.push('->');
	
	FR.UI.window = new Ext.Window({
		title: Settings.title,
		height: Settings.ui_window_height, width: Settings.ui_window_width,
		id: 'FR-MainInterface-Window',
		el: 'viewport',
		stateful: true,	stateEvents: ['resize'],
		layout: 'border',
		maximizable: true, closable: false, draggable: false, constrain: true,
		iconCls: 'headerIcons-appWindow',
		listeners: {
			resize: function() {FR.UI.window.anchorTo(Ext.get('theBODY'), 'c-c');},
			activate: function(win) {Ext.WindowMgr.sendToBack(win);}
		},
		items: [
			{
				id: 'FR-Tree-Region',
				layout: 'border',
				region: 'west',
				contentEl: 'leftCol',
				width: 190, minSize: 170, maxSize: 300,
				border:false, hideBorders: true,
				split: true, collapsible: true, hideCollapseTool: true, collapseMode: 'mini',
				tbar: FR.UI.toolbar.config,
				items: [
					{
						layout: 'fit',
						region: 'center',
						border: false,
						defaults: {
		                    autoHeight: false, autoScroll: false, closable: false, fitToFrame: true
	                    },
						items: FR.UI.tree.panel
					}
				]
			},
			{
				id: 'rightCol',
				layout: 'border',
				region: 'center',
				border: false, hideBorders: true,
				items: [
					{
						region:'center',
						layout: 'fit',
						border: false, hideBorders: true,
						items: FR.UI.grid.panel
					},{
						id: 'FR-Comments-Panel',
						region:'south',
						layout: 'fit',
						height: 260,
						split:true, fitToFrame: true, border: false,
						titleCollapse: false, collapsible: true, collapsed: true, collapseMode: 'mini', hideCollapseTool: true,
						title: FR.T('Comments'),
						html: '<iframe id="commentsFrame" frameborder="0" width="100%" marginwidth="0" marginheight="0" height="100%" src="about:blank" style="position:absolute"></iframe>'
					}
				]
			}, {
				id: 'southRegion',
				region: 'south',
				border:false, hideBorders: true,
				bodyStyle: 'display:none',
				bbar: bottomToolbar
			}
		]
	});
	
	FR.UI.window.show();
	FR.UI.window.anchorTo(Ext.get('theBODY'), 'c-c');
	Ext.EventManager.onWindowResize(function(w, h) {
		if (!Settings.ui_enable_full_screen) {
			if (!FR.UI.window.maximized && (FR.UI.window.width > w || FR.UI.window.height > h)) {
				FR.UI.window.maximize();
			} else if (FR.UI.window.maximized && FR.UI.window.restoreSize.width < w && FR.UI.window.restoreSize.height < h) {
				FR.UI.window.restore();
			}
		}
	});
	FR.UI.restoreView();
	
	if (Settings.ui_enable_full_screen) {
		FR.UI.window.maximize();
	}
	FR.UI.slidePane = Ext.getCmp('FR-Comments-Panel');
	Ext.getCmp('southRegion').getBottomToolbar().addDom({
		tag: 'div',
		id: 'trafficQuotaIndicator',
		style: 'width:200px;margin-right:5px;',
		onclick: 'FR.UI.reloadStatusBar()'
	});
	Ext.getCmp('southRegion').getBottomToolbar().addDom({
		tag: 'div',
		id: 'spaceQuotaIndicator',
		style: 'width:200px;',
		onclick: 'FR.UI.reloadStatusBar()'
	});
	if (User.perms.space_quota_max) {
		FR.UI.spaceQuotaIndicator = new Ext.ProgressBar({
			autoWidth: true,
			autoHeight: true,
			renderTo: 'spaceQuotaIndicator'
		});
		FR.UI.spaceQuotaIndicator.setSize(false, 18);
	}
	if (User.perms.traffic_quota_max) {
		FR.UI.trafficQuotaIndicator = new Ext.ProgressBar({
			autoWidth: true,
			renderTo: 'trafficQuotaIndicator'
		});
		FR.UI.trafficQuotaIndicator.setSize(false, 18);
	}
	if (User.perms.space_quota_max || User.perms.traffic_quota_max) {FR.UI.setQuotaStatus();}
	Ext.EventManager.addListener('viewport', 'contextmenu', function(e) {
		e.stopEvent();
	});

	// Sliding Pane
	FR.UI.slidePane.on('expand', function(panel) {
		Ext.getCmp('tbarCommentsToggle').toggle(true);
		FR.UI.slidePaneIsOpen = true;
		return FR.UI.onSlidePane();
	});
	FR.UI.slidePane.on('collapse', function(panel) {
		FR.UI.slidePaneIsOpen = false;
		Ext.getCmp('tbarCommentsToggle').toggle(false);
	});
}

FR.UI.setQuotaStatus = function() {
	if (FR.UI.trafficQuotaIndicator) {
	FR.UI.trafficQuotaIndicator.updateProgress(User.perms.traffic_quota_percent_used/100, FR.T('Traffic:')+' '+User.perms.traffic_quota_used+' / '+User.perms.traffic_quota_max_formated);
	}
	if (FR.UI.spaceQuotaIndicator) {
	FR.UI.spaceQuotaIndicator.updateProgress(User.perms.space_quota_percent_used/100, FR.T('Space:')+' '+User.perms.space_quota_used+' / '+User.perms.space_quota_max_formated);
	}
}
FR.UI.confirm = function(question, confirmHandler, cancelHandler) {
	Ext.Msg.show({
		title:FR.T('Confirmation'),
		msg: question,
		buttons: Ext.MessageBox.OKCANCEL,
		closable: false, modal: false,
		fn: function (btn, txt) {
			if (btn == 'ok') {
				confirmHandler();
			} else {
				cancelHandler();
			}
		}
	});
}
FR.UI.prompt = function(question, confirmHandler, cancelHandler, value) {
	m = Ext.Msg.show({
		msg: question,
		buttons: Ext.MessageBox.OKCANCEL,
		closable: false, modal: false, prompt: true,
		value: value,
		fn: function (btn, txt) {
			if (btn == 'ok') {
				confirmHandler(txt);
			} else {
				cancelHandler();
			}
		}
	});
}

FR.UI.feedback = function(text) {
	var msgCt;
	if (text.length > 0) {
		delay = text.length/15;
	} else {
		delay = 1;
	}
	if(!msgCt){
		msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div', style:'width:300px;z-index:9999999'}, true);
	}
	msgCt.alignTo(Ext.get('viewport'), 'tr-tr', [-50, 3]);
	var m = Ext.DomHelper.append(msgCt, {html:['<div class="msg" style="z-index:9999998">',
	'<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
	'<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc">', text, '</div></div></div>',
	'<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
	'</div>'].join('')}, true);
	m.slideIn('t').pause(delay).ghost('t', {remove:true});
}
FR.UI.popupCount = 0;
FR.UI.popup = function(args) {
	id = 'popups_'+(++this.popupCount);
	windowId = args.id || id+'_window';
	Ext.state.Manager.clear(windowId);
	args.src = args.src+'&_popup_id='+windowId;
	dialog = new Ext.Window({
		id: windowId,
		stateful: false,
		stateEvents: 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,
		constrain: args.constrain || false,
		iconCls: args.iconCls || false,
		closable: true, plain: 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="'+id+'" name="'+id+'"></iframe></div>'
    });
	dialog.frameId = id;
	args.centerTo = args.centerTo || false;
	dialog.show(args.centerTo);
	Ext.state.Manager.clear(windowId);
	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) {
		frm = document.createElement('FORM');
		frm.action = args.src;
		frm.method = 'POST';
		frm.target = id;
		args.post.each(function(param) {
			inpt = document.createElement('INPUT');
			inpt.name = param.name;
			inpt.value = encodeURIComponent(param.value);
			frm.appendChild(inpt);
		})
		$('theBODY').appendChild(frm);
		frm.submit();
		$('theBODY').removeChild(frm);
	}
	return dialog;
}

FR.UI.showUploadForm = function() {
	if (FR.currentFolderPerms) {
		if (!FR.currentFolderPerms.upload) {
			var notAllowed = true;
		}
	} else {
		if (FR.currentSection == 'userWithShares') {
			var notAllowed = true;
		}
	}
	if (notAllowed) {
		FR.UI.feedback(FR.T("You are not allowed to upload files in this folder."));
		return false;
	}
	if (!FR.UI.uploadDialog) {
		dialog = new Ext.Window({
			title: FR.T('Upload'),
			width: 355, height: 360,
			modal: true, resizable:false, collapsible:false, plain: true, closeAction: 'hide',
            items: new Ext.TabPanel({
				id: 'uploadDialogTP',
				height: 330,
                activeTab: (Settings.ui_default_upload_mode == 'dnd') ? 0 : ((Settings.ui_default_upload_mode == 'classic') ? 1 : 2),
                deferredRender:false,
                border:false,
				tabPosition: 'top',
				items: [
					{
						title: FR.T('Drag&Drop'),
						contentEl: Ext.DomHelper.append($('theBODY'), {tag: 'DIV', id: 'uploadJavaDiv', style: 'height:327px;overflow:hidden;'}),
						listeners: {
							activate: function() {
								if (!FR.UI.uploadTabs.java) {
									FR.UI.uploadDialogDNDiframe = Ext.DomHelper.append($('theBODY'), {tag: 'iframe', id:'dndifrm', frameBorder: 0, src: 'about:blank', height:327, width:339});
									$('uploadJavaDiv').appendChild(FR.UI.uploadDialogDNDiframe);
									if (Ext.isIE) {
										var frameDoc = document.frames['dndifrm'].document;
									} else {
										var frameDoc = FR.UI.uploadDialogDNDiframe.contentDocument;
									}
									frameDoc.write('<div style="color:dimgray;font-family:arial,tahoma,helvetica,sans-serif;font-size:11px;">'+FR.T('Loading Java applet, please wait...')+'</div>');
								FR.UI.uploadDialogDNDiframe.src = URLRoot+'/?module=fileman_myfiles&section=ajax&page=upload_form&path='+encodeURIComponent(FR.currentPath);
									FR.UI.uploadTabs.java = true;
								}
							}
						}
					},
					{
						title: FR.T('Classic'),
						contentEl: Ext.DomHelper.append($('theBODY'), {tag: 'DIV', id: 'uploadHTMLDiv', style: 'height:327px;overflow:hidden;'}),
						listeners: {
							activate: function() {
								if (!FR.UI.uploadTabs.html) {
									FR.UI.uploadDialogHTMLiframe = Ext.DomHelper.append($('theBODY'), {tag: 'iframe', frameBorder: 0, src: URLRoot+'/?module=fileman_myfiles&section=ajax&page=upload_form_classic&path='+encodeURIComponent(FR.currentPath), height:327, width:339});
									$('uploadHTMLDiv').appendChild(FR.UI.uploadDialogHTMLiframe);
									FR.UI.uploadTabs.html = true;
								}
							}
						}
					},
					{
						title: FR.T('Flash'),
						contentEl: Ext.DomHelper.append($('theBODY'), {tag: 'DIV', id: 'uploadFlashDiv', style: 'height:327px;overflow:hidden;'}),
						listeners: {
							activate: function() {
								if (!FR.UI.uploadTabs.flash) {
									FR.UI.uploadDialogSWFiframe = Ext.DomHelper.append($('theBODY'), {tag: 'iframe', frameBorder: 0, src: URLRoot+'/?module=fileman_myfiles&section=ajax&page=upload_swf&path='+encodeURIComponent(FR.currentPath), height:327, width:339});
									$('uploadFlashDiv').appendChild(FR.UI.uploadDialogSWFiframe);
									FR.UI.uploadTabs.flash = true;
								}
							}
						}
					}
				]
            })
	    });
		FR.UI.uploadDialog = dialog;
		dialog.show();
		if (!Settings.ui_enable_dnd_upload) {
			Ext.getCmp('uploadDialogTP').hideTabStripItem(0);
		}
		if (!Settings.ui_enable_classic_upload) {
			Ext.getCmp('uploadDialogTP').hideTabStripItem(1);
		}
		if (!Settings.ui_enable_flash_upload) {
			Ext.getCmp('uploadDialogTP').hideTabStripItem(2);
		}
	} else {
		FR.UI.setDNDFolder();
		FR.UI.uploadDialog.show();
	}
}
FR.UI.setDNDFolder = function() {
	if (FR.UI.uploadDialogDNDiframe) {
		if (FR.UI.uploadDialogDNDiframe.contentWindow) {
			FR.UI.uploadDialogDNDiframe.contentWindow.setPostURL();
		}
	}
}
FR.UI.reloadStatusBar = function() {
	if (User.perms.space_quota_max || User.perms.traffic_quota_max) {
		var url = FR.baseURL+'/?module=fileman&section=utils&page=status_bar';
		var myAjax = new Ajax.Request(
		url, {
		method: 'get',
		onComplete: function(originalRequest){
			var rs = eval('('+originalRequest.responseText+')');
			User.perms.space_quota_percent_used = rs.space_quota_percent_used;
			User.perms.space_quota_free = rs.space_quota_free;
			User.perms.space_quota_used = rs.space_quota_used;
			User.perms.traffic_quota_percent_used = rs.traffic_quota_percent_used;
			User.perms.traffic_quota_free = rs.traffic_quota_free;
			User.perms.traffic_quota_used = rs.traffic_quota_used;
			FR.UI.setQuotaStatus();
		}
	});
}}
FR.UI.onSlidePane = function() {
	if (FR.currentSelectedFile) {
		if (FR.UI.slidePaneIsOpen) {
			FR.UI.showComments();
		}
	} else {
		FR.UI.feedback(FR.T('Please select a file.'));
		return false;
	}
}
FR.UI.showPreview = function(path, filename) {
	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;
	}
	var path = path || FR.currentPath;
	var filename = filename || FR.currentSelectedFile.filename;
	FR.previewData = {path: path, filename: filename};
	FR.UI.popup({
		title: filename,
		width: 500, height: 500,
		src: FR.baseURL+'/?module=fileman&section=utils&page=file_preview',
		post: [
			{name: 'filename', value: filename},
			{name: 'path', value: path}
		],
		autoDestroy: true, resizable: true, maximizable: true,
		tools: [{
		    id: 'save',
			qtip: FR.T('Download'),
		    handler: function(event, toolEl, win){
				FR.actions.downloadOneFile(FR.previewData.path, FR.previewData.filename)
		    }
		}]
	});
	return true;
}
FR.UI.resetCommentsPane = function() {
	$('commentsFrame').src = FR.baseURL+'/blank.html';
	FR.UI.slidePane.collapse();
}
FR.UI.showComments = function() {
	if (FR.UI.lastCommentedFile != FR.currentSelectedFile.filename) {
		var url = FR.baseURL+'/?module=comments&section=default&page=default';
		url += '&path='+encodeURIComponent(FR.currentPath)+'&filename='+encodeURIComponent(FR.currentSelectedFile.filename);
		$('commentsFrame').src = url;
	}
	FR.UI.lastCommentedFile = FR.currentSelectedFile.filename;
}

FR.UI.changeView = function(view, toggle) {
	FR.cookieProvider.set('fr-view-mode', view);
	if (toggle) {
		Ext.getCmp('tbarView-'+view).toggle('pressed');
	}
	if (view == 'thumbnails') {
		FR.UI.grid.panel.getView().tpl = FR.UI.grid.thumbnailTpl;
		FR.UI.grid.panel.getView().refresh(true);
	} else {
		FR.UI.grid.panel.getView().tpl = null;
		FR.UI.grid.panel.getView().refresh(true);
	}	FR.UI.grid.currentView = view;
}
FR.UI.restoreView = function() {
	savedViewMode = FR.cookieProvider.get('fr-view-mode', false);
	if (savedViewMode) {
		Ext.getCmp('tbarView-'+savedViewMode).toggle('pressed');
		FR.UI.changeView(savedViewMode);
	} else {
		FR.UI.changeView(Settings.ui_default_view, 1);
	}
}
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.show();
		$(win.frameId).contentWindow.FR.update(args);
	}
}
FR.UI.showLoading = function(msg, onlyTreePane) {
	if (onlyTreePane) {
		Ext.getCmp('FR-Tree-Region').getEl().mask(msg);
	} else {
		FR.UI.window.getEl().mask(msg);
	}
}
FR.UI.doneLoading = function() {
	Ext.getCmp('FR-Tree-Region').getEl().unmask();
	FR.UI.window.getEl().unmask();
}