<?php

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


$db->ChangeDatabase(DB_WARPIT_MAIN);



	
// here we define projects tree	
	$treeWCprojects = new MakeTree('MysteryProjects');
	$treeName = $treeWCprojects->getName();
	$treeWCprojects->SetTable('_ProjectsTree',DB_WARPIT_WEBCATI_BASE);
	$treeWCprojects->SetRootVisible('true','Mystery')
	//  ->setTitle('Help'); // this is not used because we combine in one tab two trees and title is set in combined panel
	  ->setSort('idLab ASC')
	  ->setReqUrl('_ajax/ajax.groups.php')
	 /* ->setContDelete('Delete')
	  ->setContAdd('Add child')
	  ->setContAddMain('Add sibling')*/
	  //we create data for the language combobox
	  ;

       	$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$res = $db->SQLexecute("SELECT id,country_code,cp_comment FROM  _LanguageCodepage WHERE enable = 1");
			while ($row = $db->fetchRow($res))
			$sel[] = '['. $row[0].',"'.$row[1].' - '.$row[2].'"]';
		

		$resMysteryFolder = $db->SQLexecute("SELECT id FROM _ProjectsTree WHERE idLab = 'Mystery'");
		$mysteryId = $db->fetchRow($resMysteryFolder);
		$mysteryId = $mysteryId[0];
		
	$treeWCprojects->rootId = $mysteryId;
			
if($_SESSION['UserRights'][15] && false)
	  $treeWCprojects  ->addtBarItem("{iconCls:'icon-add-record',tooltip:'New'  ,handler: function(){ $treeWCprojects.addProjectHandler(); }  }")
	->addConfig('addProjectHandler',"function(item) {
	    var n;
	    if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $treeWCprojects.getSelectionModel().getSelectedNode();
				if(!n)
					n = $treeWCprojects.getRootNode();
			}
		//we open a window to get question name and question type
		new Ext.Window({title:'New Project',modal:true,width:'280px',
		items:{
		xtype:'form', buttonAlign:'center',
		frame:true,
		items: [
		//textfield with filter for questions (start with letter, only numbers and letterz )
		{xtype:'textfield',id:'wcbqAddPrompt' , fieldLabel:'Project name',width: 140,allowBlank:false,vtype:'fieldName'},
		{
                    xtype:'combo',
                    width: 140,
                    fieldLabel: 'Language',
                    id:'wcbqComboPrompt',
                    mode: 'local',
                    editable: false,
                    triggerAction:'all',
                    value: '{$_SESSION['UserInfo']['language']}', 
				    store: new Ext.data.ArrayStore({
				        fields: [
				            'id',
				            'LanguageText'
				        ],
				        data:  [ ".implode(',',$sel)."]
				        	
				    }),
				    valueField: 'id',
				    displayField: 'LanguageText'
                 }
		]//eof form items
		 ,
		keys: [{
               key: [Ext.EventObject.ENTER], fn: function(){
                   Ext.getCmp('promptOKBtn').fireEvent('click');
               }
      		 }],
		buttons:[{text:'Ok',id:'promptOKBtn',listeners:{
		click: function(){ 
		var cb = Ext.getCmp('wcbqComboPrompt');
		var text = Ext.getCmp('wcbqAddPrompt').getValue();
		var selLng = cb.getValue();
			var par;
			//if we clicked on a question or a closed group we add it to its parent one position lower otherwise to the clicked group
			var closed = !n.isExpanded();
			if(Ext.getCmp('wcbqAddPrompt').isValid())
			{
			if(n.attributes.isQuestion==true || (closed && n.id != 0))
			{par = n.parentNode; }
			 else {par = n;}
			 //we make a server requst to handle insertProject
			 //we send the parent node ID the text and a template if selected
	         $treeName.RMconn.request({params:{
	         action:'insertProject',
	         parId:par.id,
	         nodeText:text,
	         projectLanguage: selLng,
	         nodeId:n.attributes.id } 
			,success:function(resp){
			var r = Ext.decode(resp.responseText);
			if(r.success){
				//if adding was succesful we refresh the tree and open on the added question
				//NOTE: all other groups get closed
				var p = par.getPath()+'/'+Ext.decode(resp.responseText).insertId;
				$treeName.getLoader().load($treeName.getRootNode(),function(){ $treeName.selectPath(p); } );
				Ext.getCmp('wcbqAddPrompt').findParentByType('window').close();
				//lets start composing this project
				addTabAuto('buildQuestionnaire_'+ text,'webcati/_forms/buildQuestionare/forms.buildQuestionnaire.php',{ id_project:r.insertId }); 
				
			} else{//else we display a warning and focus on the name field
			Ext.Msg.alert('Warning!',Ext.decode(resp.responseText).error );
			Ext.getCmp('wcbqAddPrompt').focus()}},
				
			failure:function(){alert('failed');}	});    
			}	
			
		}
	}
			  },
		{
		text:'Cancel',handler:function(){ 
		this.findParentByType('window').close();
	
		 }
		 }
			  ] },
	defaultButton:'wcbqAddPrompt'
			   } ).show(n); 
					   
	/*  Ext.Msg.prompt('Add Project','Project name:',function(btn,text){ if(btn == 'ok' ){
		var n = item.parentMenu.contextNode;
		var par,pos,ord;
		if(n.attributes.isProject==true)
		{par = n.parentNode;  } else {par = n;}
         $treeName.RMconn.request({params:{action:'insertProject',parId:par.id,nodeText:text,nodeId:n.id} 
		,success:function(resp){
		if(Ext.decode(resp.responseText).success){
			//var newNode = new Ext.tree.TreeNode({id: Ext.decode(resp.responseText).insertId,q_pos:pos,position:ord, text: 'Novi', leaf: true});
			//par.appendChild(newNode);
			//par.reload();
			var p = par.getPath()+'/'+Ext.decode(resp.responseText).insertId;
			$treeName.getLoader().load($treeName.getRootNode(),function(){ $treeName.selectPath(p); } );
			
		} else{ }},
			failure:function(){alert('failed');}	}); }});*/ }")
	  ->addContItem('New',"function(item){ $treeWCprojects.addProjectHandler(item); }",'false','icon-add-record' )
	  ->addConfig('addGroupHandler',"function(item){
		Ext.Msg.prompt('Add Folder','Folder name:',function(btn,text){ if(btn == 'ok' ){
		var n;
	    if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $treeWCprojects.getSelectionModel().getSelectedNode();
				if(!n)
					n = $treeWCprojects.getRootNode();
			}
		var par;
		//the group gets added after the clicked group (if a q is clicked its parent is used)
		
		if(n.attributes.isProject == 1)
			{par = n.parentNode; } 
		else{ par = n;   }
		$treeName.RMconn.request({params:{
		action:'insertGroup',nodeText:text,
		nodeId:par.id
		,isTargetQ:par.attributes.isQuestion },success:function(resp){
		if(Ext.decode(resp.responseText).success){ $treeName.getLoader().load(par,function(){ par.expand();});  }
		 }  }); }  } );   }")
	->addtBarItem("{iconCls:'icon-add-folder',tooltip:'Add folder',handler: function(){ $treeWCprojects.addGroupHandler(); }}")	 
	->addContItem('Add folder',"function(item){ $treeWCprojects.addGroupHandler(item) }",'false','icon-add-folder')
	->addContSeparator()
	->addContItem('Rename',"function(item){ if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $treeWCprojects.getSelectionModel().getSelectedNode();
				if(!n)
					return;
				
			}
			$treeWCprojects.treeEditor.triggerEdit(n);
			}",'false','RMicon_edit_record',2)
	 ->addContItem('Delete',"function(item){
	 	if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $treeWCprojects.getSelectionModel().getSelectedNode();
				if(!n || !n.isLeaf())
					return;
				
			}
			var confirmText = RMrandomString();		
		Ext.Msg.prompt('Delete project '+n.text,
			'This will delete the project <b>'+n.text+'</b> and all it`s data!'+
			'<br>Enter following code and confirm<br>'+confirmText,function(btn,text){
				if(btn=='ok')
				{
					if(text == confirmText )
					{
					 $treeName.RMconn.request({ params: {action:'deleteProject',id:n.id,name:n.attributes.text},
					 success:function(resp,opt){ 
							if(Ext.decode(resp.responseText).success)
							{
								var bq = Ext.getCmp('buildQuestionnaire_'+n.text);
								if(bq) mainTabPanel.remove(bq);
								n.remove();
							}
					    } });     
			    }
				else return false;
		 }} );
	 }","node.attributes.isProject!=true",'icon-delete-record',2)
	  ->addContItem('Delete Folder',"function(item){
	 	var n = item.parentMenu.contextNode;
	 	Ext.Msg.show({ title:'Remove folder',buttons: Ext.MessageBox.YESNO,msg:'Are you sure?',
		fn: function(btn){if(btn == 'yes'){
		 $treeName.RMconn.request({ params: {action:'delete',nodeId:n.id,name:n.attributes.text},
		 success:function(resp,opt){ 
				if(Ext.decode(resp.responseText).success)
				{
					n.remove();
				}
		    } });     
		 }} });
	 }","node.attributes.isProject==true || node.hasChildNodes()",'icon-delete-folder')
	 //copy projects!!!
	   ->addContItem('Copy',"function(item){
	 	if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $treeWCprojects.getSelectionModel().getSelectedNode();
				if(!n || !n.isLeaf())
					return;
				
			}
	 	Ext.Msg.prompt('Copy project '+n.text,'New project name:',function(btn,text){ if(btn == 'ok' ){
		var par;
		//the group gets added after the clicked group (if a q is clicked its parent is used)
		if(n.attributes.isProject == 1)
			{par = n.parentNode; } 
		else{ par = n;   }
		$treeName.RMconn.request({params:{
		action:'copyProject',nodeText:text,
		nodeId:par.id,id_project:n.id
		,isTargetQ:par.attributes.isQuestion },success:function(resp){
		if(Ext.decode(resp.responseText).success){ $treeName.getLoader().load(par,function(){ par.expand();});  }
		 }  }); }  } ); 
	 }","node.attributes.isProject==false || node.id == 0",'RMicon_copy',2)
	 ->activateDD('wupGrouplink');
	 
	 //grid with old webcati projects (available only if specific config is set)
	 
	  $treeWCprojects->addtBarItem("'->'")
	  ->setSearchField('','top',100)
	 // ->addtBarItem("{text:'Expand All',handler:function(){WCprojects.expandAll();}} ")
	  ->addConfig('region',"'center'")
	  ->baseParams = "checked:'leaf'";
	 ;
	
	 
	
	// webcati_tree as first parameter in addTab function (extended addTab function from ExtJS), is meant for title of the tab
	// in this case where click on each node transfer different text, this text is used for title
	// and first argument is not used at all 
	$treeProjName = $treeWCprojects->getName();
	$noprojSelMSG = "Ext.Msg.alert('Warning!','Please select project(s)!');";
	
	
	$grid = new MakeGrid('WUPMailStatisticsGrid');
	$grid->setMainTable('project_count',DB_WARPIT_WEBCATI_BASE);
	$gridName = $grid->getName();

	
	$grid->addColumn('id');
	$grid->addColumn('status_posete',$languagePack['status_posete']);
	$grid->addColumn('broj',$languagePack['broj']);
	
	
	
	$grid->setTitle($languagePack['pregled_aktivnih_projekat'])
		->setCheckBoxSelectionModel()
		->addConfig('closable','false')
		->setRemoteSort()
		 ->setReqUrl('_ajax/ajax.groups.php')
		  ->addConfig('region',"'south'")
		 ->setHeight(200)
		;

	 $treeWCprojects->addListener('checkchange',"function(){
	 	var ids = $treeWCprojects.getChecked('id');
	 	$grid.store.reload({params:{
	 		projectIds:ids.join()
	 	}});
	 	var v=Ext.getCmp('pregledPosetaTabId');
	 	if(v)
	 	{
	 		v.store.baseParams.projectIds = ids.join();
	 		v.store.reload();
	 	}
	 	
	 }");
	
	
	echo $grid->CreateGrid();
	

	echo $treeWCprojects->CreateTree();
	
	
//	echo $treeProjName.".getRootNode().expand();";
		
// we add JS code to define a new panel which has two trees combined in one tab
//this tab we dan add to the western tabpanel with id = 'west-panel'	
?>
	var webCatiUniqePanel = new Ext.Panel({
		id:'webCatiUniqePanel',
		title:'<?php echo $languagePack['projects']; ?>',
		defaults:{split:true,border:false},
		iconCls:'icon-webcati-tab',
		layout:'border',
		border: false,
		items:[<?php echo $treeWCprojects->getName().','.$grid;   ?>  ]
		
				
	});

