Ext.define("Portfolio.settings.language.controller.Window", {
	extend: "Ext.app.ViewController",

	alias: "controller.portfolio-settings-language-window",

	onValidityChange: function(i_form, b_valid) {

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

		var i_buttonSave = i_footer.getComponent("button-save");

		i_buttonSave[b_valid ? "enable" : "disable"]();

		if (b_valid) {
			i_buttonSave[i_form.isDirty() ? "enable" : "disable"]();
		}
	},

	onDirtyChange: function(i_form, b_dirty) {

		var i_controller = this;
		var i_view = i_controller.getView();
		var i_form = i_view.getForm();
		var i_footer = i_view.getFooter();

		var b_valid = i_form.isValid();

		var i_buttonSave = i_footer.getComponent("button-save");

		if (b_valid) {
			i_buttonSave[b_dirty ? "enable" : "disable"]();
		}
		else {
			i_buttonSave.disable();
		}
	},

	onSave: function() {

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

		i_view.setLoading(ip2.i18n({
			da: "Tilføjer sprog...",
			en: "Adding language..."
		}));

		var i_record = i_form.getRecord();

		var o_values = i_form.getValues();

		i_record.set(o_values);

		var o_keys = {};

		o_keys[i_record.idProperty] = i_record.get(i_record.idProperty);

		var o_batch = Ext.apply({}, {
			type: "upsert",
			dmd: "dmd/portfolio.dmd",
			entity: "NAVLNG",
			key: o_keys,
			row: i_record.getData()
		});

		Ext.Ajax.request({
			url: "/ip2-services/ip2dmdProxy.aspx",
			jsonData: {
				batch: [
					o_batch
				]
			},
			success: function (i_response, i_request) {

				i_view.setLoading(false);

				var o_result = Ext.decode(i_response.responseText, true) || {
					success: false,
					batch: [{
						rows: []
					}]
				};

				Ext.applyIf(o_result, {
					success: false,
					batch: [{
						row: {}
					}]
				});

				if (!o_result.success) {

					Portfolio.util.Handler.messageBox({
						icon: Ext.MessageBox.ERROR,
						title: ip2.i18n({
							da: "Fejl",
							en: "Error"
						}),
						closable: true,
						message: o_result.message,
						yesText: ip2.i18n({
							da: "OK",
							en: "OK"
						})
					});
				}
				else {
					i_form.loadRecord(i_record);
					i_view.close();
				}
			}
		});
	}
});
