Ext.namespace('fcbm.component');

fcbm.component.List = function (config) {
	
	/*
	 * Public
	 */	
	return {
		
		initialConfig: Ext.apply(config),
		
		/*
		 * addListItem
		 * 
		 * L'utilisateur choisi un �l�ment
		 * 
		 */
    	addListItem: function() {
        	var grid1 = Ext.getCmp('grid-list');
			var grid2 = Ext.getCmp('grid-selList');
			
			if (grid1.getSelectionModel().getSelected() == null)
				return;
			
			var sel = grid1.getSelectionModel().getSelected();
			var selId = grid1.getSelectionModel().getSelected().id;
			var record = grid1.getStore().getById(selId);
				
			// item unique/special
			if (parseInt(record.data.isUnique) == 1) {
				grid2.getStore().removeAll();
				grid2.getStore().add(record);
			}
			else {
				if (grid2.getStore().getCount() > 0) {
					if (parseInt(grid2.getStore().getAt(0).data.isUnique) == 1) {
						// Item unique => on n'ajoute plus
						return;
					}
				}
				if (parseInt(this.maxSel) == grid2.getStore().getCount()) {
					Ext.MessageBox.show({
						title: "Erreur",
						minWidth: 300,
						msg: "D�sol�, vous avez d�j� atteint le maximum de r�ponses.",
						buttons: Ext.Msg.OK,
						icon: Ext.MessageBox.ERROR
					});
				}
				else {
					var ok = true;
					// item existant
					if (grid2.getStore().getById(selId) != null)
						ok = false;
					// synonyme deja present
					
					var synoFound = false;
					grid2.getStore().each (function(r) {
						if (parseInt(r.get('idSynonyme')) == parseInt(sel.data.id) || parseInt(sel.data.idSynonyme) == parseInt(r.get('id'))) {
							synoFound = true;
							return false;
						}
					}, {synoFound: synoFound});
					
					if (!ok || synoFound) {
						Ext.MessageBox.show({
							title: "Erreur",
							minWidth: 300,
							msg: "Cet item ou un synonyme a d�j� �t� s�lectionn�.",
							buttons: Ext.Msg.OK,
							icon: Ext.MessageBox.ERROR
						});
					}
					else {
						grid2.getStore().add(record);
					}
				}
			}	
    	},

	 	/*
		 * removeListItem
		 * 
		 * L'utilisateur choisi de retirer un �l�ment de la liste des choix
		 */
		removeListItem: function () {
			var grid1 = Ext.getCmp('grid-list');
			var grid2 = Ext.getCmp('grid-selList');
			var sel = grid2.getSelectionModel().getSelected();
			
			if (sel == null)
				return;
			
			grid2.getStore().remove(grid2.getStore().getById(sel.id));
		},
		
		/*
		 * Show function
		 */
		show: function () {
			var win = Ext.getCmp(this.initialConfig.id);
			if (win != null) {
				win.center();
				return;
			}
			
			var ds = new Ext.data.Store({
				proxy: new Ext.data.MemoryProxy([]),
			    reader: new Ext.data.ArrayReader({}, [{name: 'id'},{name: 'desc'},{name: 'isUnique'},{name: 'idSynonyme'},{name: 'idCat'},{name: 'descCat'}])
			});
			ds.load();
			
			var window_liste = new Ext.Window({
					title: this.initialConfig.title,
					id: this.initialConfig.id,
					closable: true,
					width: listWidth,
					height: listHeight,
					resizable: true,
					modal:true,
					items: [{
							/*
							 * Grid pr�sentant les choix
							 */
							xtype: 'grid',
							id: 'grid-list',
							width: '100%',
							height: listHeight - 240,
							stripeRows: true,
							border: false,
							hideHeaders: true,
							autoScroll: true,
							autoExpandColumn: 'descItem',
							store: eval(this.initialConfig.list).toDataStore(this.initialConfig.forceCategoryNameTo),
							view: new Ext.grid.GroupingView({
								emptyGroupText: 'Autres r�ponses',
								emptyText: ' ',
								showGroupName: false,
								startCollapsed: true
							}),
							columns: [{
								header: this.initialConfig.itemName,
								id: 'descItem',
								menuDisabled: true,
								dataIndex: 'desc',
								sortable: false
							}, {
								header: "Categorie",
								id: 'descCat',
								menuDisabled: true,
								dataIndex: 'descCat',
								sortable: false,
								hidden: true,
								groupRenderer: function (v, unused, r, rowIndex, colIndex, ds) {
									if (v == 'ZZZ')
										return '';
									else
										return v;
								}
							}
						]},
						{
							/*
							 * Panel des boutons ajouter/retirer choix
							 */
							xtype: 'panel',
							title: 'S�lection ('+eval(this.initialConfig.list).maxSel+' maximum) :',
							header: true,
							frame: false,
							tools: [{
								id: 'down',
								scope: eval(this.initialConfig.list),
								handler: this.addListItem
							},
							{
								id: 'up',
								scope: eval(this.initialConfig.list),
								handler: this.removeListItem
							}]
						},
						{
							/*
							 * Grid des choix s�lectionn�s
							 */
							xtype: 'grid',
							id: 'grid-selList',
							width: '100%',
							height: 130,
							stripeRows: true,
							hideHeaders: true,
							autoScroll: true,
							autoExpandColumn: 'descItem',
							store: ds,
							columns: [{
								header: this.initialConfig.itemName,
								id: 'descItem',
								menuDisabled: true,
								dataIndex: 'desc',
								sortable: false
							}, {
								header: "Categorie",
								id: 'descCat',
								menuDisabled: true,
								dataIndex: 'descCat',
								sortable: false,
								hidden: true
							}
						]
							
						},
						{
							/*
							 * Panel des boutons Ok/Annuler
							 */
							xtype: 'panel',
							header: false,
							border: false,
							frame: false,
							layout: 'column',
							items: [
								{
									xtype: 'panel',
									columnWidth: .5,
									header: false,
									frame: false,
									items: [{
										xtype: 'button',
										text: 'Ok',
										cls: 'float-right',
										scope: {initialConfig: this.initialConfig},
										handler: function() {
											var storeSrc = Ext.getCmp('grid-selList').getStore();
											var storeDest = Ext.getCmp(this.initialConfig.gridId).getStore();
											storeDest.removeAll();
											eval('document.currentFile.document.reponse.' + this.initialConfig.type + ' = [];');
											storeSrc.each(function (r) {
												this.storeDest.add(r);
												eval('document.currentFile.document.reponse.' + this.type).push(r.get('id'));
											}, {storeDest: storeDest, type: this.initialConfig.type});
											Ext.getCmp(this.initialConfig.id).close();
										}
									}]
								},
								{
									xtype: 'panel',
									columnWidth: .5,
									header: false,
									frame:false,
									items: [{
										xtype: 'button',
										text: 'Annuler',
										scope: {initialConfig: this.initialConfig},
										handler: function () {
											Ext.getCmp(this.initialConfig.id).close();
										}
									}]
								}
							]
						}
					]
				});
			
		
			/*
			 * Ajout d'�venements
			 */
			Ext.getCmp('grid-list').on('dblclick', this.addListItem, eval(config.list));
			Ext.getCmp('grid-selList').on('dblclick', this.removeListItem, eval(config.list));
			Ext.getCmp('grid-list').on('render', function(){
				// D�plie le premier groupe automatiquement
				var gv = this.initialConfig.view;
				if (gv.getGroups() != null && gv.getGroups().length > 0) {
					gv.toggleGroup(gv.getGroups()[0].id);
				}
			});
			window_liste.show();
			window_liste.on('resize', function (win, w, h) {
				this.doLayout();
				Ext.getCmp('grid-list').setWidth(w-18);
				Ext.getCmp('grid-selList').setWidth(w-18)
			}, window_liste);
			
			this.extCmp = window_liste;
			
			/*
			 * R�cup�ration de la liste des �l�ments d�j� s�lectionn�s
			 */
			var storeSrc = Ext.getCmp(this.initialConfig.gridId).getStore();
			var storeDest = Ext.getCmp('grid-selList').getStore();
			storeSrc.each(function (r) {
				this.add(r);
			}, storeDest);
			
		},

	    // Make this class usable by a Container, so that we can add and remove it.
	    // Create delegates in the scope of our contained Panel which reference Panel's methods
	    render: Ext.Window.prototype.render.createDelegate(this.extCmp),
	    destroy: Ext.Window.prototype.destroy.createDelegate(this.extCmp)
	};

}

