FR = {
	UI: {},
	init: function() {
		this.viewport = new Ext.Viewport({
			layout: 'fit',
			items: {
				layout: 'fit',
				border: false,
				html: '<div id="editor" style="position: absolute;top: 0;right: 0;bottom: 0;left: 0;"></div>',
				tbar: [{
					text: FR.T("Save"), iconCls: 'fa fa-fw fa-save', cls: 'fr-btn-default fr-btn-primary fr-btn-smaller fr-btn-icon-white',
					handler: this.save, scope: this
				}, {
					text: FR.T("Save and close"), iconCls: 'fa fa-fw fa-save', cls: 'fr-btn-default fr-btn-primary fr-btn-smaller fr-btn-icon-white',
					handler: function(){this.save(true);}, scope: this
				}]
			},
			listeners: {
				'afterrender': function() {
					FR.editor = ace.edit("editor");
					var modelist = ace.require('ace/ext/modelist');
					var mode = modelist.getModeForPath(filename).mode;
					if (!mode) {mode = 'ace/mode/html'}
					FR.editor.setTheme("ace/theme/eclipse");
					FR.editor.getSession().setMode(mode);
					FR.editor.getSession().setUseWrapMode(true);
					FR.editor.getSession().setValue(FR.getText());
					FR.editor.commands.addCommand({
						name: 'Save',
						bindKey: {win: 'Ctrl-S',  mac: 'Command-S'},
						exec: function(editor) {FR.save();}
					});
				}
			}
		});
	},
	getText: function() {
		return Ext.get('textContents').dom.value;
	},
	save: function(close) {
		this.closeAfterSave = close;
		this.viewport.getEl().mask(FR.T('Saving...'));
		Ext.Ajax.request({
			url: URLRoot+'/?module=custom_actions&action=code_editor&method=saveChanges',
			params: {
				path: path,
				filename: filename,
				textContents: FR.editor.getSession().getValue()
			},
			success: function(req) {
				this.viewport.getEl().unmask();
				try {
					var rs = Ext.util.JSON.decode(req.responseText);
				} catch (er){return false;}
				if (rs.msg) {
					window.parent.FR.UI.feedback(rs.msg);
				}
				if (rs.rs && this.closeAfterSave) {
					window.parent.FR.UI.tabs[windowId].close();
				}
			},
			scope: this
		});
	}
}