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



$idProject = $_POST['id_project'];
$tabId = 'redirectionProject_'.$idProject;
$projName = $_POST['projName'];
$linksGrid = new MakeGrid($tabId.'_links');
$linksGrid->setMainTable('_RedirectLinks',DB_WARPIT_USERSPOOL)
		->setCheckBoxSelectionModel()
		->setReqUrl('webuserspool/_ajax/redirectionManager/ajax.redirectionProject.php')
		->setAutoExpand('wwwlink',150)
		->region('west')
		->setWidth(250)
		->setPaging(30)
		->setFiltering()
		->baseParams = " SQLwhere : 'a.id_project = $idProject' , id_project : $id_project";
?>


var comboUsedFilter = new Ext.form.ComboBox({
	width: 120,
    typeAhead: true,
    triggerAction: 'all',
    mode: 'local', 
    editable:false,
    store: new Ext.data.ArrayStore({
        fields: [
            'id_used',
            'displayText',
            'num'
        ],
        data: [ [0, 'All'], 
        		[1, 'Used'], 
        	   	[2, 'Unused']      	 	   
        	  ]
        	   	
    }),
   	 valueField: 'id_used',
   	 displayField: 'displayText'
	}); 


<?php

$linksGrid->addBottomBarItem("'Show: ',comboUsedFilter");
$linksGrid->addTbarItem("'Upload links',{
	xtype:'fileuploadfield',
	buttonOnly:true,
	name: 'uploadLink',
	ctCls: 'button-fix',
	buttonCfg:
	{
		//text:'Upload links',
		text:'',
		 iconCls: 'upload-icon'
	},
	listeners: {
		fileselected: function(t,file)
		{
			Ext.getCmp('uploadForm_$tabId').getForm().submit({
				success: function(){
					$linksGrid.getStore().reload();
				}
			});
		}
	}
},'-',{ text: 'Clean',iconCls:'RMicon_eraser', handler: function(){
	
	var ids = $linksGrid.getSelectedIds();
	Ext.Msg.confirm('Clean ' + (ids.length > 0 ? ids.length : 'all' )+' links','&nbsp;&nbsp;&nbsp; Are you sure?&nbsp;&nbsp;&nbsp;', 
	function(btn){
		if(btn == 'yes')
		{
			$linksGrid.RMconn.request({ params: { action : 'cleanLinks', ids: ids.join() },
			success: function(){ $linksGrid.getStore().reload();
				 }
			 });
		}
	} );
	
}  },
{ text: 'Delete',iconCls:'icon_red_delete', handler: function(){
	
	var ids = $linksGrid.getSelectedIds();
	Ext.Msg.confirm('Delete ' + (ids.length > 0 ? ids.length : 'all' )+' links','&nbsp;&nbsp;&nbsp; Are you sure?&nbsp;&nbsp;&nbsp;', 
	function(btn){
		if(btn == 'yes')
		{
			$linksGrid.RMconn.request({ params: { action : 'deleteLinks', ids: ids.join() },
			success: function(){ $linksGrid.getStore().reload();
				 }
			 });
		}
	} );
	
}  }
/*not used, since you can quick filter and delete! 
,{ text: 'Delete used', handler: function(){
	Ext.Msg.confirm('Delete used links','&nbsp;&nbsp;&nbsp; Are you sure?&nbsp;&nbsp;&nbsp;', 
	function(btn){
		if(btn == 'yes')
		{
			$linksGrid.RMconn.request({ params: { action : 'deleteLinks', used: true },
			success: function(){ $linksGrid.getStore().reload();
				 }
			 });
		}
	} );
	
}  },
{ text: 'Delete unused', handler: function(){
	Ext.Msg.confirm('Delete unused links','&nbsp;&nbsp;&nbsp; Are you sure?&nbsp;&nbsp;&nbsp;', 
	function(btn){
		if(btn == 'yes')
		{
			$linksGrid.RMconn.request({ params: { action : 'deleteLinks', unused: true },
			success: function(){ $linksGrid.getStore().reload();
				 }
			 });
		}
	} );
	
}  }*/");
		

$linksGrid->dateSQL = "Y-m-d H:i:s";
$linksGrid->dateDisplay = "d.m.Y H:i";

$linksGrid->addListener('columnresize',"function(){
	this.getView().refresh();
}");
$linksGrid->addColumn('wwwlink','Links',"new Ext.form.TextField({readOnly: true,selectOnFocus:true })")->renderer("function(v, meta) {
	  return v.slice(-(this.width /6 ));
}");
$linksGrid->addColumn('id_user','User')->type('int')->table('a')->width(60);
$linksGrid->addColumn('email','Email')->width(150);
$linksGrid->addColumn('int_finish','Status')->width(50)->type('int')->convertNull();
$linksGrid->addColumn('startTime','Start')->width(130)->type('date');
$linksGrid->addColumn('endTime','Stop')->width(130)->type('date')->renderer("function(val,md,r){
	if(r.data.int_finish) return new Date(val).format('$linksGrid->dateDisplay');
	if(val) return 'Not finished';
	return '';
}");
$linksGrid->addColumn('webPoints','Points')->width(50);
$linksGrid->addColumn('id_project')->defaultValue($idProject);


$grpTree = 'PoolMenu_1';



$linksGrid->addtBarItem("{text:'Copy',dragCopy:true,iconCls:'RMicon_copy',
	menu: [{
		text: 'Copy selected',
		handler:function(){
			
		var grTree = Ext.getCmp( '$grpTree');
				if(!grTree) { addTabAuto('webUserspoolUniqePanel','webuserspool/_forms/tree.groups.php',{treeName : 'PoolMenu', tree:'_ProgramMenu'});Ext.Msg.alert('Warning!','Please select a group!'); return;}
				var n = grTree.getSelectionModel().getSelectedNode();
				if(n && n.isLeaf()  ){
					//if a node is selected we copy/move all/selected data to the node
					var arr=new Array(),sel = $linksGrid.selModel.getSelections();
				
					 for(x=0; x<sel.length ;x++){
					 	if(sel[x].data['id_user'] != 0)
					    	arr.push( sel[x].data['id_user'] 
					    	);}
					
					sel = arr;
					if(sel.length == 0) return;
								
					var selNum = sel;
					var cmText = 'Copy';
					Ext.Msg.confirm(cmText + \" selected to '\"+n.text+\"'\",
					'Are you sure?'
					,function(btn){
						if(btn == 'yes')
						{
								
							new RMajax().request({
								url: 'webuserspool/_ajax/ajax.showgroup.php',
								params: {
									action:'copyUser',ids:sel.join(),toGroup: n.id
										, copyMode: true,database: '".DB_WARPIT_USERSPOOL."'
								}
							});
						}
					});
				}	
				else 
				{
					Ext.Msg.alert('Warning!','Please select a group!');
				}
	
		
		}
	},
	{
		text: 'Copy all',
		handler:function(){
			//we add webuserspool tab, so that it shows/adds it!
				var grTree = Ext.getCmp( '$grpTree');
				if(!grTree) { addTabAuto('webUserspoolUniqePanel','webuserspool/_forms/tree.groups.php',{treeName : 'PoolMenu', tree:'_ProgramMenu'});Ext.Msg.alert('Warning!','Please select a group!'); return;}
				var n = grTree.getSelectionModel().getSelectedNode();
				if(n && n.isLeaf()  ){
					//if a node is selected we copy/move all/selected data to the node
								
					var selNum = $linksGrid.getStore().getTotalCount();
					var cmText = 'Copy';
					Ext.Msg.confirm(cmText + \" all to '\"+n.text+\"'\",
					'Are you sure?'
					,function(btn){
						if(btn == 'yes')
						{
							
								$linksGrid.getStore().baseParams.addOn = 'copy';
								$linksGrid.getStore().baseParams.toGroup = n.id;
								$linksGrid.getStore().reload({callback:function(r,opt,s){ 
								Ext.Msg.alert('Success',cmText+' succesful'); 
									
								 }
								});
						
						}
					});
				}	
				else 
				{
					Ext.Msg.alert('Warning!','Please select a group!');
				}
	}
	}]
	
		}")
	->addTbarItem ("{text:'Send mail',iconCls:'RMicon_send_email' , 
	 		handler: function() { 
	 		if( comboUsedFilter.store.getAt(1).data.num )
	 		CallScript('webuserspool/_forms/window.sendMailWizard.php',{sendProjUsers :true ,groupId:0,groupGridName:'".$linksGrid."',numSendTo : comboUsedFilter.store.getAt(1).data.num }); }   
	 		},'->'  ");
	

$linksGrid->addExportButton();

//$linksGrid->dateDisplay = "DD.MM.YYYY HH:MM";


$statusGrid = new MakeGrid();
$statusGrid->setMainTAble('_RedirectStatus',DB_WARPIT_USERSPOOL)
	->setTitle('Statuses','RMicon_task_list')
	->activateAdd()
	->activateRemove()
	->setAutoExpand('link')
	->region('south')
	->flex(1)
	->addTbarItem("{ text:'Points', menu:[ {
		text: 'Reset points',iconCls:'RMicon_delete_task',
		handler: function(){
			Ext.Msg.confirm('Reset points','Are you sure?',function(){
				$linksGrid.RMconn.request({params:{
					action: 'resetPoints'
				},
				success: function(){
					$linksGrid.getStore().reload();
				}
				});
			});
		}
	},{
		text: 'Calculate points',iconCls:'RMicon_add_task',
		handler: function(){
			Ext.Msg.confirm('Calculate points','Are you sure?',function(){
				$linksGrid.RMconn.request({params:{
					action: 'calculatePoints'
				},
				success: function(){
					$linksGrid.getStore().reload();
				}
				});
			});
		}
	}]},'->'")
	->addExportButton()
		->baseParams = " SQLwhere : 'id_project = $idProject'";;
$statusGrid->addColumn('id_status','Status','new Ext.form.NumberField()');
$statusGrid->addColumn('link','Link','new Ext.form.TextField()');
$statusGrid->addColumn('statusComment','Comment')->type('combo')
					  ->comboTable('_RedirectStatus','autoFill')
					  ->comboValue('statusComment',false)
					 // ->comboSQL("SELECT `statusComment` FROM `_RedirectStatus` GROUP BY `statusComment` ORDER BY `statusComment`")
					  ->comboDisplay('statusComment',false)
					  ->comboProperties('minChars:2')
					  ;
$statusGrid->addColumn('webPoints','Points','new Ext.form.NumberField()');
$statusGrid->addColumn('id_project')->defaultValue($idProject);


$propertiesForm = new MakeForm();
$propertiesForm->setMainTable('_RedirectProperties',DB_WARPIT_USERSPOOL)
	->setTitle('Properties','icon-options-3')
	->setAutoUpdate()
	->addConfig('labelWidth',160)
	->addConfig('labelAlign',"'right'")
	->addConfig('closable',"false")
	->flex(1)
	->id = $idProject;

$propertiesForm->addField('survey_close','Close survey','checkbox');
$propertiesForm->addField('survey_close_link','Close survey redirection link','textfield')->width(250);
$propertiesForm->addField('start_date','Questionnaire start date','datetimefield')->width(250);
$propertiesForm->addField('end_date','Questionnaire end date','datetimefield')->width(250);

//grid for showing status statistics
$chartGrid = new MakeGrid();

$chartGrid->dataArray = "[]";
$chartGrid->addConfig("autoHeight",'true')
	->addConfig('viewConfig',"{ getRowClass: function( rec,index){
			if(rec.data.comment.substring(0,4) == 'Used')
				return 'RM_color_red';
			if(rec.data.comment.substring(0,4) == 'Unus')
				return 'RM_color_green';
	 } }")
	->addExportButton();

$chartGrid->addColumn('id_status','Status');
$chartGrid->addColumn('comment','Comment');
$chartGrid->addColumn('freq','Freq(N)');



echo $linksGrid->createGrid();

//set a load event to get some extra data...if it's possible :/
echo "$linksGrid.store.on('load',function(s,r,o){
		//why isn't this automaticly happen ?? how can last options be empty ???
		s.lastOptions = o;

		var r = s.reader.jsonData;
		var st = comboUsedFilter.getStore();
		st.getAt(0).data.displayText = 'All';
		st.getAt(1).data.displayText = 'Used ( '+ r.usedLinks + ' links)';
		st.getAt(2).data.displayText = 'Unused ( '+ r.unUsedLinks + ' links)';
		
		st.getAt(1).data.num = r.usedLinks;
		st.getAt(2).data.num = r.unUsedLinks;
		
		comboUsedFilter.bindStore(st);
		comboUsedFilter.setValue ( comboUsedFilter.getValue() );
		
		$chartGrid.store.loadData( r.chartData.rows );
		
		
		delete s.lastOptions.params.addOn;
		delete s.baseParams.addOn;
});
	
comboUsedFilter.on('select', function(combo,rec) { 
	$linksGrid.store.reload({params:{
		filterUsed : rec.data.id_used
	}});
});

";

echo $statusGrid->createGrid();


echo $chartGrid->createGrid();

//$propertiesForm->addItem($chartGrid);


echo $propertiesForm->createForm();

echo "
	var $tabId = new Ext.Panel({
		id:'$tabId',
		title:'$projName',
		iconCls:'icon_build_questionnare',
		defaults:{split:true,border:false},
	
		layout:/*{
			    type: 'hbox',
			    pack: 'start',
			    align: 'stretch'
			}*/'border',
		border: false,
		closable:true,
		items:[
		{ xtype: 'form', region: 'center',flex:1,layout:'fit',id:'uploadForm_$tabId',enctype:'multipart/form-data',
      			  fileUpload: true,method:'POST',url: 'webuserspool/_ajax/redirectionManager/ajax.upload.php',
      			  baseParams: { id_project : $idProject },
				items: [ $linksGrid ] 
		}, 
		{ xtype:'panel',flex:1,width:450,collapseMode: 'mini',
                 layout:{
						    type: 'vbox',
						    pack: 'start',
						    align: 'stretch'
						} ,region:'east',
						items:[$statusGrid ,
						//a tab panel here
						{
						xtype : 'tabpanel',flex:2,activeTab:0,
						items: [$propertiesForm ,{ 
							xtype: 'panel',title:'Statistics',iconCls:'icon_basic_statistics',
							layout:{
						    type: 'vbox',
						    pack: 'start',
						    align: 'stretch'
							},
							items: [ $chartGrid ]
						
						} ]
						} 
						 ] 
						 
		}   ]
	});
Ext.getCmp('redirectionManagerTabPanel').add( $tabId ).show();  "


?>