<?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_WEBCATI_BASE);

if(isset($_POST["id_project"]))
	$id_proj=', id_project:'.$_POST["id_project"];
else 
	$id_proj=', id_project:0';

$proj_name = $_POST['proj_name'];
		
echo "// Grid for existing layers for the project";
	$quota_layers = new MakeGrid();
	
	$quota_layers->setGridName($proj_name.'_quota_layers')
	->setMainTable('quota_layer_addon','Warpit_delo')
	->setTitle('Quota layers');
	
	$quota_layers->reqUrl = 'webcati/_forms/_ajax/ajax.quotas.php';
	$quota_layers->baseParams='grid_action:"get_quota_layers"'.$id_proj;
	//add a function for reordering layers
	$quota_layers->addConfig('reorderLayer',"function(event,name){
	
		this.RMconn.request({scope:this,params:{
			grid_action:'reorderLayer',
			layerId:this.getSelectionModel().getSelected().id,
			name:name
		},success:function(){this.getStore().reload(); }
		});
	}");
	
	/*$quota_layers->addColumn(array(dataIndex=>'id',header=>'id',minWidth=>50) )
					  ->type('combo')
					  ->comboValue('id')
					  ->comboDisplay('id')
					  ->hidden(TRUE);*/
	
	$quota_layers->addColumn('id','');
	$quota_layers->addColumn('names','Layers')->renderer("function(value,met,rec){
		var items = value.split(',');
		var divs = new Array();
		for(var i=0;i<items.length;i++)
		{
			divs.push('<span ondblclick=\"Ext.getCmp(\'$quota_layers\').reorderLayer(event,\''+items[i]+'\')\">'+items[i]+'</span>');
		}
		return rec.data.definedCount==0 ? ('<div style=color:red>'+ divs.join(' -- ')+'</div>' ):divs.join(' -- ') ;
	}");
	$quota_layers->addColumn('active','Activated')->type('checkColumn')->width(60);
	$quota_layers->addColumn('interviewer_show','Show interviewer')->type('checkColumn');
	$quota_layers->addColumn('allow_other','Allow others')->type('checkColumn')->width(80);
	$quota_layers->addColumn('definedCount');
	$quota_layers->setEditable(false);
	$quota_layers->listeners[] = "afteredit:function(e)
	{
		$quota_layers.RMconn.request({params:{
			grid_action:'set_active_layer',
			id: e.record.id,
			value:e.value,
			field:e.field
		},success:function(resp){
			if(Ext.decode(resp.responseText).success)
				e.record.commit();
			else 
				e.record.reject();
		}
		
		});
	} ";
	
	$quota_layers->setAutoExpand('names');
		//->addButtonSendSelected('Delete layer', PATH_TO_ROOT.'warpit/webcati/_forms/_ajax/quota_layers.php?action=delete','function(opt,suc,res){' . $quota_layers->getName().'.getStore().remove(quota_layers.getSelectionModel().getSelected());}','id');
	$quota_layers->addtBarItem("{text:'Define',handler: function(){
		var rec =  $quota_layers.getSelectionModel().getSelected();
		if(rec)
			CallScript('"."webcati/_forms/forms.quotas_define.php',{layer:rec.data.id $id_proj,projName: '$proj_name'});}}")
			->addButtonSendSelected2('Delete layer', '
			
				{ params:{grid_action:"delete_layer", id_project: '.$_POST["id_project"].'}, 
				success:function(opt,suc,res){' . $quota_layers . ".getStore().reload();  }}",'id','icon-delete-record','1' );
		;
	
	echo $quota_layers->createGrid();
	
	
	
	echo "// Grid for adding the quotas from the telephone database and the questionaire";
	$tel_q_names = new MakeGrid();
	
	$tel_q_names->setGridName($proj_name.'_tel_q_names')
	->setMainTable('opravki','Warpit_delo')
	->setTitle('Add new quota layer');
	
	$tel_q_names->reqUrl = 'webcati/_forms/_ajax/ajax.quotas.php';
	$tel_q_names->baseParams='grid_action:"get_recoded_q_names"'.$id_proj;
	
	$tel_q_names->addColumn(array(dataIndex=>'id',minWidth=>50) )
					  /*->type('combo')
					  ->comboValue('id')
					  ->comboDisplay('id')
					  ->hidden(TRUE)*/;
					  
	$tel_q_names->addColumn('name','name');
	
	$tel_q_names->addColumn('id_s','id_s')->hidden(TRUE);
	
	$tel_q_names->setAutoExpand('name')
		->setCheckBoxSelectionModel(true)
		->addButtonSendSelected2('Add layer', '{url:"webcati/_forms/_ajax/ajax.quotas.php", params:{data:0, grid_action:"insert", id_project: '.$_POST["id_project"].'}, success:function(opt,suc,res){' . $quota_layers . '.getStore().reload();}}', 'id_s');
	echo $tel_q_names->createGrid();
	
?>	
	<?php echo $quota_layers->getGridName()?>.flex = 1;
	<?php echo $tel_q_names->getGridName()?>.flex = 1;
	
	
<?php


//------------------------------------------------------------------------------------
	
	//echo "// Grid for adding the quotas from the telephone database and the questionaire";
	$element_values = new MakeGrid();
	
	$element_values->setGridName($proj_name.'_element_values')
	->setMainTable('opravki','Warpit_delo')
	->setAutoLoad(false);
	
	$element_values->reqUrl = 'webcati/_forms/_ajax/ajax.quotas.php';
	$element_values->baseParams='grid_action:"get_values"'.$id_proj;
	/*$element_values->addColumn(array(dataIndex=>'id_s',header=>'id_s',minWidth=>50) )
					  ->type('combo')
					  ->comboValue('id_s')
					  ->comboDisplay('');*/
					  //->hidden(TRUE);
	
	$element_values->addColumn('id_s','id_s');//->hidden(TRUE);
	
	$element_values->addColumn('value','value');
	
	$element_values->addColumn('label','label');
	
	$element_values->setAutoExpand('label')
		->setCheckBoxSelectionModel(true);
	$element_values->addtBarItem("{text:'Recode values',handler: function(){show_window();}}");
		//->addButtonSendSelected('Send',PATH_TO_ROOT.'warpit/webcati/_forms/_ajax/element_values.php?action=nothing','function(opt,suc,res){show_window();}');
	
	$recoded_values = new MakeGrid();
	
	$recoded_values->setGridName($proj_name.'_recoded_values')
	->setMainTable('opravki','Warpit_delo')
	->setTitle('Recoded values')
	->setAutoLoad(false);
		
		
	//button for auto recoding values...creates
	$element_values->addtBarItem("{text:'Auto recode', handler:function(){
	
	$element_values.RMconn.request( { params:{grid_action:'auto_recode_values',id_s:$element_values.selected_id_s} ,success:function(){
		$recoded_values.getStore().reload(); $tel_q_names.getStore().reload();$element_values.getStore().reload();
	} }) }}");
	echo $element_values->createGrid();
	
	
	
	
	
	
	
	
	$recoded_values->reqUrl = 'webcati/_forms/_ajax/ajax.quotas.php';
	$recoded_values->baseParams='grid_action:"recoded_values"'.$id_proj;
	
	$recoded_values->addColumn('id','');
	$recoded_values->addColumn('main_values','Main values');
	$recoded_values->addColumn('reconum','Recoded number');
	$recoded_values->addColumn('rec_label','Recode label');
	
	
	$recoded_values->setAutoExpand('rec_label')
		->addButtonSendSelected2('Delete recoded value', '{url:"webcati/_forms/_ajax/ajax.quotas.php", params:{data:0, grid_action:"delete_recoded_value", id_project: '.$_POST["id_project"].'}, 
		success:function(res){
		var r = Ext.decode(res.responseText);
		if(r.success)
		{
		' . $recoded_values . ".getStore().reload(); 
		$tel_q_names.getStore().reload();
		$element_values.getStore().reload();
		 }
		 else 
		 	Ext.Msg.alert('Warning',r.error);
		 }}", 'id');
		//->addButtonSendSelected('Delete recoded value','webcati/_forms/_ajax/ajax.quotas.php?action=delete_recoded_value','function(opt,suc,res){' . $recoded_values . '.getStore().reload(); ' . $element_values . '.getStore().reload();}','id');
	echo $recoded_values->createGrid();
	
	
	
	$elValCardPanel = $proj_name.'_elemValuesCardPanel';
	
	
	
	$names_for_recode = new MakeGrid();
	
	$names_for_recode->setGridName($proj_name.'_names_for_recode')
	->setMainTable('opravki','Warpit_delo')
	->setTitle('Names for recode');
	
	$names_for_recode->reqUrl = 'webcati/_forms/_ajax/ajax.quotas.php';
	$names_for_recode->baseParams='grid_action:"get_tel_q_names"'.$id_proj;
	/*$names_for_recode->addColumn(array(dataIndex=>'id',header=>'id',minWidth=>50) )
					  ->type('combo')
					  ->comboValue('id')
					  ->comboDisplay('id')
					  ->hidden(TRUE);*/
	
	$names_for_recode->addColumn('id','');
	$names_for_recode->addColumn('name','Name');
	
	$names_for_recode->addColumn('id_s', 'id_s');
	$names_for_recode->addColumn('tip_sql');
	
	
	$names_for_recode->setAutoExpand('name');
		//->addtBarItem("{text:'Show values! ',handler:function(){".$element_values->getGridName().".getStore().load({params:{id_s:names_for_recode.getSelectionModel().getSelected().data.id_s}})}}");
		//->addButtonSendSelected('Send','/warpit/webcati/_forms/_ajax/element_values.php', 'function(opt,suc,res){'.$element_values->getGridName().'.getStore().load({params:{id_s:names_for_recode.getSelectionModel().getSelected().data.id_s}})}')
		
		//->addButtonSendSelected('Send','/warpit/webcati/_forms/_ajax/element_values.php', 'function(opt,suc,res){'.$element_values->getGridName().'.getStore().load({params:{id_s:names_for_recode.getSelectionModel().getSelected().attributes.getNamedItem("id_s")}}); }');
		//->addButtonSendSelected('Recode', PATH_TO_ROOT.'warpit/webcati/_forms/_ajax/element_values.php?do=get_values','function(opt,suc,res){' . $element_values->getName().'.getStore().reload();console.log(suc); }','id_s');
	echo $names_for_recode->createGrid();
	echo $names_for_recode->getGridName().".getSelectionModel().on('rowselect',function(sm,ind,rec ){
	 	var elTmp = Ext.getCmp('$elValCardPanel');
	 	//console.log(rec.data);
		if(rec.data.tip_sql == '4')
	 	{
	 		elTmp.getLayout().setActiveItem(1);
	 	}
	 	else 
	 	{
		 	elTmp.getLayout().setActiveItem(0);
		 	
			$element_values.getStore().load({params:{id_s: rec.data.id_s}}); 
		}
		$element_values.selected_id_s = rec.data.id_s;
		$recoded_values.getStore().load({params:{id_s: rec.data.id_s}})
		});";
	
	
	
	//------------------------------------------------------------------------------------
	
	
?>
	<?php echo $names_for_recode->getGridName()?>.flex = 1;
	<?php echo $element_values->getGridName()?>.flex = 2;
	<?php echo $recoded_values->getGridName()?>.flex = 2;

function show_window()
{
<?php

$params='var sm = '.$element_values.'.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.id_s)};}';

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

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

$recode->addField('value','Recode value');
$recode->addField('label','Label');
$recode->setTitle('Recode values');

// ,callback:$this->buttonSendCallback

$recode->addButton("Save","function(){ " . $recode->getName() . ".getForm().submit({params: {data: Ext.encode(fld),grid_action:'recode', id_project: ".$_POST["id_project"]."},
	 success:function(){".$recoded_values.".getStore().reload(); $element_values.getStore().reload();$tel_q_names.getStore().reload(); win222222222.close();} }); }");
$recode->addButton("Cancel","function(){ win222222222.close(); }");
echo $recode->createForm();

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

    }).show();*/
    
var win222222222 = new Ext.Window({
        id:'win222222222',
 		title: 'Enter recode value and label',
 		width:300,
        //layout:'fit',
         modal:true,
        closeAction:'close',
        plain: true,
		items: [recode]
    }).show();

}

<?php 

$recode_form2=new MakeForm($proj_name.'_recode_form2');
$recode_form2->reqUrl='webcati/_forms/_ajax/ajax.quotas.php';

$recode_form2->addField('range_from','Range from');
$recode_form2->addField('range_to','Range to');
$recode_form2->addField('value','Recode value');
$recode_form2->addField('label','Label');
$recode_form2->setTitle('Recode values');

// ,callback:$this->buttonSendCallback

$recode_form2->addButton("Save","function(){ " . $recode_form2->getName() . ".getForm().submit({params: {id_s: ".$names_for_recode.".getSelectionModel().getSelected().data.id_s, grid_action:'recode2', id_project: ".$_POST["id_project"]."},
 success:function(){".$recoded_values.".getStore().reload();$tel_q_names.getStore().reload();} }); }");
$recode_form2->addButton("Cancel","function(){  }");
echo $recode_form2->createForm();

?>
	
	
	
	
	var <?php echo $proj_name?>_quotas_unique_panel = new Ext.Panel({
 title:'Quota management - <?php echo $proj_name?>'
 ,id:'<?php echo $proj_name?>_quotas_unique_panel'
 ,closable:true
 ,listeners: {
 	show: function(){
 		<?php echo $names_for_recode; ?>.getStore().reload();
 	}
 }
 ,layout:'border'
 ,items:[{
 region:'center',
 layout:{
				type:'vbox',
				padding:'0',
				align:'stretch'
		},
		items:[
		
			new Ext.Panel({id:'<?php echo $proj_name?>_quotas_panelW2grids',defaults:{margins:'0 0'},flex:1,layout:'hbox',layoutConfig:{align:'stretch'},
			items:[ 
			
			<?php echo $names_for_recode->getGridName()?>,
			<?php echo"
			{layout:'card',flex:2,activeItem:0,title:'Element values',id:'$elValCardPanel',
			 items:[ $element_values ,".$proj_name.'_recode_form2'."
			
			]
			}";?>,
			<?php echo $recoded_values->getGridName()?>
					]
				}),
			 new Ext.Panel({id:'<?php echo $proj_name?>_quotas_panelW3grids',defaults:{margins:'0 1'},flex:1,layout:'hbox',layoutConfig:{align:'stretch'},
			items:[ 
		
			<?php echo $tel_q_names->getGridName()?>,
			<?php echo $quota_layers->getGridName()?>
					]
				})	

			]
 
 ,border:false
 }]
 });
	
	
	
	
	mainTabPanel.add(<?php echo $proj_name?>_quotas_unique_panel).show();
