<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_form.php");
	
$db->ChangeDatabase(DB_WARPIT_WEBRECODE);
?>

<?php
	if(isset($_POST["id_project"]))
		$id_proj=', id_project:'.$_POST["id_project"];
	else 
		$id_proj=', id_project:0';
	
		$proj_name=$_POST["proj_name"];
		
	// ----------------------------------------------------------------------------------------
	
	$qtip="function(val, cell, record) {
        // return markup
        return '<div ext:qtip=\"'+ val.replace(/\"/g,\"'\") + '\">' + stripHTML( val ) + '</div>';
    }";

	$variables = new MakeGrid();
	$recoded_groups = new MakeGrid();
	$recoded_groups->setGridName($proj_name.'_recoded_groups');
	
	$kategorije = new MakeGrid();
	$kategorije->setGridName($proj_name.'_kategorije');
	
	$variables->setGridName($proj_name.'_variables')
	->setMainTable('opravki',DB_WARPIT_WEBRECODE)
	->setTitle('Variables');
	
	$variables->reqUrl = 'webcati/_forms/_ajax/ajax.webrecode.php';
	$variables->baseParams='grid_action:"get_variables"'.$id_proj;
	
	$variables->addColumn('id');
	
	$variables->addColumn(array("dataIndex" => "variable", "header" => "Variable", "width" => 60));
	$variables->addColumn('lab','Label')->renderer($qtip);
	
	$variables->setAutoExpand('lab')
		->setCheckBoxSelectionModel(true);
	$variables->addtBarItem("{text:'Create recode group',handler: function(){ if($variables.selModel.getSelections().length > 0)  show_window();}}");
	//$variables->setExpander('{lab}');
	echo $variables->createGrid();
	
	
	// ----------------------------------------------------------------------------------------
	
	
	echo "// Grid for adding the quotas from the telephone database and the questionaire";
	$answers_in_categories = new MakeGrid();
	
	$answers_in_categories->setGridName($proj_name.'_answers_in_categories')
	->setMainTable('opravki',DB_WARPIT_WEBRECODE)
	->setTitle('Recoded answers')
	->addConfig('enableDragDrop','true')
		->addConfig('ddGroup',"'recodeGroup'");
	
	$answers_in_categories->reqUrl = 'webcati/_forms/_ajax/ajax.webrecode.php';
	$answers_in_categories->baseParams='proj_name:"'.$proj_name.'",grid_action:"get_answers_in_categories"'.$id_proj;
	
	$answers_in_categories->addColumn('id');
	$answers_in_categories->addColumn(array("dataIndex" => "id_var", "header" => "Value", "width" => 45));
	$answers_in_categories->addColumn('label','Label')->renderer($qtip)->editor('new Ext.form.TextField()');
	
	$answers_in_categories->setAutoExpand('label')
		->setAutoLoad(false)
		->setCheckBoxSelectionModel(true)
		//->setExpander('{label}')
		->addButtonSendSelected2('Remove answer', '{url:"webcati/_forms/_ajax/ajax.webrecode.php", params:{data:0, grid_action:"remove_answers_from_category", multicode:'.$proj_name.'_recoded_groups.getSelectionModel().getSelected().data.multicode, recoded_id:'.$proj_name.'_kategorije.getSelectionModel().getSelected().data.id},
			 success:function(opt,suc,res){' . 
					//NOTE: refreshing of grid 1 is not always neccesery!!! only when answer grid changes!
					"$variables.loadGrids('1,3,5'); }}", 'id');
	echo $answers_in_categories->createGrid();
	
	
	// ----------------------------------------------------------------------------------------
	

	
	echo "// Grid for adding the quotas from the telephone database and the questionaire";
	$answers = new MakeGrid();
	
	$answers->setGridName($proj_name.'_answers')
	->setMainTable('opravki',DB_WARPIT_WEBRECODE)
	->setTitle('Unrecoded answers')
	->addConfig('enableDragDrop','true')
	->addConfig('ddGroup',"'recodeGroup'")
		->setAutoLoad(false);
	
	$answers->reqUrl = 'webcati/_forms/_ajax/ajax.webrecode.php';
	$answers->baseParams='proj_name:"'.$proj_name.'",grid_action:"get_answers_to_display"'.$id_proj;
	
	$answers->addColumn('id');
	$answers->addColumn(array("dataIndex" => "id_var", "header" => "Value", "width" => 45));
	$answers->addColumn(array("dataIndex" => "procent", "header" => "%", "width" => 45));
	$answers->addColumn('label','Label')->renderer($qtip)->editor('new Ext.form.TextField()');
	$answers->addColumn(array("dataIndex" => "rec_cat", "header" => "Recoded into", "width" => 75));
	
	//setSearchField('Search','top',0,"['group_id','q_pos','variableTypeBase']");
	$answers->setSearchField('quick search', 'top', 1);
	$answers->searchFieldTwo=true;
	
	$answers->setAutoExpand('label')
		->setCheckBoxSelectionModel(true)
		//->setExpander('{label}')
		->addButtonSendSelected2('Add to category', '{url:"webcati/_forms/_ajax/ajax.webrecode.php", params:{grid_action:"insert_answers_into_categorie", id_cat:'.$proj_name.'_kategorije.getSelectionModel().getSelected().data.id, multicode:'.$proj_name.'_recoded_groups.getSelectionModel().getSelected().data.multicode},
			 success:function(opt,suc,res){' .
				"$variables.loadGrids('1,3,5',{ }); }}"
				
				  ,'id')
		->addTbarItem("{text:'Split',handler:function(){
			var ans = $answers.selModel.getSelections();
			if(ans.length)
			
		var w = new Ext.Window({
       	title: 'Split string',
        layout:'form',
        width:300,
        height:200,
        closeAction:'close',
        plain: true,
		items: [{
			ref:'splitChar',
			xtype:'textfield',
			fieldLabel:'Delimiter',
			width:150
		},
		{
			ref:'recodeText',
			value:ans[0].data.label,
			xtype:'textarea',
			fieldLabel:'Label(s)',
			width:150,
			height:100
		}
		],
		modal: true,
		buttons:[{
			text:'Save',
			handler:function(){
				$answers.RMconn.request({params:{ 
						grid_action:'splitLabel',
						id_calc:ans[0].data.id,
						id_var:ans[0].data.id_var,
						delimiter:w.splitChar.getValue(),
						recoded_group:$recoded_groups.getSelectionModel().getSelected().data.id,
						newLabel :w.recodeText.getValue()
					},
						success:function(resp){
							var r = Ext.decode(resp.responseText)
							if(r.success)
							{
								if(r.newCols)
								{
									Ext.Msg.alert('Warning','New columns were created!');
								}
								$variables.loadGrids('1,3,5',{ }); 
							}
						}
					});
				w.close();
			}
		},{
			text:'Cancel',
			handler:function(){
				w.close();
			}
		}]
    

    }).show();
			
			
			
			
		} },'->'");
	echo $answers->createGrid();
	
	
	//------------------------------------------------------------------------------------
	
	
	
	$kategorije->setMainTable('opravki',DB_WARPIT_WEBRECODE)
	->setTitle('Categories')
		->setAutoLoad(false);
	
	$kategorije->reqUrl = 'webcati/_forms/_ajax/ajax.webrecode.php';
	$kategorije->baseParams='proj_name:"'.$proj_name.'",grid_action:"get_categories"'.$id_proj;
	
	$kategorije->addColumn('id');
	//$kategorije->addColumn('var_rec');
	$kategorije->addColumn(array("dataIndex" => "id_var", "header" => "Value", "width" => 45));
	$kategorije->addColumn('label','Label')->editor('new Ext.form.TextField()');
	
	$kategorije->setAutoExpand('label');
	$kategorije->addButtonSendSelected2('Remove category', '{url:"webcati/_forms/_ajax/ajax.webrecode.php", params:{grid_action:"remove_category_from_group", data:0},
		 success:function(opt,suc,res){' 
			  .$variables .  '.loadGrids("1,3,4,5",{});  }}','id');
	$kategorije->addtBarItem("{
		 text:'Add category'
		,handler: function(){ 
			if($recoded_groups.selModel.getSelected()) 
				show_add_categorie_to_recode_group();
		}
	}");
	$kategorije->addtBarItem("{
		 text:'Import'
		,handler: function(){ 
			if($recoded_groups.selModel.getSelected()) 
				show_import_categorie_to_recode_group();
		}
	}");
	echo $kategorije->createGrid();
	
	echo $kategorije.".getSelectionModel().on('rowselect',function(gr,ind,e ){ $variables.loadGrids('5',{id_category:".$kategorije.".getSelectionModel().getSelected().data.id, var_rec:".$kategorije.".getSelectionModel().getSelected().data.var_rec, multicode:".$proj_name."_recoded_groups.getSelectionModel().getSelected().data.multicode}); });";
	
	echo "$kategorije.on('afterrender',function(cmp){
		cmp.RMdd = new Ext.dd.DropTarget(cmp.el,{
			ddGroup:'recodeGroup',
			notifyOver: function(dds,e,data){
			//we allow dropping only in the inner cells or editor
				var trg = e.getTarget('table.x-grid3-row-table');
				if(	trg )
				{
					var gv = cmp.getView();
					var row = gv.findRowIndex( trg );
					if( !cmp.getSelectionModel().isSelected(row) )
					{
						cmp.getSelectionModel().selectRow(row);
					}
					return Ext.dd.DropZone.prototype.dropAllowed;
				}
				else
				{
					return Ext.dd.DropZone.prototype.dropNotAllowed;
				}
			
				
				},
			notifyDrop: function(dds,e,data){
			//we allow dropping only in the inner cells or editor
				if(	e.getTarget('table.x-grid3-row-table') )
				{
					var gv = cmp.getView();
					var row = gv.findRowIndex( e.getTarget('table.x-grid3-row-table') );
					var rec = cmp.getStore().getAt(row);
					//console.log(dds);
					//console.log(data);
					var sels = data.selections;
					var fld = [];
					for(var i = 0;i<sels.length;i++)
					{
						fld.push( sels[i].id );
					}
					
					var obj = {url:'webcati/_forms/_ajax/ajax.webrecode.php', params:{grid_action:'insert_answers_into_categorie', id_cat:rec.id, multicode:".$proj_name."_recoded_groups.getSelectionModel().getSelected().data.multicode},
						 success:function(opt,suc,res){
						$variables.loadGrids('1,3,5',{}); }};
					obj.params.data=Ext.encode(fld);
					cmp.RMconn.request(obj); 
					
					return true;
				}
				else
				{
					return false;
				}
			
				
				}
			} ) ;
	});
	//destroying the listener
	$kategorije.on('beforedestroy',function(cmp)
		{
			if(cmp.RMdd) cmp.RMdd.destroy();
		});";
	
	
	
	// ----------------------------------------------------------------------------------------
	
	
	$recoded_groups
	->setMainTable('opravki',DB_WARPIT_WEBRECODE)
	->setTitle('Recoded variables');
	
	$recoded_groups->reqUrl = 'webcati/_forms/_ajax/ajax.webrecode.php';
	$recoded_groups->baseParams='grid_action:"get_recoded_groups"'.$id_proj;
	
	$recoded_groups->addColumn('id');
	$recoded_groups->addColumn(array("dataIndex" => "var_rec", "header" => "Var rec", "width" => 50));
	$recoded_groups->addColumn(array("dataIndex" => "multicode", "header" => "MC", "width" => 30));
	$recoded_groups->addColumn('label','Label')->renderer($qtip);
	
	$recoded_groups->setAutoExpand('label');
	//$recoded_groups->addtBarItem("{text:'Add category',handler: function(){show_add_categorie_to_recode_group();}}");
	
	echo $recoded_groups->createGrid();
	
	echo $recoded_groups.".selModel.on('rowselect',function(gr,ind,e ){
		var rec_group_id = $recoded_groups.getSelectionModel().getSelected().data.id;
		var mc = $recoded_groups.getSelectionModel().getSelected().data.multicode;
		$answers.getStore().baseParams.id = rec_group_id;
		$variables.loadGrids('3,4,5',{
		id_category:0,
		id_rec_group: rec_group_id,
		 multicode: mc }); 
	 });";
	
	//------------------------------------------------------------------------------------
	
	echo "//a load function which will load multiple grids (marked 1-5) with one ajax call!
	$variables.mlParams = {};
	$variables.loadGrids = function(nums,p){
		Ext.apply( this.mlParams,p);
		this.mlParams.multiLoad = nums;
		this.RMconn.request({params:this.mlParams, success:function(resp){
			var res = Ext.decode(resp.responseText);
			var kva = nums.split(',');
			for(var i=0;i<kva.length;i++)
			{
				var gr = kva[i];
				if(gr == 1) $variables.getStore().loadData(res[i]);
				else if(gr == 2) $recoded_groups.getStore().loadData(res[i]);
				else if(gr == 3) $answers.getStore().loadData(res[i]);
				else if(gr == 4) $kategorije.getStore().loadData(res[i]);
				else if(gr == 5) $answers_in_categories.getStore().loadData(res[i]);
			}
		}});
	};";
?>
	<?php echo $variables; ?>.flex = 1;
	<?php echo $answers_in_categories; ?>.flex = 1;
	<?php echo $answers; ?>.flex = 1;
	<?php echo $kategorije; ?>.flex = 1;
	<?php echo $recoded_groups; ?>.flex = 1;


function show_add_categorie_to_recode_group()
{
	<?php
	$cat=new MakeForm($proj_name.'_add_categorie_to_recode_group');
	$cat->reqUrl='webcati/_forms/_ajax/ajax.webrecode.php';
	
	$cat->addField('category_value','Category value')->setProperty('id',"'id_category'");
	$cat->addField('category_name','Category name');

	$cat->addButton("Save","function(){ " . $cat->getName() . ".getForm().submit({params: {id:".$recoded_groups.".getSelectionModel().getSelected().data.id, grid_action:'create_cat_in_recode_group'".$id_proj."},
		 success:function(){".
				$variables.".loadGrids('4',{}); ".
				$proj_name."_win3.close();} }); }");
	$cat->addButton("Cancel","function(){ ".$proj_name."_win3.close(); }");
	
	
	echo $cat->createForm();
	?>
    
   var <?php echo $proj_name; ?>_win3 = new Ext.Window({
        id:'web_recode_win3',
 		title: 'Create category',
        layout:'fit',
        width:300,
        height:150,
        closeAction:'close',
        plain: true,
		items: <?php echo $proj_name; ?>_add_categorie_to_recode_group,
		modal: true,
		defaultButton:'id_category'
    

    }).show();
}


function show_import_categorie_to_recode_group() {

    var storeProjects = new Ext.data.Store({
	    proxy: new Ext.data.HttpProxy({url: 'webrecode/_ajax/ajax.combo.php?action=projectsCombo'}),
	    reader: new Ext.data.JsonReader({
		    root:'rows'},
		    [{name:'id_project'},{name:'projectName'}])
    });	

    var storeQuestions = new Ext.data.Store({
	    proxy: new Ext.data.HttpProxy({url: 'webrecode/_ajax/ajax.combo.php?action=questionsCombo'}),
	    reader: new Ext.data.JsonReader({
		    root:'rows'},
		    [{name:'varID'},{name:'varLabel'}])
    });	

	var categoryImportProject = new Ext.form.ComboBox({  
	    fieldLabel:'Projects',  
	    id:'comboProjects',  
	    forceSelection: true,  
	    store: storeProjects,  
	    emptyText:'Select project ...',  
	    triggerAction: 'all',  
	    editable:false,  
	    displayField:'projectName',  
        valueField:'projectName',
		width:330,
		mode:'local'
	}); 
    	
	var categoryImportQuestion = new Ext.form.ComboBox({  
	    fieldLabel:'Questions',  
	    id:'comboQuestions',  
	    forceSelection: true,  
	    store: storeQuestions,  
	    emptyText:'Select question ...',  
	    triggerAction: 'all',  
	    editable:false,  
	    displayField:'varLabel',  
        valueField: 'varID',
        hiddenName:'varLabel',
        hiddenValue:'varID', 
		width:330,
		mode:'local',
	}); 
	
	
    var <?php echo $proj_name; ?>_FormImportCategory = new Ext.FormPanel({
        url:'webrecode/_ajax/ajax.combo.php',
        bodyStyle:'padding:15px 15px 0',
        width: 450,
        items: [categoryImportProject,categoryImportQuestion],
        buttons: [
        	{
            text: 'OK'
            ,handler:function(){
				<?php echo $proj_name; ?>_FormImportCategory.getForm().submit({
						params: {
							action:'importCategory',
							projSelected:'<?php echo $proj_name; ?>',
							varSelected:<?php echo $proj_name; ?>_recoded_groups.getSelectionModel().getSelected().data.var_rec
						},
						success:function(){
							<?php echo $variables; ?>.loadGrids('4',{});
							<?php echo $proj_name; ?>_win4.close();
						} 
					});            
        		}
        	},{
		        text: 'Cancel'
	    	    ,handler:function(){
	        	   	<?php echo $proj_name; ?>_win4.close();
	            }
	   		}
	   	]
    });
    
        
   	var <?php echo $proj_name; ?>_win4 = new Ext.Window({
        id:'web_recode_win4',
 		title: 'Import categories',
        layout:'fit',
        width:500,
        height:150,
        closeAction:'close',
        plain: true,
		items: <?php echo $proj_name; ?>_FormImportCategory,
		modal: true
    });

	// load first store into combobox
	categoryImportProject.store.load();
	
	// triger event when on first combobox item is selected
	categoryImportProject.on('select', function() {
		categoryImportQuestion.reset();
		storeQuestions.proxy= new Ext.data.HttpProxy({url: 'webrecode/_ajax/ajax.combo.php?action=questionsCombo&projectName='+categoryImportProject.getValue()});
		storeQuestions.load();
    });
    
    // show window, if import button is clicked
	<?php echo $proj_name; ?>_win4.show();
}


	
	
function show_window()
{
<?php

$params='var sm = '.$variables.'.getSelectionModel();';
$params.= 'if(sm.hasSelection()){';
$params.= 'var sel = sm.getSelections();';
$params.='var fld = [];';
$params.='var x; for(x=0; x<sel.length ;x++){ fld.push(sel[x].data.variable)};}';

echo "// PARAMETERSSSSSSSSSSS\n";
echo $params;
echo "\n// PARAMETERSSSSSSSSSSS END\n";

$recode=new MakeForm($proj_name.'_recode');
$recode->reqUrl='webcati/_forms/_ajax/ajax.webrecode.php';

$recode->addField('value','Variable name');
$recode->addField('label','Variable label');
//$recode->setTitle('Create recode group');

// ,callback:$this->buttonSendCallback

// element_values.getStore().reload(); ;
$recode->addButton("Save","function(){ ".$recode.".getForm().submit({params: {data: Ext.encode(fld),grid_action:'create_recode_group'".$id_proj."},
	 success:function(){
		 ".$variables.".loadGrids('1,2',{});; ".$proj_name."_win2.close()} }); }");
$recode->addButton("Cancel","function(){ ".$proj_name."_win2.close(); }");


echo $recode->createForm();
?>
var <?php echo $proj_name; ?>_win2 = new Ext.Window({
        id:'web_recode_win2',
 		title: 'Recode variable',
        layout:'fit',
        width:300,
        height:150,
        closeAction:'close',
        plain: true,
		items: <?php echo $proj_name; ?>_recode,
		modal: true
    

    }).show();

}

			

 var <?php echo $proj_name; ?>_panel = new Ext.Panel({
 title:'Webrecode <?php echo $_POST["proj_name"]?>'
 ,id:'<?php echo $proj_name; ?>_panel'
 ,closable:true
 ,layout:'border'
 ,items:[{
 region:'center'
 ,layout:{
				type:'vbox',
				padding:'0',
				align:'stretch'
		},
		items:[
		
			web_recode_panelW2grids = new Ext.Panel({id:'web_recode_panelW2grids',defaults:{margins:'0 0'},flex:1,layout:'hbox',layoutConfig:{align:'stretch'},
			items:[ 
			
			<?php echo $answers; ?>
					]
				}),
		web_recode_panelW3grids = new Ext.Panel({id:'web_recode_panelW3grids',defaults:{margins:'0 1'},flex:1,layout:'hbox',layoutConfig:{align:'stretch'},
			items:[ 
		
			<?php echo $kategorije; ?>,
			<?php echo $answers_in_categories; ?>
					]
				})	

			]
 ,frame:true
 ,border:false
 },{
 region:'west'
 ,layout:{
				type:'vbox',
				padding:'0',
				align:'stretch'
		},
		items:[
		
			
			<?php echo $variables; ?>,
					
			<?php echo $recoded_groups; ?>
					

			]
 ,width:250
 ,split:true
 
 ,collapseMode:'mini'
 }]
 });

	
	mainTabPanel.add(<?php echo $proj_name; ?>_panel).show();
