FR = {
	UI: {},
	init() {
		this.viewport = new Ext.Viewport({
			activeItem: 0,
			layout: 'card',
			items: [
				{
					contentEl: 'selectFormat',
					autoScroll: true
				},
				{
					autoScroll: true,
					html: '<div id="status"></div>'
				}
			],
			listeners: {
				'afterrender'(viewport) {
					Ext.each(viewport.el.query('div.format'), (el) => {
						Ext.get(el).on('click', function() {
							FR.format = this.dom.dataset.format;
							FR.requestConvertion();
						});
					});
				}
			}
		});
	},
	requestConvertion() {
		this.viewport.setActiveItem(1);
		this.log(Ext.T('Uploading file to Zamzar...'));
		Ext.Ajax.request({
			url: URLRoot+'/?module=custom_actions&action=zamzar&method=requestConversion',
			params: {
				path: path,
				format: FR.format
			},
			callback: function(opts, succ, req) {
				try {
					var rs = JSON.parse(req.responseText);
				} catch (er){return false;}
				if (rs.msg) {
					window.parent.FR.UI.feedback(rs.msg, rs.success ? 'success' : 'error');
					this.log(rs.msg);
					if (rs.success) {
						FR.jobId = rs.jobId;
						window.setTimeout(function () {
							FR.getStatus();
						}, 3000);
					}
				}
			},
			scope: this
		});
	},
	getStatus() {
		Ext.Ajax.request({
			url: URLRoot+'/?module=custom_actions&action=zamzar&method=getStatus',
			params: {
				path: path,
				jobId: FR.jobId
			},
			callback: function(opts, succ, req) {
				try {
					var rs = JSON.parse(req.responseText);
				} catch (er){return false;}
				if (rs.msg) {
					this.log(rs.msg);
					if (rs.status == 'successful') {
						window.parent.FR.UI.feedback(rs.msg, 'success');
						FR.downloadConverted(rs.fileId);
					} else {
						if (rs.status == 'failed') {
						} else {
							window.setTimeout(function(){FR.getStatus();}, 5000);
						}
					}
				}
			},
			scope: this
		});
	},
	downloadConverted(fileId) {
		this.log('Downloading converted file...');
		Ext.Ajax.request({
			url: URLRoot+'/?module=custom_actions&action=zamzar&method=downloadConverted',
			params: {
				path: path,
				fileId: fileId,
				format: FR.format,
				csrf: csrf
			},
			callback: function(opts, succ, req) {
				try {
					var rs = JSON.parse(req.responseText);
				} catch (er){return false;}
				if (rs.success) {
					window.parent.FR.utils.reloadGrid(rs.newFileName);
					window.parent.FR.UI.popups[windowId].close();
				} else {
					if (rs.msg) {
						this.log(rs.msg);
					}
				}
			},
			scope: this
		});
	},
	log(txt) {
		Ext.DomHelper.append('status', {tag: 'div', html: txt});
	}
}
Ext.onReady(FR.init, FR);