Ext.define("IceCap.controller.Window", {
	extend: "Ext.app.ViewController",

	alias: "controller.icecap.view.window",

	onSendData: function(o_config, o_data) {

		var i_controller = this;
		var o_saved = Ext.clone(o_config);
		var i_view = i_controller.getView();
		var s_session = i_view.getSessionValue();

		var o_options = i_view.getOptions();

		o_data = Ext.apply(o_data, {
			i18nLearning: false
		});

		Ext.apply(o_config, {
			session: s_session,
			translateMode: i_view.getEdit()
		});

		Ext.apply(o_config, o_options);

		if (!i_view.getWorking()) {
			i_view.setWorking(true);
			i_view.doTimer();
			IceCap.util.Handler.getData(o_config, o_data, function(o_inputData) {

				if (o_inputData.statusUpdate) {

					i_view.setWorking(false);
					i_view.updateMessage(o_inputData);
					if (o_inputData.status > -1) {
						i_view.doCreateFromData(o_inputData);
					}
					i_controller.onSendData(o_saved, o_data);
				}
				else {

					i_view.setLoading(false);
					i_view.cancelTimer();

					var f_callback = i_view.getResponseCallBack() || Ext.emptyFn;

					if (f_callback != Ext.emptyFn) {

						f_callback(o_inputData);
					}

					var o_plugin = o_inputData.plugin || Ext.apply({}, {
						require: []
					});

					var a_require = o_plugin.require || [];
					var s_run = o_plugin.run || "";

					i_controller.doRequire(a_require, function() {

						if (s_run) {
							eval(s_run);
						}

						if (o_inputData.close) {
							i_view.fireEvent("applicationClose", true);
						}
						else {

							i_view.setWorking(false);
							i_view.doCreateFromData(o_inputData);
						}
					});
				}
			});
		}
	},

	onWheel: function(i_event) {

		var i_controller = this;
		var i_view = i_controller.getView();

		var b_hasGrid = i_view.query("gridpanel").length > 0;
		var b_mappanel = i_view.query("icecap-gmappanel").length > 0;

		var n_delta = i_event.getWheelDelta();
		var s_event = "";

		if (n_delta > 0) {
			s_event = "ROLLDOWN";
		}
		else {
			s_event = "ROLLUP";
		}

		if (!b_hasGrid && !b_mappanel && !i_event.ctrlKey) {
			i_controller.doKeyEvent(s_event);
		}
	},

	onDblClick: function(i_event) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_cursor = i_view.getCursor();

		var o_rules = i_view.getCssRules();

		var i_content = i_view.getContent();
		var i_region = i_content.getRegion(true, false);

		var b_fireEvent = i_view.getEnterOnDblClick();

		var o_click = Ext.apply({
			x: i_event.pageX - i_region.x,
			y: i_event.pageY - i_region.y
		});

		var o_position = IceCap.util.Handler.toColAndLine(o_click, o_rules);

		if (b_fireEvent) {

			var i_currentField = i_view.getCurrentField();

			if (i_currentField) {
				o_position = Ext.apply(o_position, {
					lin: i_currentField.lin,
					col: i_currentField.col
				});
				if (i_currentField.inputEl && i_currentField.getValue()) {
					o_position = IceCap.util.Handler.toColAndLine(o_click, o_rules);
				}
			}
			else {
				i_cursor.moveCursor(o_position);
				i_cursor.show();
			}

			i_view.setCurrentPosition(o_position);
			i_controller.doKeyEvent("ENTER");
		}
		else {

			var n_x = IceCap.util.Handler.getX(o_position.col, o_rules.fontScale);
			var n_y = IceCap.util.Handler.getY(o_position.lin, o_rules.lineScale);

			var o_rect = Ext.apply(o_click, {
				x: n_x,
				y: n_y,
				width: IceCap.util.Handler.getWidth(1, o_rules.fontScale),
				height: IceCap.util.Handler.getHeight(1, o_rules.lineScale),
				left: n_x,
				right: n_x+  IceCap.util.Handler.getWidth(1, o_rules.fontScale),
				top: n_y,
				bottom: n_y + IceCap.util.Handler.getHeight(1, o_rules.lineScale)
			});

			var a_labels = IceCap.util.Handler.getLabels(i_view);

			Ext.Array.each(a_labels, function(i_label) {

				var i_labelRegion = i_label.getRegion(false, true);

				if (i_labelRegion.intersect(o_rect)) {

					var i_selector = i_view.getSelector();

					var o_labelPos = IceCap.util.Handler.toColAndLine(i_labelRegion, o_rules);

					var n_x = IceCap.util.Handler.getX(o_labelPos.col - 1, o_rules.fontScale);
					var n_y = IceCap.util.Handler.getY(o_labelPos.lin + 1, o_rules.lineScale);

					var a_split = i_label.el.dom.innerText.split(" ");

					var i_result;

					var n_posCol = 0;

					Ext.Array.each(a_split, function(s_word) {

						var n_wordX = i_labelRegion.x + IceCap.util.Handler.getX(n_posCol, o_rules.fontScale);
						var n_wordY = i_labelRegion.y;

						var i_wordRegion = Ext.util.Region.create();

						if(/[\/]/g.test(s_word)) {

							var a_temp = s_word.split(/[\/]/g);

							Ext.Array.each(a_temp, function(s_temp) {

								n_wordX = i_labelRegion.x + IceCap.util.Handler.getX(n_posCol, o_rules.fontScale);
								n_wordY = i_labelRegion.y

								Ext.apply(i_wordRegion, {
									x: n_wordX,
									y: n_wordY,
									width: IceCap.util.Handler.getWidth(s_temp.length, o_rules.fontScale),
									height: i_label.getHeight(),
									left: n_wordX,
									right: n_wordX +  IceCap.util.Handler.getWidth(s_temp.length, o_rules.fontScale),
									top: n_wordY,
									bottom: n_wordY + i_label.getHeight()
								});

								if (i_wordRegion.intersect(o_rect)) {
									i_result = i_wordRegion;
									return false;
								}

								n_posCol = n_posCol + s_temp.length + 1;
							});

						}
						else {

							Ext.apply(i_wordRegion, {
								x: n_wordX,
								y: n_wordY,
								width: IceCap.util.Handler.getWidth(s_word.length, o_rules.fontScale),
								height: i_label.getHeight(),
								left: n_wordX,
								right: n_wordX +  IceCap.util.Handler.getWidth(s_word.length, o_rules.fontScale),
								top: n_wordY,
								bottom: n_wordY + i_label.getHeight()
							});

							if (i_wordRegion.intersect(o_rect)) {
								i_result = i_wordRegion;
							}

							n_posCol = n_posCol + s_word.length + 1;
						}

						if (i_result) {
							return false;
						}
					});

					var n_dragX = IceCap.util.Handler.getX(o_labelPos.col, o_rules.fontScale);
					var n_dragY = IceCap.util.Handler.getY(o_labelPos.lin + 2, o_rules.lineScale);

					if (i_result) {

						n_x = i_result.x;
						n_y = i_result.y;

						n_dragX = i_result.right;
						n_dragY = i_result.bottom;
					}

					i_selector.resetPos(n_x, n_y);

					i_selector.show();

					i_selector.setSelecting(true);

					i_selector.setDragX(n_dragX);
					i_selector.setDragY(n_dragY);

					i_event.stopEvent();

					return false;
				}
			});
		}
	},

	onClick: function(i_event) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var o_inputData = i_view.getInputData();
		var i_cursor = i_view.getCursor();
		var i_content = i_view.getContent();
		var o_rules = i_view.getCssRules();

		var i_activeComponent = Ext.ComponentManager.getActiveComponent();

		var o_click = Ext.apply({
			x: i_event.pageX - i_content.getX(),
			y: i_event.pageY - i_content.getY() 
		});

		var o_position = IceCap.util.Handler.toColAndLine(o_click, o_rules);

		if (i_content.contains(i_activeComponent) || i_content.ownerCt == i_activeComponent) {

			var i_currentField = i_view.getCurrentField();

			var a_metaFields = o_inputData.metaFields || [];

			if (i_currentField) {
				o_position = Ext.apply(o_position, {
					lin: i_currentField.lin,
					col: i_currentField.col
				});
				if (i_currentField.inputEl && i_currentField.getValue()) {
					o_position = IceCap.util.Handler.toColAndLine(o_click, o_rules);
				}
			}
			else {

				var a_inputs = IceCap.util.Handler.getInputFields(i_view);

				var n_width = Math.ceil(IceCap.util.Handler.getWidth(1));
				var n_height = 2;

				var o_box = Ext.apply({
					x: IceCap.util.Handler.getX(o_position.col),
					y: IceCap.util.Handler.getY(o_position.lin),
					width: i_cursor.getWidth() || n_width,
					height: i_cursor.getHeight() || n_height,
					right: IceCap.util.Handler.getX(o_position.col) + i_cursor.getWidth(),
					bottom: IceCap.util.Handler.getY(o_position.lin) + i_cursor.getHeight()
				});

				var b_intersect = false;

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

					var i_element = i_field.getEl();

					if (i_element) {

						var i_region = i_field.getRegion(false, true);

						if (i_region.intersect(o_box)) {

							b_intersect = true;
							i_field.focus(false, 10);

							var n_start = o_position.col - i_field.col;
							var i_inputEl = i_field.inputEl;
							i_inputEl.dom.selectionStart = i_inputEl.dom.selectionEnd = n_start;

							return false;
						}
					}
				});

				if (!b_intersect) {

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

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

					i_cursor.moveCursor(o_position);

					i_cursor[a_metaFields.length === 0 ? "show" : "hide"]();
				}
			}
		}

		i_view.setCurrentPosition(o_position);
	},

	doArrowKeys: function (n_direction) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var a_fields = IceCap.util.Handler.getInputFields(i_view);
		var n_tabIndex = i_view.getCurrentTabIndex();

		var i_lastFocus = Ext.ComponentManager.getActiveComponent();

		var n_part = n_direction ? 1 : -1;

		if (i_lastFocus.isXType("field")) {

			var n_next = n_part > 0 ? n_tabIndex + 1 : n_tabIndex - 1;

			var i_found;

			i_found = Ext.Array.findBy(a_fields, function (i_field) {
				return i_field.getTabIndex() === n_next;
			});

			if (!i_found) {
				i_found = n_part > 0 ? a_fields[0] : a_fields[a_fields.length - 1];
			}

			if (i_found) {
				i_found.focus(true, 10);
				n_tabIndex = i_found.getTabIndex();
			}
		}

		i_view.setCurrentTabIndex(n_tabIndex);
	},

	doTabKey: function (n_direction) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var a_fields = IceCap.util.Handler.getInputFields(i_view);
		var n_tabIndex = i_view.getCurrentTabIndex();

		var i_lastFocus = Ext.ComponentManager.getActiveComponent();

		var n_part = n_direction ? 1 : -1;

		if (i_lastFocus.isXType("field")) {

			var n_next = n_part > 0 ? n_tabIndex + 1 : n_tabIndex - 1;

			var i_found;

			i_found = Ext.Array.findBy(a_fields, function (i_field) {
				return i_field.getTabIndex() === n_next;
			});

			if (!i_found) {
				i_found = n_part > 0 ? a_fields[0] : a_fields[a_fields.length - 1];
				n_tabIndex = i_found.getTabIndex();
			}

			if (i_found) {
				i_found.focus(true, 10);
				n_tabIndex = i_found.getTabIndex();
			}
		}
		else {
			var i_field = a_fields[0];
			i_field.focus(true, 10);
			n_tabIndex = i_field.getTabIndex();
		}

		i_view.setCurrentTabIndex(n_tabIndex);
	},

	doKeyEvent: function(s_value) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var o_rules = i_view.getCssRules();

		var i_cursor = i_view.getCursor();

		var o_data = {
			key: s_value
		};

		var o_position = i_view.getCurrentPosition() || {
			col: 1,
			lin: 1
		};

		if (i_cursor && i_cursor.getEl()) {
			o_position = IceCap.util.Handler.toColAndLine({
				x: i_cursor.getLocalX(),
				y: i_cursor.getLocalY()
			}, o_rules);
		}

		var i_content = i_view.getContent();
		var i_form = i_content.getForm();
		var i_collectionField = i_form.getFields();
		var o_values = {};

		Ext.Array.each(i_collectionField.items, function(i_field) {
			if (i_field.isDirty()) {
				var value = i_field.getSubmitValue ? i_field.getSubmitValue() : i_field.getValue();
				o_values[i_field.itemId || i_field.initialConfig.id || i_field.name] = value;
			}
		});

		Ext.Object.each(o_values, function(s_key, value) {
			var s_id = "ses2.win." + s_key;
			o_data[s_id] = value;
		});

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

		var f_callback = i_view.getRequestCallBack() || Ext.emptyFn;

		if (f_callback != Ext.emptyFn) {

			f_callback(o_data);
		}

		i_controller.onSendData({
			func: ""
		}, o_data);
	},

	doFKey: function(s_value) {

		var i_controller = this;

		i_controller.doKeyEvent(s_value);
	},

	doRequire: function(a_require, f_callback) {

		f_callback = f_callback || Ext.emptyFn;

		a_require = a_require || [];

		if (a_require.length > 0) {

			var a_external = Ext.Array.filter(Ext.Array.map(a_require, function(s_value) {
				if (s_value.indexOf("/") > -1) {
					return s_value;
				}
			}), function(value) {
				return value;
			});

			var a_internal = Ext.Array.filter(Ext.Array.map(a_require, function(s_value) {
				if (s_value.indexOf("/") < 0) {
					return s_value;
				}
			}), function(value) {
				return value;
			});

			if (a_external.length > 0) {
				Ext.Loader.loadScriptsSync(a_external);
			}

			if (a_internal.length > 0) {
				Ext.syncRequire(a_internal);
			}
		}

		f_callback();
	}
});
