ip2.declare("Sitemule.widgets.pagestack", {

	xtype: "container",

	require: [
		"Ext.ux.stackorganizer.Field"
	],

	layout: "fit",

	_pagestack: null,
	_parent: null,

	onInitialize: function(i_widget, i_owner) {

		var i_self = this;

		var i_parent = i_owner.getDataParent();
		var o_config = i_owner._config;

		i_widget._parent = i_parent;

		 var i_stack = Ext.create("Ext.ux.stackorganizer.Field", {
			dataTokenKey: "PAGPAGTKN",
			xpd: "stack.xpd",
			supportXpd: "pages.xpd",
			dataParent: i_parent,
			name: "PAGPAGTKN_XPD",
			cid: i_owner._config.id,
			border: false,
			listeners: {
				needcid: {
					fn: function (i_field) {
						var i_stack = this;
						i_field.setCid(i_stack.getCid());
					},
				}
			}
		});

		i_widget._pagestack = i_stack;

		i_widget.add(i_stack);
	},

	getStack: function () {
		return this._pagestack;
	},
	getValue: function () {

		return this.getStack().getValue();
	},
	getDataParent: function () {

		return this.getStack().getDataParent();
	},

	doSave: function(f_callback) {

		f_callback = f_callback || Ext.emptyFn;

		var i_self = this;
		var i_stack = i_self._pagestack;
		var i_record = i_stack.dataParent.getRecord();
		var i_stackPanel = i_stack.getStackPanel();
		var o_value = i_stackPanel.getValue();
		var b_new = o_value.token != i_record.get(i_record.idProperty);

		if (!b_new && !i_self.isDirty() ) {
			f_callback();
			return false;
		}

		if (b_new) {
			o_value.token = i_record.get(i_record.idProperty);
			o_value.stacktoken = 0;
			var a_children = o_value.children ||  [];
			Ext.Array.each(a_children, function(o_child) {
				o_child.stacktoken = 0;
			});
		}
		else {
			var token = i_stack.getToken();
			var n_token = Number(token);
			o_value.token = n_token;
		}


		Ext.Ajax.request({
			url: "/wsh-services/wshproxy.aspx",
			jsonData: o_value,
			params: {
				action: "updateStack"
			},
			success: function (i_response) {

				if (b_new) {

					var o_json;

					try { 
						o_json = Ext.decode(i_response.responseText);
					}
					catch (err) {  }

					var o_value = i_stackPanel.getValue();
					o_value.stacktoken = o_json.stacktoken;
					i_stack.setValue(o_value);
				}

				i_stack.resetOriginalValue();

				f_callback();
			}
		});

		return i_self;
	},
	doDelete: function(f_callback) {

		var i_self = this;

		f_callback = f_callback || Ext.emptyFn;

		f_callback.call(i_self);
	},

	isDirty: function() {

		var i_self = this;
		var i_stack = i_self.getStack();

		var b_dirty = false;

		if (i_stack) {
			b_dirty = i_stack.isDirty();
		}

		return b_dirty;
	}
});
