{

	xtype: 'container',

	require: [
		'Ext.ux.xpd.I18nField',
		'Ext.ux.form.field.QuickCombo',
		'Ext.window.Window'
	],

	layout: 'fit',

	xpdObject: null,
	xpdFlattened: null,
	widgetConfig: null,
	dataParent: null,
	keys: null,
	form: null,
	boundWidgets: null,
	collectionId: 0,

	xpdField: null,

	onInitialize: function(i_widget, i_owner) {

		ip2.waitMask.show();

		var o_config = i_owner._config;

		Ext.apply(o_config, {
			dmd: o_config.dmd || 'webshop.dmd',
			entity: o_config.entity || 'WSHPLGET00',
			xpd: o_config.xpd || 'pages.xpd',
			view: o_config.view || 'portfolio',
			propertyKey: o_config.propertyKey || 'PLGPROP',
			fieldKey: o_config.fieldKey || 'PAGPAGTKN',
			foreignKey: o_config.foreignKey || 'PLGLNGCOD',
			relationKey: o_config.relationKey || 'PLGPAGTKN',
			action: i_owner.dataParent.action
		});

		Ext.apply(i_widget, {
			widgetConfig: o_config
		});

		i_widget.xpdObject = ip2.resource.get(i_widget.widgetConfig.xpd);
		i_widget.xpdFlattened = ip2.xpd.flatten(i_widget.xpdObject);
		i_widget.dataParent = i_owner.dataParent;

		i_widget.collectionData = (function (o_xpd, o_flattened) {
			var a_data = [];
			ip2.each(o_flattened.collections, function (o_collection, s_key) {
				if ( s_key != 'all' ) {
					a_data.push({
						id: o_collection.id,
						title: ip2.xpd.translate(o_xpd, o_collection.title)
					});
				}
			});
			return a_data;
		})(i_widget.xpdObject, i_widget.xpdFlattened);

		i_widget.keys = i_widget.getKeys();

		i_widget.boundWidgets = [];

		i_widget.languages = i_widget.getLanguages();
		// Note: We may later change default language once data has been loaded
		// this is because we need to ensure there is data for default language
		i_widget.defaultLanguage = i_widget.getPrimaryLanguage();

		// Everything is setup - now we need to either load the XPD forms
		// or present the user with an option of collections to choose from.
		// If only 1 collection is present, no need for picker no matter
		var b_new = i_widget.dataParent.action == 'new';

		if ( b_new ) {
			i_widget.collectionSelect();
		}
		else {

			ip2.waitMask.show();

			i_widget.loadLanguageData(function (o_value) {

				// Even if not new, then there could easily be no XPD data,
				// so we need to show picker if so (unless only 1 collection present)
				// There may also be an instance where one language value has the
				// collection value and the other does not.
				//var n_collection = i_widget.hasCollectionId(o_value);

				/*if ( !n_collection ) {
					i_widget.collectionSelect(o_value);
				}*/
				
				if ( !Ext.Object.getSize(o_value) ) {
					i_widget.collectionSelect(o_value);
				}
				else {
					var n_collection = (function () {

						var n_found;
						//var s_defaultLanguage = i_widget.defaultLanguage;

						Ext.Array.some(i_widget.languages, function (s_lang) {

							var s_idProperty = i_widget.xpdObject.idProperty;

							if ( o_value[s_lang] && o_value[s_lang][s_idProperty] ) {
								//i_widget.defaultLanguage = s_lang;
								n_found = o_value[s_lang][s_idProperty];
								return true;
							}
						});

						return n_found;
					})();

					i_widget.createI18nXpdField(o_value);

					i_widget.createBoundWidgets(n_collection);

					i_widget.updateTitle();

					i_widget.setActiveLanguage();
				}

				ip2.waitMask.hide();
			});
		}

		ip2.waitMask.hide();
		/*


			if ( i_widget.dataParent.action == 'new' ) {

				ip2.waitMask.hide();

				this.createPickerWindow();
			}
			else {

				// Something else to do here!
				i_widget.loadLanguageData(function (o_value) {

					// This is a new one
					if ( !Ext.Object.getSize(o_value) ) {
						
						ip2.waitMask.hide();
						
						i_widget.createPickerWindow();
					}
					else {
						
						var n_collection,
							s_defaultLanguage = i_widget.defaultLanguage,
							s_idProperty = i_widget.xpdObject.idProperty;

						n_collection = o_value[s_defaultLanguage][s_idProperty];

						i_widget.createI18nXpdField(o_value);

						i_widget.createBoundWidgets(n_collection);

						i_widget.updateTitle();

						ip2.waitMask.hide();
					}
				});
			}
		*/
	},

	/*
		hasCollectionId: function (o_value) {

			var i_widget = this;
			var n_id;
			var s_idProperty = i_widget.xpdObject.idProperty;

			ip2.each(o_value, function (o_lang) {
				if ( o_lang[s_idProperty] != null && !n_id ) {
					n_id = o_lang[s_idProperty];
				}
			});

			return n_id;
		},
	*/

	setActiveLanguage: function (s_lang) {

		s_lang || (s_lang=this.getCurrentLanguage());

		var i_cmp = this;
		var i_parent = i_cmp.dataParent;
		var i_toolbar = i_parent.down('toolbar');
		var i_flag = i_toolbar.down('#flag');
		var s_class = 'AIL-icon AIL-icon-24 icon-flag_'+s_lang;

		if ( !i_flag ) {
			i_cmp.items.items[0].items.items[0].on({
				'tabchange': {
					fn: function (i_self, i_tab) {
						var s_lang = i_tab.language;
						i_cmp.setActiveLanguage(s_lang)
					}
				}
			});
		}
		else {
			i_flag.destroy();
		}

		i_flag = Ext.widget('tbitem', {
			itemId: 'flag',
			height: 18,
			width: 23,
			style: 'margin-left: 5px;',
			cls: s_class,
			language: s_lang
		});
		i_toolbar.insert(0, i_flag);
	},

	getCurrentLanguage: function () {

		return this.items.items[0].items.items[0].getActiveTab().language;
	},

	collectionSelect: function () {

		var i_cmp = this;
		var o_flat = i_cmp.xpdFlattened;
		var s_idProp = i_cmp.xpdObject.idProperty;

		// If only 1 collection in here, then there is no need for the picker!
		var n_count = 0;
		var n_collection = 0;
		Ext.Object.each(o_flat.collections, function (s_key, o_collection) {
			if ( s_key != 'all' ) {
				n_count++;
				n_collection = o_collection.id;
			}
		});

		if ( n_count == 1 ) {

			var o_value = {};
			o_value[i_cmp.defaultLanguage] = {};
			o_value[i_cmp.defaultLanguage][s_idProp] = n_collection;
			
			i_cmp.createI18nXpdField(o_value);
			
			i_cmp.createBoundWidgets(n_collection);

			i_cmp.updateTitle();
		}
		else {
			var i_window = i_cmp.createPickerWindow();
			i_window.show();
		}
	},

	/*createPickerWindow: function() {

		var i_cmp = this;
		var i_pickerWindow = i_cmp.drawPickerWindow();
		
		i_pickerWindow.show();

		i_pickerWindow.down('#ok').on('click', function () {

			var o_pickerValue = i_pickerWindow.down('#collectionForm').getValues();

			var o_value = {},
				s_defaultLanguage = i_cmp.defaultLanguage,
				n_collection;

			o_value[s_defaultLanguage] = o_pickerValue;
			n_collection = o_pickerValue[i_cmp.xpdObject.idProperty];
			
			i_cmp.createI18nXpdField(o_value);
			
			i_cmp.createBoundWidgets(n_collection);

			i_cmp.updateTitle();

			i_pickerWindow.destroy();
		});
		
		i_pickerWindow.down('#cancel').on('click', function () {

			i_pickerWindow.close();

			i_cmp.dataParent.close();
		});
	},*/

	createForm: function (i_window) {

		var i_cmp = this;
		var i_form = i_window.down('#collectionForm');
		var o_values = i_form.getValues();
		var s_idProperty = i_cmp.xpdObject.idProperty;
		var o_value = {};
		var n_collection;

		o_value[i_cmp.defaultLanguage] = o_values;
		n_collection = o_values[s_idProperty];

		i_cmp.createI18nXpdField(o_value);
		i_cmp.createBoundWidgets(n_collection);
		i_cmp.updateTitle();

		i_window.destroy();
	},
	cancelForm: function (i_window) {
		var i_cmp = this;
		i_window.close();
		i_cmp.dataParent.close();
	},

	createPickerWindow: function () {

		var i_cmp = this;

		var i_picker = Ext.create('Ext.ux.form.field.QuickCombo', {
			name: i_cmp.xpdObject.idProperty,
			hideLabel: true,
			itemId: 'collectionPicker',
			minWidth: 400,
			anchor: '100%',
			style: 'margin-top: 10px',
			fields: ['id', 'title'],
			valueField: 'id',
			displayField: 'title',
			forceSelection: true,
			typeAhead: true,
			minChars: 1,
			data: i_cmp.collectionData,
			listeners: {
				afterrender: function (i_self) {
					var i_first = i_self.getStore().getAt(0);                     
					i_self.setValue(i_first.get('id'));
					i_self.focus(false, 200);
				},
				specialkey: function(i_self, i_event){

					var s_key = i_event.getKey();
					var i_window = i_self.up('#pickerWindow');

					if ( s_key == i_event.ENTER ) {
						if ( !i_self.isExpanded ) {
							i_cmp.createForm(i_window);
						}
					}
					if ( i_event.getKey() == i_event.ESC ) {
						i_cmp.cancelForm(i_window);
					}
				}
			}
		});

		var i_window = Ext.create('Ext.window.Window', {
			title: ip2.i18n({
				da: 'Vælg type',
				en: 'Choose Type'
			}),
			modal: true,
			closable: false,
			layout: 'fit',
			itemId: 'pickerWindow',
			items: [
				{
					xtype: 'form',
					itemId: 'collectionForm',
					bodyPadding: '20px 20px 30px 20px',
					layout: 'anchor',
					items: [
						{
							xtype: 'label',
							text: ip2.i18n({
								da: 'Vælg hvilken type du ønsker at oprette',
								en: 'Choose which type to create'
							})
						},
						i_picker,
						{
							xtype: 'checkbox',
							labelWidth: 110,
							name: '__tr__',
							inputValue: true,
							uncheckedValue: false,
							fieldLabel: ip2.i18n({
								da: 'Synkroniser indhold',
								en: 'Sync content'
							}),
							boxLabel: ip2.i18n({
								da: 'Tekstuel indhold undtaget',
								en: 'Textual content excepted'
							}),
							checked: true,
							hidden: true
						}
					]
				}
			],
			buttons: [
				{
					text: ip2.i18n({
						da: 'Opret',
						en: 'Create'
					}),
					itemId: 'ok',
					handler: function () {
						var i_self = this;
						var i_window = i_self.up('#pickerWindow');
						i_cmp.createForm(i_window);
					}
				},
				{
					text: ip2.i18n({
						da: 'Annuller',
						en: 'Cancel'
					}),
					itemId: 'cancel',
					handler: function () {
						var i_self = this;
						var i_window = i_self.up('#pickerWindow');
						i_cmp.cancelForm(i_window);
					}
				}
			]
		});

		return i_window;
	},
	createI18nXpdField: function (o_values) {

		var i_widget = this;
		var a_languages = i_widget.languages;
		var s_defaultLanguage = i_widget.defaultLanguage;
		var s_value = '';
		var i_field;

		// Add collection ID to widget
		i_widget.collectionId = o_values[s_defaultLanguage][i_widget.xpdObject.idProperty];

		// Sanitize the value
		// TODO: Gather all the sanitizing here
		try {
			s_value = ip2.JSON.stringify(o_values);
		}
		catch (e) {}

		i_field = Ext.create('Ext.ux.xpd.I18nField', {
			name: i_widget.widgetConfig.propertyKey,
			margin: 0,
			xpd: i_widget.widgetConfig.xpd,
			defaultLanguage: s_defaultLanguage,
			languages: a_languages,
			value: s_value,
			dataParent: i_widget.dataParent,
			itemId: 'i18nField'
		});

		i_widget.add(i_field);

		i_widget.form = i_field;
		i_widget.xpdField = i_field;

		i_field.items.getAt(0).setActiveTab(0);

		// Create the translate button
		i_widget.createTranslateButton();

		return i_field;
	},
	createTranslateButton: function () {

		var i_cmp = this;
		var a_translate = i_cmp.getTranslateMap();
		var b_translate = a_translate.length ? true : false;

		if ( b_translate ) {
			
			var i_toolbar = i_cmp.up('entityform').down('toolbar');
			
			i_toolbar.add(['-', {
				xtype: 'themedbutton',
				icon: 'close',
				text: ip2.i18n({
					da: 'Oversæt',
					en: 'Translate'
				}),
				handler: function () {
					
					// Find currently chosen language via tab
					var i_field = i_cmp.down('#i18nField');
					var i_current = i_field.down('tabpanel').getActiveTab();
					var s_to = i_current.language;

					// Gather data from translate map
					var s_value = i_field.getValue();
					var o_value = JSON.parse(s_value);

					var o_translate = ip2.pick(o_value[s_to], a_translate);
					//o_translate = i_cmp.translateHotFix(o_translate);

					ip2.waitMask.show();
					
					i_cmp.translate(o_translate, s_to, function (o_translated) {
						
						var o_apply = o_value[s_to];

						ip2.extend(o_apply, o_translated);

						o_value[s_to] = o_apply;

						i_field.setValue(JSON.stringify(o_value))

						ip2.waitMask.hide();
					});
				}
			}]);
		}
	},
	translateHotFix: function (o_value) {

		var json = JSON.stringify(o_value);
		
		json
			.replace(/[\u2000-\u200f\u2028-\u202f\u205f\u2060\u206a-\u206f\u0000]/g, '')
			.replace(/(?![ÆØÅæøå])[\u007f-\uffff]/g, function(c) {
				return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
			});

		return JSON.parse(json);
	},
	translate: function (o_value, s_lang, f_callback) {

		f_callback || (f_callback=Ext.emptyFn);

		Ext.Ajax.request({
			url: '/ip2-services/translateData.aspx',
			params: {
				data: JSON.stringify(o_value),
				to: s_lang
			},
			success: function (o_resp) {
				var o_translated = JSON.parse(o_resp.responseText);
				f_callback(o_translated);
			},
			failure: function (o_resp) {

			}
		});
	},
	createBoundWidgets: function (n_collection) {

		var i_cmp = this,
			o_xpd = i_cmp.xpdObject,
			o_flattened = i_cmp.xpdFlattened,
			s_idProperty = o_xpd.idProperty,
			o_widgetConfig = i_cmp.widgetConfig.widgets,
			i_parent = i_cmp.up().up();

		var o_collection = o_flattened.collections[n_collection];

		ip2.each(o_collection.widgets, function (o_widget) {

			var o_config = o_widgetConfig[o_widget.name],
				o_settings;

			Ext.Object.merge(o_config, o_widget);

			o_config.action = i_cmp.widgetConfig.action;

			o_settings = {
				xtype: 'ip2widgetcontainer',
				title: ip2.i18n(o_config.title),
				itemId: o_widget.name,
				src: o_config.path,
				border: false,
				layout: 'fit',
				dataParent: i_cmp.dataParent,
				_config: o_config
			};

			var n_id = o_widget.id || n_collection,
				o_value = {};

			o_value[s_idProperty] = n_id;
			o_settings.value = o_value;

			var i_bound = i_parent.add(o_settings);

			i_cmp.boundWidgets.push(i_bound);
		});
	},

	preventErrorMark: function (b_prevent) {

		var i_widget = this;
		var o_controllers = i_widget.xpdField.languageControllers;

		Ext.Object.each(o_controllers, function (s_key, i_controller) {

			var i_field = i_controller.getField();
			if ( i_field ) {
				i_field.preventMark = b_prevent;
			}
		});
	},

	getTranslateMap: function () {

		var i_cmp = this;
		var i_i18nField = i_cmp.xpdField;

		var i_xpdField = (function () {
			var i_found;
			i_cmp.xpdField.items.getAt(0).items.each(function (i_tab) {
				if ( i_tab.down('#xpdfield') ) {
					i_found = i_tab;
				}
			});
			return i_found;
		})();

		var a_map = [];

		ip2.each(i_xpdField.xpdFields, function (i_field) {
			if ( i_field.translate ) {
				a_map.push(i_field.name);
			}
		});

		return a_map;
	},

	getKeys: function (s_language) {

		var i_cmp = this,
			i_dataParent = i_cmp.dataParent,
			o_parentKeys = i_dataParent.getKeys(),
			o_keys = {};

		if ( Ext.isString(o_parentKeys) ) {
			o_parentKeys = ip2.JSON.parse(o_parentKeys);
		}

		o_keys[i_cmp.widgetConfig.relationKey] = o_parentKeys[i_cmp.widgetConfig.fieldKey];

		if ( s_language ) {
			o_keys[i_cmp.widgetConfig.foreignKey] = s_language;
		}

		return o_keys;
	},
	isDirty: function() {

		var i_cmp = this,
			i_xpd = i_cmp.xpdField,
			b_dirty;

		b_dirty = i_xpd ? i_xpd.isDirty() : false;

		return b_dirty;
	},

	doSave: function(f_callback) {

		ip2.waitMask.show();

		var i_cmp = this;
			
		i_cmp.saveLanguageData(function () {

			i_cmp.xpdField.resetOriginalValue();

			var o_values = JSON.parse(i_cmp.xpdField.getValue());

			i_cmp.updateDataParent(o_values);

			Ext.Array.forEach(i_cmp.boundWidgets, function (i_bound) {

				var i_widget = i_bound.getWidgetComponent();

				i_widget.doSave && i_widget.doSave();
			});

			i_cmp.updateTitle();

			ip2.waitMask.hide();

			f_callback && f_callback();
		});
	},
	doDelete: function(f_callback) {

		var i_cmp = this,
			i_form = i_cmp.form;

		i_form.on({
			'xpddestroy': {
				fn: function () {
					f_callback && f_callback();
				},
				single: true
			}
		});

		i_cmp.xpdForm.xpdDelete();
	},

	getLanguages: function () {

		/*

			var i_cmp = this;
			var i_parent = i_cmp.dataParent;
			var i_record = i_parent.getRecord();
			var o_model = ip2.getModelFromRecord(i_record);
			var o_languages = o_model.languages;
			var a_languages = [];

			Ext.Object.each(o_languages, function (s_language) {
				a_languages.push(s_language);
			});

			return a_languages;

		*/

		var i_cmp = this;
		var a_languages = wsh.i18n.getAll();

		return a_languages;
	},
	getPrimaryLanguage: function () {

		var i_cmp = this;
		var s_primary = wsh.i18n.getPrimary();

		return s_primary;
	},
	
	loadLanguageData: function (f_callback) {

		var i_cmp = this,
			o_payload;

		o_payload = {
			transaction: {
				dmd: ip2.resource.getFullPath(i_cmp.widgetConfig.dmd),
				batch: (function () {

					var a_batch = [];
					var a_languages = i_cmp.getLanguages();
					
					ip2.each(a_languages, function (s_language) {

						var o_keys = i_cmp.getKeys(s_language);

						a_batch.push({
							type: 'get',
							entity: i_cmp.widgetConfig.entity,
							uiName: i_cmp.widgetConfig.view,
							context: 'form',
							fullresponse: true,
							key: o_keys
						});
					});

					return a_batch;
				})()
			}
		};

		var s_url = '/wsh-services/services/ip2dmdProxy.aspx',
			s_payload = ip2.JSON.stringify(o_payload);

		s_url += '?action=transaction&payload='+s_payload;

		Ext.Ajax.request({
			url: s_url,
			success: function (o_transaction) {
				
				var o_response = ip2.JSON.parse(o_transaction.responseText),
					o_value = {};

				ip2.each(o_response.batch, function (o_batch) {

					if ( o_batch.rows.length ) {

						var o_data = o_batch.rows[0],
							s_language = o_data[i_cmp.widgetConfig.foreignKey],
							s_property = o_data[i_cmp.widgetConfig.propertyKey],
							o_property = ip2.JSON.parse(s_property);

						o_value[s_language] = o_property;
					}
				});

				f_callback(o_value);
			}
		});

		return i_cmp;
	},
	saveLanguageData: function (f_callback) {

		f_callback || (f_callback=Ext.emptyFn);

		var i_cmp = this,
			i_field = i_cmp.xpdField,
			s_values = i_field.getValue(),
			o_values;

		o_values = JSON.parse(s_values);

		var s_dmd = ip2.resource.getFullPath(i_cmp.widgetConfig.dmd);

		var o_payload = {
			transaction: {
				dmd: s_dmd,
				batch: (function () {

					var a_batch = [];
					
					ip2.each(o_values, function (o_value, s_key) {
						
						var s_language = s_key.toLowerCase(),
							o_keys = i_cmp.getKeys(s_language),
							o_payload = {},
							s_property = i_cmp.widgetConfig.propertyKey;

						o_payload[s_property] = ip2.JSON.stringify(o_value);

						a_batch.push({
							type: 'upsert',
							entity: i_cmp.widgetConfig.entity,
							key: o_keys,
							row: o_payload
						});
					});

					return a_batch;
				})()
			}
		};

		var s_url = '/wsh-services/services/ip2dmdProxy.aspx',
			s_payload = ip2.JSON.stringify(o_payload);

		Ext.Ajax.request({
			url: s_url,
			method: 'POST',
			params: {
				payload: s_payload
			},
			success: function (o_transaction) {
				
				var o_response = ip2.JSON.parse(o_transaction.responseText);

				f_callback();
			}
		});
	},

	updateTitle: function () {

		var i_cmp = this;
		var i_dataParent = i_cmp.dataParent;
		var s_defaultLanguage = i_cmp.defaultLanguage;

		var a_title = [];

		if ( i_dataParent.action == 'new' ) {
			a_title.push(ip2.i18n({
				da: 'Opretter:',
				en: 'Creating:'
			}));
		}

		// Get the collection type name
		var s_value = i_cmp.xpdField.getValue();
		var o_value = JSON.parse(s_value);
		var n_id;

		// Get the default language value to get values from
		o_value = o_value[s_defaultLanguage];
		
		// Get the id of the collection so we can get collection title
		n_id = o_value[i_cmp.xpdObject.idProperty];
		var o_collection = i_cmp.xpdFlattened.collections[n_id];
		var s_collection = ip2.xpd.translate(i_cmp.xpdObject, o_collection.title);
		a_title.push(s_collection);

		var b_allow = true;

		if ( i_dataParent.action == 'update' ) {
			a_title.push(':');

			var s_titleField = i_cmp.xpdObject.titleField || 'title';
			var s_titleValue = o_value[s_titleField];

			if ( s_titleValue ) {
				a_title.push(o_value[s_titleField]);
			}
			else {
				b_allow = false;
			}
		}

		if ( b_allow ) {
			i_dataParent.setTitle(a_title.join(' '));
		}
	},
	updateDataParent: function (o_values) {

		var i_cmp = this,
			o_config = i_cmp.widgetConfig,
			i_form = i_cmp.dataParent,
			s_prop = o_config.propertyKey;

		var o_info = i_form.dmdInfo;
		var i_grid = i_form.dataParent.grid;

		if ( o_info.view.parentRefresh ) {
			i_grid.store.load();			
		}
		else {

			// Get the ID of the grid row by immediate dataParents record
			var n_id = (function () {
				var i_record = i_cmp.dataParent.getRecord();
				return i_record.getId();
			})();

			// Get the relevant parent variables, grid, store and record
			var i_store = i_grid.getStore();
			var i_record = i_store.getById(n_id);

			if ( !i_record ) return;

			// Get the language we are using to view values
			var s_lang = ip2.session.getLanguage();
			// Get the language based values to use for updating the grid
			o_values = o_values[s_lang];

			// HARDCODED LEAVE ALONE VALUES
			var a_ignore = ['webactive'];

			// Itereate each value and check if grid has a column matching to update
			Ext.Object.each(o_values, function (s_key, value) {

				// Is this field represented in the grid columns?
				var s_name = [
					s_prop.toUpperCase(),
					s_key.toUpperCase()
				].join('_');

				// If this field is represented in grid, and is not to be ignored
				// then we update the grid record field
				if ( i_record.data[s_name] != null && Ext.Array.indexOf(a_ignore, s_key)) {
					i_record.set(s_name, value);
				} 
			});
		}
	}
}