Ext.define("Portfolio.login.view.Html", {
	extend: "Ext.Component",

	xtype: "portfolio-login",

	alias: [
		"widget.login.view.html"
	],

	controller: "portfolio-login-html",

	draggable: false,

	resizable: false,

	requires: [
		"Portfolio.login.util.Handler",
		"Portfolio.login.controller.Html"
	],

	hidden: true,

	mixins: [
		"Ext.mixin.Mashup"
	],

	requiredScripts: [
		"/custom-config/login/custom.css"
	],

	listeners: {
		destroy: {
			fn: function() {

				var i_self = this;

				var i_login = Ext.get("login");
				i_login.destroy();

				Ext.GlobalEvents.un("resize", i_self.doResize);
			}
		}
	},

	config: {
		loginConfig: {},
		messageField: null,
		endServerSession: false
	},

	loader: {
		url: "/custom-config/login/login.html",
		listeners: {
			load: {
				fn: function(i_context, i_response) {

					var i_self = i_context.target;
					var o_config = i_self.getLoginConfig();
					var i_controller = i_self.getController();

					var i_body = Ext.getBody();

					var s_html = i_response.responseText;

					if (s_html) {

						var s_loginHtml = Portfolio.login.util.Handler.getTemplate(s_html, o_config.loginTheme);
						Ext.DomHelper.append(i_body, s_loginHtml);

						var i_login = Ext.get("login");

						if (i_login) {

							var i_box = Ext.get("box");

							if (i_box) {

								i_box.show();
								i_box.center();

								var i_loginElement = Ext.DomQuery.selectNode("a.button.login") || Ext.DomQuery.selectNode("a.button.login-btn");

								if (i_loginElement) {
									i_self.doNormalRender(i_login);
								}
								else {
									i_self.doLegacyRender(i_login);
								}

								var a_inputs = i_box.query("input");

								Ext.Array.each(a_inputs, function(i_dom) {

									var i_element = Ext.get(i_dom);

									var i_parent = i_element.parent();
									i_parent.addCls("has-value");
								});

								i_login.on({
									keypress: {
										fn: function(i_event, i_domElement) {

											if (i_event.keyCode == i_event.ENTER) {

												i_event.stopEvent();
												i_controller.onLoginClick(function(o_result, o_values) {

													if (o_result.msgid == "IP21100") {
														i_self.doMutilFactorAuth(o_result, o_values);
													}
													else {
														i_self.doHandleError(o_result);
													}
												});
											}
										}
									}
								});

								var f_buffer = Ext.Function.createBuffered(function() {
									var i_userId = Ext.get("userid");
									i_userId.focus();
								}, 500);

								f_buffer.call();

								Ext.GlobalEvents.on("resize", i_self.doResize);

								var b_endServerSession = i_self.getEndServerSession();

								if (b_endServerSession) {

									if (!i_loginElement) {
										i_loginElement = Ext.DomQuery.selectNode(".button");
									}

									i_loginElement = Ext.get(i_loginElement);

									i_loginElement.mask();

									Ext.Ajax.request({
										url: "/ip2-services/ip2navigator.aspx",
										params: {
											func: "cleanUp"
										},
										success: function (response, request) {

											i_self.setEndServerSession(false);

											var f_buffer = Ext.Function.createBuffered(function () {
												i_loginElement.unmask();
											}, 1000);

											f_buffer.call();
										}
									});
								}
							}
						}
					}
				}
			}
		}
	},

	initComponent: function() {

		var i_self = this;
		i_self.callParent(arguments);

		Portfolio.login.util.Handler.getLoginConfig(function(o_config) {

			Ext.apply(o_config.loginTheme, {
				userID: "User ID",
				password: "Password",
				login: "Login",
				forgotPassword: "Forgot password",
				sitemuleLogo: o_config.sitemuleLogo
			});

			i_self.setLoginConfig(o_config);

			i_self.getLoader().load();
		});

		i_self.enableBubble("login");
	},

	doMutilFactorAuth: function(o_auth, o_values) {

		var i_self = this;

		var i_controller = i_self.getController();

		var a_state = [];

		var o_loginInfo = Ext.Object.merge({}, o_values, {
			devId: o_auth.text
		});

		var o_preset = Portfolio.util.Handler.baseconfig.session.preset;

		a_state.push(o_preset.origin.toLowerCase());
		a_state.push(o_values.username.toLowerCase());

		var s_state = a_state.join("-");

		Ext.state.Manager.set(s_state, o_auth.text);

		var i_window = Ext.widget("window", {
			title: "Auth",
			layout: "fit",
			closable: false,
			width: 300,
			height: 150,
			modal: true
		});

		var i_formpanel = Ext.widget("form", {
			layout: "anchor",
			bodyPadding: 10,
			defaults: {
				anchor: "100%",
				labelAlign: "top"
			},
			items: [
				{
					xtype: "textfield",
					name: "key",
					fieldLabel: "Please enter code sent to you"
				}
			]
		});

		var i_toolbar = Ext.widget("toolbar", {
			ui: "footer",
			dock: "bottom",
			layout: {
				type: "hbox",
				pack: "center"
			},
			defaults: {
				margin: "0 5 0 0"
			},
			items: [
				{
					xtype: "button",
					text: "OK",
					minWidth: 75,
					handler: function() {

						var o_values = i_formpanel.getValues();
						Ext.apply(o_loginInfo, o_values);

						Portfolio.login.util.Handler.doDeviceAuth(o_loginInfo, function(o_result) {

							i_controller.onLoginClick();
						});

						i_window.close();
					}
				},
				{
					xtype: "button",
					text: "Cancel",
					minWidth: 75,
					handler: function() {
						i_window.close();
					}
				}
			]
		});

		i_formpanel.addDocked(i_toolbar);

		i_window.add(i_formpanel);

		i_window.show();
	},

	doNormalRender: function(i_login) {

		var i_self = this;
		var i_controller = i_self.getController();

		var i_loginElement = Ext.DomQuery.selectNode("a.button.login") || Ext.DomQuery.selectNode("a.button.login-btn");
		var i_forgotElement = Ext.DomQuery.selectNode("a.button.forgot-password");

		if (i_loginElement) {

			i_loginElement.href = "";

			var i_loginButton = Ext.get(i_loginElement);

			i_loginButton.on({
				click: {
					fn: function(i_event) {

						i_event.stopEvent();
						i_controller.onLoginClick(function(o_result, o_values) {

							if (o_result.msgid == "IP21100") {
								i_self.doMutilFactorAuth(o_result, o_values);
							}
							else {
								i_self.doHandleError(o_result);
							}
						});
					}
				}
			});
		}

		if (i_forgotElement) {

			i_forgotElement.href = "";

			var i_forgotButton = Ext.get(i_forgotElement);

			i_forgotButton.on({
				click: {
					fn: function(i_event) {

						i_event.stopEvent();

						i_controller.onForgotPassword(function (o_result) {

							var i_messageField = Ext.get("message");

							if (i_messageField && o_result.message) {
								i_messageField.el.dom.innerText = Portfolio.util.Handler.i18n(o_result.message);
								i_messageField.addCls("error");
							}
						});
					}
				}
			});
		}
	},

	doLegacyRender: function(i_login) {

		var i_self = this;

		var i_controller = i_self.getController();

		var i_loginElement = Ext.DomQuery.selectNode(".button");
		var i_companyElement = Ext.DomQuery.selectNode(".companyname");

		var i_loginText = Ext.DomQuery.selectNode(".button .text");

		var i_userElement = Ext.get("userid");
		var i_passElement = Ext.get("password");

		i_userElement.el.dom.placeholder = ip2.i18n("userID");
		i_passElement.el.dom.placeholder = ip2.i18n("password");

		i_loginText.innerHTML = ip2.i18n("login");

		i_loginElement.href = "";

		var i_loginButton = Ext.get(i_loginElement);

		i_companyElement.innerHTML = Portfolio.util.Handler.preset.text;

		i_loginButton.on({
			click: {
				fn: function(i_event) {

					i_event.stopEvent();
					i_controller.onLoginClick(function(o_result, o_values) {

						if (o_result.msgid == "IP21100") {
							i_self.doMutilFactorAuth(o_result, o_values);
						}
						else {
							i_self.doHandleError(o_result);
						}
					});
				}
			}
		});
	},

	doHandleError: function(o_result) {

		var i_self = this;

		var i_errorElement = Ext.DomQuery.selectNode(".message");

		if (o_result.msgid == "CPF22E4") {

			var s_password = ip2.i18n({
				da: "Ny Kodeord",
				en: "New Password"
			});

			var s_confirm = ip2.i18n({
				da: "Bekræft kodeord",
				en: "Confirm Password"
			});

			var i_window = Ext.widget("window", {
				title: o_result.text,
				layout: "fit",
				closable: false,
				width: 300,
				modal: true
			});

			var i_passwordfield = Ext.widget("textfield", {
				name: "password",
				itemId: "password",
				allowBlank: false,
				fieldLabel: s_password,
				stripCharsRe : /\s+/g,
				inputType: "password",
				listeners: {
					validitychange: {
						fn: function(i_field) {
							this.next().validate();
						}
					},
					blur: {
						fn: function(i_field) {
							this.next().validate();
						}
					},
					specialkey: {
						fn: function(i_field, i_event) {

							if (i_event.getKey() === i_event.ENTER) {

								Ext.getBody().mask("Please wait...");

								Portfolio.login.util.Handler.onResetPassword(i_field.getValue(), function(o_result) {

									Ext.getBody().unmask();

									i_self.doAfterReset(o_result, i_window, i_errorElement);

								});
							}
						}
					}
				}
			});

			var i_confirmfield = Ext.widget("textfield", {
				name: "confirmpassword",
				fieldLabel: s_confirm,
				stripCharsRe: /\s+/g,
				inputType: "password",
				vtype: "password",
				initialPasswordField: i_passwordfield,
				validateBlank: true,
				listeners: {
					specialkey: {
						fn: function (i_field, i_event) {

							if (i_event.getKey() === i_event.ENTER) {

								Ext.getBody().mask("Please wait...");

								Portfolio.login.util.Handler.onResetPassword(i_field.getValue(), function (o_result) {

									Ext.getBody().unmask();

									i_self.doAfterReset(o_result, i_window, i_errorElement);

								});
							}
						}
					}
				}
			});

			var i_formpanel = Ext.widget("form", {
				layout: "anchor",
				bodyPadding: 10,
				defaults: {
					anchor: "100%",
					labelAlign: "top"
				},
				items: [
					i_passwordfield,
					i_confirmfield
				],
				listeners: {
					afterrender: {
						fn: function (i_panel) {
							i_panel.isValid();
							i_passwordfield.focus(false, 10)
						},
						buffer:10
					}
				}
			});

			var i_toolbar = Ext.widget("toolbar", {
				ui: "footer",
				dock: "bottom",
				items: [
					"->",
					{
						xtype: "button",
						text: "OK",
						minWidth: 75,
						handler: function() {

							var o_values = i_formpanel.getValues();

							Ext.getBody().mask("Please wait...");

							Portfolio.login.util.Handler.onResetPassword(o_values.password, function(o_result) {

								Ext.getBody().unmask();

								i_self.doAfterReset(o_result, i_window, i_errorElement);
							});
						}
					},
					{
						xtype: "button",
						text: "Cancel",
						minWidth: 75,
						handler: function() {
							i_window.close();
						}
					}
				]
			});

			i_formpanel.addDocked(i_toolbar);

			i_window.add(i_formpanel);

			i_window.show();
		}
		else {

			if (i_errorElement) {

				var s_message = o_result.message || o_result.msg || o_result.text;

				if (s_message) {
					i_errorElement.innerHTML = s_message;
				}
				else {
					var s_msgId = o_result.messageId || o_result.msgid;
					i_errorElement.innerHTML = ip2.i18n(s_msgId);
				}
			}
		}
	},

	doResize: function() {

		var i_box = Ext.get("box");

		if (i_box) {
			i_box.center();
		}
	},

	doAfterReset: function(o_result, i_window, i_errorElement) {

		i_errorElement.innerHTML = "";

		if (o_result.success) {
			i_window.close();

			ip2.messageBox({
				title: "Status",
				icon: Ext.Msg.Info,
				message: ip2.i18n({
					da: "Kodeord er blevet ændret",
					en: "Password has been changed."
				}),
				yesText: ip2.i18n({
					"da": "OK",
					"en": "OK"
				})
			});
		}
		else {
			ip2.messageBox({
				title: ip2.i18n({
					da: "Fel ved reset",
					en: "Error on reset"
				}),
				icon: Ext.Msg.WARNING,
				message: o_result.msg,
				yesText: ip2.i18n({
					"da": "OK",
					"en": "OK"
				})
			});
		}
	}
});
