var FR = {
	initForm: function() {
		this.windowHeight = 260;
		if (Settings.allowPersistentLogins || Settings.passwordRecoveryEnabled) {
			this.windowHeight += 20;
		}
		if (Settings.ui_login_title) {
			this.windowHeight += 20;
		}
		if (Settings.ui_login_logo.length || Settings.ui_login_text.length) {
			var windowWidth = 560;
		} else {
			var windowWidth = 320;
		}
		if (selectedLang  == 'finnish') {
			windowWidth += 17;
		}
		this.formPanel = new Ext.form.FormPanel({
			labelAlign: 'right', ref: '../frm', border: false,
			defaultType: 'textfield', autoHeight: true, hideLabels: true,
			cls: 'loginForm', standardSubmit: true, url: URLRoot+'/?module=fileman&page=login&action=login',
			listeners: {
				'render': function() {
					this.getForm().el.set({
						'target': 'submitIframe',
						'onSubmit': 'FR.submitForm();return false;'
					});
				}
			},
			defaults: {listeners: {specialkey: function(field, e){
				if (Ext.isIE8 && e.getKey() == e.ENTER) {FR.submitForm();}}}
			},
			items: [
				{xtype: 'displayfield', value: FR.T('Username'), cls: 'loginFormLabel'},
				{
					ref: 'usrField', name: 'username', value: prefilledUsername,
					width:265, tabIndex: 1, height:30, cls: 'loginFormField',
					autoCreate: {tag: 'input', type: 'text', size: '20', autocomplete: 'on'}
				},
				{xtype: 'displayfield', value: FR.T('Password'), cls: 'loginFormLabel'},
				{
					xtype: 'compositefield',
					items: [
						{
							xtype: 'textfield', ref: '../passField',
							id: 'pass', tabIndex: 2, value: prefilledPassword, width:265,
							name: 'password', inputType: 'password', height:30, cls: 'loginFormField',
							autoCreate: {tag: 'input', type: 'password', size: '20', autocomplete: 'on'}
						}
					]
				},
				{xtype: 'component', html: '<input type="submit" hidefocus="true" tabindex="-1" style="position:absolute;z-index:-100;width:1px;height:1px;" />'},
				{xtype: 'displayfield', value: FR.T('Verification code'), ref: 'otp_label', cls: 'loginFormLabel', hidden: true},
				{
					xtype: 'compositefield',
					items: [
						{
							xtype: 'textfield', ref: '../otp', hidden: true,
							id: 'otp', value: '', width:265,
							name: 'otp', height:30, cls: 'loginFormField'
						}
					]
				},
				{xtype: 'hidden', name: 'redirectAfterLogin', value: redirectAfterLogin},
				{xtype: 'hidden', name: 'two_step_secret', ref: 'two_step_secret', value: ''},
				{
					xtype: 'panel', border: false, layout: {type: 'hbox'},
					items: [
						{
							xtype: 'checkbox', checked: true,
							id: 'persistent', boxLabel: '<span style="color:gray">'+FR.T('Keep me signed in')+'</span>',
							inputValue: '1', name: 'persistent', tabIndex: 2, hidden: !Settings.allowPersistentLogins
						},
						{xtype:'spacer', flex:1},
						{xtype: 'displayfield',  value: '<a href="'+URLRoot+'/?module=fileman&page=password_recovery" style="font-size:11px">'+FR.T('Forgot password?')+'</a>', style:'text-align:right;padding-right:20px;', hidden: !Settings.passwordRecoveryEnabled}
					]
				}
			]
		});
		this.iframe = Ext.DomHelper.append(document.body, {
			tag: 'iframe', name: 'submitIframe', id:'submitIframe',
			frameBorder: 0, width: 0, height: 0,
			css: 'display:none;visibility:hidden;height:0px;',
			src: 'about:blank'
		});
		Ext.get('submitIframe').on('load', function() {
			this.win.body.unmask();
			if (this.iframe.contentDocument) {
				if (this.iframe.contentDocument.document) {
					var frameDoc = this.iframe.contentDocument.document;
				} else {
					var frameDoc = this.iframe.contentDocument;
				}
			} else {
				if (this.iframe.contentWindow.document) {
					var frameDoc = this.iframe.contentWindow.document;
				}
			}
			var responseText = frameDoc.body.innerHTML;
			if (responseText.length == 0) {
				return false;
			}
			try {
				var rs = Ext.util.JSON.decode(responseText);
			} catch (er) {
				if (confirm(FR.T('Unexpected server reply. Press "OK" to display it.'))) {
					document.write(responseText);
				}
				return false;
			}
			if (rs.success) {
				if (rs.redirect_url) {
					document.location.href = decodeURIComponent(rs.redirect_url);
				} else {
					document.location.href = URLRoot+(startFolder ? '/?folder='+encodeURIComponent(startFolder): '/');
				}
			} else if (rs.success == false) {
				if (rs.twoStepSecret) {
					FR.win.frm.two_step_secret.setValue(rs.twoStepSecret);
					FR.showQR(rs.twoStepSecret, rs.keyURI);
				} else {
					if (rs.ask_otp) {
						FR.showOTPField();
					}
					new Ext.ux.prompt({text: rs.error, width:rs.ask_otp?'350':false, callback: function() {FR.win.frm.usrField.focus(true);}});
				}
			}
		}, this);
		this.win = new Ext.Window({
			title: FR.T(Settings.ui_login_title),
			layout: 'border', width: windowWidth, height: this.windowHeight, buttonAlign: 'left',
			closable: false, resizable: false, draggable: false, hideBorders: true,
			listeners: {'show': function(){
				this.frm.usrField.focus(false, 20);
				if (Settings.ui_login_logo.length) {
					this.logoImgDOM = Ext.get(Ext.DomHelper.createDom({tag: 'img', src: '', border: 0, alt: ''}));
					this.logoImgDOM.addListener('load', function() {
						this.alignTo(Ext.getCmp('logoArea').body, 'c-c');
					});
					Ext.get('logoHolder').appendChild(this.logoImgDOM);
					this.logoImgDOM.set({src: Settings.ui_login_logo});
					if (Settings.ui_login_text.length) {
						var loginTextPanel = new Ext.Window({
							html: '<div class="loginText">'+Settings.ui_login_text+'</div>', autoHeight: true,
							closable: false, frame: false, resizable: false, draggable: false, width: windowWidth
						});
						loginTextPanel.show();
						loginTextPanel.alignTo(FR.win.getEl(), 'tr-br', [0,8]);
					}
				} else {
					if (Settings.ui_login_text.length) {
						Ext.get('loginText').update(Settings.ui_login_text);
						Ext.get('loginText').show().alignTo(Ext.getCmp('logoArea').body, 'c-c');
					}
				}
			}},
			items: [
				{
					region: 'west', width: 230, id: 'logoArea',
					html:'<div id="logoHolder"></div><div id="loginText" class="loginTextLogo"></div>',
					hidden: (!Settings.ui_login_logo.length && !Settings.ui_login_text.length)
				},
				{
					region: 'center', hideBorders: true,
					items: [
						this.formPanel
					]
				}
			],
			buttons: [
				{
					id: 'lang', xtype: 'combo', hidden: !Settings.ui_display_language_menu,
					hidden: !Settings.ui_display_language_menu,
					fieldLabel: '&nbsp;', labelSeparator: '', editable: false, 
					autoCreate:true, mode: 'local', displayField:'n', style: 'color:gray',
					valueField:'k', hiddenName:'language', name: 'language', 
					value: selectedLang, width:100, triggerAction:'all',
					store: new Ext.data.SimpleStore({
						fields: ['n', 'k'],
						data: Languages
					}),
					listeners: {
						select: function(el) {
							usrName = this.ownerCt.ownerCt.frm.usrField.getValue();
							if (!usrName || usrName.length == 0) {
								document.location.href = URLRoot+'/?language='+encodeURIComponent(el.getValue());
							}
						}
					}
				},
				new Ext.Toolbar.Fill(),
				{
					text: FR.T('Sign in'),  tabIndex: 4, cls: 'fr-btn-default fr-btn-primary',
					handler: function(){FR.submitForm();}
				},
				{
					text: FR.T('Register'), cls: 'fr-btn-default',
					handler: function(){document.location.href=signUpURL;}, hidden: !Settings.signUpEnabled
				}
			]
		});
		this.win.show();
		if (Settings.allowPersistentLogins)	{
			new Ext.ToolTip({
				target: Ext.getCmp('persistent').wrap.last(),
				anchor: 'top', showDelay: 100, dismissDelay: 0, width: 300,
				html: FR.T('By checking this box, you\'ll stay logged in for up to 2 weeks or until you log out. You\'ll get easier access to the files, even if you close your browser or shut down your computer.<br>If you\'re using a public computer or you share this computer with others, we recommend that you uncheck the box.')
			});
		}
		this.win.anchorTo(Ext.get('theBODY'), 'c-c');
	},
	submitForm: function() {
		this.win.body.mask(FR.T('Signing in...'));
		FR.formPanel.getForm().submit();
	},
	showOTPField: function() {
		FR.win.frm.otp_label.show();
		FR.win.frm.otp.show();
		FR.win.frm.doLayout();
		FR.win.setHeight(FR.windowHeight+50);
		FR.win.center();
	},
	showQR: function(secret, keyURI) {
		FR.QRWindow = new Ext.Window({
			title: FR.T('2-step verification: add account'), closable: false, resizable: false,
			layout: 'border', width: 350, height: 400, modal: true, hideBorders: true,
			items: [
				{
					region: 'north', bodyStyle: 'padding:10px;text-align:center;font-size:14px;', height: 50,
					html: FR.T('Scan this barcode with the <a href="%1" target="_blank">Google Authenticator</a> app on your mobile device to add your account.').replace('%1', 'https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en')
				},
				{
					region: 'center',
					html:
					'<div style="text-align:center;">' +
						'<div style="" class="loginQRCodeWrap">' +
							'<img title="'+secret+'" src="'+URLRoot +'/?module=fileman&section=utils&page=qrcode&encoded=1&size=6&data='+encodeURIComponent(keyURI)+'" />' +
						'</div>' +
					'</div>'
				}
			],
			buttonAlign: 'center',
			buttons: [{
				cls: 'fr-btn-default fr-btn-primary',
				text: FR.T('Done'), handler: function(){
					FR.QRWindow.close();
					FR.showOTPField();
				}
			}]
		});
		FR.QRWindow.show();
	}
};
Ext.onReady(function() {
	FR.initForm();
	if (message) {
		new Ext.ux.prompt({text: message, callback: function() {FR.win.frm.usrField.focus(true);}});
	}
});