<?php

include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include (PATH_TO_ROOT."webcati/init.php");
	
include_once(PATH_TO_ROOT."webcati/_class/buildQuestionare/class.bqClasses.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_form.php");
include_once(PATH_TO_ROOT."webcati/_forms/buildQuestionare/forms.buildQuestionnaire_old.php");



	
	
//the table for the project in DB_WARPIT_WEBCATI is named after the project name
//the coresponding tree table has a _tree suffix
	
	
	$tabId = $_POST['uniqueTabId'];
	
	$projectName = $_POST['project'];
	echo "	
       Ext.Ajax.request({
  			url: 'webcati/_forms/_ajax/ajax.buildQpanels.php',
			params:{
				action: 'getView',
				id_user: '".$_SESSION['UserInfo']['id']."',
				id_project:'".$_POST['id_project']."'
						},
			method:'POST', 
			success: function(res, opts){
			nacin_Pogleda=res.responseText; 
					}
		});
	
	";

	$projectId = $_POST['id_project'];
	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	//let's get the default language of this project!
	$res = $db->SQLexecute("SELECT proj_name,language FROM _Projects WHERE id = $projectId");
	if(!$row = $db->fetchRow($res))
	{
		//maybe the project was deleted ?
		echo "removeSession('$tabId');";
		return;
	}
	
	$tableName = $row[0];
	$tableNameTree = $tableName.'_tree';
	
	$telephoneTableCBId = "telNumberDatabaseCombo_".$tableName;
	
	
	$defLng = $row[1];
	
	
	$ajaxUrl = 'webcati/_ajax/buildQuestionare/ajax.buildQuestionnaire.php';
	
	
	
	$hasDialer = false;
	$db->ChangeDatabase(DB_WARPIT_WEBCATI);
	if($rs = $db->SQLexecute("SELECT id from {$tableName} WHERE tip_sql = 7") )
	{
		if($db->fetchArray($rs))
		{
			$hasDialer = true;
		}
	}
	
	
	//we define all the components here so that we have the name references
	
	//the tree on the left that has all the questions structured in fodlers
	$treeWC = new makeWebcatiTree($tableName.'_tree');
	//the table name is same as the project name
	//the special ajax manipulator takes care of geting the _tree table
	$treeWC->setMainTable($tableName,DB_WARPIT_WEBCATI);
	//for easier access to the tree name
	$treeName = $treeWC->getName();
	
	//the main grid with basic questions data
	$grid = new MakeGrid();
	$gridName = $grid->getName();
	
	
	$showVarGrid = new MakeGrid();
	
	
	//the grid in the properties for the go to conditions
	$gridjmp = new MakeGrid($tableName.'_jumpTo');
	$gridjmpName = $gridjmp->getName();
	
	//the card layout which containes different properties for status and other questions
	$cardPropName = $tableName.'_propCardPanel';
	
	//the top bar, with buttons for inserting numbers and operation signs into text areas and grid
	$tbarName = "CalcTbar_$tableName";
	
	if($hasDialer)
	{
		$rootNameAdd[] = 'D';
		$treeWC->addConfig('hasDialer','true');
	}
	
	$rootName = "Questions";
	if($rootNameAdd)
	{
		$rootName .= " <span style=\'color:red;\'>(".implode(',',$rootNameAdd).")</span>"; 
	}
	
	$treeWC->SetRootVisible("true",$rootName)
		->addConfig('region',"'west'")
	//	->setLinesVisible(false)
		//->setBoldRoots()
		->setFontMedium()
		//we set the tree editable but the ajax manipulator sets the leafs (questions) un-editable
		//so that only the groups are editable in the tree
		->setEditable()
		->setTextPadding('1px')
		->addWCaddQuestion("SpecStoretip_sql$grid->rndID")
		->addWCaddGroup()
		->addContSeparator()
		->addContItem('Preview',"function(item){
			var nodes = $treeWC.getSelectionModel().getSelectedNodes();
			for(var i= 0;i<nodes.length;i++)
			{
				var n = nodes[i];
				if(n.isLeaf())
				CallScript('webcati/_forms/buildQuestionare/forms.previewQuestion.php',{projectId:$projectId,tableName:'$tableName',
				questionId: n.id ,
				id_language: Ext.getCmp('lngCombo_$tableName').getValue() } );
			}
		}",'!node.isLeaf()','RMicon_view_details')
		->addShowTogether()
		->addContSeparator()
		->addContItem('Copy',"function(item){ 
		
		
			var nodes = $treeWC.getSelectionModel().getSelectedNodes();
			if(nodes.length == 0)
				nodes = new Array($treeWC.getRootNode() );
			var ids = new Array();
			for(var i= 0;i<nodes.length;i++)
				ids.push(nodes[i].id);

			$treeWC.RMconn.request({
				params:{
					action:'copyQuestion',
					ids:ids.join(),
					id_project:$projectId
				},
				success:function(resp){
					if(Ext.decode(resp.responseText).success) RMcopyClipboardQuestion = true;
					else RMcopyClipboardQuestion = false;
						
				}
			});	
			
		}",'false','RMicon_copy')
		
		->addContItem('Paste',"function(item){
			if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $treeWC.getSelectionModel().getSelectedNodes()[0];
				if(!n)
					n = $treeWC.getRootNode();
			}
			
			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.isQuestion==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
			 var reqConfig = {params:{
	         action:'pasteQuestion',
	         parId:par.id,
	         nodeId:n.attributes.id , closed:closed,
	         isTargetQ:n.attributes.isQuestion} 
			,success:function(resp){
			var r = Ext.decode(resp.responseText);
			if(r.success){
				//if adding was succesful we refresh the tree and open on the added question
				//NOTE: all other groups get closed
				//var p = par.getPath()+'/'+Ext.decode(resp.responseText).insertId;
				$treeWC.getLoader().load(par,function(){par.expand()} );
			} else{
			//we check if the error is becouse of duplicate names!
			if(r.error = 'dupNames') //we create a form that let's the user type diff var names
			{
				
				//var fs = new Ext.form.FieldSet({title: 'Please write new name',border:false});
				
					 var form = new Ext.form.FormPanel({
					 method:'POST',ref:'testForm',
					 labelWidth:150,
					 labelAlign:'right',
					frame:true
						});
				for(var i=0;i<r.names.length;i++)
					form.add({xtype:'textfield',vtype:'questionName',name:'names['+r.names[i] +']',
							fieldLabel: r.names[i],
							value:r.names[i]+'x'
					 });
				var v = new Ext.Window({
					title:'Please set the new variable name(s) for copied question(s)',modal:true,
					items:form,
					width:'400',
					buttons:[{
						text:'Ok',
						handler: function(){
							//v.testForm.getForm().doAction('oosubmit'.reqConfig);
							Ext.apply(reqConfig.params, form.getForm().getValues())
							  $treeWC.RMconn.request(reqConfig );    
							v.close(); }
					},{
						text:'Cancel',
						handler:function(){v.close();}
					}]
				
				}).show();
			}
			//else we display a warning and focus on the name field
			else
			Ext.Msg.alert('Warning!',Ext.decode(resp.responseText).error );
			}},
				
			failure:function(){alert('failed');}	};
	         $treeWC.RMconn.request(reqConfig);    
			
			
		}",'!RMcopyClipboardQuestion','RMicon_paste')
		->addTbarItem("'-'")
		->setSearchField('','top',100)
		->addContSeparator()
		->addWCdialer($grid,$telephoneTableCBId,$showVarGrid)
		->addCapiTable($projectId,$grid)
		->multiSelect()
		->setWidth(180)
		->setReqUrl($ajaxUrl)
	// ***************************** new code ************************************	
		->addContItem('xx'," function(item) {

				
	".$tabId.".reload();
// 		if (nacin_Pogleda=='standard')  
// 		{	

// 			Ext.getCmp('tree_question_vew_".$tableName."').removeAll();
				
// 			//	glavniPan.removeAll();	
// 		//	glavniPan.remove(tatab);
// 				Ext.getCmp('tree_question_vew_".$tableName."').add(centerPanel);	
// 				Ext.getCmp('tree_question_vew_".$tableName."').doLayout();	
// 				console.log(glavniPan);
// 		}
// 		else
// 		{
			
// 			glavniPan.removeAll();	
// 			glavniPan.add(".$grid->getName().");
// 			glavniPan.add(tatab);
// 			glavniPan.doLayout();	
// 			console.log(glavniPan);
				
// 		}			



		}",'false','RMicon_numbered_list',2 ); 
	
	$treeWC->enableWCdd();
	//the SQL sentence to get the tree and additional data from the question table
	$treeWC->selectSQL = "SELECT a.*,$tableName.q_pos,$tableName.id as q_id ,tip_sql,attachAnswers,c.id_question as hasScript from {$tableName}_tree a LEFT JOIN $tableName on a.id_question = $tableName.id LEFT JOIN {$tableName}_script c on c.id_question = $tableName.id";

	//!!!!!!!!!!!!!!!!!!!!!!!!!the grid to show the main attributes of the question!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	
	$grid->setReqUrl($ajaxUrl);
	$grid->setMainTable($tableName,DB_WARPIT_WEBCATI)
	->addConfig('region',"'center'")
	->addConfig('cls',"vline-on")
	->setSortable(false);
	
	$grid->addColumn('id');
	$grid->addColumn('idLab');
	$grid->addColumn('q_pos','Position')->hidden(true)->type('int');
	$grid->addColumn('q_name','Name')->editor('new Ext.form.TextField({vtype:"questionName"})')->width(60);
	
	$grid->addColumn('tip_sql','Type')->width(35)
					  ->type('combo')
					  ->comboTable('_QuestionTypes')
					  ->comboValue('id')
					  ->comboSQL("SELECT * FROM _QuestionTypes")
					  ->comboDisplay('name',false)
					  ->comboRender('type')
					  ->renderer("function(value){var combo = SpecColtip_sql$grid->rndID;
					  var idx = combo.store.find(combo.valueField, value);
		if(idx==-1){ if(value == 7) return 'D'; if(value==8) return 'ST'; if(value==9) return 'App';	return 'Select';}
		var rec = combo.store.getAt(idx);
		return rec.data.type;}")
					  ;
	
	$grid->addColumn('nav_sql','Instruction')->editor('new Ext.form.TextArea()')->width(150)->
		//the renderer: it strips HTML tags and on empty questions it displays empty with gray
		renderer("questionFieldsDataRenderer")
		//the icon in questions to open the HTML editor for this question
			->addIconAction('RMicon_edit_record',"addEditTab_$tableName(record,grid,col,value,dataIndex)");
	
	$grid->addColumn('vpr_sql','Question')->editor('new Ext.form.TextArea()')->width(150)->
		//the renderer: it strips HTML tags and on empty questions it displays empty with gray
		renderer("questionFieldsDataRenderer")
		//the icon in questions to open the HTML editor for this question
			->addIconAction('RMicon_edit_record',"addEditTab_$tableName(record,grid,col,value,dataIndex)");
	$grid->addColumn('odg_sql','Answers')->width(150)->editor('new Ext.form.TextArea()')
	->renderer("function(val,md,rec){value = questionFieldsDataRenderer(val); if(rec.data.tip_sql == 11) return '<font color=\"#c0c0c0\">[Not available]</font>'; if(rec.data.srot_sql > 0 || rec.data.erot_sql > 0 ) return '<font color=red><b>(R)</b></font>  ' + value;
		 return value || '&#160;'; }")
	//the icon in answer and legend to open the grid for defining answers (called in forms.scriptGrid.php)
	->addIconAction('RMicon_edit_record',"addGridEditTab_$tableName(record,grid,col,value,dataIndex)");
	$grid->addColumn('leg_sql','Legend')->width(150)->editor('new Ext.form.TextArea()')
	->renderer("function(value,md,rec){ if(rec.data.tip_sql == 1 || rec.data.tip_sql == 11) return '<font color=\"#c0c0c0\">[Not available]</font>'; value = questionFieldsDataRenderer(value); if(rec.data.srotLegend > 0 || rec.data.erotLegend > 0 ) return '<font color=red><b>(R)</b></font>  ' + value;
		return value || '&#160;'; }")
	->addIconAction('RMicon_edit_record',"addGridEditTab_$tableName(record,grid,col,value,dataIndex)");
	//we add the group as hidden, and render it to display the name instead of value
	$grid->addColumn('group_id','skupina')->setProperty('groupRenderer',"function(a,b,r){return r.data.idLab ? r.data.idLab : '/';}"   );
	//type of answers...combobox for integer or character				  ;
	//we create the combo array for data types
	
	include_once(PATH_TO_ROOT."config.php");
	$comboArray = $configCombo['DataType'][$_SESSION['UserInfo']['lng_admin'] ]; 
	for ($i=0;$i< count($comboArray);$i++ )
	{
		$comboStr[] = "['$i','".$comboArray[$i]."']";
	}
	$storeDataType = 'StoreBaseType_'.$tableName;
	
	echo "var $storeDataType = new Ext.data.ArrayStore({
        fields: [
            'myId',
            'displayText'
        ],
        data: [".implode(',',$comboStr).  "]
	});";
	/*$grid->addColumn('variableTypeBase','Type')->width(80)->editor("new Ext.form.ComboBox({
		valueField:'myId',displayField:'displayText',mode:'local',triggerAction:'all',store:$storeDataType
	})")->renderer("function(val){
		var idx =$storeDataType.find('myId', val);
		if(idx==-1)	return 'Select';
		var rec = $storeDataType.getAt(idx);
		return rec.get('displayText');
	}");*/

    
    $comboCapiTables = array();
	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	$sql = "SELECT id, name FROM _CapiTables WHERE is_leaf=1 ORDER by name";
	$res = $db->SQLexecute($sql);
	while($row = $db->fetchArray($res)) {
		$comboCapiTables[] = "['".$row['id']."','".$row['name']."']";
	}	
    // create datastore for all capi tables
	echo "var storeDataCapi = new Ext.data.ArrayStore({
        fields: [
            'idCapi',
            'capiTableName'
        ],
        data: [".implode(',',$comboCapiTables).  "]
	});";
    $db->ChangeDatabase(DB_WARPIT_WEBCATI);
        	
	/*$grid->addColumn('lenght_variable_base','Length')->width(50)
			->editor('new Ext.form.NumberField()');*/
	$grid->addColumn('must_answer','MA')->type('checkColumn')->width(25);
	$grid->addColumn('disable_question','hide')->type('checkColumn')->width(30);
	//al the columns that we need data for handling
	$grid->addColumn('multi_nogo_answers');
	$grid->addColumn('filter_answer');
	$grid->addColumn('filter_legend');
	$grid->addColumn('open_answers');
	$grid->addColumn('open_legend');
	$grid->addColumn('srot_sql');
	$grid->addColumn('erot_sql');
	$grid->addColumn('srotLegend');
	$grid->addColumn('erotLegend');
	$grid->addColumn('atr_sql');
	$grid->addColumn('filter_attributes');
	$grid->addColumn('srotAttributes');
	$grid->addColumn('erotAttributes');
	$grid->addColumn('open_attributes');
	$grid->addColumn('rot_sql');
	$grid->addColumn('fil_sql');
	$grid->addColumn('con_sql');
	//transformed data for the goto grid!!!
	$grid->addColumn('gotoData');
	
	$grid->addColumn('variableTypeBase');
	$grid->addColumn('variableTypeOpen');
	$grid->addColumn('open_sql');
	$grid->addColumn('attachAnswers');
	$grid->addColumn('id_mask');
	$grid->addColumn('attachFalse');
	$grid->addColumn('use_for_quotas');
	$grid->addColumn('les_sql');
	$grid->addColumn('id_showTogether');
	$grid->addColumn('templateName');
	$grid->addColumn('isFinal');
	
	$grid->addColumn('answers_filter'); //this column is now used, so that you can unset open answers filtering!
	
	//we add before edit listener so that we can make some fields uneditable
	$grid->listeners[] = "beforeedit:function(e){ if(e.record.data.q_pos < 0){ 
	//for instructional and sr sistem variables we can edit instruction and question
	if( (e.field == 'nav_sql' || e.field == 'vpr_sql') )
		return true;
	if( (e.record.data.tip_sql == 1) && (e.field == 'odg_sql') )
		return true;
	
	return false;}
	//only scale has legend so far
	if(e.record.data.tip_sql == 1 && e.field == 'leg_sql') return false;
	 }";
	
	
//the tree for showing design templates
	$designTree = new MakeTree();
	$designTree->setTable('_DesignerTemplates',DB_WARPIT_WEBCATI_BASE)
	->addConfig('anchor',"'99% -250'")
	->baseParams = "nameField : 'name'";
	echo $designTree->createTree();
	$desWindow = $tableName.'_desWindow';
	echo "var $desWindow = new Ext.Window({
			modal:true,
			title:'Select template',
			layout:'form',
			height:700,width:250,
			closeAction:'hide',
			items: [$designTree,{
				xtype:'radio',name:'selectDesignRadio',fieldLabel:'Questions',checked:true,value:1
				},{
				xtype:'radio',name:'selectDesignRadio',fieldLabel:'Project'},
				{ xtype:'fieldset',title:'Use template for',items: [{ xtype:'radio',fieldLabel:'Normal',name:'templateType',checked:true,inputValue:0 },
			  { xtype:'radio',fieldLabel:'Answers',name:'templateType',inputValue:6 },
			  { xtype:'radio',fieldLabel:'Control',name:'templateType',inputValue:7 }] } ,
				 { xtype:'fieldset',title:'Use for device',items: [{ xtype:'radio',fieldLabel:'Default',name:'deviceDesktop',checked:true,inputValue:0 },
			  { xtype:'radio',fieldLabel:'Mobile',name:'deviceDesktop',inputValue:2 }] } ],
			buttons:[{
				text:'OK',
				handler:function(){
				
					var radio = $desWindow.find('name','selectDesignRadio');
					
				
					var selNode = $designTree.selModel.getSelectedNode();
					if(!selNode || !selNode.isLeaf())
						return;
					var sm = $grid.getSelectionModel();
					var p = {
						action:'addDesign',
						id_project:$projectId,template_id:selNode.id,
						 isProject: radio[1].getValue(),
						 forDevice: $desWindow.find('name','deviceDesktop')[0].getGroupValue()
						};
					
					if(radio[0].getValue())
					{
						if(sm.hasSelection() )
						{
							var ids = [];
							Ext.each(sm.getSelections(),function(item){
								ids.push(item.id);
							});
							p.selections = true;
							p.ids = ids.join();
					
						}
						else 
						{
							Ext.applyIf(p, filters$grid->rndID.buildQuery(filters$grid->rndID.getFilterData()) );
							Ext.applyIf( p,$grid.getStore().lastOptions.params );
							Ext.applyIf(p, $grid.getStore().baseParams );
							
						}
						p.templateType = $desWindow.find('name','templateType')[0].getGroupValue();
					}
					$grid.RMconn.request({
							params:p,
							success:function(){ $grid.getStore().reload(); }
						} );
					
					$desWindow.hide();
				}
			}]
		});";
	
	$grid->setSort('q_pos')
		->setRemoteSort(true)
		->setAutoExpand('odg_sql')
		->setCheckBoxSelectionModel()
		//this is to cancel the basic afteredit event
		//all fields are still editable due to the assigned editors
		->setEditable(false)
		->setFiltering(true)
		->addConfig('enableColumnHide','false')
		//deleting is in grid instead of tree for easier multi delete
		//a custom delete button is used for special functionality to update the tree
		->addtBarItem("{text:'Delete',iconCls:'icon-delete-record', handler:function(){
			var sm = $gridName.getSelectionModel();if(sm.hasSelection()){
			var sel = sm.getSelections();
			var qNames = new Array();
			var x;var p = {action:'delete'};
					 for(x=0; x<sel.length ;x++)
						{if(sel[x].data.tip_sql < 7 || sel[x].data.tip_sql == 11) //changed the condition to acommodate the missing IDs in _QuestionTypes (7,8,9,10 are reserved)
							{ p['id['+x+']'] = sel[x].data.id;
							 qNames.push(sel[x].data.q_name);
							 }
							}
			
			//we save all the id's to delete
			//we get the path to reopen the tree after refresh
			var selNode = $treeName.getSelectionModel().getSelectedNodes()[0] ? $treeName.getSelectionModel().getSelectedNodes()[0].getPath() : '';
			Ext.Msg.show({ title:'Remove questions',buttons: Ext.MessageBox.YESNO,msg:'<b>'+qNames.join()+'</b><br>Are you sure?',
			fn: function(btn){if(btn == 'yes'){
					
			 	$gridName.RMconn.request({ params: p,
					 success:function(res,opt){
					 	var sucFunc = function(){
					 		$treeName.getRootNode().reload(function(){ 
								$treeName.selectPath(selNode,'id',function(s,b){
								 	//if the node cannot be selected (we deleted it), we refresh the grid!!	

								 	// Borut change on 24.02.2013, always refresh also grid, not only tree 
								 	//if(!s){ $gridName.getStore().reload();  }  
								 	$gridName.getStore().reload(); 
						 		})
						 	});
						 };
						 	var r = Ext.decode(res.responseText);
						 	if(r.success)
						 	{
						 		sucFunc();
						 		     
						 	}
						 	else if(r.error == 'hasData') //we check if error is becouse of data included
						 	{
						 		Ext.Msg.show({title:'Warning! Data exists',msg:'Do you want to:',buttons:{ ok:'Delete',yes:'Backup' },
						 			fn: function(btn){
						 				if(btn == 'ok') p.deleteConfirm = 'delete';
						 				else if(btn == 'yes') p.deleteConfirm = 'backup';
						 				$gridName.RMconn.request({ params : p,success: sucFunc });
						 			}
						 		});
						 	}
  }});     }} }); } }}
		")
		
 	//a button to togle between system questions and ordinary questions!
 		->addtBarItem("{text:'Show System',iconCls:'RMicon_doc_settings',enableToggle:true,toggleHandler:function(bt,state)
 		{
 			$grid.getStore().baseParams.system = state;
 			$grid.getStore().reload();
 		}}")
 		//we add a bind template button, to bind a designer template to selected questions
		->addtBarItem("{text:'Set style template',iconCls:'RMicon_designer',handler:function(){
		$desWindow.show();
	}}")
	->addtBarItem("{text:'Style manager',iconCls:'RMicon_layout_doc',handler:function(){
			addTabAuto('styleTemplateManager'+$projectId , 'webcati/_forms/designerPanel/forms.designerTemplates.php',{id_project:$projectId});
		}
	}")
	//we disable the columns that are not in the main table, to avoid the errors!
	->setSearchField('Search','top',0,"['group_id','q_pos','variableTypeBase']");
		
	//this will be moved to the tree...since structure is automaticly created, there is no need to have this! :)
	/*
		$grid->addtBarItem("{text:'Create Structure',iconCls:'icon_create_structure',handler:function(){
			$gridName.RMconn.request({params:{action:'createStructure'},success:function(rsp){
				var r = Ext.decode(rsp.responseText);
				if(r.success) Ext.Msg.alert('Success','Structure successful created!');
				else {  
					if(r.error == 'dataExist')
					{
						Ext.Msg.prompt('Warning - data exist','Enter password and confirm!',function(btn,text){
							if(btn=='ok')
							$gridName.RMconn.request({params:{action:'createStructure',deleteConfirm:true,pass:text},success:function(rsp){
									var r = Ext.decode(rsp.responseText);
									if(r.success) Ext.Msg.alert('Success','Structure successful created!');
									
								}	});
						})
					}
				}
			}	});
		} }");*/
		//print questionairre
		$grid->addtBarItem("'->',{text:'Print',iconCls:'RMicon_printer',handler:function(){
			var a = $grid.getSelectedIds();
			if(a.length > -1)
				CallScript('webcati/_forms/buildQuestionare/forms.printQuestion.php',{projectId:$projectId,tableName:'$tableName',id_language: Ext.getCmp('lngCombo_$tableName').getValue(),ids:a.join() } );
			else
				Ext.Msg.alert('Warning','Please select questions!');
		}},'-'")
		//preview
		->addtBarItem("{text:'Preview',iconCls:'RMicon_view_details',handler:function(){
			var q = $grid.selModel.getSelections();
			if(q.length)
			for(var i=0;i<q.length;i++)
			CallScript('webcati/_forms/buildQuestionare/forms.previewQuestion.php',{projectId:$projectId,tableName:'$tableName',
			questionId: q[i].id ,id_showTogether : q[i].data.id_showTogether,
			id_language: Ext.getCmp('lngCombo_$tableName').getValue() } );
			else //no question selected = we start the questionare
			{
				CallScript('webcati/_forms/buildQuestionare/forms.previewQuestion.php',{projectId:$projectId,tableName:'$tableName' } );
			}
		}}")
		->addtBarItem("{text:'Export',iconCls:'file-xml',handler:function(){
			Ext.util.FileOps.downloadFile('$ajaxUrl', {project_id:$projectId,RMcomp:'grid',action:'exportXML'} );
			
		}}")
		->setGrouping('group_id',"{showGroupName:false,hideGroupedColumn:true,enableGroupingMenu:false}")
		->setPaging(10);
		//lets load languages!
	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
	$res = $db->SQLexecute("SELECT id_language,country_code,cp_comment FROM _LanguageProjects INNER JOIN _LanguageCodepage a ON a.id = id_language WHERE id_project = $projectId");
		while ($row = $db->fetchRow($res))
		$sel[] = '['. $row[0].',"'.$row[1].' - '.$row[2].'"]';
	
	
	$grid->baseParams = "id_language:$defLng,id_lngDef:$defLng,id_project:$projectId";	
	$grid->addBottomBarItem("'-','Language:', {
			xtype: 'combo',
			store: [ ".implode(',',$sel)."],
			id:'lngCombo_$tableName',
			autoSelect: true,
			value:$defLng,
			triggerAction: 'all',
			listeners:{
				select:function(cb,rec)
				{
					var st = $grid.getStore();
					$grid.RMconn.baseParams.id_language = rec.data.field1;
					st.baseParams.id_language = rec.data.field1;
					st.reload();
				}
			}
		},
		{xtype:'button', iconCls: 'RMicon_green_plus_minus',handler: function(){

		$grid.RMconn.request({ params: { action:'getAllLanguage',id_project : $projectId },
		success: function(resp,opt)
		{
			var r = Ext.decode(resp.responseText);
			var lngArr = r.rows;
			var selLng = r.selectedLng;
			
			var tmpForm = new Ext.form.FormPanel({labelWidth:250,autoScroll:true,
			frame:true, url:'$ajaxUrl'
			});
			Ext.each(lngArr,function(lng)
			{
				if(lng.id != $defLng)
					tmpForm.add({xtype:'checkbox',inputValue: lng.id,name:'lng['+lng.id+']',
					checked: selLng[ lng.id ] ,
					fieldLabel:lng.country_code+' - '+lng.cp_comment });
			});
				var w = new Ext.Window({
					title:'Add language',
					width:350,
					layout:'fit',
					autoScroll:true,
					height:500,
					modal:true,
					items: tmpForm,
					buttons:[{
						text:'Save',
						scope:this,
						handler: function()
						{
							tmpForm.getForm().submit({
							params:{
								id_project: $projectId,
								action: 'addLanguage',
								defLng:$defLng,
								RMtable:'$tableName' },
							success:function(frm,act){
								Ext.getCmp('lngCombo_$tableName').getStore().loadData( Ext.decode(act.response.responseText).data );
								w.close();
								}
							});
							
						}
						
					}]
				} ).show();
			} });
		} },{
			text:'Interface',
			iconCls:'RMicon_interface',
			handler: function(){
				var q = $grid.selModel.getSelections();
				var p= {id_project:$projectId};
				if(q)
				{
					var qId = new Array();
					for(var i=0;i<q.length;i++)
						qId.push( q[i].id );
					p.id_questions = qId.join();
				}
				
				addTabAuto('multiLanguageSettings_'+$projectId , 'webcati/_forms/buildQuestionare/forms.multiLanguage.php',p); 
			}
		}")
	
		;
	
		
	
//!!!!!!!!!!!!!!!!!!!!!!! the left form in the properties tab !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	//this form and $formCol2 are in the properties tab in a vbox to apear one next to another
	$form = new MakeForm($tableName.'_form');
	$formName = $form->getName();
	$form->setReqUrl($ajaxUrl);
	$form->setMainTable($tableName,DB_WARPIT_WEBCATI)
	->addConfig('padding','10')
	->addConfig('flex','1')
	->addConfig('border','false');
	//the trigger properties is added in for each when we add dragNdrop properties
	$form->addField('fil_sql','Filter in','trigger')->setProperty('anchor',"'95%'")->setProperty('triggerClass',"'icon-edit-field-t'");
	$form->addField('con_sql','Filter out','trigger')->setProperty('anchor',"'95%'")->setProperty('triggerClass',"'icon-edit-field-t'");
	$form->autoUpdateFunction = "function(fld,val){
					var rec = $grid.getStore().getById($formName.selectedRowId);
					new RMajax().request({
					url:'$ajaxUrl',
					params:{ action:'update',RMtable:'$tableName',database:'".DB_WARPIT_WEBCATI."',field:fld.RMfieldName,
					 value:val,id: $formName.selectedRowId } ,
					 success:function(resp){
					 	r = Ext.decode(resp.responseText);
					 	if(!r.success)
					 	{
					 		alert( r.error );
					 	}
					 	else 
					 	{
					 		
					 		rec.data[fld.RMfieldName] = val;	
					 	}
					 }
					 });
					 
					 }";
	$form->setAutoUpdate()
	//->addSaveCancel()
	//we add the change listener to all fields, so that they are automaticly saved
	//->addConfig('boxMinHeight',"150")
	->addConfig('autoScroll ',"true")
	//->addConfig('region',"'south'")->setHeight(200)
	
	;
	
	$form->addListener('render',"function(cmp){
		var tt = cmp.findByType('textfield');
		for(var i=0;i<2;i++)
			tt[i].on('focus',function(fld){ 
						$tbarName.field = fld;
						$tbarName.cmp = 'field';
					        });
	}");
	
	//!!!!!!!!!!!!!!!!!!!!!Jump to (or goto) grid!!!!!!!!!!!!
	//this grid is in the $form, and has the jump conditions
	//this textfield has a listener save the current caret position so that we can insert in with the tbar
	$gridjmp->addColumn('cnd','Condition')->editor("new Ext.form.TextField({
	listeners:{
	blur:function(fld){
	if(Ext.isIE){
		$tbarName.fCaret = fld.getValue().length;
		fld.fCaret = fld.getValue().length;
		
		
	}
	else{  $tbarName.fCaret = getCaretPosition(  fld.getId() );   }  }
	}
	})");
	$gridjmp->addColumn('toProject','To Project','','checkColumn');
	//the question or project to jump to (depends if toProject is set)
	$gridjmp->addColumn('question','Jump to','new Ext.form.TextField()');
	$gridjmp->addColumn('ic',' ')->addIconAction('icon_save_document',
		"//if there's no data in this row we ingore the click
	if(!record.data.cnd && record.data.cnd == '')
		{
			return;
		}
		var tst = new Array();
		//we go through the grid and get all the data
		$gridjmpName.getStore().each(function(rec){
			if(rec.data.cnd)
			{
				tst.push(rec.data);
			}
		});
		$gridName.RMconn.request(
					{ //we send to the server the data, where it is checked if q/p exists and the goto statement is created 
					params:{action:'updateGoto',
					id: $formName.selectedRowId 
					,goTo:Ext.encode(tst) },
					success :function(resp,opt){if(Ext.decode(resp.responseText).success){  
					//if the last line was saved we create a new one
							st = grid.getStore();
							if(row == st.getCount() - 1 )
							{
								st.insert(st.getCount(),new st.recordType({ic:'&#160;',toProject:false,cnd:'',question:''  }   ) );
							}
							$gridjmpName.getStore().commitChanges();
							$grid.getStore().reload();
					   }
					   else
					   {
					   	alert(Ext.decode(resp.responseText).error);
					   } 
					      }
					});
		
		st = grid.getStore();
		
	")->width(60)
	->addIconAction('icon_red_delete',"
		st = grid.getStore();
		if(row == st.getCount() -1 )
		{
			//you cant delete the last (probably empty) row!!! but we clear it!
			record.data.cnd = '';
			record.data.question = '';
			//grid.getView().refresh();
			record.commit();
			return;
		}
		st.remove(record);
		var tst = new Array();
		$gridjmpName.getStore().each(function(rec){
			if(rec.data.cnd)
			{
				tst.push(rec.data);
			}
		});
		new RMajax().request(
					{url:'$ajaxUrl',
					params:{RMcomp:'grid',action:'updateGoto',RMtable:'$tableName',
					id: $formName.selectedRowId ,database:'".DB_WARPIT_WEBCATI."',field:'goto_sql'
					,goTo:Ext.encode(tst) },
					success:function(){
						$grid.getStore().reload();
					}
					});
		
	")				
		;
	$gridjmp->dataArray = "[ ['',false,'','&#160;' ] ]";
	$gridjmp->setTitle('Go to')
	->setEditable(false)
	->setAutoExpand('cnd')
	->addConfig('anchor',"'95% -60'")
	//we add before edit listeners to set the proper data for our calculator top bar!!!
	->listeners[] = "beforeedit:function(e){
						$tbarName.gRow = e.row;
						
						$tbarName.gCell =   e.column;
						$tbarName.cmp = 'grid';
	}"
	;
	
	$form->addItem($gridjmp->getName());
	
	//!!!!!!!!!!!!!!!!!!!!!!!!! the right form in the properties panel!!!!!!!!!!!!!!!!!!!
	//most of this fields are hidden on rowselect, dependent on some question properties!
	$formCol2 = new MakeForm($tableName.'_formCol2');
	$formCol2Name = $formCol2->getName();
	$formCol2->setReqUrl($ajaxUrl);
	$formCol2->setMainTable($tableName,DB_WARPIT_WEBCATI)
	->addConfig('padding','10')
	->addConfig('border','false');
	//showing which designer template is chosen for this question
	$formCol2->addField('id_template','Style template','label'); 
	
	//the field for the open variable type (shows only if open is checked)
	$formCol2->addField('variableTypeBase','Var type','combo')->setProperty('store',$storeDataType)->setProperty('displayField','"displayText"')
		->setProperty('valueField','"myId"')->setProperty('mode','"local"')->setProperty('triggerAction','"all"')->setProperty('editable','false');
	//the field for the open variable type (shows only if open is checked)
	$formCol2->addField('variableTypeOpen','Open type','combo')->setProperty('store',$storeDataType)->setProperty('displayField','"displayText"')
		->setProperty('valueField','"myId"')->setProperty('mode','"local"')->setProperty('triggerAction','"all"')->setProperty('editable','false');
	//the field for open variable length 
	//$formCol2->addField('lenght_variable_open','Open Length','textfield');
	//combo for how to show the legend in scale questions (combobox, radio etc etc), shows only for scale questions
	echo "if( typeof( buildQuestionareShowAsTypeScale ) == 'undefined' )
		{
		 buildQuestionareShowAsTypeScale	= new Ext.data.JsonStore({
		url:'$ajaxUrl',
		baseParams:{database:'".DB_WARPIT_WEBCATI."',RMtable:'_ShowAsTypes',action:'getShowAs',SQLwhere:'scale = 1' },
		fields:['id','showAs','scale','single','open','multi'],
		autoLoad:true,root:'rows'
	})
		}
		";
	$formCol2->addField('les_sql','Show as','combo')->setProperty('store',"buildQuestionareShowAsTypeScale" )->setProperty('displayField','"showAs"')
		->setProperty('valueField','"id"')->setProperty('mode','"local"')->setProperty('triggerAction','"all"')->setProperty('editable','false')
		->setProperty('lastQuery',"''");
	//number of open questions (only for open)
	$formCol2->addField('atr_sql','Attributes','textarea')->hidden(true)->width(164);
	$formCol2->addField('editAttr','Edit attributes','button')->setProperty('text','"Edit"')
	->setProperty('handler',"function(){
			
			addGridEditTab_$tableName($form.selectedRecord,$grid,'atr_sql',$form.selectedRecord.data.atr_sql ,'atr_sql')
	}");
	
	//$formCol2->addItem();
	$formCol2->addField('open_sql','Number of answers','numberfield');
	
	
	//attach to combobox...allows selection question or dragging question
	$formCol2->addField('attachAnswers','Attach','combo')->setProperty('store',"new Ext.data.JsonStore({
			url:'$ajaxUrl',
			baseParams: { action: 'qCombo',RMtable: '$tableName' },
			fields: ['id','q_name'],
			autoLoad: true,
			root: 'rows'
	})" )->setProperty('displayField','"q_name"')
		->setProperty("tpl","'<tpl for=\".\">' +
'<div class=\"x-combo-list-item\">' +
'{q_name}&nbsp;' +
'</div></tpl>'")
		->setProperty('valueField','"id"')->setProperty('mode','"remote"')->setProperty('triggerAction','"all"')->setProperty('editable','false');
		
	
		//attach a combobox for selecting custom masks from mask designer
	
	$formCol2->addField('id_mask','Select mask','combo')->setProperty('store',"new Ext.data.JsonStore({
			url:'$ajaxUrl',
			baseParams: { action: 'maskCombo',RMtable: '".WC_MASK_TEMPLATES."' },
			fields: ['id','name'],
			autoLoad: true,
			root: 'mask_rows'
	})" )->setProperty('displayField','"name"')
	->setProperty('valueField','"id"')->setProperty('mode','"remote"')->setProperty('triggerAction','"all"')->setProperty('editable','false');
	
		
		
	$formCol2->addField('attachFalse','Hide if false','checkbox')->hidden();
	//shows only for single respons and open! determines whether they can be used in quotas!	
	$formCol2->addField('use_for_quotas','Use for quotas','checkbox')
	->setProperty('hidden','true');
	
	//question isFinal...only for info question
	$formCol2->addField('isFinal','Question is final','checkbox')
	->setProperty('hidden','true');
	$formCol2->addField('answers_filter','Allow open without text','checkbox');
	//button for adding script to this question	
	$formCol2->addField('editScript','Edit script','button')->setProperty('text','"Edit script"')
	->setProperty('handler',"function(){
	
		addScriptTab_$tableName($formName.selectedRowId,$formName.selectedRowName );
		
		
	}");
	//same as for $form we add a default listener to save changes
	$formCol2->autoUpdateFunction = "function(fld,val){
			var url = '$ajaxUrl';
			var action = 'update';
			if(fld.xtype == 'combo')
				val = fld.getValue();
			
			var p = { RMcomp:'form', 
			action: action ,RMtable:'$tableName',database:'".DB_WARPIT_WEBCATI."',
			field:fld.RMfieldName, value:val,id:$formName.selectedRowId };
						if(fld.RMfieldName == 'use_for_quotas')
			{
				url = '$ajaxUrl';
				p.action = 'updateUseForQuotas';
				p.q_name = $formName.selectedRowName;
			}
			else if (fld.RMfieldName == 'atr_sql')
			{
				p.RMcomp = 'grid';
				p.id_language = $grid.getStore().baseParams.id_language;
				p.id_lngDef=$defLng;
			}
			
					new RMajax().request({
					url: url,
					params: p,
					success : function(resp,opt){
				var r = Ext.decode(resp.responseText);
				if(r.success){ 
				
				 if(r.error)  Ext.Msg.alert('Warning!',r.error);
				 }
				 else if(r.error == 'hasData') //we check if error is becouse of data included
				 	{
				 		var buttons = { ok:'Delete',yes:'Backup' };
				 		if(r.canRecode)
				 			buttons.no = 'Recode';
				 		buttons.cancel = 'Cancel';
				 		Ext.Msg.show({title:'Warning! Data exists',msg:'Fields '+r.fields.join(', ')+ ' will be dropped!<br>Do you want to:',buttons:buttons,
				 			fn: function(btn){
				 				if(btn == 'ok') p.updateConfirm = 'delete';
				 				else if(btn == 'yes') p.updateConfirm = 'backup';
				 				else if(btn == 'no') p.updateConfirm = 'recode';
				 				else { /*restore!!!*/ return;}
				 				$gridName.RMconn.request({ params : p });
				 			}
				 		});
				 	}
				  else {
			
				 Ext.Msg.alert('Error!',r.error);
				 }}
					 });   
					 var rec = $grid.getStore().getById($formName.selectedRowId);
					 rec.data[fld.RMfieldName] = val;
					 }";
	$formCol2->setAutoUpdate()
	
	->addConfig('flex','1')
	//so that when hidden the labels also disapears and the item doesn't take unnecessary space!!!
	->addConfig('layoutConfig','{trackLabels:true}')
	->addListener('afterrender',"function(){
	
		var t = $formCol2Name.find('name','podatki[attachAnswers]')[0];
		t.on('beforequery', function(qe){ delete qe.combo.lastQuery;} );
		t.on('change', function(cb){ 
			var t;
			if(cb.getValue())
						{
							t = $formCol2Name.find('name','podatki[attachFalse]')[0];
							t.setVisible(true);
						}
						else 
						{
							t = $formCol2Name.find('name','podatki[attachFalse]')[0];
							t.setVisible(false);
						}
		} );
		
		t = $formCol2Name.find('name','podatki[les_sql]')[0];
		t.on('change', function(cb){
			var recTmp = $grid.store.getById($form.selectedRowId);
			if(recTmp.data.tip_sql != 2 ) return; // only for scale!
			var t = $formCol2Name.find('name','podatki[atr_sql]')[0];
			if(cb.getValue() == 2 )
						{
							t.setVisible(true);
						}
						else 
						{
							t.setVisible(false);
						}
		} );
		
		
	}")
	;
	
	
		$grid->addConfig('rowSelectHandler',"function(sm,index,r){
					
					 //we load data for the form
				//		$form.load({params:{id:r.data.id,action:'load',projId:$projectId},
				//	  success:function(f,a){
					  //we store the ID and name of  the selected row in the form
					  $form.selectedRowId = r.data.id;
					  $form.selectedRecord = r;
						$formName.selectedRowName = r.data.q_name;
						var loadData = r.data; 
					//let's decode the goto_sql, to get the data for the grid
						 gotoArr= Ext.decode(    loadData['gotoData'] ) ;
						
						gotoArr.push(['',false,'','&#160;'] );
						//on the server side we created the data
						$gridjmpName.getStore().loadData(gotoArr );   
						//we set the filter in and filter out
						$form.find('name','podatki[fil_sql]')[0].setValue( loadData['fil_sql'] );
						$form.find('name','podatki[con_sql]')[0].setValue( loadData['con_sql'] );
						
						//we set the template name
						$formCol2Name.find('name','podatki[id_template]')[0].setText( loadData['templateName'] );
						
						var t = $formCol2Name.find('name','podatki[variableTypeBase]')[0].setVisible(true);
							t.setValue(loadData['variableTypeBase']  );
						
						t = $formCol2Name.find('name','podatki[attachAnswers]')[0];
						t.setValue(loadData['attachAnswers']  );
						if(t.getValue() && parseInt(t.getValue()))
						{
							t = $formCol2Name.find('name','podatki[attachFalse]')[0];
							t.setValue(loadData['attachFalse']  );
							t.setVisible(true);
						}
						else 
						{
							t = $formCol2Name.find('name','podatki[attachFalse]')[0];
							t.setValue(loadData['attachFalse']  );
							t.setVisible(false);
						}
							
						//if open is checked we show the open type and lenght fields, otherwise we hide it (except for open questions)
						if(loadData['open_answers'] && loadData['tip_sql'] != 4)
						{
							var t = $formCol2Name.find('name','podatki[variableTypeOpen]')[0].setVisible(true);
							t.setValue(loadData['variableTypeOpen']    );
						//	 t = $formCol2Name.find('name','podatki[lenght_variable_open]')[0].setVisible(true);
						//	t.setValue(loadData['podatki[lenght_variable_open]']    );
						}
						else 
						{
							 $formCol2Name.find('name','podatki[variableTypeOpen]')[0].setVisible(false);
							//$formCol2Name.find('name','podatki[lenght_variable_open]')[0].setVisible(false);
							
						}
						$formCol2Name.find('name','podatki[atr_sql]')[0].setVisible(false)
						//scale question has the show as combobox
						if(loadData['tip_sql'] == 2)
						{
							var t = $formCol2Name.find('name','podatki[les_sql]')[0].setVisible(true);
							t.store.filter('scale',1);
							t.setValue(loadData['les_sql']    );
							if(loadData['les_sql'] == 2)
							{
								t = $formCol2Name.find('name','podatki[atr_sql]')[0].setVisible(true);
								t.setValue(loadData['atr_sql']);
							}
						}
						else if(loadData['tip_sql'] == 4)
						{
							var t = $formCol2Name.find('name','podatki[les_sql]')[0].setVisible(true);
							t.store.filter('open',1);
							t.setValue(loadData['les_sql']    );
						}
						else if(loadData['tip_sql'] == 1)
						{
							var t = $formCol2Name.find('name','podatki[les_sql]')[0].setVisible(true);
							t.store.filter('single',1);
							t.setValue(loadData['les_sql']    );
						}
						else 
						{
							var t = $formCol2Name.find('name','podatki[les_sql]')[0].setVisible(true);
							t.store.filter('multi',1);
							t.setValue(loadData['les_sql']    );
						}
						//open questions have the number of other answers field
						if(loadData['tip_sql'] == 4)
						{
							var t = $formCol2Name.find('name','podatki[open_sql]')[0].setVisible(true);
							t.setValue(loadData['open_sql']    );
						}
						else 
						{
							$formCol2Name.find('name','podatki[open_sql]')[0].setVisible(false);
						}
						//info questions have isFinal checkbox
						if(loadData['tip_sql'] == 5)
						{
							var t = $formCol2Name.find('name','podatki[isFinal]')[0].setVisible(true);
							t.setValue(loadData['isFinal']    );
						}
						else 
						{
							$formCol2Name.find('name','podatki[isFinal]')[0].setVisible(false);
						}
						
						//sr and open questions have the use for quotas check box
						if(loadData['tip_sql'] == 1 || loadData['tip_sql'] == 4)
						{
							var t = $formCol2Name.find('name','podatki[use_for_quotas]')[0].setVisible(true);
							t.setValue(loadData['use_for_quotas']    );
						}
						else 
						{
							$formCol2Name.find('name','podatki[use_for_quotas]')[0].setVisible(false);
						}
						
						var t = $formCol2Name.find('name','podatki[answers_filter]')[0].setVisible(true);
						t.setValue(loadData['answers_filter']);
						
						
						//cs questions have a limited set of options
						if(loadData['tip_sql'] == 11)
						{
							t = $formCol2Name.find('name','podatki[id_mask]')[0];
							t.setValue(loadData['id_mask']  );
							$formCol2Name.find('name','podatki[id_mask]')[0].setVisible(true); //show select mask combobox
							$formCol2Name.find('name','podatki[open_sql]')[0].setVisible(false); //hide Number of answers
							$formCol2Name.find('name','podatki[les_sql]')[0].setVisible(false); //hide Show as combobox 
							$formCol2Name.find('name','podatki[answers_filter]')[0].setVisible(false); //hide Allow open without text checkbox
							$formCol2Name.find('name','podatki[attachAnswers]')[0].setVisible(false); //hide Attach answers combobox
							$formCol2Name.find('name','podatki[editAttr]')[0].setVisible(false); //hide Edit attributes button
							$formCol2Name.find('name','podatki[variableTypeBase]')[0].setVisible(false); //hide Var type combobox
						}
						else
						{
							$formCol2Name.find('name','podatki[id_mask]')[0].setVisible(false); //hide select mask combobox
							$formCol2Name.find('name','podatki[attachAnswers]')[0].setVisible(true); //show Attach answers combobox
						}

						
					//    } }); //eo form.load
				
					}" );
		
	
	
	//JS for the tree
	echo $treeWC->CreateTree();
	//we define the root as not question so that we don't have problems identfying it
	echo $treeName.".getRootNode().isQuestion = 0;";
	//echo $treeName.".getRootNode().expand();";
	
	echo $grid->createGrid();
	echo $gridjmp->createGrid();
	echo $form->createForm();
	echo $formCol2->createForm();
	
	
	//attach listeners for rowselect to update the question properties tab with detailed data
	//here we also fill the jump to grid and show/hide special columns like open, show as legend etc.
	echo $grid->getName().".getSelectionModel().on( 'rowselect', function(sm,index,r){ 
	// we show the properties panel!	
					if(!Ext.getCmp('wcbqTabPanel_$tableName').getActiveTab() )			
						Ext.getCmp('wcbqTabPanel_$tableName').activate(0); 
					var propPanel = Ext.getCmp('$cardPropName');
					propPanel.setTitle( 'Properties - '+r.data.q_name );
					if(r.data.tip_sql == 8)
					{
						propPanel.getLayout().setActiveItem(1);
						return;
					}
					if(r.data.tip_sql == 7)
					{
						propPanel.getLayout().setActiveItem(2);
						return;
					}
					propPanel.getLayout().setActiveItem(0);
					propPanel.doLayout();
					
	setTimeout( function(){ $grid.rowSelectHandler(sm,index,r) } ,100 )} ); ";
	
	
//************************************new code ****************************************
		//we add listener to select on tree, to adjust the selected row on the grid
		//ali listtener dodaja na standart view ali na old view
		echo $treeWC->getName()."/*.getSelectionModel()*/.on('click', function(node,e){
		
		
       Ext.Ajax.request({
  			url: 'webcati/_forms/_ajax/ajax.buildQpanels.php',
			params:{
				action: 'getView',
				id_user: '".$_SESSION['UserInfo']['id']."',
				id_project:'".$_POST['id_project']."'
						},
			method:'POST', 
			success: function(res, opts){
			if (res.responseText!='standard') {	
								var innerPanel =  new Ext.TabPanel({
											flex:1,
											height:500,
											id: '".$projectName."'+node.id+'_inner',
											defaults:{
											autoScroll: true},
										});
										
								innerPanel.add({
							     title: 'Basic oprions',
							     id: '".$projectName."'+node.id+'basic_panel',
							     closable:true,
							     items:[]
							     }).show(); 
							     
							     innerPanel.add({
							     title: 'Advanced oprions',
							     id: '".$projectName."'+node.id+'advancted_panel',
							     closable:true,
							     items:[]
							     }).show(); 
							     
							    innerPanel.add({
							     title: 'Script',
							     id: '".$projectName."'+node.id+'script',
							     closable:true,
							     items:[]
							     }).show(); 
							     
							    innerPanel.add({
							     title: 'Multilanguage options',
							     id: '".$projectName."'+node.id+'multilanguage_options',
							     closable:true,
							     items:[]
							     }).show(); 
										
								
								  centerPanel.add({
							     title: '".$projectName."'+'-'+node.id,
							   
							     closable:true,
							     items:[ innerPanel]
							     }).show(); 
							
							     centerPanel.doLayout();
				
						}
						else
						{
							//the last selected node! commented becouse click is used instead of selModel.on(selectionchange) !!!
								//if(nodeArr.length == 0) return;
								//var node = nodeArr[nodeArr.length -1 ];
								$gridName.getSelectionModel().clearSelections();
								//we must fetch the position and relaod with start param, otherwise the pager gets messed up
								$treeName.RMconn.request({params:{action:'getPos',nodeId:node.id,isQ:node.attributes.isQuestion},
								success:function(r){
								var pos = Ext.decode(r.responseText).pos;
								//we call a special function that reloads the grid on the passed position!!!
								reloadGrid_$tableName(pos); }  }); 
						
						}			
					}
		});
						
	}  ); ";
		


	//we override the basic afteredit listener, so that we can update the tree on changes		
	echo $grid->getName().".on('afteredit' , function(e) {
		var qId = e.record.get( e.grid.getColumnModel().config[e.column].idField );
		e.record.commit();
		var p = {
				 //if we update q_name the server must updates both tables (basic and _tree)
				 action: e.field == 'q_name' ? 'updateName' : 'update', 
				 id:qId ,
				idField : e.grid.getColumnModel().config[e.column].idField ,
				field: e.grid.getColumnModel().config[e.column].name ,
				value : e.value ,
				'RMtable': e.grid.getColumnModel().config[e.column].RMtable
				};
				
		$gridName.RMconn.request({			
				 params: p,
				success : function(resp,opt){
				var r = Ext.decode(resp.responseText);
				if(r.success){ //debugger;
				if(e.field == 'q_name'){ 
				//we update the tree name
				$treeName.getRootNode().cascade(function(n){
					if(n.attributes.q_id == qId && n.attributes.isQuestion==true)
						{n.setText(e.value ); n.attributes.text = e.value; n.attributes.qName = e.value; return false; } }  );
				 $grid.getStore().reload(); //we refresh the grid becouse some conditions may have been updated!
				  }
				  else if(e.field == 'tip_sql')
				  {//we must update the properties panel
				  $grid.store.reload({callback:function(){
				  	$grid.rowSelectHandler(true,true,$grid.store.getById( e.record.id ) );
				  } });
				  
				   } 
				 if(r.error)  Ext.Msg.alert('Warning!',r.error);
				 }
				 else if(r.error == 'hasData') //we check if error is becouse of data included
				 	{
				 		var buttons = { ok:'Delete',yes:'Backup' };
				 		if(r.canRecode)
				 			buttons.no = 'Recode';
				 		buttons.cancel = 'Cancel';
				 		Ext.Msg.show({title:'Warning! Data exists',msg:'Fields '+r.fields.join(', ')+ ' will be dropped!<br>Do you want to:',buttons:buttons,
				 			fn: function(btn){
				 				if(btn == 'ok') p.updateConfirm = 'delete';
				 				else if(btn == 'yes') p.updateConfirm = 'backup';
				 				else if(btn == 'no') p.updateConfirm = 'recode';
				 				else { e.record.set(e.field,e.originalValue);e.record.commit(); return;}
				 				$gridName.RMconn.request({ params : p });
				 			}
				 		});
				 	}
				  else {
				 e.record.set(e.field,e.originalValue);e.record.commit(); 
				 Ext.Msg.alert('Error!',r.error);
				 }},
				failure: function(){e.record.set(e.field,e.originalValue);e.record.commit();}});  }); ";
				
		//the function for reloading grid 
	echo "var reloadGrid_$tableName = function(start){	".$grid->getName().".getStore().reload({
		params:{start:start },callback:function(){".$grid->getName().".getSelectionModel().selectFirstRow();   }}); }; ";
	//we configure the ontrigger click function to open the bigger filter text area
	echo "
	Ext.each(".  $form->getName().".findByType('field'),function(field) {	
		field.onTriggerClick = function(e){ 
			var tmpName = 'edit_'+$formName.selectedRowName+'_'+field.RMfieldName;
			//we create a new Calc top bar
			//and we use it's field as the basic textarea for this form
			var tmpTbar = new Ext.ux.CalcTBar({field:new Ext.form.TextArea({name:'value',value:field.getValue()
					  }),cmp:'field'  });
				tmpTbar.field.on('afterrender',function(fldTmp){
					if(Ext.isIE) //for IE we have special functions to always remember the last caret position
					{
						tmpTbar.field.el.on('keyup',function(fld){
							var textArea = document.getElementById(tmpTbar.field.getId());
							var rangeCopy;
							var range = document.selection.createRange();
							  rangeCopy = range.duplicate();
							rangeCopy.moveToElementText(textArea);
							rangeCopy.setEndPoint( 'EndToEnd', range );
							   start = rangeCopy.text.length - range.text.length;
							 tmpTbar.fCaret = start;
							 tmpTbar.field.fCaret = start;
							
						});
						tmpTbar.field.el.on('click',function(fld){
							 var textArea = document.getElementById(tmpTbar.field.getId());
							var rangeCopy;
							var range = document.selection.createRange();
							  rangeCopy = range.duplicate();
							rangeCopy.moveToElementText(textArea);
							rangeCopy.setEndPoint( 'EndToEnd', range );
							   start = rangeCopy.text.length - range.text.length;
							 tmpTbar.fCaret = start;
							 tmpTbar.field.fCaret = start;
						});
					}
					fldTmp.RMdd = new Ext.wc.DropQuestion(tmpTbar.field.getId(),{RMconn:$gridName.RMconn,field:tmpTbar.field,cmp:'field',textVar:'qName'});	
					fldTmp.on('beforedestroy',function(cmp)
					{
						if(cmp.RMdd) cmp.RMdd.destroy();
					});
					
					});
					
			//we add a form to the lower tab and insert the field from the top bar (heh...reverse logic)
			Ext.getCmp('wcbqTabPanel_$tableName').add({
					xtype:'form',closable:true,layout:'fit'
					,url:'_ajaxManipulators/formDataManipulator.php'
					, id :tmpName
					, title: $formName.selectedRowName+' - ' + field.fieldLabel
					, iconCls: 'RMicon_edit_record'
					,items: [tmpTbar.field]
					,tbar:tmpTbar
					,buttons:[{text:'Save',handler: function()
					{ this.findParentByType('form').getForm().submit({params:{
					action:'update',RMtable:'$tableName',
					id:$formName.selectedRowId,database:'".DB_WARPIT_WEBCATI."',field:field.RMfieldName }
					,success:function(){ ".$grid->getGridName(). ".getStore().reload();Ext.getCmp('wcbqTabPanel_$tableName').remove(Ext.getCmp(tmpName));  }});
					
					} },{text:'Cancel',handler:function(){ Ext.getCmp('wcbqTabPanel_$tableName').remove(Ext.getCmp(tmpName));  }} ]  
			}).show();
			
			
		  };   
		
		
	});";
	
	
	
	//we go through each children in the form and set a dropTarget with the group of the tree!
	echo $form->getName(). ".on('afterlayout',function(){
	//afterlayout get's called multiple times so we have a safety pin!
		if($formName.hasDDTarget)
		{
			return;
			}	
		$formName.hasDDTarget = true;
	
		Ext.each(".  $formName.".findByType('field'),function(field) {
		//we add the new special DropQuestion (_plugins/DropQuestion.js)
		field.RMdd = new Ext.wc.DropQuestion(field.getId(),{RMconn:$gridName.RMconn,field:field,cmp:'field',textVar:'qName'});
		field.on('beforedestroy',function(cmp)
		{
			if(cmp.RMdd) cmp.RMdd.destroy();
		});
		if(Ext.isIE)
		{//we add special listeners to keep the caret position in IE (becouse IE is serious deep shit!!!)
			field.fCaret = 99999;
			field.el.on('keyup',function(fld){
				field.fCaret = getCaretPosition(  field.getId() );
			//	 $tbarName.fCaret = getCaretPosition(  field.getId() );
			});
			field.el.on('click',function(fld){
				field.fCaret = getCaretPosition(  field.getId() );
			//	 $tbarName.fCaret = getCaretPosition(  field.getId() );
			});
		}
		
		
		
	})  } );";
	//function for adding HTML editing tabs on iconactions in the grid
	echo  "var addEditTab_$tableName = function(record,grid,col,value,dataIndex){ 
					var tmpName = 'edit_$tableName'+ record.data.q_name+'_' + grid.getColumnModel().getColumnHeader(col); 
					var tmpHtmlName = 'HTML'+tmpName;
					if(Ext.getCmp(tmpName))
					{
						Ext.getCmp('wcbqTabPanel_$tableName').activate(tmpName);
						return;
					}
					
					var tmpForm = Ext.getCmp('wcbqTabPanel_$tableName').add(new Ext.form.FormPanel({
					closable:true,layout:'fit',
					listeners:{ activate:function(){ setTimeout(\"Ext.getCmp('\"+tmpHtmlName+\"').focus()\",200); 
									
					  },
					  beforeclose: function(frm){
					  	if(frm.eHtml.isDirty() )
					  	{
					  		//let's open a confirm window!
						  	Ext.Msg.show({title:'Save changes',msg:'Do you want to save the changes?',buttons:Ext.Msg.YESNOCANCEL,
						  	fn: function(btn){
						  		if(btn == 'yes')
						  		{
						  			frm.saveHandler(true);
						  		}
						  		else if(btn == 'no')
						  		{
						  			Ext.getCmp('wcbqTabPanel_$tableName').remove(frm); 
						  		}
						  	} } );
						  	return false;
					  	}
					  } }
					,url:'$ajaxUrl'
					, id : tmpName
					, saveHandler: function(cl)
					{
					if(this.eHtml.sourceEditMode )
					{
						Ext.Msg.alert('Warning','Cannot save in source mode editor!');
						return;
					}
					this.getForm().submit({params:{RMtrim:true,action:'update',id_language:$grid.getStore().baseParams.id_language, RMtable:'$tableName',id:record.data.id,database:'".DB_WARPIT_WEBCATI."',field:dataIndex }
					,success:function(){ $grid.getStore().reload(); if(cl) Ext.getCmp('wcbqTabPanel_$tableName').remove(tmpForm);  }});
					
					}
					, title: record.data.q_name+' - ' + grid.getColumnModel().getColumnHeader(col)
					, iconCls: 'RMicon_edit_record'
					,items: [{ id : tmpHtmlName,
					xtype:'htmleditor',value:value,name:'value',ref:'eHtml' }] 
					,buttons:[{text:'Save',handler: function(){ tmpForm.saveHandler(false);} },{text:'Save&Close',handler: function()
					{
					tmpForm.saveHandler(true);
					
					} },{text:'Cancel',handler:function(){ 
					Ext.getCmp('wcbqTabPanel_$tableName').remove(Ext.getCmp(tmpName)); 
    								
					 }} ]   
					
			})); 
			tmpForm.show();
			};";
			//function for adding grid for answer and script!
			//it's called upon click on the action icons in the answers and legend column
		echo  "var addGridEditTab_$tableName = function(record,grid,col,value,dataIndex){ 
					var colName = dataIndex == 'atr_sql' ? 'Attributes' : grid.getColumnModel().getColumnHeader(col);
					var tmpName = 'edit_$tableName'+ record.data.q_name+'_' + colName; 
			var isAns = dataIndex == 'odg_sql';
			var isLeg = dataIndex == 'leg_sql';
			CallScript('webcati/_forms/buildQuestionare/forms.scriptGrid.php',{
			'name':tmpName,data: value,tableName:'$tableName',gridName:'$gridName', 
			title: record.data.q_name+' - ' + colName,
			dataIndex:dataIndex,id:record.data.id,nogo_answers:record.data.multi_nogo_answers,slider_data: record.data.open_sql,
			tip:record.data.tip_sql,
			filter_answer: isAns ? record.data.filter_answer : isLeg ? record.data.filter_legend : record.data.filter_attributes ,
			rotFrom: isAns ? record.data.srot_sql : isLeg ? record.data.srotLegend : record.data.srotAttributes ,
			rotTo: isAns ? record.data.erot_sql : isLeg ? record.data.erotLegend : record.data.erotAttributes ,
			open_data: isAns ? record.data.open_answers : isLeg ? record.data.open_legend : record.data.open_attributes ,
			id_language: $grid.getStore().baseParams.id_language,
			dataBase : '".DB_WARPIT_WEBCATI."' 
			 }   );
		               
		//	tmpForm.show();
			};";
		//function for adding script editing tab!
	echo  "var addScriptTab_$tableName = function(rowId,qName){ 
					var tmpName = 'script_$tableName'+ qName; 
					var tmpHtmlName = 'area'+tmpName;
					if(Ext.getCmp(tmpName))
					{
						Ext.getCmp('wcbqTabPanel_$tableName').activate(tmpName);
						return;
					}
					//lets make ajax call to get value of the script
					$grid.RMconn.request({
						params:{action:'getScript',id:rowId,idEvent:1},
						success:function(rsp,opt)
						{
							var val = Ext.decode(rsp.responseText).value;
						
					
						var tmpForm = Ext.getCmp('wcbqTabPanel_$tableName').add({
								id:tmpName,
							   xtype: 'uxCodeMirrorPanel',
						        title: 'Script - '+qName,
						        closable: true,
						        listeners: {
						            render: function(){
						                this.doLayout();
						            }
						        },
						        sourceCode: val,
						        //layout: 'fit',
						        parser: 'rmmix',
						        onSave: function() {
						            $grid.RMconn.request({
						            	params: {
						            		action:'saveScript',
						            		id_question: rowId,
						            		value: tmpForm.codeMirrorEditor.getCode(),
						            		idEvent:this.idEvent
						            	}
						            });
						        },
						        idEvent:1,
						        codeMirror: {
						            height: '100%',
						            width: '100%'
						        },
						        listeners:{
						        	
						        	afterrender:function(p){
						        		//create a combobox with script events
						        		
						        		var pecl = new Ext.form.ComboBox({
						        		typeAhead: true,
									    triggerAction: 'all',
									    mode:'local',
									    value:1,
									    store: webCatiScriptEventsStore,
									    valueField: 'id',
									    displayField: 'name',
									    listeners:{
									    	scope:this,
									    	select:function(cb,rec)
									    		{
									    		this.idEvent = rec.id;
									    		$grid.RMconn.request({
													params:{action:'getScript',id:rowId,idEvent:this.idEvent},
													scope:this,
													success:function(rsp,opt)
													{
														this.codeMirrorEditor.setCode( Ext.decode(rsp.responseText).value || '' );
														if(rec.data.parser == 'php')
															this.codeMirrorEditor.setParser('PHPParser');
														else if(rec.data.parser == 'js')
															this.codeMirrorEditor.setParser('JSParser');
													}
													});
									    		}
									    	}
									    
									    });
									    p.topToolbar.add(pecl);
									   
						        	}
						        }
						});
						//tmpForm.topToolbar.addField(new Ext.form.TextField());
						tmpForm.show();
					}
					});
			};";	
			
			
	
	//we add a dropTarget to the grid (the special DropQuestion)
	echo "$gridjmp.on('afterrender',function(){
	
	$gridjmpName.RMdd = new Ext.wc.DropQuestion($gridjmpName.el,{RMconn:$gridName.RMconn,grid:$gridjmpName,field: $gridjmpName,cmp:'grid',textVar:'qName',
	notifyOver: function(dds,e,data){
	//we allow dropping only in the inner cells or editor
		if(	(e.getTarget('div.x-grid3-cell-inner') || e.getTarget('input.x-form-text'))
	//we allow only leafes!
		&& data.node && data.node.attributes.leaf
		)
		{
			return Ext.dd.DropZone.prototype.dropAllowed;
		}
		else
		{
			return Ext.dd.DropZone.prototype.dropNotAllowed;
		}
	
		
		},
		//we override the DropQuestion notify drop becouse project has a special drop
		notifyDrop: function(dds,e,data){
		if(!(data.node && data.node.attributes.leaf))
			return true;
		
		this.elTarget = e.getTarget('div.x-grid3-cell-inner');
		if(	this.elTarget) 
		{//if the target is a cell (other option is editor)
			this.elTargCmp = 'cell';
			var gv = $gridjmpName.getView();
			var row = gv.findRowIndex(this.elTarget);
			var cell = gv.findCellIndex(this.elTarget);
			var rec = $gridjmpName.getStore().getAt(row);
			if(cell == 2)
			{
			//if we drop into the question/project column we set the value to the name (instead of adding \$name to the value)
			//we also set the toProject accordingly
				if(dds.dragData.node.ownerTree == $treeName)
				{
					rec.set('toProject',false);
					rec.set('question',data.node.attributes.qName);
				}
				else 
				{
					rec.set('toProject',true);
					rec.set('question',data.node.attributes.text);
				}
				return true;
			}
			else if(cell == 0)
			{
				//if column is condition we call the basic add data
				return this.myNotifyDrop(dds,e,data);
				
			}
		}
		this.elTarget = e.getTarget('input.x-form-text');
		if(	this.elTarget) 
		{//if we drop to the editor we get the info and call the basic notify drop
			var ae = $gridjmpName.activeEditor;
			//if the editor is of project/question column we do the same as above
			if(ae.col == 2)
			{
				var rec = $gridjmpName.getStore().getAt(ae.row);
				$gridjmp.stopEditing();
				if(dds.dragData.node.ownerTree == $treeName)
				{
					rec.set('toProject',false);
					rec.set('question',data.node.attributes.qName);
				}
				else 
				{
					rec.set('toProject',true);
					rec.set('question',data.node.attributes.text);
				}
				return true;
			}
			this.gRow = ae.row;
			this.gCell = ae.col;
			this.fCaret= getCaretPosition(  ae.field.getId() );
			this.elTargCmp = 'editor';
			//$gridjmpName.stopEditing();
			return this.myNotifyDrop(dds,e,data);;
		}
		
		return false;
		
	
		
		},
	 updateField:function(dds,e,val){ 
	 	//elTargt =  e.getTarget('div.x-grid3-cell-inner');
		if(this.elTargCmp == 'cell')
		{
			var gv = $gridjmpName.getView();
			var row = gv.findRowIndex(this.elTarget);
			var cell = gv.findCellIndex(this.elTarget);
			var rec = $gridjmpName.getStore().getAt(row);
			if(cell == 0)
			{
				var text = rec.get('cnd');
				if(text.length != 0 && text.charAt(text.length - 1) != ' ')
				{
					text+=' ';
				}
				rec.set('cnd',text+val);
				$gridjmpName.startEditing(row,cell);
				
			}
			return true;
		}
		//elTargt =  e.getTarget('input.x-form-text');
		if(this.elTargCmp == 'editor')
		{
		
		
		wcbqAddTextField(this,val,true);
		
		return true;
		}
	 }
	});
	//destroying the listener
	$gridjmpName.on('beforedestroy',function(cmp)
		{
			if(cmp.RMdd) cmp.RMdd.destroy();
		});
	
	 })//EOF gridhmpName afterrender listener  
	;
	$grid.on('beforedestroy',function(cmp)
		{
			$desWindow.destroy();
		});
	";
	
	echo "var $tbarName = new Ext.ux.CalcTBar();
		$tbarName.grid = $gridjmpName;";
		
	//lets create objects for the properties of the status
	//somehow this would be wise to create only if project has a status or when it gets a status...but how? :/
	
	
	//lets create the grid where we define the items that are displayed in status		
	
	$showVarGrid->setMainTable('_TelephoneTblAddonProject',DB_WARPIT_WEBCATI_BASE);
	$showVarGrid->setReqUrl('webcati/_ajax/buildQuestionare/ajax.showVariables.php')
	->flex(1)
	->setTitle('Project Items');
	
	$showVarGrid->addColumn('is_addon');
	$showVarGrid->addColumn('id_var');
	$showVarGrid->addColumn('name','Name');
	$showVarGrid->addColumn('show_var','Show')->type('checkColumn');
	
	$showVarGrid->setEditable(false)
	->addConfig('anchor',"'99% -50'")
	
	->baseParams = "id_project : $projectId,projName:'$tableName'";
	
	echo $showVarGrid->createGrid();
	
	echo $showVarGrid.".on('afteredit' , function(e) {
		$showVarGrid.RMconn.request({			
				 params: {
				 //if we update q_name the server must updates both tables (basic and _tree)
				 action: 'update', 
				 isA:e.record.data.is_addon ,
				 name:e.record.data.name,
				 value:e.value,
				 id_var:e.record.data.id_var
				},
				success : function(resp,opt){if(Ext.decode(resp.responseText).success){ e.record.commit(); 
				 } else {e.record.reject();}},
				failure: function(){e.record.reject();}});  }); ";
	//let's create the grid where you select which statuses show for this specific project!
	$statusGrid = new MakeGrid();
	$statusGrid->setMainTable('_TelephoneStatuses',DB_WARPIT_WEBCATI_BASE);
	$statusGrid->setReqUrl('webcati/_ajax/buildQuestionare/ajax.showVariables.php')
	->setTitle('Project Statuses');
	
	$statusGrid->addColumn('id_var');
	$statusGrid->addColumn('name','Status','new Ext.form.TextField()');
	$statusGrid->addColumn('show_status','Show')->type('checkColumn');
	
	$statusGrid->setEditable(false)
	->setAutoExpand('name')
	->addConfig('flex',"1")
	->addTbarItem("{ text: 'Add',iconCls:'icon-add-record',handler: function(){
		var form;
		var w = new Ext.Window({
			modal:true,
			title:'Add status',
			layout:'fit',
			width:350,
			height:300,
			closeAction:'hide',
			items: [
			form = new Ext.form.FormPanel({
			frame: true,
			items:[	{
				xtype:'textarea',name:'opis',fieldLabel:'Text',width:200,allowBlank:false	},
				{xtype:'numberfield',name:'status',fieldLabel:'Status',width:50,allowBlank:false},
				{ xtype:'numberfield',name:'status_rec',fieldLabel:'Status rec',width:50,allowBlank:false  } ,
				{
				xtype:'checkbox',name:'show_default',fieldLabel:'Show by default'	},
				{xtype:'checkbox',name:'isPublic',fieldLabel:'Public'},
				{ xtype:'checkbox',name:'autodial_disable',fieldLabel:'Manual only' }
				 ]})]
				 ,
			buttons:[{
				text:'Ok',
				handler: function(){
					if(form.getForm().isValid())
					$statusGrid.RMconn.request({
						params: Ext.apply({
							action: 'insertStatus',
							id_project: $projectId
						},form.getForm().getValues()),
						success: function(resp){
							var r = Ext.decode(resp.responseText);
							if(r.success)
							{
								$statusGrid.getStore().reload();
								w.close();
							}
							else
								Ext.Msg.alert('Error',r.error);
						}
					}); 
					 }
			},{
				text:'Cancel',
				handler:function(){w.close();}
			}]
			}).show();
	} },
	{ text:'Edit',iconCls:'RMicon_edit_record',handler: function(){
		addTabAuto('manageStatuses','webcati/_forms/buildQuestionare/forms.manageStatus.php',{});
	} }")
	->baseParams = "id_project : $projectId,grid:'status'";
	
	echo $statusGrid->createGrid();
	
	echo $statusGrid.".on('afteredit' , function(e) {
		$statusGrid.RMconn.request({			
				 params: {
				 //if we update q_name the server must updates both tables (basic and _tree)
				 action: 'update', 
				 value:e.value,
				 field:e.field,
				 id_var:e.record.data.id_var
				},
				success : function(resp,opt){if(Ext.decode(resp.responseText).success){ e.record.commit(); 
				 } else {e.record.reject();}},
				failure: function(){e.record.reject();}});  }); ";
	
				
	//forms for dialing options!!!
	//!!!!!!!!!!!!!!!!!!!!!!!!! the right form in the properties panel!!!!!!!!!!!!!!!!!!!
	//most of this fields are hidden on rowselect, dependent on some question properties!
	$dialerFormCol1 = new MakeForm($tableName.'_dialerCol1');
	//$dialerFormCol1->setReqUrl($ajaxUrl);
	$dialerFormCol1->setMainTable('_Projects',DB_WARPIT_WEBCATI_BASE)
	->addConfig('padding','10')
	->addConfig('border','false');
	//showing which designer template is chosen for this question
	$dialerFormCol1->addField('num_max_call','Maximum number of calls<br>(not, if appointment)','numberfield'); 
	$dialerFormCol1->addField('num_max_call_app','Maximum number of calls<br>(if appointment)','numberfield'); 
	
	$dialerFormCol1->addField('busy_call_delay','Call delay for bussy calls (min)','numberfield'); 
	
	$dialerFormCol1->addField('noanswer_call_delay','Call delay for unanswered call (min)','numberfield'); 
	
	$dialerFormCol1->addField('call_time_length','Call time length (sec)','numberfield'); 
	

	//shows only for single respons and open! determines whether they can be used in quotas!	
	
	//same as for $form we add a default listener to save changes

	$dialerFormCol1->autoUpdateFunction= "function(fld,val){
			var url = '_ajaxManipulators/formDataManipulator.php';
			var action = 'update';
			var p = { RMcomp:'form', 
			action: action ,RMtable:'_Projects',database:'".DB_WARPIT_WEBCATI_BASE."',
			field:fld.RMfieldName, value:val,id:$projectId };
					new RMajax().request({
					url: url,
					params: p });   
					 }";
	$dialerFormCol1->setAutoUpdate()
	->addConfig('flex','1')
	->addConfig('labelWidth',200)
	//so that when hidden the labels also disapeasr and the item doesn't take unnecessery space!!!
	->addConfig('layoutConfig','{trackLabels:true}')
	;
	
	$dialerFormCol2 = new MakeForm($tableName.'_dialerCol2');
	//$dialerFormCol2->setReqUrl($ajaxUrl);
	$dialerFormCol2->setMainTable(_Projects,DB_WARPIT_WEBCATI_BASE)
	->addConfig('padding','10')
	->addConfig('border','false');
	
	$dialerFormCol2->addField('telselect','Select telephone number manually','checkbox');
	$dialerFormCol2->addField('strictlock_manual','Use strict-lock also with manual dialing','checkbox');
	$dialerFormCol2->addField('set_use_autodial','Use automatic dialing system','checkbox');
	$dialerFormCol2->addField('use_predictive','Use predictive dialing','checkbox');
	$dialerFormCol2->addField('predictive_work','Activate predictive','checkbox');
	$dialerFormCol2->addField('predictive_overcall','Over calling %','numberfield');
	$dialerFormCol2->addField('predictive_numbers_tofind','Find numbers at once','numberfield');
	
//	$dialerFormCol2->addConfig('defaults',"{listeners:{ change:function(fld,val){
//			var url = '_ajaxManipulators/formDataManipulator.php';
//			var action = 'update';
//			var p = { RMcomp:'form', 
//			action: action ,RMtable:'_Projects',database:'".DB_WARPIT_WEBCATI_BASE."',
//			field:fld.RMfieldName, value:val,id:$projectId };
//			if(fld.RMfieldName == 'use_for_quotas')
//			{
//				url = '$ajaxUrl';
//				p.action = 'updateUseForQuotas';
//				p.q_name = $formName.selectedRowName;
//			}
//			
//					new RMajax().request({
//					url: url,
//					params: p });   
//					 }
//					         }   }")
	$dialerFormCol2->autoUpdateFunction = "function(fld,val){
			var url = '_ajaxManipulators/formDataManipulator.php';
			var action = 'update';
			var p = { RMcomp:'form', 
			action: action ,RMtable:'_Projects',database:'".DB_WARPIT_WEBCATI_BASE."',
			field:fld.RMfieldName, value:val,id:$projectId };
			if(fld.RMfieldName == 'use_for_quotas')
			{
				url = '$ajaxUrl';
				p.action = 'updateUseForQuotas';
				p.q_name = $formName.selectedRowName;
			}
			
					new RMajax().request({
					url: url,
					params: p });   
					 }";
	$dialerFormCol2->setAutoUpdate(true)
	->addConfig('flex','1')
	->addConfig('labelWidth',200)
	//so that when hidden the labels also disapeasr and the item doesn't take unnecessery space!!!
	->addConfig('layoutConfig','{trackLabels:true}')
	;
	echo $dialerFormCol1->createForm();
	echo $dialerFormCol2->createForm();
	echo "$dialerFormCol1.on('render',function(cmp){cmp.getForm().load({params:{action:'load',id:$projectId}})});
	$dialerFormCol2.on('render',function(cmp){cmp.getForm().load({params:{action:'load',id:$projectId}})});
	if(typeof webCatiScriptEventsStore == 'undefined')
        		{
        			webCatiScriptEventsStore = new Ext.data.JsonStore({
        				url:'$ajaxUrl',
						baseParams:{database:'".DB_WARPIT_WEBCATI_BASE."',RMtable:'_ScriptEvents',action:'selectScriptEvents' },
						fields:['id','name','parser'],
						autoLoad:true,root:'rows'
						
        			});
        		}"
        		
        		
	
?>

	var <?php echo $tabId; ?> = new Ext.Panel({
		id:'<?php echo $tabId; ?>',
		//title:'Build Questionnaire - <?php echo $tableName; ?>',
		title:'<?php echo $tableName; ?>',
		iconCls: "icon_build_questionnare",
		closable:true,
		
		defaults:{split:true,border:false},
		layout:'border',
		border: false,
		items:[]
			});
				//*****************************************new code******add**********************************************************		
		 var centerPanel= new Ext.TabPanel({
id:'centerPanel_old',

xtype: 'tabpanel',
title: 'Compose panel',
flex:1,
items:[]
});

		 var tatab= new Ext.TabPanel({
					xtype:'tabpanel',
					region:'south',
					id:'wcbqTabPanel_<?php echo $tableName; ?>',
					height:370,activeItem:0,
					items:[ //a card layout for status/dailer and other types of question
						{layout:'card',title:'Properties',iconCls:'icon-options-3',id:'<?php echo $cardPropName?>',activeItem:3,
						listeners:{ show:function(){
						//sometimes if another panel is active during the form load, the layout dissapiers mysterioly :) we have this as a safety pin
						//example: before any row is selected we click on the edit question icon...
						this.layout.activeItem.doLayout();
						} },
						items:[
						 {layout:'hbox',layoutConfig:{align:'stretch'},autoScroll:true,
						 
							    buttons: [{ text:'Save' }],
								tbar: <?php echo $tbarName;?>
								
							, items:[  <?php echo $form->getName().','.$formCol2->getName() ; ?>  ]},
							//panel that cointans status properties (combo,grid and grid)
							{layout:'hbox',layoutConfig:{align:'stretch'},autoScroll:true,
							items:[
									{xtype:'panel',flex:1,layout:'vbox',layoutConfig:{align:'stretch'},
									items:[
									{ xtype: 'form',//wrapper panel to define padding to the combobox
									padding: '2px 0px 0px 7px',
									labelWidth:250,
									height: 30,
									items: [ new Ext.form.ComboBox({
										fieldLabel:'Attach table with telephone numbers',triggerAction:'all',style:{padding:2},
										displayField:'name',
										valueField:'id',
										store : new Ext.data.JsonStore({
											url: '_ajaxManipulators/gridDataManipulator.php', <?php 
											$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
											$idTel = $db->fetchArray($db->SQLexecute("SELECT id_telname FROM _Projects WHERE proj_name = '$tableName'"));
											$idTel = $idTel[0];
										/*	$res = $db->SQLexecute("SELECT * FROM _TelephoneTables WHERE is_leaf = 1 ORDER BY name");
											//echo "[0,'Select']";
											while ($row = $db->fetchAssoc($res))
											{
												$telTablSel[] = "[".$row['id'].",'".$row['name']."']";
											}
											if(is_array($telTablSel))
												echo implode(',',$telTablSel);
											echo "],";*/
											echo "baseParams:{
												RMtable: '_TelephoneTables',
												database: '".DB_WARPIT_WEBCATI_BASE."',
												action:'select',
												SQLwhere: 'is_leaf = 1'
											},";
											if($idTel) echo "listeners:{ load:function(){
													var cmbTmp = Ext.getCmp('$telephoneTableCBId');
													if(!cmbTmp.getValue()) cmbTmp.setValue($idTel);
											} },autoLoad:true,";
											echo "fields:['id','name'],
											root:'rows'";
											?>}),<?php 
											
											if ($idTel) echo "value: ".$idTel.", "; // dodal soulcek
											echo "id:'$telephoneTableCBId',
											listeners:{'beforeselect':function(cb,rec){
														$showVarGrid.RMconn.request({params:{
															action:'changeDatabase',value:rec.data.id
														},success:function(){ $showVarGrid.getStore().reload(); }
														});
													},beforequery:function(qe){ delete qe.combo.lastQuery;}}";
										?> 
										
									})
									]},
									<?php echo $showVarGrid ?> ]
									},
									<?php echo $statusGrid ?> 
								]},
								//panel that contains calling options!
								{layout:'hbox',layoutConfig:{align:'stretch'},autoScroll:true
								, items:[  <?php echo $dialerFormCol1->getName().','.$dialerFormCol2->getName() ; ?>  ]}
							 ,{}//an empty layout to show when no question is selected!
							 ]}
						 ]
				});
		
		<?php echo $tabId;?>.add(<?php echo $treeWC->getName()?> );
			
			var glavniPan = new Ext.Panel(	{
				id:'tree_question_vew_<?php echo $tableName?>',
				name:'tree_question_vew',
				layout:'border',
				region:'center',
				defaults:{split:true,border:false},
				items:[]
			 });
		
	
	if (nacin_Pogleda=='standard') 
	{	
		glavniPan.add(<?php echo $grid->getName(); ?>);	
		glavniPan.add(tatab);	
	}
	else 
	{
		glavniPan.add(centerPanel);
			console.log(centerPanel); 
	}
	<?php echo $tabId;?>.add(glavniPan);	
	
			
	
<?php 	
	// write a name of a component, ExtJS evaluate this object into tree on the screen
	//if multiple tabs are shown at once, the tab manager takes care that only one is shown by sending uniqueNotShow as params!
	//in this case we only add the panel
	if($_POST['uniqueNotShow'])
		echo "mainTabPanel.add($tabId); ";
	else
		echo "mainTabPanel.add($tabId).show(); ";
?>