Ext.define("IceCap.view.Main", {

	xtype: "icecap-panel",

	extend: "Ext.panel.Panel",

	layout: "fit",

	ui: "",

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

	requiredScripts: [
		"/icecap/app/theme/default.css",
		"/icecap/app/icecap-overrides.js"
	],

	requires: [
		"IceCap.controller.Main",
		"IceCap.view.Window",
		"IceCap.view.WebContainer",
		"IceCap.util.Handler",
		"IceCap.util.Scale",
		"IceCap.util.Breakout",
		"IceCap.component.Marker",
		"IceCap.ux.form.panel.Panel4Area",
		"IceCap.ux.form.panel.TabPanel",
		"IceCap.ux.grid.editor.Main",
		"IceCap.ux.container.Column",
		"IceCap.ux.form.label.Label",
		"IceCap.ux.form.field.Field",
		"IceCap.ux.form.panel.fusionChart",
		"IceCap.ux.form.field.SimpleComboBox",
		"IceCap.ux.form.field.sqlComboBox",
		"IceCap.ux.form.field.sqlSearchBox",
		"IceCap.ux.form.field.LINKFIELD",
		"IceCap.ux.form.field.AdvancedComboBox",
		"IceCap.ux.form.field.CommandField",
		"IceCap.ux.form.field.LibraryFileDependency",
		"IceCap.ux.form.field.FileLibraryDependency",
		"IceCap.ux.form.field.RadioGroup",
		"IceCap.ux.container.CommandPanel",
		"IceCap.ux.container.GMapPanel"
	],

	config: {
		inputData: null,
		lastTabIndex: 1,
		currentTabIndex: 1,
		content: null,
		keyArea: null,
		working: false,
		needFocus: 1,
		ignoreTitle: false,
		currentPosition: {
			col: 1,
			lin: 1
		},
		activeWindow: null,
		statusBar: null,
		main: null,
		sessionValue: "",
		keyMap: null,
		cursor: null,
		timer: null,
		func: "",
		initFunc: "",
		initCmd: "",
		responseCallBack: Ext.emptyFn,
		requestCallBack: Ext.emptyFn,
		theme: "",
		scale: 14,
		enterOnDblClick: false,
		marker: null,
		markerActive: false,
		options: {},
		messageText: "",
		typeMode: 1
	},

	controller: "icecap.view.main",

	focusable: true,

	listeners: {
		afterrender: {
			fn: "onAfterRender",
			buffer: 100,
			single: true
		},
		activate: {
			fn: "onActivated",
			buffer: 10
		},
		dblclick: {
			fn: "onDblClick",
			element: "body"
		},
		click: {
			fn: "onClick",
			element: "body"
		},
		wheel: {
			fn: "onWheel",
			element: "body"
		},
		destroy: {
			fn: "onDestroy"
		},
		beforedestroy: {
			fn: "onBeforeDestroy"
		},
		applicationClose: {
			fn: "onApplicationClose"
		},
		fieldoption: {
			fn: function(a_config) {

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

				var o_data = {};

				Ext.apply(o_data, {
					key: "ENTER"
				});

				Ext.Array.each(a_config, function(o_config) {

					var s_field = o_config.field;

					o_data[s_field] = o_config.option;

					Ext.apply(o_data, {
						csrCol: o_config.col,
						csrLin: o_config.lin
					});
				});

				i_self.setCurrentPosition({
					col: o_data.csrCol,
					lin: o_data.csrLin
				});

				i_controller.onSendData({
					func: ""
				}, o_data);
			}
		},
		key: {
			fn: function(s_value) {

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

				i_controller.doKeyEvent(s_value);
			}
		}
	},

	initComponent: function() {

		Ext.tip.QuickTipManager.init();

		var i_self = this;

		var o_params = Ext.Object.fromQueryString(window.location.search);

		Ext.Object.each(o_params, function(s_key, value) {
			o_params[s_key] = Ext.decode(value, true) || value;
		});

		var o_options = Ext.apply(i_self.options, o_params.options || {});

		Ext.apply(i_self, o_options);

		i_self.callParent(arguments);

		i_self.setTypeMode(IceCap.util.Handler.typeMode.INSERT);

		i_self.add(i_self.createLayout());

		var o_data = i_self.getInputData();
		var s_sessionValue = i_self.getSessionValue();

		if (o_data) {
			if (o_data.close) {
				i_self.close();
			}
			else {

				IceCap.util.Handler.useScale(i_self.getScale());

				if (s_sessionValue) {

					IceCap.util.Handler.isSessionAlive(s_sessionValue, function(b_alive) {
						if (!b_alive) {
							i_self.setSessionValue(null);
							i_self.setInputData(null);

							i_self.doInit(function(o_data) {
								i_self.cancelTimer();
								i_self.setLoading(false);
								if (o_data.close) {
									i_self.close();
								}
								else {
									i_self.setInputData(o_data);
									i_self.doCreateFromData(o_data);
								}
							});
						}
						else {
							i_self.doCreateFromData(o_data);
						}
					});
				}
			}
		}
		else {
			i_self.doInit(function(o_data) {
				i_self.cancelTimer();
				i_self.setLoading(false);
				if (o_data.close) {
					i_self.close();
				}
				else {
					i_self.setInputData(o_data);
					i_self.doCreateFromData(o_data);
				}
			});
		}

		if (i_self.getTheme()) {
			Ext.Loader.loadScriptsSync([
				"/icecap/app/theme/" + i_self.getTheme() + ".css"
			]);
		}

		i_self.enableBubble("onAddWebContainer");
		i_self.enableBubble("stateupdate");
	},

	doInit: function(f_callback) {

		var i_self = this;

		IceCap.util.Handler.useScale(i_self.getScale());

		if (i_self.getSessionValue()) {

			IceCap.util.Handler.addSession(i_self.getSessionValue());

			IceCap.util.Handler.getData(Ext.apply({
				session: i_self.getSessionValue(),
				func: i_self.getFunc(),
				initFunc: i_self.getInitFunc() || i_self.getInitCmd() || "",
			}, i_self.getOptions()), {}, function(o_data) {
				f_callback(o_data);
			});
		}
		else {

			IceCap.util.Handler.getNewSession(function(o_result) {

				if (o_result.success) {

					i_self.setSessionValue(o_result.session);
					i_self.doTimer();
					IceCap.util.Handler.getData(Ext.apply({
						session: o_result.session,
						func: i_self.getFunc(),
						initFunc: i_self.getInitFunc() || i_self.getInitCmd() || "",
					}, i_self.getOptions()), {}, function(o_data) {
						f_callback(o_data);
					});
				}
				else {
					Ext.Msg.show({
						title: "Error",
						msg: "No session pls! retry to connect",
						buttons: Ext.Msg.OK
					});
				}
			});
		}
	},

	createLayout: function() {

		var i_self = this;

		return i_self.createContent();
	},

	createContent: function() {

		var i_self = this;
		var o_inputData = i_self.getInputData() || {};
		var b_focusable = true;

		var i_panel = Ext.widget("panel", {
			layout: {
				type: "vbox",
				align: "stretch"
			},
			border: false,
			focusable: true,
			tabIndex: -1,
			items: i_self.createItems()
		});

		i_self.setMain(i_panel);

		var i_statusbar = i_self.createStatusBar();

		i_self.addDocked(i_statusbar);

		i_self.setStatusBar(i_statusbar);

		i_self.updateMessage(o_inputData);

		return i_panel;
	},

	createStatusBar: function() {

		var i_statusbar = Ext.widget("toolbar", {
			dock: "bottom",
			cls: "icecap-statusbar",
			height: 30,
			hidden: false,
			items: [
				{
					xtype: "label",
					itemId: "icecap-message"
				},
				"->",
				{
					xtype: "label",
					itemId: "icecap-position"
				},
				{
					xtype: "label",
					text: " INS",
					itemId: "icecap-typemode"
				}
			],
			setText: function(s_text) {

				var i_toolbar = this;

				var i_message = i_toolbar.getComponent("icecap-message");

				if (i_message) {
					i_message.setText(s_text);
				}
			}
		});

		return i_statusbar;
	},

	createItems: function() {

		var i_self = this;

		var a_items = [];

		var i_center = Ext.widget("form", {
			bodyPadding: 5,
			border: false,
			layout: "absolute",
			autoScroll: true,
			focusable: false,
			flex: 1,
			ui: ["icecap", i_self.getTheme()].filter(Boolean).join("-")
		});

		a_items.push(i_center);

		var i_south = Ext.widget("panel", {
			layout: {
				type: "column"
			},
			border: false,
			bodyPadding: 5,
			focusable: false,
			defaults: {
				margin: "0 5 5 0"
			},
			ui: ["icecap", i_self.getTheme()].filter(Boolean).join("-")
		});

		a_items.push(i_south);

		i_self.setContent(i_center);
		i_self.setKeyArea(i_south);

		return a_items;
	},

	splitFields: function() {

		var i_self = this;
		var o_inputData = i_self.getInputData();

		var a_sliced = Ext.Array.from(o_inputData.fields || []);

		var a_outputs = Ext.Array.from(o_inputData.output || []);
		var a_inputs = Ext.Array.from(o_inputData.input || []);

		Ext.Array.each(a_sliced, function(o_config) {
			if (o_config.type == "input" || o_config.type == "grid") {
				a_inputs.push(o_config);
			}
			else if (o_config.type == "output") {
				a_outputs.push(o_config);
			}
		});

		Ext.apply(o_inputData, {
			input: a_inputs,
			output: a_outputs
		});

		if (a_sliced.length > 0) {
			o_inputData.processedFields = true;
		}

		delete o_inputData.fields;

		i_self.setInputData(o_inputData);
	},

	createFields: function() {

		var i_self = this;
		var o_inputData = i_self.getInputData();

		var a_fields = [];

		var n_tabIndex = 1;
		var n_focus = o_inputData.focus;

		var n_inputWidth = o_inputData.width || 80;
		var n_inputHeight = o_inputData.height || 24;

		var b_fixed = IceCap.util.Handler.getFixed();

		var a_sliced = Ext.Array.from(o_inputData.input || []);

		Ext.Array.each(a_sliced, function(o_config, n_index) {

			var n_default = IceCap.util.Handler.getDefaultWidth();
			var n_width = n_default;

			var o_meta = o_config.metaData || {};

			var o_field = {
				inputType: "text",
				xtype: "textfield"
			};

			if (o_config.len > 1) {
				n_width = ((o_config.len - 1) * IceCap.util.Handler.getColSize()) + n_default;
			}

			Ext.apply(o_field, i_self.applyFFW(o_config));

			var s_type = o_field.xtype || "textfield";
			var n_x = IceCap.util.Handler.getX(o_config.col);
			var n_y = IceCap.util.Handler.getY(o_config.lin);
			var b_password = o_config.atr == "27";

			if (o_field.readOnly) {

				o_field.xtype = s_type = "displayfield";

				Ext.apply(o_field.fieldStyle, {
					"font": "normal " + IceCap.util.Handler.getTextSize() + "px / " + IceCap.util.Handler.getColSize() + "px Lucida Console",
					"white-space": "pre",
					"margin-top": IceCap.util.Handler.getMargin() + "px !important",
					"min-height": "0px !important"
				});

				Ext.apply(o_field, {
					style: {
						padding: "1px 0px !important"
					}
				});

				Ext.apply(o_field, {
					fieldCls: ["x-form-display-field iceCap-output-" + (o_config.atr || 20), i_self.getTheme()].filter(Boolean).join("-")
				});
			}

			if (o_config.len > n_inputWidth) {
				var n_temp = n_inputWidth - o_config.col;
				n_width = ((n_temp - 1) * IceCap.util.Handler.getColSize()) + n_default;
			}


			if (o_config.hasOwnProperty("colsize") && o_config.hasOwnProperty("rows")) {

				var s_data = o_config.dta || "";

				o_field.xtype = s_type = "textarea";
				o_field.height = IceCap.util.Handler.getTextSize() * o_config.rows;
				o_field.preventScrollbars = true;

				var a_split = s_data.split("\n");

				var s_result = "";

				var n_split = a_split.length;

				Ext.Array.each(a_split, function(s_part, n_index) {

					var regex = new RegExp(".{" + o_config.colsize + "}", "g");

					var a_match = s_part.match(regex);

					if (a_match) {
						s_result += s_part;
					}
					else {
						if (n_index != n_split - 1) {
							s_result += s_part + "\n";
						}
						else {
							s_result += s_part;
						}
					}
				});

				o_config.dta = s_result;


				o_field.getSubmitValue = function() {

					var i_field = this;

					var s_value = i_field.stripReturns(i_field.getRawValue());

					var regex = new RegExp(".{1,"+ o_config.colsize +"}", "g");

					var a_split = s_value.match(regex) || [];

					return a_split.join("\n");
				};

			}

			var o_listeners = Ext.apply({}, o_meta.listeners);
			delete o_meta.listeners;

			var a_field = ["icecap-field", i_self.getTheme()];

			var a_pass = [b_password ? "iceCap-input-password" : "iceCap-input-" + (o_config.atr || 20)];

			a_pass.push(i_self.getTheme());

			var a_cls = [a_field.filter(Boolean).join("-"), a_pass.filter(Boolean).join("-")];

			var s_cls = a_cls.join(" ");

			if (isNaN(n_x)) {
				n_x = IceCap.util.Handler.getColSize();
			}

			if (isNaN(n_y)) {
				n_y = IceCap.util.Handler.getLineHeight();
			}

			Ext.Object.merge(o_field, {
				width: n_width,
				enforceMaxLength: true,
				maxLength: o_config.len,
				minWidth: IceCap.util.Handler.getDefaultWidth(),
				tabIndex: !o_field.readOnly ? n_tabIndex : -1,
				focusable: !o_field.readOnly,
				lin: o_config.lin,
				col: o_config.col,
				emuId: o_config.id,
				name: o_config.id,
				value: o_config.dta || "",
				itemId: o_config.id,
				inputAttrTpl: "spellcheck=false",
				x: n_x,
				y: n_y,
				cls: s_cls,
				enableKeyEvents: true,
				selectOnFocus: false,
				listeners: {
					afterrender: {
						fn: function(i_field) {

							if (i_field.inputEl && !i_field.metaField) {

								i_field.inputEl.setMinHeight(0);

								if (i_field.xtype == "textfield") {
									i_field.inputEl.setHeight(IceCap.util.Handler.getDefaultHeight());
								}
								if (i_field.xtype == "textarea") {
									i_field.inputEl.dom.setAttribute("rows", o_config.rows);
								}

								i_field.inputEl.set({
									autocomplete: "off"
								});

								if (i_field.getTabIndex() === i_self.getNeedFocus()) {

									i_field.focus(false, 10, function() {
										var o_inputData = i_self.getInputData();

										var s_value = i_field.getValue();
										var n_col = i_field.col;
										var n_diff = 0;

										if (n_col < o_inputData.csrCol) {
											n_diff = o_inputData.csrCol - n_col;
											i_field.inputEl.el.dom.selectionEnd = i_field.inputEl.el.dom.selectionStart = i_field.inputEl.el.dom.selectionStart + n_diff;
										}

										var o_position = {
											col: o_inputData.csrCol,
											lin: o_inputData.csrLin
										}

										i_self.setCurrentPosition(o_position);

										var i_cursor = i_self.getCursor();
										i_cursor.moveCursor(o_position);
										i_cursor.hide();
									});
								}
							}
						}
					},
					change: {
						fn: function(i_field, value) {

							var s_direction = i_field.inputEl.el.dom.selectionDirection;

							var n_curpos = s_direction == "forward" ? i_field.inputEl.el.dom.selectionEnd : i_field.inputEl.el.dom.selectionStart;

							if (value.length == i_field.maxLength && n_curpos == i_field.maxLength) {
								i_self.doNavigationKey(1, true);
							}
						}
					},
					focus: {
						fn: function(i_field) {

							var n_tabIndex = i_field.getTabIndex();
							i_self.setCurrentTabIndex(n_tabIndex);

							var o_position = {
								col: i_field.col,
								lin: i_field.lin
							};
							i_self.setCurrentPosition(o_position);

							var i_cursor = i_self.getCursor();
							i_cursor.moveCursor(o_position);
							i_cursor.hide();
						}
					},
					keyup: {
						fn: function(i_field, i_event) {

							if (i_field.xtype === "textfield") {

								var value = i_field.getValue();

								var s_direction = i_field.inputEl.el.dom.selectionDirection;

								var n_start = s_direction == "forward" ? i_field.inputEl.el.dom.selectionEnd : i_field.inputEl.el.dom.selectionStart;
								var n_add = value.length * IceCap.util.Handler.getColSize();

								if (n_start != value.length) {
									n_add = n_start * IceCap.util.Handler.getColSize();
								}

								var o_input = Ext.apply({
									x: i_field.getLocalX() + n_add,
									y: i_field.getLocalY()
								});

								var o_position = IceCap.util.Handler.toColAndLine(o_input);
								i_self.setCurrentPosition(o_position);

								var i_cursor = i_self.getCursor();
								i_cursor.moveCursor(o_position);
							}
						}
					},
					keydown: {
						fn: function(i_field, i_event) {

							var i_regext = new RegExp("^\\w{1}$");

							var value = i_field.getValue();

							if (i_event.ctrlKey) {

								if (i_event.keyCode == Ext.event.Event.DOWN ||
									i_event.keyCode == Ext.event.Event.UP) {

									i_event.stopEvent();

									var i_main = i_self.getMain();

									var n_y = IceCap.util.Handler.getLineHeight();

									if (i_event.keyCode == Ext.event.Event.UP) {
										n_y = -IceCap.util.Handler.getLineHeight();
									}

									var o_input = Ext.apply({
										x: i_field.getLocalX(),
										y: i_field.getLocalY() + n_y
									});

									var o_position = IceCap.util.Handler.toColAndLine(o_input);
									i_self.setCurrentPosition(o_position);

									var i_cursor = i_self.getCursor();
									i_cursor.moveCursor(o_position);

									var a_inputs = i_self.query("field[focusable]");

									var o_box = Ext.apply({
										width: IceCap.util.Handler.getColSize(),
										height: 1
									}, o_input);

									var b_intersect = false;

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

										var o_bound = i_field.el.dom.getBoundingClientRect();

										var o_rect = Ext.apply({}, {
											x: i_field.getLocalX(),
											y: i_field.getLocalY(),
											width: o_bound.width,
											height: o_bound.height
										});

										if (!Ext.draw.Draw.isBBoxIntersect(o_box, o_rect)) {
											b_intersect = true;
											i_field.focus(false, 10);
											return false;
										}
									});

									if (!b_intersect) {

										i_field.blur();
										i_cursor.show();

										i_main.focus(true, 10);
									}
								}
								if (i_event.keyCode == Ext.event.Event.LEFT ||
									i_event.keyCode == Ext.event.Event.RIGHT) {

									var i_inputEl = i_field.inputEl;
									var n_selection = i_event.keyCode == Ext.event.Event.LEFT ? i_inputEl.dom.selectionStart : i_inputEl.dom.selectionEnd;

									i_event.stopEvent();

									if (n_selection === 0 && i_event.keyCode === Ext.event.Event.LEFT) {

										var i_main = i_self.getMain();

										var n_x = IceCap.util.Handler.getLineHeight();

										var o_input = Ext.apply({
											x: i_field.getLocalX() - n_x,
											y: i_field.getLocalY()
										});

										var o_position = IceCap.util.Handler.toColAndLine(o_input);
										i_self.setCurrentPosition(o_position);

										var i_cursor = i_self.getCursor();
										i_cursor.moveCursor(o_position);

										var a_inputs = i_self.query("field[focusable]");

										var o_box = Ext.apply({
											width: IceCap.util.Handler.getColSize(),
											height: 1
										}, o_input);

										var b_intersect = false;

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

											var o_bound = i_field.el.dom.getBoundingClientRect();

											var o_rect = Ext.apply({}, {
												x: i_field.getLocalX(),
												y: i_field.getLocalY(),
												width: o_bound.width,
												height: o_bound.height
											});

											if (!Ext.draw.Draw.isBBoxIntersect(o_box, o_rect)) {
												b_intersect = true;
												i_field.focus(false, 10);
												return false;
											}
										});

										if (!b_intersect) {

											i_field.blur();
											i_cursor.show();

											i_main.focus(true, 10);
										}
									}
									else if (n_selection == value.length && i_event.keyCode == Ext.event.Event.RIGHT) {

										var i_main = i_self.getMain();

										var n_x = IceCap.util.Handler.getColSize();

										n_x = n_x * (i_field.maxLength + 2);

										var o_input = Ext.apply({
											x: i_field.getLocalX() + n_x,
											y: i_field.getLocalY()
										});

										var o_position = IceCap.util.Handler.toColAndLine(o_input);
										i_self.setCurrentPosition(o_position);

										var i_cursor = i_self.getCursor();
										i_cursor.moveCursor(o_position);

										var a_inputs = i_self.query("field[focusable]");

										var o_box = Ext.apply({
											width: IceCap.util.Handler.getColSize(),
											height: 1
										}, o_input);

										var b_intersect = false;

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

											var o_bound = i_field.el.dom.getBoundingClientRect();

											var o_rect = Ext.apply({}, {
												x: i_field.getLocalX(),
												y: i_field.getLocalY(),
												width: o_bound.width,
												height: o_bound.height
											});

											if (!Ext.draw.Draw.isBBoxIntersect(o_box, o_rect)) {
												b_intersect = true;
												i_field.focus(false, 10);
												return false;
											}
										});

										if (!b_intersect) {

											i_field.blur();
											i_cursor.show();

											i_main.focus(true, 10);
										}
									}
								}
							}
							else {

								if (i_field.xtype == "textarea") {

									if (i_event.keyCode == Ext.event.Event.UP) {

										var s_value = i_field.stripReturns(i_field.getRawValue());

										var regex = new RegExp("^.*\n$|.{1," + o_config.colsize + "}", "gm");

										var a_lines = s_value.match(regex) || [];
										var a_newLines = s_value.split("\n");

										var n_start = i_field.inputEl.dom.selectionStart;

										var n_row = 1;
										var n_char = 0;
										var b_last = i_field.inputEl.dom.selectionStart == i_field.inputEl.dom.value.length;

										Ext.Array.each(a_lines, function (s_part, n_index) {

											n_char += s_part.length;

											if (n_char <= n_start) {
												n_row++;
											}
											else {
												return false;
											}
										});

										if (n_row > 1) {

											i_event.stopEvent();

											n_char = 0;
											var n_left = 0;
											var n_current = 0;
											var n_nextLine = 0;

											n_start = n_start - (a_newLines.length - 1);

											Ext.Array.each(a_lines, function (s_part, n_index) {

												n_char += s_part.length;

												var n_count = 0;

												n_left = 0;

												while (n_count < s_part.length) {
													n_count++;
													if (n_current < n_start) {
														n_current++;
														n_left++;
													}
												}

												if (n_char < n_start) {
													n_row++;
												}
												else {
													n_nextLine = n_index - 1;
													return false;
												}
											});

											if (n_nextLine == -1) {
												n_nextLine = 0;
											}

											var n_newPos = 0;

											Ext.Array.each(a_lines, function (s_part, n_index) {

												if (n_index < n_nextLine) {
													n_newPos += s_part.length;
												}
												else {
													n_newPos += n_left;
													return false;
												}
											});

											i_event.stopEvent();
											i_field.inputEl.dom.setSelectionRange(n_newPos, n_newPos);
										}
									}

									if (i_event.keyCode == Ext.event.Event.DOWN) {

										var s_value = i_field.stripReturns(i_field.getRawValue());
										var n_length = s_value.length;

										var regex = new RegExp("^.*\n$|.{1," + o_config.colsize + "}", "g");
										var n_pos = i_field.inputEl.dom.selectionStart;

										var a_lines = s_value.match(regex) || [];
										var a_newLines = s_value.split("\n");

										if (a_lines.length < o_config.rows && a_newLines.length < o_config.rows) {

											i_event.stopEvent();

											s_value = s_value + "\n";

											i_field.setValue(s_value);

											i_field.inputEl.dom.setSelectionRange(s_value.length, s_value.length);
										}
										else {
											var n_row = 1;
											var n_char = 0;
											var n_left = 0;
											var n_current = 0;
											var n_nextLine = 0;

											Ext.Array.each(a_lines, function (s_part, n_index) {

												n_char += s_part.length;

												var n_count = 0;

												n_left = 0;

												while(n_count < s_part.length) {
													n_count++;
													if (n_current < n_pos) {
														n_current++;
														n_left++;
													}
												}

												if (n_char <= n_pos) {
													n_row++;
												}
												else {
													n_nextLine = n_index + 1;
													return false;
												}
											});

											if (n_nextLine < a_lines.length || n_nextLine < a_newLines.length) {

												var n_newPos = 0;

												Ext.Array.each(a_lines, function(s_part, n_index) {

													if (n_index < n_nextLine) {
														n_newPos += s_part.length;
													}
													else {
														n_newPos += n_left + (a_newLines.length - 1);
														return false;
													}
												});

												if (n_row < o_config.rows) {
													i_event.stopEvent();
													i_field.inputEl.dom.setSelectionRange(n_newPos, n_newPos);
												}
											}
										}

									}
								}
								else if (i_field.xtype == "textfield") {

									var n_typeMode = i_self.getTypeMode();

									if (n_typeMode == IceCap.util.Handler.typeMode.OVERWRITE) {

										var s_direction = i_field.inputEl.el.dom.selectionDirection;

										var n_curpos = s_direction == "forward" ? i_field.inputEl.el.dom.selectionEnd : i_field.inputEl.el.dom.selectionStart;

										var s_key = String.fromCharCode(i_event.keyCode);

										if (n_curpos < value.length && i_regext.test(s_key)) {

											var a_values = value.split("");
											a_values[n_curpos] = i_event.browserEvent.key;
											value = a_values.join("");
											i_field.setValue(value);
											i_field.inputEl.el.dom.selectionEnd = i_field.inputEl.el.dom.selectionStart = n_curpos + 1;
											i_event.stopEvent();
										}
									}
								}
							}
						}
					}
				}
			}, o_meta);

			var o_clone = Ext.clone(o_field);

			if (o_meta.xtype) {

				o_clone.metaField = true;

				o_clone.xtype = s_type = o_meta.xtype;

				delete o_clone.cls;
				delete o_clone.fieldStyle;
				delete o_clone.inputType;
			}

			if (o_config.type == "grid") {

				Ext.apply(o_clone, {
					xtype: s_type = "iceCapGrid",
					gridConfig: o_config.grid,
					width: IceCap.util.Handler.getColSize() * n_inputWidth
				});

				delete o_clone.cls;
				delete o_clone.fieldStyle;
				delete o_clone.inputType;
				delete o_clone.listeners;
				delete o_clone.grid;

				Ext.apply(o_clone, {
					listeners: {
						fieldoption: {
							fn: function(a_config) {
								i_self.fireEvent("fieldoption", a_config);
							}
						},
						key: {
							fn: function(s_key) {
								i_self.fireEvent("key", s_key);
							}
						}
					}
				});
			}

			var i_field = Ext.widget(s_type, o_clone);

			var o_on = {};

			Ext.Object.each(o_listeners, function(s_key, value) {

				if (Ext.isFunction(value)) {
					o_on[s_key] = Ext.apply({}, {
						fn: value,
						scope: i_self
					});
				}
				else if (Ext.isObject(value)) {
					value.scope = i_self;
					o_on[s_key] = value;
				}
			});

			i_field.on(o_on);

			if (!i_field.readOnly) {
				n_tabIndex++;
			}

			if (o_config.atr == 25) {

				if (o_field.readOnly) {
					i_field.addCls("icecap-invalid");
				}
				else {
					i_field.markInvalid(true);
				}
			}

			a_fields.push(i_field);
		});

		n_tabIndex = n_tabIndex - 1;
		i_self.setLastTabIndex(n_tabIndex);
		i_self.setCurrentTabIndex(o_inputData.focus);

		i_self.setNeedFocus(n_focus);

		return a_fields;
	},

	createLabels: function() {

		var i_self = this;
		var o_inputData = i_self.getInputData();
		var b_fixed = IceCap.util.Handler.getFixed();

		var a_fields = [];

		Ext.Array.each(o_inputData.output, function(o_config) {

			var s_value = o_config.dta || o_config.label || o_config.text;

			if (s_value) {
				if (o_config.ta == "right" && !o_config.off) {
					//o_config.col += o_config.len - o_config.dta.length;
				}

				if (o_config.off) {
					s_value = Ext.String.leftPad(s_value, s_value.length + o_config.off);
				}

				var n_x = Math.ceil((IceCap.util.Handler.getX(o_config.col) + (IceCap.util.Handler.getColSize() / 2)));
				var n_y = IceCap.util.Handler.getY(o_config.lin);

				if (isNaN(n_x)) {
					n_x = IceCap.util.Handler.getColSize();
				}

				if (isNaN(n_y)) {
					n_y = IceCap.util.Handler.getLineHeight();
				}

				var o_field = {
					value: s_value,
					htmlEncode: true,
					x: n_x - 1,
					y: n_y,
					cls: ["icecap-field", i_self.getTheme()].filter(Boolean).join("-")
				};

				var o_style = {
					"font": "normal " + IceCap.util.Handler.getTextSize() + "px Segoe UI,Segoe,DejaVu Sans,Trebuchet MS,Verdana,sans-serif",
					"margin-top": IceCap.util.Handler.getMargin() + "px !important",
					"min-height": "0px !important"
				};

				if (b_fixed) {

					Ext.apply(o_field, {
						fieldCls: ["x-form-display-field iceCap-output-" + (o_config.atr || 20), i_self.getTheme()].filter(Boolean).join("-")
					});

					Ext.apply(o_style, {
						"font": "normal " + IceCap.util.Handler.getTextSize() + "px / " + IceCap.util.Handler.getColSize() + "px Lucida Console",
						"white-space": "pre",
						"margin-top": IceCap.util.Handler.getMargin() + "px !important",
						"min-height": "0px !important"
					});
				}

				Ext.apply(o_field, {
					fieldStyle: o_style
				});

				if (o_config.atr == "27") {
					o_field.hidden = true;
				}

				var i_field = Ext.widget("displayfield", o_field);

				if (o_config.atr == 23) {

					//i_field.addCls("icecap-invalid");
				}

				a_fields.push(i_field);
			}
		});

		return a_fields;
	},

	createMetaFields: function() {

		var i_self = this;
		var o_inputData = i_self.getInputData();

		var a_fields = [];
		var n_tabIndex = i_self.getLastTabIndex() || 0;

		var a_sliced = Ext.Array.slice(o_inputData.metaFields || []);

		var n_inputHeight = o_inputData.height || 24;

		var n_inputWidth = o_inputData.width || 80;

		Ext.Array.each(a_sliced, function(o_config) {

			var n_x = o_config.x;
			var n_y = o_config.y;

			if (!o_config.x) {
				n_x = Math.ceil((IceCap.util.Handler.getX(o_config.col) + (IceCap.util.Handler.getColSize() / 2)));
			}

			if (!o_config.y) {
				n_y = IceCap.util.Handler.getY(o_config.lin);
			}

			if (isNaN(n_x)) {
				n_x = IceCap.util.Handler.getColSize();
			}

			if (isNaN(n_y)) {
				n_y = IceCap.util.Handler.getLineHeight();
			}

			var o_listeners = o_config.listeners || {};

			Ext.apply(o_config, {
				tabIndex: n_tabIndex + 1,
				keys: Ext.Array.slice(o_inputData.keys),
				theme: i_self.getTheme(),
				x: n_x,
				y: n_y,
				listeners: {
					fieldoption: {
						fn: function(a_config) {
							i_self.fireEvent("fieldoption", a_config);
						}
					},
					key: {
						fn: function(s_key) {
							i_self.fireEvent("key", s_key);
						}
					}
				}
			});

			o_config.xtype = o_config.xtype || o_config.type || "textfield";

			o_config.name = o_config.id;

			delete o_config.id;

			var i_field = Ext.widget(o_config.xtype, o_config);

			var o_on = {};

			if (!Ext.Object.isEmpty(o_listeners)) {

				Ext.Object.each(o_listeners, function(s_key, value) {

					if (Ext.isFunction(value)) {
						o_on[s_key] = Ext.apply({}, {
							fn: value,
							scope: i_self
						});
					}
					else if (Ext.isObject(value)) {
						value.scope = i_self;
						o_on[s_key] = value;
					}
				});
			}

			i_field.on(o_on);

			a_fields.push(i_field);

			n_tabIndex++;
		});

		i_self.setLastTabIndex(n_tabIndex);

		return a_fields;
	},

	createKeys: function() {

		var i_self = this;
		var o_inputData = i_self.getInputData();
		var a_disabledKey = o_inputData.disabledKeys || [];
		var a_buttons = [];

		var i_template = Ext.create("Ext.XTemplate",
			"{id}={text}"
		);

		Ext.Array.each(o_inputData.keys, function(o_config) {

			var s_template = i_template.apply(o_config);

			var o_found = Ext.Array.findBy(a_disabledKey, function(o_disabled) {
				return o_config.id == o_disabled.id;
			});

			o_found = o_found || {
				showKey: 1
			};

			var b_hidden = Number(o_found.showKey) < 1  || false;

			var i_button = Ext.widget("button", {
				text: s_template,
				key: o_config.id,
				focusable: false,
				cls: "icecap-key",
				hidden: b_hidden,
				handler: function(i_button) {
					i_self.doKeyEvent(i_button.key);
				}
			});

			a_buttons.push(i_button);
		});

		return a_buttons;
	},

	doCreateFromData: function(o_inputData) {

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

		i_self.setInputData(o_inputData);
		i_self.splitFields();

		var b_fixed = o_inputData.hasOwnProperty("fixed") ? o_inputData.fixed : true;

		IceCap.util.Handler.setFixed(b_fixed);

		i_self.suspendLayouts();

		if (o_inputData.window && o_inputData.window.level > 0) {
			if (i_self.rendered) {
				i_self.mask(false);
				i_self.createWindow(o_inputData);
			}
		}
		else {

			if (i_self.rendered) {
				i_self.unmask();
			}

			if (o_inputData.title) {
				i_self.doTitleUpdate(o_inputData.title);
			}

			var i_content = i_self.getContent();

			var i_keyArea = i_self.getKeyArea();
			var i_main = i_self.getMain();

			if (i_content.rendered) {
				i_content.removeAll(true);
			}

			if (i_keyArea.rendered) {
				i_keyArea.removeAll(true);
			}

			var a_inputs = o_inputData.input || [];
			var n_tabIndex = a_inputs.length > 0 ? 0 : 1;

			var b_focusable = n_tabIndex > 0;

			i_content.focusable = b_focusable;
			i_content.setTabIndex(n_tabIndex);

			i_self.setCursor(null);

			var a_created = i_self.createFields();
			a_created = a_created.concat(i_self.createLabels());
			a_created = a_created.concat(i_self.createMetaFields());

			a_created.push(i_self.createCursor());
			a_created.push(i_self.createMarker());

			if (o_inputData.processedFields) {

				var a_toAdd = Ext.Array.slice(a_created);

				var n_inputWidth = o_inputData.width || 80;
				var n_inputHeight = o_inputData.height || 24;

				var i_container = Ext.widget("container", {
					layout: "anchor",
					width: n_inputWidth * IceCap.util.Handler.getColSize(),
					height: n_inputHeight * IceCap.util.Handler.getLineHeight(),
					focusable: false,
					tabIndex: -1,
					defaults: {
						margin: "5 0 0 0"
					},
					items: a_toAdd
				});

				a_created = [i_container];
			}

			i_content.add(a_created);

			var a_fields = i_content.query("field[focusable]");
			var a_grids = i_content.query("gridpanel");

			var b_found = false;
			var b_error = false;

			if (o_inputData.msgBox && o_inputData.msgBox.text) {
				b_error = true;
				i_self.onError(o_inputData);
			}

			if (a_fields.length > 0) {
				b_found = Ext.Array.findBy(a_fields, function(i_field) {
					return i_field.getTabIndex() === i_self.getNeedFocus();
				});

				if (!b_found) {
					b_found = true;
					var i_field = a_fields[0];
					if (!b_error) {
						setTimeout(function() {
							i_field.focus(false, 10);
						}, 10);
					}
				}
			}

			if (!b_found) {

				i_self.setCurrentPosition({
					col: o_inputData.csrCol || 1,
					lin: o_inputData.csrLin || 1
				});

				if (!b_error) {

					if (a_grids.length == 0) {
						i_content.focusable = true;
						setTimeout(function() {
							i_content.focus(true, 10);
						}, 10);
					}
				}
			}

			i_self.updateMessage(o_inputData);

			var a_keys = i_self.createKeys();
			i_keyArea.add(a_keys);

			i_keyArea[a_keys.length === 0 ? "hide" : "show"]();

			if (o_inputData.cmd) {

				i_controller.onPCO(o_inputData);
				i_controller.doKeyEvent("ENTER");
			}

			var i_marker = i_self.getMarker();
			i_marker.setInUse(i_self.getMarkerActive());
		}
		IceCap.util.Handler.setFixed(true);

		i_self.resumeLayouts(true);

		var a_metafields = o_inputData.metaFields || [];

		if (
			o_inputData.input.length === 0 &&
			o_inputData.input.length === 0 &&
			a_metafields.length === 0 && o_inputData.messageText) {

				var s_message = o_inputData.messageText;

				i_self.setMessageText(s_message);

				i_self.setLoading(s_message);
				i_controller.onSendData({
					func: ""
				}, {});
			}
	},

	createWindow: function(o_inputData) {

		var i_self = this;
		var o_config = o_inputData.window;
		var i_active = i_self.getActiveWindow();
		var a_keys = o_inputData.keys || [];

		var i_content = i_self.getContent();

		var o_size = {
			width: (o_config.width * (IceCap.util.Handler.getColSize() + 1)),
			height: (o_config.height * IceCap.util.Handler.getLineHeight()) + (a_keys.length > 0 ? 105 : 70)
		};

		if (i_active) {

			i_active.setTitle(o_config.title);

			i_active.getContent().setSize(o_size);

			i_active.setInputData(o_inputData);

			i_active.recreate();
		}
		else {

			i_active = Ext.create("IceCap.view.Window", {
				title: o_config.title,
				inputData: o_inputData,
				sessionValue: i_self.getSessionValue(),
				modal: false,
				onEsc: Ext.emptyFn,
				theme: i_self.getTheme(),
				markerActive: i_self.getMarkerActive(),
				options: i_self.getOptions(),
				listeners: {
					destroy: {
						fn: function(i_window) {
							i_self.setActiveWindow(null);
						}
					},
					toWindow: {
						fn: function(i_window, o_inputData) {
							if (!o_inputData.close) {
								i_self.doCreateFromData(o_inputData);
								if (o_inputData.window && !o_inputData.window.level) {
									i_window.close();
								}
							}
							else {
								i_window.close();
								i_self.close();
							}
						}
					}
				}
			});

			i_content.add(i_active);

			i_active.getContent().setSize(o_size);

			i_active.show();
		}

		i_self.setActiveWindow(i_active);

		var i_query = Ext.get(i_self.getMaskTarget().query(".x-mask"));

		Ext.Array.each(i_query.elements, function(i_mask) {
			Ext.get(i_mask).setStyle("opacity", 0);
		});
	},

	getCurrentField: function() {

		var i_self = this;

		var a_fields = i_self.query("field[focusable]");
		var n_tabIndex = i_self.getCurrentTabIndex();
		var i_controller = i_self.getController();

		var i_content = i_self.getContent();
		var i_form = i_content.getForm();
		var o_values = i_form.getFieldValues(true);

		var i_currentField;

		Ext.Array.each(a_fields, function(i_field) {
			if (i_field.getTabIndex() === n_tabIndex && i_field.hasFocus) {
				i_currentField = i_field;
				return false;
			}
		});

		return i_currentField;
	},

	doKeyEvent: function(s_value) {

		var i_self = this;

		var i_controller = i_self.getController();

		var o_inputData = i_self.getInputData() || {};

		var a_disabledKeys = Ext.Array.from(o_inputData.disabledKeys || []);

		var o_found = Ext.Array.findBy(a_disabledKeys, function(o_key) {
			return s_value == o_key.id;
		});

		if (!o_found)  {
			i_controller.doKeyEvent(s_value);
		}
		else {

			Ext.Msg.show({
				title: "Error",
				msg: "Funktionstasten er ikke tilladt",
				icon: Ext.MessageBox.INFO,
				buttons: Ext.MessageBox.OK,
				fn: function () {
					i_self.findFocus();
				}
			});
		}
	},

	doNavigationKey: function(n_direction, b_tab) {

		var i_self = this;
		var i_controller = i_self.getController();
		i_controller[b_tab ? "doTabKey" : "doArrowKeys"](n_direction);
	},

	addKeyEvents: function() {

		var i_self = this;

		var a_bindings = [
			{
				key: Ext.event.Event.PAGE_DOWN,
				fn: function(n_key, i_event) {

					var i_key = this;
					var i_self = i_key.target.component;
					i_self.doKeyEvent("ROLLUP");
				}
			},
			{
				key: Ext.event.Event.PAGE_UP,
				fn: function(n_key, i_event) {

					var i_key = this;
					var i_self = i_key.target.component;
					i_self.doKeyEvent("ROLLDOWN");
				}
			},
			{
				key: Ext.event.Event.ENTER,
				fn: function(n_key, i_event) {

					var i_key = this;
					var i_self = i_key.target.component;
					i_self.doKeyEvent("ENTER");
				}
			},
			{
				key: Ext.event.Event.ESC,
				fn: function(n_key, i_event) {

					var i_key = this;
					var i_self = i_key.target.component;
					i_self.doKeyEvent("ATTN");
				}
			},
			{
				key: Ext.event.Event.UP,
				fn: function(n_key, i_event) {

					var i_key = this;
					var i_self = i_key.target.component;

					if (!i_event.target.type) {

						i_event.stopEvent();

						var i_cursor = i_self.getCursor();
						var o_position = i_self.getCurrentPosition();

						var a_inputs = i_self.query("field[focusable]");

						o_position.lin = o_position.lin - 1;

						if (o_position.lin < 1) {
							o_position.lin = 1;
						}

						var o_box = Ext.apply({
							x: IceCap.util.Handler.getX(o_position.col + 1),
							y: IceCap.util.Handler.getY(o_position.lin),
							width: IceCap.util.Handler.getColSize(),
							height: 1
						});

						var b_intersect = false;

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

							var o_bound = i_field.el.dom.getBoundingClientRect();

							var o_rect = Ext.apply({}, {
								x: i_field.getLocalX(),
								y: i_field.getLocalY(),
								width: o_bound.width,
								height: o_bound.height
							});

							if (!Ext.draw.Draw.isBBoxIntersect(o_box, o_rect)) {
								b_intersect = true;
								i_field.focus(false, 10);
								return false;
							}
						});

						if (!b_intersect) {
							i_cursor.moveCursor(o_position);
						}
						i_self.setCurrentPosition(o_position);
					}
					else {
						i_self.doNavigationKey(0);
					}
				}
			},
			{
				key: Ext.event.Event.DOWN,
				fn: function(n_key, i_event) {

					var i_key = this;
					var i_self = i_key.target.component;

					if (!i_event.target.type) {

						i_event.stopEvent();

						var i_cursor = i_self.getCursor();
						var o_position = i_self.getCurrentPosition();
						var o_inputData = i_self.getInputData();

						var a_inputs = i_self.query("field[focusable]");

						o_position.lin = o_position.lin + 1;

						if (o_position.lin > o_inputData.height) {
							o_position.lin = o_inputData.height;
						}

						var o_box = Ext.apply({
							x: IceCap.util.Handler.getX(o_position.col + 1),
							y: IceCap.util.Handler.getY(o_position.lin),
							width: IceCap.util.Handler.getColSize(),
							height: 1
						});

						var b_intersect = false;

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

							var o_bound = i_field.el.dom.getBoundingClientRect();

							var o_rect = Ext.apply({}, {
								x: i_field.getLocalX(),
								y: i_field.getLocalY(),
								width: o_bound.width,
								height: o_bound.height
							});

							if (!Ext.draw.Draw.isBBoxIntersect(o_box, o_rect)) {
								b_intersect = true;
								i_field.focus(false, 10);
								return false;
							}
						});

						if (!b_intersect) {
							i_cursor.moveCursor(o_position);
						}
						i_self.setCurrentPosition(o_position);
					}
					else {
						i_self.doNavigationKey(1);
					}
				}
			},
			{
				key: Ext.event.Event.LEFT,
				fn: function(n_key, i_event) {

					var i_key = this;
					var i_self = i_key.target.component;

					if (!i_event.target.type) {
						i_event.stopEvent();

						var i_cursor = i_self.getCursor();
						var o_position = i_self.getCurrentPosition();

						var a_inputs = i_self.query("field[focusable]");

						o_position.col = o_position.col - 1;

						if (o_position.col < 1) {
							o_position.col = 1;
						}

						var o_box = Ext.apply({
							x: IceCap.util.Handler.getX(o_position.col),
							y: IceCap.util.Handler.getY(o_position.lin),
							width: IceCap.util.Handler.getColSize(),
							height: 1
						});

						var b_intersect = false;

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

							var o_bound = i_field.el.dom.getBoundingClientRect();

							var o_rect = Ext.apply({}, {
								x: i_field.getLocalX(),
								y: i_field.getLocalY(),
								width: o_bound.width,
								height: o_bound.height
							});

							if (!Ext.draw.Draw.isBBoxIntersect(o_box, o_rect)) {
								b_intersect = true;
								i_field.focus(false, 10);
								return false;
							}
						});

						if (!b_intersect) {
							i_cursor.moveCursor(o_position);
						}

						i_self.setCurrentPosition(o_position);
					}
				}
			},
			{
				key: Ext.event.Event.RIGHT,
				fn: function(n_key, i_event) {

					var i_key = this;
					var i_self = i_key.target.component;

					if (!i_event.target.type) {

						i_event.stopEvent();

						var i_cursor = i_self.getCursor();
						var o_position = i_self.getCurrentPosition();
						var o_inputData = i_self.getInputData();

						var a_inputs = i_self.query("field[focusable]");

						o_position.col = o_position.col + 1;

						if (o_position.col > o_inputData.width) {
							o_position.col = o_inputData.width;
						}

						var o_box = Ext.apply({
							x: IceCap.util.Handler.getX(o_position.col + 1),
							y: IceCap.util.Handler.getY(o_position.lin),
							width: IceCap.util.Handler.getColSize(),
							height: 1
						});

						var b_intersect = false;

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

							var o_bound = i_field.el.dom.getBoundingClientRect();

							var o_rect = Ext.apply({}, {
								x: i_field.getLocalX(),
								y: i_field.getLocalY(),
								width: o_bound.width,
								height: o_bound.height
							});

							if (!Ext.draw.Draw.isBBoxIntersect(o_box, o_rect)) {
								b_intersect = true;
								i_field.focus(false, 10);
								return false;
							}
						});

						if (!b_intersect) {
							i_cursor.moveCursor(o_position);
						}

						i_self.setCurrentPosition(o_position);
					}
				}
			},
			{
				key: Ext.event.Event.TAB,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_event.stopPropagation();

					var i_key = this;
					var i_self = i_key.target.component;
					i_self.doNavigationKey(1, true);
				}
			},
			{
				key: Ext.event.Event.TAB,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_event.stopPropagation();

					var i_key = this;
					var i_self = i_key.target.component;
					i_self.doNavigationKey(0, true);
				}
			},
			{
				key: Ext.event.Event.NUM_PLUS,
				fn: function(n_key, i_event) {

					i_event.stopEvent();

					var i_key = this;
					var i_self = i_key.target.component;

					var i_field = i_self.getCurrentField();

					if (i_field) {

						var n_start = i_field.inputEl.el.dom.selectionStart;

						var s_text = i_field.getValue();

						s_text = s_text.substr(0, n_start);

						i_field.setValue(s_text);

						i_self.doNavigationKey(1, true);
					}
				}
			},
			{
				key: Ext.event.Event.HOME,
				ctrl: true,
				alt: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();

					var i_key = this;
					var i_self = i_key.target.component;

					var b_markerActive = i_self.getMarkerActive();
					var i_marker = i_self.getMarker();

					i_self.setMarkerActive(!b_markerActive);

					i_marker.toggle();
				}
			},
			{
				key: Ext.event.Event.INSERT,
				ctrl: false,
				alt: false,
				fn: function (n_key, i_event) {

					var n_type = i_self.getTypeMode();
					switch (n_type) {
						case IceCap.util.Handler.typeMode.OVERWRITE:
							n_type = IceCap.util.Handler.typeMode.INSERT;
							break;
						default:
							n_type = IceCap.util.Handler.typeMode.OVERWRITE;
							break;
					}

					i_self.setTypeMode(n_type);
				}
			}
		];

		a_bindings = a_bindings.concat(i_self.getFKeys());

		var i_keyMap = Ext.create("Ext.util.KeyMap", {
			target: i_self.getEl(),
			binding: a_bindings
		});
	},

	getFKeys: function() {

		var i_self = this;

		var a_keys = [
			{
				key: Ext.event.Event.F1,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F1");
				}
			},
			{
				key: Ext.event.Event.F2,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F2");
				}
			},
			{
				key: Ext.event.Event.F3,
				shift: false,
				alt: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F3");
				}
			},
			{
				key: Ext.event.Event.F4,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F4");
				}
			},
			{
				key: Ext.event.Event.F5,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F5");
				}
			},
			{
				key: Ext.event.Event.F6,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F6");
				}
			},
			{
				key: Ext.event.Event.F7,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F7");
				}
			},
			{
				key: Ext.event.Event.F8,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F8");
				}
			},
			{
				key: Ext.event.Event.F9,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F9");
				}
			},
			{
				key: Ext.event.Event.F10,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F10");
				}
			},
			{
				key: Ext.event.Event.F11,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F11");
				}
			},
			{
				key: Ext.event.Event.F12,
				shift: false,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F12");
				}
			}
		];

		a_keys = a_keys.concat(i_self.getFShiftKeys());

		return a_keys;
	},

	getFShiftKeys: function() {

		var i_self = this;

		var a_keys = [
			{
				key: Ext.event.Event.F1,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F13");
				}
			},
			{
				key: Ext.event.Event.F2,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F14");
				}
			},
			{
				key: Ext.event.Event.F3,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F15");
				}
			},
			{
				key: Ext.event.Event.F4,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F16");
				}
			},
			{
				key: Ext.event.Event.F5,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F17");
				}
			},
			{
				key: Ext.event.Event.F6,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F18");
				}
			},
			{
				key: Ext.event.Event.F7,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F19");
				}
			},
			{
				key: Ext.event.Event.F8,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F20");
				}
			},
			{
				key: Ext.event.Event.F9,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F21");
				}
			},
			{
				key: Ext.event.Event.F10,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F22");
				}
			},
			{
				key: Ext.event.Event.F11,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F23");
				}
			},
			{
				key: Ext.event.Event.F12,
				shift: true,
				fn: function(n_key, i_event) {

					i_event.stopEvent();
					i_self.doKeyEvent("F24");
				}
			}
		];

		return a_keys;
	},

	createCursor: function() {

		var i_self = this;
		var o_inputData = i_self.getInputData();

		var i_cursor = Ext.widget("component", {
			cls: ["iceCap-cursor", i_self.getTheme()].filter(Boolean).join("-"),
			autoEl: {
				tag: "div",
				style: {
					"border": "1px solid red;",
					"position": "absolute !important;",
					"width": (IceCap.util.Handler.getColSize() + 0.3) + "px !important;"
				}
			},
			listeners: {
				hide: {
					fn: function(i_cursor) {

						var i_marker = i_self.getMarker();
						//i_marker.hide();
					}
				},
				show: {
					fn: function(i_cursor) {

						var i_marker = i_self.getMarker();
						var b_active = i_marker.getInUse();

						if (b_active) {
							i_marker.show();
						}
					}
				},
				render: {
					fn: function(i_item) {
						i_item.hide();
					}
				},
				afterrender: {
					fn: function(i_cursor) {

						var i_content = i_self.getContent();

						var a_fields = i_content.query("field[focusable]");

						if (a_fields.length === 0) {

							i_cursor.show();

							i_cursor.moveCursor({
								col: o_inputData.csrCol || 1,
								lin: o_inputData.csrLin || 1
							});
						}
					}
				}
			},
			moveCursor: function(o_position) {

				var i_cursor = this;
				var i_marker = i_self.getMarker();

				i_cursor.setPosition({
					x: IceCap.util.Handler.getX(o_position.col) + 3,
					y: (IceCap.util.Handler.getY(o_position.lin + 1) - IceCap.util.Handler.getColSize()) + 3
				});

				var a_pos = [
					IceCap.util.Handler.getX(o_position.col),
					(IceCap.util.Handler.getY(o_position.lin + 1) - IceCap.util.Handler.getColSize()) + 3
				];

				i_marker.move(a_pos);

				i_self.updateCurrentPosition(o_position);
			}
		});

		i_self.setCursor(i_cursor);

		return i_cursor;
	},

	createMarker: function() {

		var i_self = this;

		var i_marker = Ext.widget("icecap-marker", {
			hidden: true,
			active: false,
			inUse: false,
			ui: i_self.getTheme() || "default"
		});

		i_self.setMarker(i_marker);

		return i_marker;
	},

	findFocus: function() {

		var i_self = this;
		var i_main = i_self.getMain();
		var i_content = i_self.getContent();

		var a_fields = i_content.query("field[focusable]");

		if (a_fields.length > 0) {

			var i_field = a_fields[0];
			i_field.focus(false, 10);
		}
		else {
			i_main.focus(false, 10);
		}
	},

	doTimer: function() {

		var i_self = this;
		var s_message = i_self.getMessageText();

		var i_timer = i_self.getTimer();
		if (!i_timer) {
			i_timer = new Ext.util.DelayedTask(function() {

				i_self.setLoading(s_message ? s_message :true);
			});

			i_self.setTimer(i_timer);

			i_timer.delay(1000);
		}
	},

	cancelTimer: function() {

		var i_self = this;

		var i_timer = i_self.getTimer();

		if (i_timer) {
			i_timer.cancel();
			i_self.setTimer(null);
		}
	},

	doTitleUpdate: function(s_value) {

		var i_self = this;
		var i_window = i_self.up("window");
		i_self.setTitle("");

		if (i_window && !i_window.isXType("ip2DomainModelEntityManager", false)) {

			if (!i_self.getIgnoreTitle()) {
				i_window.setTitle(s_value);
			}
		}
		else {
			if (!i_self.getIgnoreTitle()) {
				i_self.setTitle(s_value);
			}
		}
	},

	onError: function(o_inputData) {

		var i_self = this;

		Ext.Msg.show({
			title: "Server Message",
			msg: o_inputData.msgBox.text,
			icon: Ext.MessageBox.INFO,
			buttons: Ext.MessageBox.OK,
			fn: function(btn) {
				i_self.findFocus();
			}
		});
	},

	updateMessage: function(o_inputData) {

		var i_self = this;
		var i_statusbar = i_self.getStatusBar();

		var a_messages = Ext.Array.from(o_inputData.message);

		if (a_messages.length > 0) {

			var a_result = [];

			Ext.Array.each(a_messages, function(o_message) {
				a_result.push(o_message.text);
			});

			i_statusbar.setText(a_result.join(" "));
		}
	},

	applyFFW: function(o_config) {

		var i_self = this;
		var s_hex = o_config.ffw;
		var b_fixed = IceCap.util.Handler.getFixed();

		var o_field = {
			xtype: "textfield"
		};

		var o_fieldStyle = {
			font: "normal " + IceCap.util.Handler.getTextSize() + "px Segoe UI,Segoe,DejaVu Sans,Trebuchet MS,Verdana,sans-serif",
			padding: "1px 3px 2px 3px !important"
		};

		if (b_fixed) {

			Ext.apply(o_fieldStyle, {
				font: "normal " + IceCap.util.Handler.getTextSize() + "px / " + IceCap.util.Handler.getColSize() + "px Lucida Console",
			});
		}

		if (o_config.ta) {

			Ext.apply(o_fieldStyle, {
				"text-align": o_config.ta
			});
		}

		if (s_hex) {

			var n_hex = parseInt(s_hex);

			var n_sanHex = IceCap.util.Handler.createIndicators(s_hex);

			if (n_sanHex & IceCap.util.Handler.FFW.BYPASS) {

				Ext.apply(o_field, {
					readOnly: true
				});
			}

			if (n_sanHex & IceCap.util.Handler.FFW.ALPHA_ONLY) {

				Ext.apply(o_field, {
					maskRe: new RegExp("[a-z A-Z ,.-]")
				});
			}

			if (n_sanHex & IceCap.util.Handler.FFW.NUMERIC_ONLY) {

				Ext.apply(o_field, {
					maskRe: new RegExp("[+\\-,. 0-9]")
				});
			}

			if (n_sanHex & IceCap.util.Handler.FFW.DIGITS_ONLY) {

				Ext.apply(o_field, {
					maskRe: new RegExp("[0-9]")
				});
			}

			if (n_sanHex & IceCap.util.Handler.FFW.MOD_DATA) {

				Ext.apply(o_field, {
					listeners: {
						afterrender: {
							fn: function(i_field) {

								i_field.originalValue = 0xFF;
							},
							single: true
						}
					}
				});
			}

			if (n_sanHex & IceCap.util.Handler.FFW.AUTO_ENTER) {

				// THIS WE DONT NEED IN THE MODERN WORLD...

				// Ext.apply(o_field, {
				// 	listeners: {
				// 		blur: {
				// 			fn: function(i_field) {
				// 				i_self.doKeyEvent("ENTER");
				// 			}
				// 		}
				// 	}
				// });
			}

			if (n_sanHex & IceCap.util.Handler.FFW.MONOCASE) {

				// Ext.apply(o_fieldStyle, {
				// 	"text-transform": "uppercase"
				// });
			}

			if (n_sanHex & IceCap.util.Handler.FFW.MAND_ENTER) {

				Ext.apply(o_field, {
					allowBlank: false
				});
			}

			if (n_sanHex & IceCap.util.Handler.FFW.RA_ZEROFILL ||
				n_sanHex & IceCap.util.Handler.FFW.RA_BLANKFILL ||
				n_sanHex & IceCap.util.Handler.FFW.RA_MANDATORY) {

				Ext.apply(o_fieldStyle, {
					"text-align": "right"
				});
			}

			if (o_config.atr == "27" && n_hex & (1 << 13)) {

				Ext.apply(o_field, {
					hidden: true,
					disabled: true
				});
			}
		}

		Ext.apply(o_field, {
			fieldStyle: o_fieldStyle
		});

		return o_field;
	},

	getState: function() {

		var i_self = this;

		var o_inputData = i_self.getInputData();
		var s_sessionValue = i_self.getSessionValue();

		var o_result = {
			appConfig: {
				inputData: o_inputData,
				sessionValue: s_sessionValue
			}
		};

		return o_result;
	},

	updateCurrentPosition: function(o_position) {

		var i_self = this;
		var i_statusbar = i_self.getStatusBar();

		if (i_statusbar) {
			var i_position = i_statusbar.getComponent("icecap-position");

			if (i_position) {

				var a_result = [
					o_position.lin,
					o_position.col
				];

				i_position.setText(a_result.join("/"));
			}
		}
	},

	updateTypeMode: function (n_type) {

		var i_self = this;

		var i_statusbar = i_self.getStatusBar();

		if (i_statusbar) {

			var i_typeLabel = i_statusbar.getComponent("icecap-typemode");

			var a_mode = [
			];

			if (i_typeLabel) {

				switch (n_type) {
					case IceCap.util.Handler.typeMode.OVERWRITE:
						a_mode.push(" DEL");
						break;

					default:
						a_mode.push(" INS");
						break;
				}

				i_typeLabel.setText(a_mode.join(" "));
			}
		}
	}
});
