<?php 

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


$grid = new MakeGrid();

$idTemplate = $_POST['id_template'];
$ajaxUrl = 'webuserspool/_ajax/sampling/ajax.userSampling.php';

if(!$idTemplate)
{
	$treeWhere = 'id_user = '.$_SESSION['UserInfo']['id'];
	$tableName = 'samplingDataUser___'.$_SESSION['UserInfo']['id'];
	$title = 'Sample';
	$closable = 'false';
}
else
{
	$treeWhere = 'id = '.$idTemplate;
	$tableName = 'samplingDataTemplate___'.$idTemplate;
	$title = $_POST['templateName'];
	$closable = 'true';
	$baseParams = ",id_template : $idTemplate";
}

$db->ChangeDatabase(DB_WARPIT_USERSPOOL);
$data = $db->get('_SamplingTemplates',$treeWhere,'id_group,id_fields');
$fieldIds = $data[0]['id_fields'];
$idGroup = $data[0]['id_group']; 

$groupData = $db->get('_groups','id IN ('.$idGroup.')');
foreach ($groupData as $gr) {
	$storeData[] = "[".$gr['id'].",'".$gr['idLab']."']";
}

$grid->setMainTable($tableName,DB_WARPIT_USERSPOOL);

if($idTemplate)
	$grid->baseParams= "id_template : $idTemplate";
	
$grid//->setTitle('Sample')
	->addTbarItem("
	'Groups: ',
	{
		xtype:'combo',
		ref: 'grCombo',
		store: new Ext.data.ArrayStore({
			fields: ['myId','name'],
			data :[".implode(',',$storeData)."]
		}),
		valueField: 'myId',
		mode:'local',
		triggerAction: 'all',
   	 	displayField: 'name',
   	 	forceSelection: true
	},
	{
	text:'Group',
	menu:[
	{text:'Add Group',iconCls:'icon-add-record',handler: function(){
		var grTree = Ext.getCmp( 'PoolMenu_1');
		if(grTree)
		{	
			var n = grTree.getSelectionModel().getSelectedNode();
			if(n && n.isLeaf()  ){
				new RMajax().request({
					url: '$ajaxUrl',
					params: {
						action: 'addGroup',
						id_group: n.id
						$baseParams
					},
					success: function(resp){
						var r = Ext.decode(resp.responseText);
						
						$grid.getTopToolbar().grCombo.store.loadData(r.groupStore);
						$grid.store.reload();
						
					}
				});
				return;
			}
		}
		
		Ext.Msg.alert('Warning!','Please select a group!');
	}},{
		text:'Remove Group',iconCls:'icon-remove-record',handler: function(){
			var cb = $grid.getTopToolbar().grCombo;
			
			var groupId = cb.getValue();
			if(groupId)
			{
				if(cb.store.getCount() == 1)
				{
					Ext.Msg.alert('Warning','You cannot remove last group!');
					return;
				}
				new RMajax().request({
					url: '$ajaxUrl',
					params: {
						action: 'addGroup',
						id_group: groupId,
						remove: true
						$baseParams
					},
					success: function(resp){
						var r = Ext.decode(resp.responseText);
						
						$grid.getTopToolbar().grCombo.store.loadData(r.groupStore);
						$grid.getTopToolbar().grCombo.reset();
						$grid.store.reload();
						
					}
				});
			}
		}
	}
	]
	},{
		text: 'Run Sampling',
		handler: function(){
		
		
			var grTree = Ext.getCmp( 'PoolMenu_1');
			if(grTree)
			{	
				var n = grTree.getSelectionModel().getSelectedNode();
					if(n && n.isLeaf()  ){
							Ext.Msg.confirm('Run Sampling',\"This will sample users and save to '\"+n.attributes.idLab+\"'\" , function(btn){if(btn == 'yes') {
								new RMajax().request({
								url: '$ajaxUrl',
								params: {
									action: 'runSampling',
									toGroup: n.id
									$baseParams
								},
								success: function(resp){
									addTabAuto('wupShowGroup_'+n.id,'webuserspool/_forms/forms.showgroup.php',{group_id: n.id,name: n.attributes.idLab}); 
									n.parentNode.reload();
								}
							});
							
							}  } );
							
							return;
							
				}
			}
			
			Ext.Msg.alert('Warning!','Please select a group!');
			
		}
	}".",{//save template button
		text: 'Save as',
		handler: function(){
			var tempTree = Ext.getCmp('userSampling_Templatetree');
			var n = tempTree.getSelectionModel().getSelectedNode();
				if(!n)
					n = tempTree.getRootNode();
					//why did I do this you ask? it looks like I kicked myself in the nuts...from the back!
					//I set the \$hidden variable in the context menu, so that it does not show,
					//but this same variable ends the funkction if called from the menu...so I added the item that it looks like it was called from context
					Ext.apply(tempTree.RMconn.baseParams, { templateId : '$idTemplate '  } );
					tempTree.contextHandler_0({ parentMenu: { contextNode: n } });
		}
	}" .",'->'")
	->addImportButton()
	->addExportButton(null,null,array('title' => 'Export - Sampling;') )
	->setPaging()
	->setFiltering()
	->addListener('afterrender',"function(gr){
		gr.RMdd = new Ext.dd.DropZone(gr.el,{
			ddGroup: 'wupGrouplink' ,
			onContainerOver: function(dd,e,data)
			{
				return (dd.tree && dd.tree.id == 'PoolMenu_1' && data.node.leaf) ? this.dropAllowed : this.dropNotAllowed
					return true;
				return false;
			}
			,onContainerDrop: function(dd,e,data){
				if(dd.tree && dd.tree.id == 'PoolMenu_1' && data.node.leaf)
				{
					new RMajax().request({
					url: 'webuserspool/_ajax/sampling/ajax.userSampling.php',
					params: {
						action: 'addGroup',
						id_group: data.node.id
					},
					success: function(resp){
						var r = Ext.decode(resp.responseText);
						
						$grid.getTopToolbar().grCombo.store.loadData(r.groupStore);
						$grid.store.reload();
						
					}
					});
					return true;
				}
				return false;
			}
			
		});
	}")
	->addListener('beforedestroy',"function(cmp)
		{
			if(cmp.RMdd) cmp.RMdd.destroy();
		}");
/*
$fields = $db->get('_InterviewerStructure','id IN ('.$fieldIds.')','field_name,data_type,field_text');

foreach ($fields as $data) {
	$grid->addColumn($data['field_name'],$data['field_text']);
	
}*/
$addEditor = true;
$selFields = $fieldIds;
$notEditable = true;
include_once (PATH_TO_ROOT.'webuserspool/_forms/grid.showgroup.php');
$grid->addColumn('freq_N','N')->width(50);
$grid->addColumn('percent','%')->width(50);
$grid->addColumn('select_N','(n)',"new Ext.form.NumberField({selectOnFocus:true})")->width(50);





echo $grid->CreateGrid();



echo "
	
	/*var $tabId = new Ext.Panel({
		id:'$tabId',
		title:'Sampling',
		//iconCls:'RMicon_redirect',
		defaults:{split:true,border:false},
	
		layout:'border',
		border: false,
		closable:true,
		items:[ {region:'west',collapseMode:'mini',xtype:'panel',width:250,layout:{
						    type: 'vbox',
						    align: 'stretch'
							},items: [$fieldTree,$tree] } , { xtype:'tabpanel',id:'userSamplerTabPanel',region:'center'  }   ]
	});*/
Ext.getCmp('userSamplerTabPanel').add({ layout:'fit',id:'$tabId',items: $grid, title:'$title',closable: $closable }).show();  ";

?>