<?php

include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_tree.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_form.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");
include_once(PATH_TO_ROOT."config.php");

$tabId = $_POST['uniqueTabId'];
$tableName = '_InterviewerStructure';

//the stores for the both comboboxes (they're used in grid and forms)
$storeDataType = $tabId.'_dataTypeStore';
$storeFieldType = $tabId.'_dataFieldStore';

$tree = new MakeTree($tabId.'_tree');
$treeName = $tree->getName();

//the grid to show all the fields
$fieldGrid = new MakeGrid($tabId.'_fieldGrid');
$fieldGName = $fieldGrid->getName();

$tree->SetTable($tableName,DB_WARPIT_USERSPOOL);
$tree->SetRootVisible('true','Fields')
	->setWidth('300')
	->setEditable()
;
$tree->setTextPadding('1px');
$tree
	->addConfig('region',"'west'")
	->activateDD()
	->setReqUrl('webuserspool/_ajax/ajax.fieldEdit.php')
	//the context function for adding fields
		->addContItem('Add Field'," function(item) {
		 if(item)
				n = item.parentMenu.contextNode;
			else
				{
					n = $tree.getSelectionModel().getSelectedNode();
					if(!n)
						n = $tree.getRootNode();
					
				}
		//we open a window to get field name and question type
		new Ext.Window({title:'Add Field',modal:true,width:'280px',
		items:{
		xtype:'form', buttonAlign:'center',
		frame:true,
		items: [
		//textfield with filter for questions (start with letter, only numbers and letterz )
		{xtype:'textfield',id:'wupAddPrompt' , fieldLabel:'Field name',vtype:'questionName',width: 140,allowBlank:false},
		//a combobox taken from the grid, with question types
		{xtype:'combo',id:'wcbqComboPrompt', store: $storeDataType ,fieldLabel:'Data type',displayField:'displayText',mode:'local',
		triggerAction:'all',width: 140,valueField:'myId',editable:false}
		]//eof form items
		 ,
		keys: [{
               key: [Ext.EventObject.ENTER], fn: function(){
                   Ext.getCmp('promptOKBtn').fireEvent('click');
               }
      		 }],
		buttons:[{text:'Ok',id:'promptOKBtn',listeners:{
		click: function(){ 
			var text = Ext.getCmp('wupAddPrompt').getValue();
			if(Ext.getCmp('wupAddPrompt').isValid()   )
			{	
				var par;
				//if we clicked on a question or a closed group we add it to its parent one position lower otherwise to the clicked group
				var closed = !n.isExpanded();
				if(n.attributes.leaf==true || closed)
				{par = n.parentNode; }
				 else {par = n;}
				 //we make a server requst to handle insertQuestion
				 //we send the parent node ID the text and type
		         $treeName.RMconn.request({params:{
		         action:'insertField',
		         parId:par.id,
		         nodeText:text,
		         nodeType:Ext.getCmp('wcbqComboPrompt').getValue(),
		         nodeId:n.attributes.id , closed:closed,
		         isTargetF:n.attributes.leaf ? 1 : 0 } 
				,success:function(resp){
				if(Ext.decode(resp.responseText).success){
					//if adding was succesful we refresh the parent and open the location
					//NOTE: all other groups get closed
					var p = par.getPath()+'/'+Ext.decode(resp.responseText).insertId;
					$treeName.getLoader().load($treeName.getRootNode(),function(){ $treeName.selectPath(p); } );
					$fieldGName.getStore().reload();
					Ext.getCmp('wupAddPrompt').findParentByType('window').close();
				} else{//else we display a warning and focus on the name field
				Ext.Msg.alert('Warning!',Ext.decode(resp.responseText).error );
				Ext.getCmp('wupAddPrompt').focus()}},
					
				failure:function(){alert('failed');}	});    
				
			}
		}
	}
			  },
		{
		text:'Cancel',handler:function(){ 
		this.findParentByType('window').close();
	
		 }
		 }
			  ] },
	defaultButton:'wupAddPrompt'
			   } ).show(n); 
		//we set the combobox value on the first item
		Ext.getCmp('wcbqComboPrompt').setValue(0); 
					    }" //eof handler
			  ,'false','icon-add-record' ,2)
			  
	//context function for adding groups	
		->addContItem('Add Group',"function(item){ 
		Ext.Msg.prompt('Add Group','Group name:',function(btn,text){ if(btn == 'ok' ){
		 if(item)
				n = item.parentMenu.contextNode;
			else
				{
					n = $tree.getSelectionModel().getSelectedNode();
					if(!n)
						n = $tree.getRootNode();
					
				}
		var par;
		//the group gets added after the clicked node
		var closed = !n.isExpanded();
		if(n.attributes.leaf == true || closed )
			{par = n.parentNode; } 
		else{ par = n;   }
		$treeName.RMconn.request({params:{
		action:'insertGroup',nodeText:text,
		parId:par.id,nodeId:n.id , closed:closed
		,isTargetF:n.attributes.leaf ? 1 : 0 },success:function(resp){
		if(Ext.decode(resp.responseText).success){ 
		$treeName.getLoader().load($treeName.getRootNode(),function(){ $treeName.getRootNode().expand();});  
		}
		 }  }); }  } );   }",'false','icon-add-folder',2)

	->addContItem('Rename',"function(item){
		  if(item)
							n = item.parentMenu.contextNode;
			else
				{
					n = $tree.getSelectionModel().getSelectedNode();
					if(!n)
						n = $tree.getRootNode();
					if(n.attributes.leaf == 1) return;
				}
		 {$treeName}.treeEditor.triggerEdit(n);
		 }","node.attributes.leaf == 1",'RMicon_edit_record',2)
		 
	->addContItem('Delete',"function(item){
		  if(item)
							n = item.parentMenu.contextNode;
			else
				{
					n = $tree.getSelectionModel().getSelectedNode();
					if(!n)
						n = $tree.getRootNode();
					if(n,hasChildNodes()) return;
				}
		
		 Ext.Msg.show({ title:'Remove record',buttons: Ext.MessageBox.YESNO,msg: 'Are you sure?',
		fn: function(btn){if(btn == 'yes'){
			$treeName.RMconn.request({params:{
			action:'delete',
			nodeId:n.id,isTargetF:n.attributes.leaf ? 1 : 0,
			nodeText:n.text
			},success:function(resp){
			if(Ext.decode(resp.responseText).success){
			n.parentNode.select();
			n.remove();
			var pm = Ext.getCmp('PoolMenu');
			if(pm)
			{
				pm.getNodeById('4').reload();
			}
			//$fieldGName.getStore().reload(); 
			 }
			 }  }); 
		  }} });
		 }"
		 ,"node.hasChildNodes()",'icon_red_delete',2)
	
	->baseParams = "nameField : 'field_name',uneditable:'leaf'"
;
	 
	
	$fieldGrid->setMainTable($tableName,DB_WARPIT_USERSPOOL);
	$fieldGrid->baseParams = "SQLwhere : 'is_leaf = 1',sort:'b.orderBy' ";
	
	$fieldGrid->selectSQL = "SELECT a.id,b.id AS id_order,a.field_name,a.data_type,field_text,field_type,is_hidden FROM _InterviewerStructure as a INNER JOIN _InterviewerFieldOrder as b ON a.id = b.field_id AND b.user_id = 0";
	
	$fieldGrid->addColumn('id');
	$fieldGrid->addColumn('id_order');
	$fieldGrid->addColumn('field_name','Variable name');
	$fieldGrid->addColumn('data_type','Variable type')->renderer("function(val){
		var idx =$storeDataType.find('myId', val);
		if(idx==-1)	return 'Select';
		var rec = $storeDataType.getAt(idx);
		return rec.get('displayText');
	}"  );
	$fieldGrid->addColumn('field_text','Display name','new Ext.form.TextField()');
	$fieldGrid->addColumn('field_type','Display type')->renderer("function(val){
		var idx =$storeFieldType.find('myId', val);
		if(idx==-1)	return 'Select';
		var rec = $storeFieldType.getAt(idx);
		return rec.get('displayText');
	}"  ) ;
	$fieldGrid->addColumn('is_hidden','Hidden')->type('checkColumn')->table('_InterviewerFieldOrder')->idField('id_order');
	
	//this is the form for setting base properties for each field
	$form = new MakeForm($tabId.'_form');
	$formName = $form->getName();
	
	$form->selectSQL = "SELECT a.id,a.field_name,a.data_type,field_text,field_type,is_hidden FROM _InterviewerStructure as a INNER JOIN _InterviewerFieldOrder as b ON a.id = b.field_id AND b.user_id = 0";
	
	
	//$form->setReqUrl('webcati/_forms/_ajax/ajax.buildQuestionnaire.php');
	$form->setMainTable($tableName,DB_WARPIT_USERSPOOL)
	->addConfig('padding','10')
	->addConfig('border','false')
	->addConfig('region',"'center'")
	->addConfig('labelAlign',"'right'")
	->addConfig('defaults','{ width: 250 }');
	//the trigger properties is added in for each when we add dragNdrop properties
	$form->addField('field_name','Variable name')
		//we turn off the defualt auto updato, to attach our own change listener
		->setAutoUpdate(false)->setProperty('vtype',"'questionName'")
		->addListener('change',"function(fld,val,oldVal){
				if(!fld.isValid())
				{
					Ext.Msg.alert('Warning','Not valid field name!');
					fld.setValue(oldVal);
				}
				Ext.Msg.RMconfirm({ title:'Change name',
				fn: function(btn){if(btn == 'yes'){
					
					var dataType = $formName.find('name','podatki[data_type]')[0];
					var fieldType = $formName.find('name','podatki[field_type]')[0];
					$treeName.RMconn.request({
					params:{ action:'updateName',field:fld.RMfieldName,
					dataType:dataType.getValue(),
					displayType : fieldType.getValue(),
					oldName:oldVal,
					 value: fld.getValue(),id: $formName.selectedId },
					success:function(r){
						var resp = Ext.decode( r.responseText );
						if(resp.success)
						{
							var node = $treeName.root.findChild('id',$formName.selectedId,true);
							node.setText(val);
						}
						else
						{
							Ext.Msg.alert('Warning!',resp.error );
								fld.setValue(oldVal);
						}
					}
					   });
					
					 }else //button no
					 	fld.setValue(oldVal);
					  }}); 
				 }" )
	;
	$comboArray = $configCombo['DataType'][$_SESSION['UserInfo']['lng_admin'] ]; 
	for ($i=0;$i< count($comboArray);$i++ )
	{
		$comboStr[] = "['$i','".$comboArray[$i]."']";
	}
	
	echo "var $storeDataType = new Ext.data.ArrayStore({
        fields: [
            'myId',
            'displayText'
        ],
        data: [".implode(',',$comboStr).  "]
	});";
	
	
	$form->addField('data_type','Variable type','combo')->setProperty('store',$storeDataType)
	->setProperty('valueField',"'myId'")
	->setProperty('displayField',"'displayText'")
	->setProperty('mode',"'local'")
	->setProperty('triggerAction',"'all'")
	->setAutoUpdate(false)
		->addListener('select',"function(fld){
			  	var val = fld.getValue();
			  	if(val == fld.startValue) return;
				Ext.Msg.show({ title:'Change type',buttons: Ext.MessageBox.YESNO,msg: 'Are you sure?',
				fn: function(btn){if(btn == 'yes'){
					
					var fldName = $formName.find('name','podatki[field_name]')[0].getValue();
					$treeName.RMconn.request({
					params:{ action:'updateName',field:fld.RMfieldName,
					fieldName:fldName,
					oldName:fldName,
					 value: fld.getValue(),id: $formName.selectedId },
					success:function(r){
						var resp = Ext.decode( r.responseText );
						if(resp.success)
						{
							fld.startValue = val;
						}
						else
						{
							Ext.Msg.alert('Warning!',resp.error );
								fld.setValue(fld.startValue);
						}
					}
					   });
					
					 }else //button no
					 	fld.setValue(fld.startValue);
					  }}); 
				 }" )
	;
	$form->addField('field_text','Display name')
	->setAutoUpdate(false)
	->addListener('change',"function(fld,val){
		if(val == '')
		{
			val = $formName.find('name','podatki[field_name]')[0].getValue();
			fld.setValue(val);
		}
		$form.RMconn.request({params:{
			action:'update',
			field: fld.RMfieldName,
			value:val,
			id: $form.selectedId
		}})
	}");
	
	$comboArray = $configCombo['FieldType'][$_SESSION['UserInfo']['lng_admin'] ]; 
	$comboStr = array();
	foreach ($comboArray as $key => $value) 
	{
		$comboStr[] = "['$key','".$value."']";
	}
	
	echo "var $storeFieldType = new Ext.data.ArrayStore({
        fields: [
            'myId',
            'displayText'
        ],
        data: [".implode(',',$comboStr). "]
	});";
	
	
	$form->addField('field_type','Display type','combo')->setProperty('store',$storeFieldType)
	->setProperty('valueField',"'myId'")
	->setProperty('displayField',"'displayText'")
	->setProperty('mode',"'local'")
	->setProperty('triggerAction',"'all'")
	->setAutoUpdate(false)
		->addListener('select',"function(fld,rec){
				
					var val = fld.getValue();
				  	if(val == fld.startValue) return;
				  	//in this cases we  have to delete some data, so we fire a warning!!!
					if( fld.startValue == 2 || (fld.startValue == 3 || fld.startValue == 4 ) && (val != 2 && val != 3 && val != 4 )  )
					{
						Ext.Msg.RMconfirm({msg:'This will delete field options!<br/>Are you sure?',
							fn:function(btn)
							{
								if(btn == 'yes')
								{
									var fldName = $formName.find('name','podatki[field_name]')[0].getValue();
									$treeName.RMconn.request({
									params:{ action:'updateDisplayType',field:fld.RMfieldName,fieldName:fldName,
									 value: fld.getValue(),oldVal:fld.startValue, id: $formName.selectedId },
									success:function(r){
										var resp = Ext.decode( r.responseText );
										if(resp.success)
										{
											$formName.switchType(fld.getValue());
											fld.startValue = val;
										}
										else
										{
											Ext.Msg.alert('Warning!',resp.error );
												fld.setValue(fld.startValue);
										}
									}
									   });
								}
								else //button no
					 				fld.setValue(fld.startValue);
					 		}
							
						});
						return;
					}
					else if (val == 2 && (fld.startValue == 3 || fld.startValue == 4 ))
					{  //we selected checkboxes and previously had combo/radio...we must create the extstra structure!
						var fldName = $formName.find('name','podatki[field_name]')[0].getValue();
									$treeName.RMconn.request({
									params:{ action:'updateDisplayType',field:fld.RMfieldName,fieldName:fldName,
									 value: fld.getValue(),oldVal:fld.startValue, id: $formName.selectedId },
									success:function(r){
										var resp = Ext.decode( r.responseText );
										if(resp.success)
										{
											$formName.switchType(fld.getValue());
											fld.startValue = val;
										}
										else
										{
											Ext.Msg.alert('Warning!',resp.error );
												fld.setValue(fld.startValue);
										}
									}
									   });
					return;
					}
					
					$formName.RMconn.request({
					params:{ action:'update',field:fld.RMfieldName,
					 value: fld.getValue(),id: $formName.selectedId },
					success:function(r){
						var resp = Ext.decode( r.responseText );
						if(resp.success)
						{
							$formName.switchType(fld.getValue());
							fld.startValue = val;
						}
						else
						{
							Ext.Msg.alert('Warning!',resp.error );
								fld.setValue(fld.startValue);
						}
					}
					   });
				 }" )
	;

	
	$form->addField('is_hidden','Hidden','checkbox')
	//special update becouse it is in another table!
	->setAutoUpdate(false)->addListener('change',"function(fld,val,oldVal){
		Ext.Ajax.request({ url:'_ajaxManipulators/formDataManipulator.php',
					params:{ action:'update',field:fld.RMfieldName,idField:'field_id',SQLwhere:'user_id = 0',RMtable:'_InterviewerFieldOrder',database:'".DB_WARPIT_USERSPOOL."',
					 value: fld.getValue(),id: $formName.selectedId },
					success:function(r){
						var resp = Ext.decode( r.responseText );
						if(!resp.success)
						
						{
							Ext.Msg.alert('Warning!',resp.error );
								fld.setValue(fld.startValue);
						}
					}
					   });
	}")
	;
	
	$form->setAutoUpdate()
		->setTitle('Title')
	;


	$grid = new MakeGrid($tabId.'_grid');
	$gridName = $grid->getName();
	
	//the combo for the languages in grids tbar
	$lngCombo = $tabId.'_lngCombo';
	
	echo "var $lngCombo = new Ext.form.ComboBox({
	width:80,hideMode:'offsets',store:new Ext.data.ArrayStore({fields: [
            'myId',
            'displayText'
        ],
        data:[[1,'Default']] }),valueField:'myId',displayField:'displayText',triggerAction:'all',mode:'local',
			listeners:{ afterrender:function(fld){fld.setValue(1); },
				select:function(){ 
				$gridName.getStore().reload({params:{ SQLwhere:'lab_field = '+ $formName.selectedId + ' AND language = '+$lngCombo.getValue() }  } );
				}
			 }
          });
          
    
          ";
	
	$grid->setMainTable('user_input_labels',DB_WARPIT_USERSPOOL);
	$grid->setReqUrl('webuserspool/_ajax/ajax.fieldEdit.php')
		//->addConfig('hideMode',"'offsets'")
		->baseParams = "sort:'lab_position'"
	;
	$grid->ignoreUpdate = "e.field == 'cb_checked'";
	
	$grid->addColumn('id');
	$grid->addColumn('lab_field')->defaultValue("\"+$formName.selectedId+\"");
	$grid->addColumn('language')->defaultValue("\"+$lngCombo.getValue() +\"");
	$grid->addColumn('lab_position')->defaultValue("\"+$gridName.getStore().getCount() +\"");
	$grid->addColumn('lab_code','Value','new Ext.form.NumberField()');
	$grid->addColumn('lab_label','Text','new Ext.form.TextField()');
	$grid->addColumn('cb_checked','Checked')->type('checkColumn')->hidden(true);
	
	$grid->activateAdd()
		->activateRemove()
		->addTbarItem("
		 { 
		 	text: 'copy/paste',
		 	 handler: function() {
		           	 	winPrilepi = new Ext.Window({
			                id:'IdPrilepi',
			                layout:'fit',
			                title: 'Copy/Paste',
			                width:300,
			                height:200,
			                closeAction:'close',
			                plain: true,
			                items: [
			               		new Ext.form.TextArea({
			               			id: 'importArea'
			               		})
			               		
			                ],
			                
			                bbar:[{
			                	text : 'Shrani',
			                	handler: function() {
			                		
			                		Ext.Ajax.request({
					       			url:'webuserspool/_ajax/ajax.fieldEdit.php',
					       				params: { action: 'import' ,
					       						  import_value : Ext.getCmp('importArea').getValue(),	
					       						  field: $formName.selectedId,
					       						  language: $lngCombo.getValue()			
					       						 
					       				},
										success : function(resp,opt){ 
												Ext.getCmp('IdPrilepi').close();
												$gridName.getStore().reload();
										}							  							
									})
			                	}
			                }]
			            }).show()
		           	 }
		 },'->',". $lngCombo .",'-'")
		->addExportButton()
		
		;
	
	//this is the form for setting base properties for each field
	$propForm = new MakeForm($tabId.'_Propform');
	$propName = $propForm->getName();
	//$form->setReqUrl('webcati/_forms/_ajax/ajax.buildQuestionnaire.php');
	$propForm->setMainTable($tableName,DB_WARPIT_USERSPOOL)
	->addConfig('padding','10')
	->addConfig('border','false')
	->setAutoUpdate(true)
	->addConfig('layoutConfig','{trackLabels:true}')
//	->addConfig('region',"'center'");
	;
	$propForm->addField('field_opt1','lenght','numberfield')->setProperty('anchor',"'95%'");
	$propForm->addField('field_defaultValue','lenght')->setProperty('anchor',"'95%'");
	$propForm->addField('field_cb_checked','lenght','checkbox')->setProperty('anchor',"'95%'");

	$cardName = $tabId.'_card';
	$cardFieldsName = $tabId.'_fieldsCard';
	
		
echo $tree->createTree();
echo $fieldGrid->createGrid();
echo $form->createForm();
echo $grid->createGrid();
echo $propForm->createForm();

echo $treeName.".getSelectionModel().on('beforeselect',function(sm,n){
	if(n.isLeaf())
	{
		$formName.selectedId = n.id;
		$propName.selectedId = n.id;
		$formName.getForm().load({params:{action:'load',id:n.id  } });
		$cardFieldsName.getLayout().setActiveItem(1);
	}
	else 
	{
		$fieldGName.getStore().reload();
		$cardFieldsName.getLayout().setActiveItem(0);
		$cardName.getLayout().setActiveItem(2);
	}
}); 

	$formName.switchType = function(showType){
		switch(showType)
		{
			case '0':
				$cardName.getLayout().setActiveItem(1);
				var f = $propName.items.items[0];
				f.label.update('length');
				
				//$propName.items.items[0].setVisible(true) ;
				$propName.items.items[1].setVisible(true) ;
				$propName.items.items[2].setVisible(false) ;
				
				$propName.items.items[0].label.update('max char');
				$propName.items.items[1].label.update('default value');
				
				$propName.getForm().load({params:{action:'load',id:$propName.selectedId  } });
		
				
			break;
			case '1':
				$cardName.getLayout().setActiveItem(1);
				var f = $propName.items.items[0];
				f.label.update('length');
				//$propName.items.items[0].setVisible(true) ;
				$propName.items.items[1].setVisible(true) ;
				$propName.items.items[2].setVisible(false) ;
				
				$propName.items.items[0].label.update('number of lines');
				$propName.items.items[1].label.update('default value');
				$propName.getForm().load({params:{action:'load',id:$propName.selectedId } });
		
			break;
			case '2':
				$cardName.getLayout().setActiveItem(0);
				$gridName.getColumnModel().setHidden(2,false);
				$gridName.getStore().reload({params:{checkBox:true, fieldName : $formName.find('name','podatki[field_name]')[0].getValue(),
				 SQLwhere:'lab_field = '+ $formName.selectedId + ' AND language = '+$lngCombo.getValue() }  } );
				
			break;
			case '3':
			case '4':
				$cardName.getLayout().setActiveItem(0);
					$gridName.getColumnModel().setHidden(2,true);
				$gridName.getStore().reload({params:{ SQLwhere:'lab_field = '+ $formName.selectedId + ' AND language = '+$lngCombo.getValue() }  } );
							
			break;
			case '5':
				$cardName.getLayout().setActiveItem(2);
			break;
		}
	};

	$formName.getForm().on('actioncomplete',function(f,a){
		var data = Ext.decode(a.response.responseText).data;
		$propName.getForm().setValues(data);
		$formName.setTitle( a.result.data['podatki[field_name]' ] + ': '+  a.result.data['podatki[field_text]' ] );
		var showType = a.result.data['podatki[field_type]' ];
		var showData = a.result.data['podatki[field_options]'];
		$formName.switchType(showType);
	});
	//special event for changing the grid with checkboxes
	$gridName.on('afteredit',function(e){
		var dType =  $formName.find('name','podatki[field_type]')[0].getValue();
		if(e.field == 'lab_code' && dType == 2)
		{
			var nodeText = $formName.find('name','podatki[field_name]')[0].getValue();
			var nodeType = $formName.find('name','podatki[data_type]')[0].getValue();
			$gridName.RMconn.request({ params:{action:'cbRename',nodeText:nodeText,nodeType:nodeType,newVal:e.value,oldVal:e.originalValue}
			,success: function(resp){
				var r = Ext.decode(resp.responseText);
				if(!r.success)
				{
					
					Ext.Msg.alert('Warning!',r.error);
				}
			}
			} );
		}
		else if (e.field == 'cb_checked') {
				var nodeText = $formName.find('name','podatki[field_name]')[0].getValue();
				var nodeType = $formName.find('name','podatki[data_type]')[0].getValue();
				$gridName.RMconn.request({ params:{action:'cbChecked',nodeText:nodeText,nodeType:nodeType,newVal:e.value,nodeId:e.record.data.lab_code }
				,success: function(resp){
					var r = Ext.decode(resp.responseText);
					if(r.success)
					{
						
						e.record.commit();
					}
					else 
					{
						e.record.reject();
					}
				}
				} );
		}
		
		
	});
	$gridName.getStore().on('add',function(st,recs,index){
		var dType =  $formName.find('name','podatki[field_type]')[0].getValue();
		if(dType == 2)
		{
			var nodeText = $formName.find('name','podatki[field_name]')[0].getValue();
			var nodeType = $formName.find('name','podatki[data_type]')[0].getValue();
			$gridName.RMconn.request({ params:{action:'cbAdd',nodeText:nodeText,nodeType:nodeType}} );
		}
	});
	$gridName.getStore().on('remove',function(st,recs,index){
		var dType =  $formName.find('name','podatki[field_type]')[0].getValue();
		if(dType == 2)
		{
			var nodeText = $formName.find('name','podatki[field_name]')[0].getValue();
			$gridName.RMconn.request({ params:{action:'cbRemove',nodeText:nodeText,nodeId:recs.data.lab_code }} );
		}
	});
";


?>
	var <?php echo $tabId; ?> = new Ext.Panel({
		id:'<?php echo $tabId; ?>',
		iconCls : 'icon_userspool_fieldedit',
		title:'Field editor',
		defaults:{split:true,border:false},
	
		layout:'border',
		border: false,
		closable:true,
		items:[<?php echo $tree->getName()." 
		 ,$cardFieldsName = new Ext.Panel({layout:'card',width:400,activeItem:0, region:'center',items:[{layout:'fit',title:'Fields',border:false,defaults:{border:false}, items: $fieldGName } ,$formName  ]  }) 
		 ,$cardName = new Ext.Panel({
		 title: 'Properties', iconCls:'icon-options-3',
		 layout:'card',layoutConfig:{ deferredRender: true }, width:400, region:'east',items:[{layout:'fit',border:false,defaults:{border:false},items: $gridName } ,$propName ,{} ]  }) " ;  ?>   ]
	});
	mainTabPanel.add(<?php echo $tabId; ?>).show();