<?php

include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_tree.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");
include_once(PATH_TO_ROOT."_support/class.UserSession.php");
include_once(PATH_TO_ROOT."_support/class.Permissions.php");
include (PATH_TO_ROOT."/_support/repository.php");

include_once (PATH_TO_ROOT."CRM/_CRM_config.php");
include_once(PATH_TO_ROOT."CRM/class/class.Language-Pack.php");

$db->ChangeDatabase(DB_WARPIT_MAIN);
$ajax = "CRM/_forms/prisotnost/_ajax/ajax.statistics.php";

$LangPack = new LanguagePack($db, $aLanguage);
// here we define first tree with webcati options
	$treeWC = new MakeTree($_POST['treeName']);
	$treeWC->SetTable($_POST[tree],WARPIT_CRM)
			->setReqUrl('CRM/_ajax/ajax.groups.php');
	$treeWC->SetRootVisible("false")
		->setSort('id ASC')
		->setLinesVisible(true)
		->setBoldRoots()
		->setFontMedium()
		->addConfig('minHeight',100)
		->setTitle($LangPack->GetLabel("CRM_main_panel", "CRM-tools-title","Orodja"))
		->setHeight(100)
		->addConfig('maxHeight', 200)
		//->addtBarItem("'->'")
		->region('center')
		->addConfig('updateNode',"function(){}")
		->setTextPadding('1px')
	
		
	;
	
// here we define projects tree	
	$treeWCprojects = new MakeTree('WCprojectsx');
	$treeName = $treeWCprojects->getName();
	$treeWCprojects->SetTable('_Projects',DB_WARPIT_WEBCATI_BASE);
	$treeWCprojects->SetRootVisible('false','Projects')
	  ->addConfig('updateNode',"function(){}")
	  ->region('north')
	  ->addConfig('minHeight',100)
	  ->setHeight(200)
	//  ->setTitle('Help'); // this is not used because we combine in one tab two trees and title is set in combined panel
	  ->setReqUrl('CRM/_forms/_ajax/ajax.groups.php');
	 /* ->setContDelete('Delete')
	  ->setContAdd('Add child')
	  ->setContAddMain('Add sibling')*/
	  //we create data for the language combobox
		
				        	
	  $treeWCprojects->addtBarItem("'->'")
	  ->setSearchField('','top')
	 // ->addtBarItem("{text:'Expand All',handler:function(){WCprojects.expandAll();}} ")
	 ;
	 
	 
	echo $treeWC->CreateTree();
	
	
	// 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('".$LangPack->GetLabel("CRM_main_panel", "alert-no-project-warning-title","Opozorilo")."','".$LangPack->GetLabel("CRM_main_panel", "alert-no-project-warning-msg","Prosim izberite projekt!")."');";
	echo $_POST['treeName'].".on('click',function(node) {
		//we changed it that only checked projects count as selected!
		var nodeProj = null;
		var sel = $treeProjName.getSelectionModel().selNode;
		if(node.leaf){
			if(node.attributes.id == '78'){
				addTabAuto('webPDFSettings', 'CRM/_forms/PDF/forms.settings.php');
			} else if(node.attributes.id == '79'){
				addTabAuto('webAllSettings', 'CRM/_forms/nastavitve/forms.mainPanel.php');
			} else if(node.attributes.id == '81'){
				addTabAuto('DeliveryTab','CRM/_forms/delivery/forms.Delivery.php', { admin: 1 });
			} else if(node.attributes.id == '87'){
				addTabAuto('FinanceTab','CRM/_forms/financial/forms.Financial.php', { admin: 1 });
			} else if(node.attributes.id == '83'){
				addTabAuto('OrdersTab','CRM/_forms/orders/forms.Orders.php', { admin: 1 });
			}else if(node.attributes.id == '84'){
				addTabAuto('StatisticTab','CRM/_forms/statistic/forms.statistics.php');
			}else if(node.attributes.id == '100'){
				addTabAuto('deliveryContractTab','CRM/_forms/deliveryContract/forms.deliveryContract.php');
			}else if(node.attributes.id == 101){
				addTabAuto('loggerMainTab', 'CRM/_forms/logger/forms.main.php');
			}else if(node.attributes.id == 102){
				addTabAuto('visitorStatisticTab', 'CRM/_forms/visitStatistic/forms.statistics.php');
			}else if(node.attributes.id == 103){
				addTabAuto('changeTerminsTab', 'CRM/_forms/changeTermins/forms.main.php');
			}else if(node.attributes.id == 104){
				CallScript('CRM/_forms/kartoteka/window.selectPerson.php');
			}else if(node.attributes.id == 105){
			    addTabAuto('MoneyTab', 'CRM/_forms/checkingAccount/forms.checkingAccount.php');
			}else if(node.attributes.id == 106){
                addTabAuto('clubMembersTab', 'CRM/_forms/clubMembers/forms.main.php');
            }
			else if(sel != null){
				var selectedId = $treeProjName.getSelectionModel().selNode.id.split('_');
				if(sel.attributes.isProject == '1' && node.attributes.id == 76){
					addTabAuto('webVabila_'+selectedId[0]+'_'+selectedId[1],'CRM/_forms/telephoneUsers/forms.mainPanel.php',{ projectId: selectedId[0], cati_location: selectedId[1] });
				}else if(node.attributes.id == 76){
					addTabAuto('webVabila_'+selectedId[0]+'_'+selectedId[1]+'_'+selectedId[2]+'_'+selectedId[3],'CRM/_forms/telephoneUsers/forms.mainPanel.php',{ projectId: selectedId[0], cati_location: selectedId[1], dan: selectedId[2], ura: selectedId[3] });
				}else if(node.attributes.id == 75 && sel.attributes.isProject == 0){
					addTabAuto('webPrisotnost_'+selectedId[0]+'_'+selectedId[1]+'_'+selectedId[2]+'_'+selectedId[3], 'CRM/_forms/prisotnost/forms.mainPanel.php',{ projectId: selectedId[0], zipId: selectedId[1], dan: selectedId[2], ura: selectedId[3], cati_location: selectedId[4] });
					
					Ext.getCmp('StatisticGrid').getEl().mask('".$LangPack->GetLabel("CRM_all", "loading_mask_text","Posodabljanje...")."');
					Ext.getCmp('StatisticGrid').getStore().load({
						params: { 
							action: 'get',
							project_id: selectedId[0],
							dan: selectedId[2],
							ura: selectedId[3],
							cati_location: selectedId[4]
						},
						callback: function(store, opt, success){
							if(success){
								Ext.getCmp('StatisticGrid').getEl().unmask();
							}
						}
					});
				}
			}else{
				$noprojSelMSG
			}
		}
	});
	";
	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 StatisticGrid = new Ext.grid.EditorGridPanel({
	loadMask: true,
	id:'StatisticGrid',
	region: 'south',
	title: '<?php echo $LangPack->GetLabel("CRM_main_panel", "CRM_statistics_title","Statistika"); ?>',
	minHeight: 100,
	height: 200,
	store: new Ext.data.Store({
		autoLoad: true,
		url: '<?php echo $ajax; ?>',
		reader: new Ext.data.JsonReader({
			root: 'rows',
			totalProperty: "results"
		},
			new Ext.data.Record.create([
				{ name: 'Statistika', type: 'string' },
				{ name: 'Stevilo', type: 'string' }
			])
		)		
	}),
	border: false,
	viewConfig:{
		forceFit: true
	},
	columns: [
		{ header: 'Statistika', dataIndex: 'Statistika' },
		{ header: 'Število', dataIndex: 'Stevilo', width: 30 }
	]
})  

	var CRMUniqePanel = new Ext.Panel({
		id:'CRMUniqePanel',
		title:'<?php echo $LangPack->GetLabel("CRM_main_panel", "CRM_main_panel_title","CRM"); ?>',
		defaults:{split:true,border:false},
		iconCls:'icon-webcati-tab',
		layout: 'border',
		border: false,
		closable:true,
		items:[<?php echo $treeWC->getName().",".$treeWCprojects->getName(); ?>, StatisticGrid
		]				
	});
	Ext.getCmp('west-panel').add( CRMUniqePanel)
	<?php 
	if(true || !$_POST['uniqueNotShow'])
		echo  ".show();";
	?>

	var fileref=document.createElement('link');
	
	fileref.setAttribute("rel","stylesheet")
	fileref.setAttribute("type","text/css")
    fileref.setAttribute("href", "CRM/_css/mainCRM.css")
    document.getElementsByTagName("head")[0].appendChild(fileref)