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

	extend: "Ext.grid.Panel",

	alias: [
		"widget.ip2Call2ActionGridGrid"
	],
	border: true,

	autoScroll: true,

	refreshCount: 0,

	viewConfig: {
		plugins: {
			ptype: "gridviewdragdrop"
		}
	},

	initComponent: function() {

		var i_self = this;

		i_self.buttonText = {};

		i_self.columns = [
			{
				text: ip2.i18n({
					da: "Design",
					en: "Design"
				}),
				flex: 1, dataIndex: "behaviour",
				renderer: i_self.wrapper.behaviours.renderer
			},
			{
				text: ip2.i18n({
					da: "Tekst",
					en: "Text"
				}),
				flex: 2,
				dataIndex: "buttontext",
				renderer: function (value) {

					var s_return = value;

					var s_lang = i_self.language;


					s_return = ip2.i18nWithLanguage(value, s_lang);

					return s_return;
				}
			},
			{
				text: ip2.i18n({
					da: "Linker til...",
					en: "Link to..."
				}),
				flex: 2,
				dataIndex: "link",
				renderer: function() {

					var a_copy = [].slice.call(arguments);

					if (!a_copy[1]) {

						var n_columnIndex = this.getIndex();
						var n_rowIndex = i_self.getStore().indexOf(a_copy[2]);

						a_copy[3] = n_rowIndex;
						a_copy[4] = n_columnIndex;
					}

					return i_self.linkRenderer.apply(i_self, a_copy);
				}
			},
			{
				text: ip2.i18n({
					da: "Åben indhold i",
					en: "Open contents in"
				}),
				flex: 2, dataIndex: "target",
				renderer: i_self.wrapper.targets.renderer
			},
			{
				xtype: "actioncolumn",
				iconCls: "pf-edit",
				handler: function(grid, rowIndex, colIndex) {
					var record = grid.getStore().getAt(rowIndex);
					i_self.doEdit(i_self.buttonText.edit, record);
				}
			},
			{
				xtype: "actioncolumn",
				iconCls: "pf-navigate_cross",
				handler: function(grid, rowIndex, colIndex) {
					var record = grid.getStore().getAt(rowIndex);
					i_self.doDelete(i_self.buttonText.remove, record);
				}
			}
		];

		var i_store  = Ext.create("Ext.data.Store", {
			fields: [
				{
					name: "behaviour",
					type: "auto"
				},
				{
					name: "buttontext",
					type: "auto"
				},
				{
					name: "target",
					type: "auto"
				},
				{
					name: "link",
					type: "auto"
				}
			],
			proxy: {
				type: "memory",
				reader: {
					type: "json",
					rootProperty: "relations"
				}
			},
			listeners: {
				add: {
					fn: function(store) {
						i_self.wrapper.checkChange();
					}
				},
				update: {
					fn: function(store) {
						i_self.wrapper.checkChange();
					}
				},
				remove: {
					fn: function(store) {
						i_self.wrapper.checkChange();
					}
				}
			}
		});

		var i_toolbar = Ext.widget("toolbar", {
			dock: "top",
			style: {
				"background-color": "white"
			},
			items: [
				{
					xtype: "button",
					text: ip2.i18n({
						da: "Tilføj",
						en: "Add"
					}),
					handler: function(button) {
						i_self.doAdd(i_self.buttonText.add);
					},
					listeners: {
						afterrender: function(button) {
							i_self.buttonText.add = button.getText();
						}
					}
				},
				{
					xtype: "button",
					text: ip2.i18n({
						da: "Rediger",
						en: "Edit"
					}),
					hidden: true,
					handler: function(button) {
						i_self.doEdit(i_self.buttonText.edit);
					},
					listeners: {
						afterrender: function(button) {
							i_self.buttonText.edit = button.getText();
						}
					}
				},
				{
					xtype: "button",
					text: ip2.i18n({
						da: "Slet",
						en: "Delete"
					}),
					hidden: true,
					handler: function(button) {
						i_self.doDelete(i_self.buttonText.remove);
					},
					listeners: {
						afterrender: function(button) {
							i_self.buttonText.remove = button.getText();
						}
					}
				}
			]
		});

		var i_menu = Ext.create("Ext.menu.Menu", {
			items: [
                {
					xtype: "menuitem",
					text: ip2.i18n({
						da: "Rediger",
						en: "Edit"
					}),
					iconCls: "pf-edit",
					handler: function () {
						i_self.doEdit(i_self.buttonText.edit);
					}
				},
				{
					xtype: "menuitem",
					text: ip2.i18n({
						da: "Slet",
						en: "Delete"
					}),
					iconCls: "pf-delete",
					handler: function () {
						i_self.doDelete(i_self.buttonText.remove);
					}
				}
            ]
		});

		i_self.store = i_store;

		i_self.callParent(arguments);

		i_self.addDocked(i_toolbar);

		i_self.on({
			afterrender: {
				fn: function() {

					var a_records = i_store.getRange();

					i_self.setHideHeaders(Ext.isEmpty(a_records));
				}
			},
			itemdblclick: {
				fn: function(i_view, i_record, i_element, n_index, i_event) {
					i_event.preventDefault();
					i_self.doEdit(i_self.buttonText.edit);
				}
			},
			itemcontextmenu: {
				fn: function(i_view, i_record, i_element, n_index, i_event) {
					i_event.stopEvent();
					i_menu.showAt(i_event.getXY());
				}
			}
		});

		i_store.on({
			datachanged: {
				fn: function() {
					var a_records = i_store.getRange();

					i_self.setHideHeaders(Ext.isEmpty(a_records));
				}
			}
		});

		if (i_self.data) {
			i_self.setValue(i_self.data);
		}

		return i_self;
	},

	changeLanguage: function(s_lang) {

		var i_self = this;
		var i_view = i_self.getView();
		i_self.language = s_lang;
		i_view.refresh();
	},

	/* ----------------------------------------------------------------------------------------------------
	    Edit a row
	   ---------------------------------------------------------------------------------------------------- */
	getPropertyValue: function(o_properties) {

		if (o_properties.header) {
			return o_properties.header;
		}
		else if (o_properties.name) {
			return o_properties.name;
		}
		else if (o_properties.title) {
			return o_properties.title;
		}
		else if (o_properties.metatitle) {
			return o_properties.metatitle;
		}
	},

	linkRenderer: function (value, meta, record, rowIndex, colIndex, store, view) {

		{

			var position = {
				row: rowIndex,
				column: colIndex
			};

			var data = record.getData();

			var s_return = "";

			if (data.link && data.link.type) {

				switch (data.link.type) {
					case "stack":
						if (data.link.token > 0) {
							Ext.Ajax.request({
								url: "/wsh-services/wshproxy.aspx",
								params: {
									action: "getStack",
									stacktoken: data.link.token,
									languagecode: ip2.session.getLanguage(),
									xpd: ip2.resource.getFullPath("pages.xpd")
								},
								position: position,
								view: view,
								success: function (response, request) {
									var result = {};
									eval("result = " + response.responseText);
									if (result.properties) {
										var title = i_self.getPropertyValue(result.properties);
										var cell = request.view.getCellByPosition(request.position);
										if (cell && cell.id) {
											document.getElementById(cell.id).innerHTML = "<div unselectable=\"on\" class=\"x-grid-cell-inner x-unselectable\" style=\"text-align: left;\">" + title + "</div>";
										}
									}
								}
							});
						}

						break;
					case "page":
						if (data.link.token > 0) {
							var key = {
								PLGPAGTKN: data.link.token
							};
							Ext.Ajax.request({
								url: "ip2-services/ip2dmdproxy.aspx",
								params: {
									action: "getRow",
									model: "WSHPLGET00",
									key: Ext.encode(key),
									dmdfile: ip2.resource.getFullPath("webshop.dmd")
								},
								position: position,
								view: view,
								success: function (response, request) {
									var result = {};
									eval("result = " + response.responseText);
									if (result.rows.length == 1) {
										var props = Ext.decode(result.rows[0].PLGPROP);
										if (props.title) {
											var cell = request.view.getCellByPosition(request.position);
											if (cell && cell.id) {
												document.getElementById(cell.id).innerHTML = "<div unselectable=\"on\" class=\"x-grid-cell-inner x-unselectable\" style=\"text-align: left;\">" + props.title + "</div>";
											}
										}
									}
								}
							});
						}

						break;
					case "file":

						var sep = "";

						if (data.link.items) {
							if (Ext.isArray(data.link.items)) {
								for (var i = 0; i < data.link.items.length; i++) {
									s_return += sep + ((data.link.items[i].name) ? data.link.items[i].name : data.link.items[i].url);
									sep = ", ";
								}
							}
							else {
								if (Ext.isObject(data.link.items)) {
									s_return += sep + ((data.link.items.name) ? data.link.items.name : data.link.items.url);
								}
							}
						}

						s_return.trim();
						break;

					case "url":

						if (data.link.title) {
							s_return = data.link.title;
						}

						break;

					case "mediagallery":

						s_return = ip2.i18n({
							da: "Billeder",
							en: "Images"
						});

						break;
				}
			}
			return s_return;
		}
	},

	/* ----------------------------------------------------------------------------------------------------
	    Edit a row
	   ---------------------------------------------------------------------------------------------------- */
	doAdd: function(s_buttonText) {

		var i_self = this;
		var i_store = i_self.getStore();

		var i_model = i_store.getModel();
		var a_fields = i_model.getFields();
		var i_record = i_model.create({});

		Ext.Array.each(a_fields, function(i_field) {
			if (!i_field.identifier) {
				i_record.set(i_field.name, "");
			}
		});

		var i_window = Ext.create("Ext.ux.call2action.Window", {
			title: ip2.i18n({
				da: "Opret Call2Action",
				en: "Create Call2Action"
			}),
			action: "create",
			actionText: s_buttonText,
			record: i_record,
			wrapper: i_self.wrapper,
			success: function(i_record) {
				i_store.insert(0, i_record);
			}
		});

		i_window.show();
	},

	/* ----------------------------------------------------------------------------------------------------
	    Edit a row
	   ---------------------------------------------------------------------------------------------------- */
	doEdit: function(s_buttonText, i_record) {

		var i_self = this;

		var a_records = i_record ? [i_record] : i_self.getSelection();
		if (a_records.length === 0) {
			Ext.MessageBox.show({
				msg: ip2.i18n({
					da: "Du skal vælge en række først.",
					en: "You have to select at least one row."
				}),
				icon: Ext.MessageBox.WARNING
			});

			setTimeout(function() {
				Ext.MessageBox.hide();
			}, 1000);
			return;
		}

		Ext.Array.each(a_records, function(i_record) {

			var i_window = Ext.create("Ext.ux.call2action.Window", {
				title: ip2.i18n({
					da: "Rediger Call2Action",
					en: "Edit Call2Action"
				}),
				action: "update",
				actionText: s_buttonText,
				record: i_record,
				wrapper: i_self.wrapper,
				okFn: function() {
					i_self.wrapper.checkChange();
				}
			});

			i_window.show();
		});
	},

	/* ----------------------------------------------------------------------------------------------------
	    Delete a row
	   ---------------------------------------------------------------------------------------------------- */
	doDelete: function(buttonText, i_record) {

		var i_self = this;
		var i_store = i_self.getStore();

		var a_records = i_record ? [i_record] : i_self.getSelection();
		if (a_records.length === 0) {
			Ext.MessageBox.show({
				msg: ip2.i18n({
					da: "Du skal vælge en række først.",
					en: "You have to select at least one row."
				}),
				icon: Ext.MessageBox.WARNING
			});

			setTimeout(function() {
				Ext.MessageBox.hide();
			}, 1000);
			return;
		}
		else {
			Ext.MessageBox.show({
				title: ip2.i18n("confirmDeleteTitle"),
				msg: ip2.i18n("confirmDelete"),
				buttons: Ext.MessageBox.OKCANCEL,
				fn: function(btn) {
					if (btn == "ok") {
						Ext.Array.each(a_records, function(record) {
							i_store.remove(record);
						});
						i_self.wrapper.checkChange();
					}
				},
				icon: Ext.MessageBox.WARNING
			});

			// Set owner container as dirty to trigger enable of save button
			i_self.wrapper.setDirty(true);
		}
	},

	/* ----------------------------------------------------------------------------------------------------
	    Get value
	   ---------------------------------------------------------------------------------------------------- */
	getValue: function () {

		var i_self = this;
		var value = i_self.getRawValue();

		return value;
	},

	/* ----------------------------------------------------------------------------------------------------
	    Get raw value
	   ---------------------------------------------------------------------------------------------------- */
	getRawValue: function () {

		var i_self = this;
		var a_value = [];

		var i_store = i_self.getStore();

		var a_records = i_store.getRange(0);

		Ext.Array.each(a_records, function(i_record) {

			var o_data = i_record.getData();

			var o_record = {
				ptype: "call2action"
			};

			Ext.apply(o_record, o_data);

			a_value.push(o_record);
		});

		return a_value;
	},

	/* ----------------------------------------------------------------------------------------------------
	    Set value
	   ---------------------------------------------------------------------------------------------------- */
	setValue: function (value) {

		var i_self = this;
		var i_store = i_self.getStore();

		// value can be a stringed array or array - normalize
		if (Ext.isString(value)) {
			if (value.length) {
				value = Ext.isString(value) ? Ext.decode(value) : value;
			}
			else {
				value = [];
			}
		}

		// We ended up with something else than an array - return false
		if (!Ext.isArray(value)) {
			value = [];
		}

		i_store.loadData(value);

		return i_self;
	}

});
