Ext.define("Ext.ux.container.Ip2Widget", {

	extend: "Ext.ux.container.Widget",

	alias: [
		"widget.ip2widget",
		"widget.ip2widgetcontainer"
	],

	config: {
		i18nValues: {},
		modified: {},
		language: "en",
		languageChange: false,
		attr: {},
		context: "portfolio"
	},

	trackResetOnLoad: true,

	requires: [
		"Ext.ux.plugin.data.Tracker"
	],

	initComponent: function() {

		var i_self = this;

		var i_user = ip2.getUser();

		var s_language = i_user ? i_user.get("USRLNG") : "en";
		var a_languages = wsh.getLanguages(i_self.getContext());

		i_self.setLanguage(s_language);

		var i_tracker = Ext.create("Ext.ux.plugin.data.Tracker");

		var a_plugins = Ext.Array.from(i_self.plugins);

		a_plugins.push(i_tracker);

		i_self.plugins = a_plugins;

		var o_modified = i_self.getModified();

		Ext.Array.each(a_languages, function(s_language) {
			o_modified[s_language] = [];
		});

		i_self.setModified(o_modified);

		i_self.on({
			loaded: {
				fn: function(i_widget) {

					var i_form = i_self.getForm();
					var i_widgetCmp = i_self.getWidgetCmp();
					var a_languages = wsh.getLanguages(i_self.getContext());

					var o_i18nValue = i_self.getI18nValues();

					if (i_widgetCmp && i_widgetCmp.isDirty && i_form) {

						var a_fields = i_widgetCmp.query("field");
						var a_trees = i_widgetCmp.query("treepanel");

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

							i_field.inWidget = true;

							if (i_field.isFormField) {

								if (i_field.i18n) {

									var s_value = i_field.value;
									var o_value = {};
									var o_fieldvalue = null;
									var regex = new RegExp("/n","g");

									if (ip2.isStringedObject(s_value)) {
										o_fieldvalue = Ext.decode(s_value);
									}

									if (o_fieldvalue) {

										Ext.Array.each(a_languages, function(s_lang) {

											var value = o_fieldvalue[s_lang];

											o_value[s_lang] = !Ext.isEmpty(value, false) ? value : "";

											value = o_value[s_lang];

											if (Ext.isString(value)) {
												value = value.replace(regex, "\n");
												o_value[s_lang] = value;
											}
										});
									}
									else {

										Ext.Array.each(a_languages, function(s_lang) {
											o_value[s_lang] = "";
										});
									}

									o_i18nValue[i_field.name] = o_value;

									var value = o_value[i_self.getLanguage()];

									i_field.suspendCheckChange++;
									i_field.isReseting = true;
									i_field.setValue(value);
									i_field.resetOriginalValue();
									i_field.fireEvent("change", i_field, value);
									i_field.isReseting = false;
									i_field.suspendCheckChange--;

									i_field.on({
										change: {
											fn: function(i_field, value) {

												if (!i_self.getLanguageChange()) {

													var b_dirty = i_field.isDirty();
													var b_valid = i_field.isValid ? i_field.isValid() : true;
													var b_found = false;
													var o_modified = i_self.getModified();
													var s_language = i_self.getLanguage();

													Ext.Array.each(o_modified[s_language], function(o_field) {

														if (o_field.name == i_field.name) {

															o_field.dirty = b_dirty;
															o_field.valid = b_valid;
															o_field.value = value;
															b_found = true;

															if (b_found && i_field.isReseting) {
																o_field.originalValue = i_field.originalValue;
															}
															return false;
														}
													});

													if (!b_found) {

														var o_field = {
															name: i_field.name,
															valid: b_valid,
															dirty: b_dirty,
															value: value,
															originalValue: i_field.originalValue
														};

														o_modified[s_language].push(o_field);
													}
												}
											}
										}
									});
								}
							}
						});

						Ext.Array.each(a_trees, function(i_tree) {

							i_tree.inWidget = true;

							var i_store = i_tree.getStore();

							i_store.on({
								update: {
									fn: function(store, i_record, operation, a_modified) {

										var b_valid = i_widgetCmp.isValid ? i_widgetCmp.isValid() : true;

										if (!b_valid) {
											i_self.fireEvent("validitychange", i_self, b_valid);
										}
										else {
											var b_dirty = i_widgetCmp.isDirty();
											i_self.fireEvent("dirtychange", i_self, b_dirty);
										}
									}
								},
								datachanged: {
									fn: function(store, i_record, operation, a_modified) {

										var b_valid = i_widgetCmp.isValid ? i_widgetCmp.isValid() : true;

										if (!b_valid) {
											i_self.fireEvent("validitychange", i_self, b_valid);
										}
										else {
											var b_dirty = i_widgetCmp.isDirty();
											i_self.fireEvent("dirtychange", i_self, b_dirty);
										}
									}
								}
							});
						});
					}
				}
			},
			dirtychange: {
				fn: function(i_form, b_dirty) {

					var i_widgetCmp = i_self.getWidgetCmp();

					if (i_self.title && i_widgetCmp && i_widgetCmp.isDirty) {

						if (i_form.getForm || i_form.isValid) {

							var b_valid = true;

							if (i_form.getForm) {
								b_valid = i_form.getForm().isValid();
							}
							else if (i_form.isValid) {
								b_valid = i_form.isValid();
							}

							if (b_valid) {

								if (b_dirty) {
									i_self.setIconCls("flatui icon-data-new");
								}
								else {
									i_self.setIconCls("");
								}
							}
						}
						else {

							if (b_dirty) {
								i_self.setIconCls("flatui icon-data-new");
							}
							else {
								i_self.setIconCls("");
							}
						}
					}
				}
			},
			validitychange: {
				fn: function(i_form, b_valid) {

					if (i_self.title) {
						if (!b_valid) {
							i_self.setIconCls("flatui icon-data-error");
						}
						else {
							var b_dirty = i_self.isDirty();
							i_self.fireEvent("dirtychange", i_self, b_dirty);
						}
					}
				}
			}
		});

		// widgets are not to be considered fields or forms in any respect for parents who may
		// be gathering data - they live their own lives

		if (i_self.title) {
			i_self.iconCls = "";
		}

		i_self.callParent(arguments);

		var i_form = i_self.getForm();

		i_form.wasValid = true;

		i_self.enableBubble([
			"dirtychange",
			"validitychange"
		]);

		var o_attr = i_self.getAttr();

		if (o_attr.url) {
			i_self.addDocked(i_self.createLinkBar());
		}

		return i_self;
	},

	createLinkBar: function() {

		var i_self = this;

		var a_items = [
			{
				xtype: "tbfill"
			},
			{
				xtype: "button",
				iconCls: "pf-link",
				itemId: "button-link",
				handler: function(i_button) {

					var o_attr = i_self.getAttr();

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

						var o_attr = o_attr;
						var s_widget = o_attr.url;
						var s_name = s_widget.split(".").shift();

						var i_window = Ext.widget("link.window", {
							model: {
								widget: {
									name: s_name
								}
							}
						});

						i_window.show();
					}
				}
			}
		];

		var i_toolbar = Ext.widget("toolbar", {
			dock: "bottom",
			items: a_items,
			itemId: "linkbar"
		});

		return i_toolbar;
	},

	changeLanguage: function(s_lang) {

		var i_self = this;
		i_self.setLanguageChange(true);

		var i_form = i_self.getForm();
		var a_fields = i_form.getFields().items;
		var o_i18nValue = i_self.getI18nValues();
		var o_newvalues = {};
		var s_language = i_self.getLanguage();
		var o_modified = i_self.getModified();

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

			if (i_field.i18n) {
				o_i18nValue[i_field.name][s_language] = i_field.getValue();
			}
		});

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

			if (i_field.i18n) {
				o_i18nValue[i_field.name] = o_i18nValue[i_field.name] || {};
				o_newvalues[i_field.name] = o_i18nValue[i_field.name][s_lang] || "";
			}
		});

		if (i_form) {
			i_form.setValues(o_newvalues);
		}
		else {

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

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

					if (i_field.name == s_key) {

						i_field.suspendCheckChange++;
						i_field.setValue(value);
						i_field.resetOriginalValue();
						i_field.suspendCheckChange--;
					}
				});
			});
		}

		var a_modified = Ext.Array.from(o_modified[s_lang]);

		Ext.Array.each(a_modified, function(o_field) {

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

				if (i_field.name == o_field.name) {

					var value = i_field.getValue();
					var valueOld = o_field.originalValue;

					i_field.suspendCheckChange++;
					i_field.setValue(valueOld);
					i_field.resetOriginalValue();
					i_field.wasDirty = o_field.dirty;
					i_field.setValue(value);
					i_field.suspendCheckChange--;
				}
			});
		});

		i_self.setLanguageChange(false);
		i_self.setLanguage(s_lang);
	},

	_aftersave: function(f_callback) {

		var i_self = this;
		var i_form = i_self.getForm();
		var a_fields = i_form.getFields().items;
		var a_languages = wsh.getLanguages(i_self.getContext());
		var o_i18nValue = i_self.getI18nValues();
		var s_language = i_self.getLanguage();

		f_callback = f_callback || Ext.emptyFn;

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

			if (i_field.i18n) {

				var value = o_i18nValue[i_field.name][s_language];

				i_field.suspendCheckChange++;
				i_field.setValue(value);
				i_field.suspendCheckChange--;
			}

			i_field.resetOriginalValue();
		});

		var o_modified = {};

		Ext.Array.each(a_languages, function(s_language) {
			o_modified[s_language] = [];
		});

		i_self.setModified(o_modified);

		f_callback.call(i_self);
	},

	_doSave: function() {

		var i_self = this;
		var i_form = i_self.getForm();
		var a_fields = i_form.getFields().items;

		var o_i18nValue = i_self.getI18nValues();
		var s_language = i_self.getLanguage();

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

			if (i_field.i18n) {

				o_i18nValue[i_field.name][s_language] = i_field.getValue();

				var o_value = o_i18nValue[i_field.name];
				var s_value = JSON.stringify(o_value);

				i_field.setValue(s_value);
			}
		});
	},

	doSave: function (f_callback) {

		var i_self = this;
		var i_widget = i_self.getWidgetComponent();

		f_callback = f_callback || Ext.emptyFn;

		i_self._doSave();

		if (i_widget.doSave) {
			i_widget.doSave(function() {
				i_self._aftersave(f_callback);
			});
		}
		else {
			f_callback.call(i_self);
		}
	},

	doPreSave: function(i_record, f_callback) {

		var i_self = this;
		var i_widget = i_self.getWidgetComponent();

		f_callback = f_callback || Ext.emptyFn;

		if (i_widget.doPreSave) {
			i_widget.doPreSave(i_record, function(i_record) {
				f_callback(i_record);
			});
		}
		else {
			f_callback(i_record);
		}
	}
});
