Ext.define("Ext.ux.buffer.controller.Form", {
	extend: "Ext.app.ViewController",

	alias: "controller.ux.buffer.controller.form",

	onSpecialKey: function(i_field, i_event) {

		var i_controller = this;

		if (i_event.getKey() === i_event.ENTER) {
			i_controller.onSave();
		}
	},

	onSave: function(f_callback) {

		f_callback = f_callback ||  Ext.emptyFn;

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

		var i_record = i_view.getRecord();
		var o_values = i_view.getValues();

		i_record.set(o_values);

		var url = i_view.getUrl();
		var s_url = "";

		if (Ext.isObject(url)) {
			s_url = url.save || url.set;
		}

		i_view.setLoading("Saving");

		Ext.Ajax.request({
			url: s_url,
			jsonData: {
				row: i_record.getData()
			},
			method: "POST",
			success: function (o_response) {

				i_view.setLoading(false);

				var o_result = Ext.decode(o_response.responseText, true) || {};

				if (!o_result.success) {

					var a_errors = o_result.errors;

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

						var i_field = i_view.getForm().findField(o_config.name || o_config.id);
						if (i_field) {
							i_field.markInvalid(o_config.message || o_config.msg);
						}
					});
				}

				f_callback(o_result.success);
			},
			failure: function(o_err) {

				i_view.setLoading(false);
				f_callback(false);
			}
		});
	}

});
