var loginTool = null;
var autoShow = false;
var errPanel;

Ext.onReady(function() {
	Ext.BLANK_IMAGE_URL = 'images/s.gif';
	createLoginTool();
	if (autoShow)
		showLoginForm();
});
function showLoginForm() {
	if (loginTool)
		loginTool.show();
}

function setAutoShow(isAutoShow) {
	autoShow = isAutoShow;
}

function createLoginTool() {
	errPanel = new Ext.Panel({
		layout : 'absolute',
		name : 'errStatusPanel',
		hidden: true,
		height : 25,
		width : 400,
		items : [{
			x : 0,
			y : 0,
			width : 400,
			xtype : 'label',
			style: 'color: #e32727;',
			name : 'errStatus',
			text: 'Ошибка при входе. Проверьте правильность ввода.'
		}]
	});
	
	loginTool = new Ext.Window({
		title : 'Вход',
		layout : 'fit',
		width : 400,
		height : 160,
		modal : true,
		resizable : false,
		closeAction : 'hide',
		items : {
			xtype : 'form',
			bodyStyle : 'padding: 10px',
			frame : true,
			labelWidth : 110,
			labelAlign : 'left',
			buttonAlign : 'center',
			defaults : {
				xtype : 'textfield',
				allowBlank : false,
				style : 'font-size: 12px;'
			},
			items : [errPanel, {
				name : 'login',
				fieldLabel : 'Имя пользователя',
				width : 230
			}, {
				inputType : 'password',
				name : 'password',
				fieldLabel : 'Пароль',
				width : 230
			}],
			buttons : [{
				xtype : 'button',
				text : 'Войти',
				handler : login
			}, {
				text : 'Отмена',
				handler : function() {
					this.findParentByType('window').hide();
				}
			}]
		}
	});
	var f = loginTool.findByType('form')[0].getForm();
	loginTool.on('hide', function() {
		form = f.reset();
	});
	loginTool.on('show', function() {
		form = f.findField('login').focus();
	});
}

function login() {
	var form = loginTool.findByType('form')[0];
	if (form.getForm().isValid()) {
		var login = form.getForm().findField('login').getValue();
		var password = form.getForm().findField('password').getValue();
		Ext.Ajax.request({
			url : 'security?do=login',
			params : {
				login : login,
				password : password
			},
			success : function(val) {
				loginTool.hide();
				var redirectTo = getRequestParameter('redirectTo');
				if (!redirectTo) {
					location.reload(true);
				} else {
					document.location = redirectTo;
				}
			},
			failure : function(val) {
				loginTool.setHeight(180);
				errPanel.show();
			}
		});
	} else {
		Ext.Msg.show({
			msg : 'Заполните корректно все поля',
			title : 'Ошибка',
			buttons : Ext.Msg.OK,
			icon : Ext.MessageBox.ERROR
		});
	}
}

function logout() {
	if (loginTool) {
		Ext.Ajax.request({
			url : 'security?do=logout',
			success : function() {
				location.reload(true);
			}
		});
	}
}
