<?php

	include("_dirinfo.php");
	$sessionHandling = true;
	include(PATH_TO_ROOT."mystery/init.php");
	include(PATH_TO_ROOT."_class/class.Extjs_grid.php");
	include("../_class/class.Language-Pack.php");

	$db->ChangeDatabase(DB_WARPIT_MAIN);
	
	$langPack = new LanguagePack($db,"en");
	
	$grid = new MakeGrid($_POST['tabId']);
	$grid->setMainTable('pregledPoseta',DB_WARPIT_WEBCATI_BASE);

	$grid->addColumn('projId');
	$grid->addColumn('id_sample');
	$grid->addColumn('id_sampleTable');
	$grid->addColumn('strucId');
	$grid->addColumn('id',$langPack->GetLabel("visit-preview","grid-fields-incremental-number","Zap broj"));
	$grid->addColumn('projekat',$langPack->GetLabel("visit-preview","grid-fields-project","projekat"));
	$grid->addColumn('podprojekat',$langPack->GetLabel("visit-preview","grid-fields-subproject","Podprojekat"));
	// permissions for editing fields
	 if ( $_SESSION['UserRights'][48] && $_SESSION['UserRights'][49] )
			$grid->addColumn('user_id',$langPack->GetLabel("visit-preview","grid-fields-user","User"))->editor("new Ext.form.TextField()");
		else 
			$grid->addColumn('user_id',$langPack->GetLabel("visit-preview","grid-fields-user","User"));
			
	$grid->addColumn('uniqueAddress_1',$langPack->GetLabel("visit-preview","grid-fields-address","Address"))->width(250);
	
	
	
	// $statCol = $grid->addColumn('status','Status')->type('combo')->comboStore('pregledStatusComboStore','pregledStatusComboStoreData')->comboValue('id')->comboDisplay('name');
	$statCol = $grid->addColumn('status',$langPack->GetLabel("visit-preview","grid-fields-status","Status"))->renderer('function (a) { 
      				if (!a) return "";
      				st = pregledStatusComboStore;
					index = st.find(\'id\',a);					
	   				return st.getAt(index).get(\'name\');
				} ');
	
	
	if( $_POST['visitsFolder'] || $_POST['visitsFilter'] ) {
		//if there's no data in this row we ingore the click
		$statCol->addIconAction('icon_zoom_document',"CallScript('_forms/forms.report.php',{id_project:record.data.projId,id_record:record.data.strucId});");
	}
	
	$grid->addColumn('postignuce',$langPack->GetLabel("visit-preview","grid-fields-achievement","Postignuće"))->width(80)->renderer("function(val){ if(val) { return val+'%'} else return '/'}");
	 
	// permissions for editing fields
	if ( $_SESSION['UserRights'][48] && $_SESSION['UserRights'][50] )
			$grid->addColumn('visitDateTime',$langPack->GetLabel("visit-preview","grid-fields-date-time","Date/time"))->width(130)->editor("new Ext.form.TextField()");
		else 
			$grid->addColumn('visitDateTime',$langPack->GetLabel("visit-preview","grid-fields-date-time","Date/time"))->width(130);
			
	$grid->addColumn('planned_visit_time',$langPack->GetLabel("visit-preview","grid-fields-planned","Planned"))->width(130);
	
	$grid->setTitle($_POST['title'])
		->setCheckBoxSelectionModel()
		->addConfig('closable','false')
		->setRemoteSort()
		->setReqUrl('_ajax/ajax.groups.php')
		->setHeight(200)
		->addConfig('closable','true')
		->setFiltering()
		->addTbarItem("{iconCls:'x-tbar-loading',handler:function(){ $grid.getStore().reload(); }}")
		->addConfig('enableDragDrop','true')
		->addConfig('ddGroup',"'mystVisitView'");
		
		
		
	if($_POST['tabId'] == 'pregledPosetaTabId') {
	
		if ( $_SESSION['UserRights'][27] ) {
			
				$grid->addTbarItem("{
					iconCls: 'iconCopy',
				  	text:'".$langPack->GetLabel("visit-preview","grid-button-save","Save")."',
				  	handler: function(){
				  	
				  		Ext.Msg.prompt('".$langPack->GetLabel("visit-preview","save-window-titel","Name")."','".$langPack->GetLabel("visit-preview","save-window-label","Folder name")."',function(btn,text){
				  			if(btn=='ok')
				  			{
						  		var recs = $grid.selModel.getSelections();
						  		var combId = new Array();
						  		var uqA = new Array();
						  		for(var i=0;i<recs.length;i++ )
						  		{
						  			// check if records are done and/or confirmed
						  			if ( recs[i].data.strucId > 0) {
						  				// project ID + structure ID
										combId.push( recs[i].data.projId+'_'+recs[i].data.strucId );
										uqA.push( recs[i].data.uniqueAddress_1 );
						  			}		  			
						  		}
						  		$grid.RMconn.request({params:{
						  			combId:combId.join(),
						  			uniqId:uqA.join('<,>'),	
						  			action:'saveVisits',
						  			folder:text
						  		},
						  		success:function(){
						  			Ext.getCmp('visitsUniqePanel').show();
						  			Ext.getCmp('MysteryVisits').getRootNode().reload();
						  		}
						  		});
						  	}
				  		})
				  	}
				  }");
	  } // end if ( $_SESSION['UserRights'][27] ) {

	  if ( $_SESSION['UserRights'][28] ) {
		$grid->addTbarItem("{
				iconCls: 'iconMovePost',
			  	text:'".$langPack->GetLabel("visit-preview","grid-button-move","Move")."',
			  	handler: function(){
			  			  
			  		tree = Ext.getCmp('MysteryVisits');
			  		SelectedNode = tree.getSelectionModel().getSelectedNode();	 
			  		
			  		if (SelectedNode == null ||  SelectedNode.attributes.id_project > 0 ) {
			  		
			  			alert('".$langPack->GetLabel("visit-preview","move-alert-message-1","Please select visit Folder")."');
			  			return;
			  		}
			  		
			  		
			  		
					var recs = $grid.selModel.getSelections();
					var combId = new Array();
					var uqA = new Array();
					 flag = 0;
					for(var i=0;i<recs.length;i++ ) {
						//alert(recs[i].data.status);
						// check if records are done and/or confirmed
						
						if (recs[i].data.status != 1) flag = 1;
						if ( recs[i].data.strucId > 0 && recs[i].data.status == 1) {
							// project ID + structure ID
							
							combId.push( recs[i].data.projId + '_' + recs[i].data.strucId);
							uqA.push(recs[i].data.uniqueAddress_1);
						}
					}
					if (flag) {						
						alert('".$langPack->GetLabel("visit-preview","move-alert-message-2","Neke posete nisu stavljene u grupu poseta za pojedinacne izvestaje jer nisu potvrdjene.")."');
					}
					//return;
					
					$grid.RMconn.request({
						params:{
								combId:combId.join(),
								uniqId:uqA.join('<,>'),							
								action:'moveVisits',
								node: SelectedNode.id
								 
								
						},
						success:function(){
								Ext.getCmp('visitsUniqePanel').show();
								Ext.getCmp('MysteryVisits').getLoader().load(SelectedNode,function(){ SelectedNode.expand(); });
						}
					});  		
			  	}
			  }");
	} // end if ( $_SESSION['UserRights'][28] ) {

	 if ( $_SESSION['UserRights'][29] || $_SESSION['UserInfo']['user_type'] == 0) {	
		$grid->addTbarItem("{
				iconCls: 'iconMakeInterview',
			  	text:'".$langPack->GetLabel("visit-preview","grid-button-make-interview","Make interview")."',
			  	handler: function(){
	
			  		var recs = $grid.selModel.getSelections();
					if (recs.length != 1) {
						alert('".$langPack->GetLabel("visit-preview","make-interview-alert-1","Please select only one sample point")."');
						return;
					}
					
					if ( recs[0].data.strucId > 0) {
							alert('['+ recs[0].data.strucId +'] ".$langPack->GetLabel("visit-preview","make-interview-alert-2","This sample point is finished")."');
							return;
					}
					//alert(recs[0].data.uniqueAddress_1);
					mainTabPanel.add(new Ext.ux.IFrameComponent({ 
					             						closable: true, 
					             						title: '".$langPack->GetLabel("visit-preview","make-interview-frame-titel","Make Interview:")." ' + recs[0].data.uniqueAddress_1, 				             						
					             						id: recs[0].data.id, 
					             						url: '_ajax/ajax.make-interview.php?id_user=' + recs[0].data.user_id + '&id_project=' +  recs[0].data.projId + '&id_capi_sample=' + recs[0].data.id_sample + '&address=' + recs[0].data.uniqueAddress_1
					             					})
					 ).show(); 
					
			  	}
			  }");
	} // end  if ( $_SESSION['UserRights'][29] || $_SESSION['UserInfo']['user_type'] == 0) {	
	
	 if ( $_SESSION['UserRights'][51]) {	
		$grid->addTbarItem("{
				iconCls: 'iconResetInterview',
			  	text:'".$langPack->GetLabel("visit-preview","grid-button-reset-interview","Reset interview")."',
			  	handler: function(){
	
			  		var recs = $grid.selModel.getSelections();
					if (recs.length != 1) {
						alert('".$langPack->GetLabel("visit-preview","reset-interview-alert-1","Please select only one sample point")."');
						return;
					}
					
					if ( recs[0].data.strucId == 0) {
							alert('['+ recs[0].data.strucId +'] ".$langPack->GetLabel("visit-preview","reset-interview-alert-2","This sample point is not done yet")."');
							return;
					}
					
					$grid.RMconn.request({
						params:{
								action:			'ResetSamplePoint',
								idProject: 		recs[0].data.projId,
								idSample: 		recs[0].data.id_sample,							
								id_user:		recs[0].data.user_id,
								id_structure: 	recs[0].data.strucId							
						},
						success:function(){
								// Ext.getCmp('visitsUniqePanel').show();
								
						}
					});  		
					
					
			  	}
			  }");
	} // end  if ( $_SESSION['UserRights'][51] ) {
	
	
	if ( $_SESSION['UserRights'][51]) {	
		$grid->addTbarItem("{
				iconCls: 'iconCalculatePosts',
			  	text:'".$langPack->GetLabel("visit-preview","grid-button-calculate-success","Calculate postignuce")."',
			  	handler: function(){
	
			  		
					$grid.RMconn.request({
						params:{
								action:			'calculatePostignuce',
								projectIds: 		'".$_POST['projectIds']."'	
						},
						success:function(){
							$grid.getStore().reload(); 
								
						}
					});  		
					
					
			  	}
			  }");
	} // end  if ( $_SESSION['UserRights'][29] || $_SESSION['UserInfo']['user_type'] == 0) {
	
	
}
	
	if($_POST['visitsFolder']) {
		
		$grid->baseParams= "visitsFolder:'".$_POST['visitsFolder']."'";
		
	} elseif ($_POST['visitsFilter']) {
		$grid->baseParams= "projectIds:'".$_POST['projectId']."', visitsFilter: '".$_POST['visitsFilter']."'";
		
	} else { 
		$grid->baseParams= "projectIds:'".$_POST['projectIds']."'";
	}
	
	// we add extra variables in afteredit event in grid which are send with ajax after some field is edited. In our case date is editable.
	$grid->ExtraAfterEditParameters[] = " project_name: e.record.get('podprojekat') ";
	$grid->ExtraAfterEditParameters[] = " id_record: e.record.get('strucId') ";

	echo $grid->CreateGrid();
	
?>
	mainTabPanel.add(<?php echo $grid;?>).show();

