Ext.define("Ext.ux.call2action.Tabpanel", {

	extend: "Ext.tab.Panel",

	alias: [
		"widget.ip2Call2ActionTabpanel"
	],

	config: {
		generalPanel: null,
		LinkTabpanel: null
	},

	layout: "fit",

	requires: [
		"Ext.ux.call2action.GeneralPanel",
		"Ext.ux.call2action.LinkTabpanel"
	],

	initComponent: function() {

		var i_self = this;
		var o_data = i_self.config.data;
		i_self.data = o_data;

		var i_general = Ext.create("Ext.ux.call2action.GeneralPanel", {
			data: o_data,
			title: ip2.i18n({
				da: "Knap",
				en: "Button"
			}),
			listeners: {
				activate: {
					fn: function(i_panel) {

						var i_form = i_panel.getForm();
						var i_field = i_form.findField("buttontext");

						if (i_field) {
							i_field.focus(false, 50);
						}
					}
				}
			}
		});

		var i_linkpanel = Ext.create("Ext.ux.call2action.LinkTabpanel", {
			data: o_data,
			layout: "fit"
		});

		i_self.callParent();

		var i_linkContainer = Ext.widget("panel", {
			title: ip2.i18n({
				da: "Link til",
				en: "Link to"
			}),
			border: false,
			layout: "fit",
			items: [
				i_linkpanel
			]
		});

		i_self.add([
			i_general,
			i_linkContainer
		]);

		i_self.setGeneralPanel(i_general);
		i_self.setLinkTabpanel(i_linkpanel);

		i_self.setActiveTab(0);
	},

	doSave: function(args) {

		var i_self = this;

		var f_success = args.success || Ext.emptyFn;
		var f_faliure = args.failure || Ext.emptyFn;

		var i_general = i_self.getGeneralPanel();
		var i_linkpanel = i_self.getLinkTabpanel();

		i_self.messageSent = false;

		i_self.savecomplete = {
			generalPanel: false,
			LinkTabpanel: false
		};

		i_general.doSave({
			success: function() {
				i_self.savecomplete.generalPanel = true;
			},
			failure: function(errors) {
				i_self.setActiveTab(0);
				if (!i_self.messageSent && Ext.isArray(errors) && errors.length > 0) {
					i_self.messageSent = true;
					i_self.showMessage(errors);
				}
			}
		});

		i_linkpanel.doSave({
			success: function() {
				i_self.savecomplete.LinkTabpanel = true;
			},
			failure: function(errors) {
				i_self.setActiveTab(1);
				if (!i_self.messageSent && Ext.isArray(errors) && errors.length > 0) {
					i_self.messageSent = true;
					i_self.showMessage(errors);
				}
			}
		});

		if (i_self.savecomplete.generalPanel && i_self.savecomplete.LinkTabpanel) {
			f_success();
		}
		else {
			f_faliure();
		}
	},

	getValue: function() {

		var i_self = this;
		var o_data = i_self.getData();
		var i_general = i_self.getGeneralPanel();
		var i_linkpanel = i_self.getLinkTabpanel();

		var o_generalValues = i_general.getValue();
		var o_linkValues = i_linkpanel.getValue();

		Ext.apply(o_data, o_generalValues);

		o_data.link = o_linkValues;

		return o_data;
	},

	showMessage: function(a_error) {

		var o_error = a_error[0];

		if (o_error.message) {
			Ext.MessageBox.show({
				title: ip2.i18n("error"),
				msg: o_error.message,
				buttons: Ext.MessageBox.OK,
				icon: Ext.MessageBox.ERROR
			});
		}
	}
});
