<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");
include_once(PATH_TO_ROOT."CRM/class/class.checkString.php");

	
$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

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

$LangPack = new LanguagePack($db, $aLanguage);

$ajax = "CRM/_forms/nastavitve/_ajax/ajax.permissions.php";

$compName = str_replace(' ', '_', StringChecker::Check($_POST['tabName']));
?>

Ext.ns('Ext.ux.grid');
Ext.ux.grid.CheckColumn = Ext.extend(Ext.grid.Column, {
    processEvent : function(name, e, grid, rowIndex, colIndex){
        if (name == 'mousedown') {
            var record = grid.store.getAt(rowIndex);
            record.set(this.dataIndex, !record.data[this.dataIndex]);
            Ext.Ajax.request({
            	url:'<?php echo $ajax;?>',
   				params: { 
   					action: 'updatePermission' ,
					permission_id : record.data.id,
					Interviewer_id: Ext.getCmp('userSelectTree').value,
				    field	: 'active',
			    	oldValue: !record.data.Active == true ? 0 : 1,
					value 	: record.data.Active == true ? 1 : 0,
					table: '<?php echo WARPIT_CRM."._PermissionLink";?>'					
   				}
            });
            record.commit();
            return false; // Cancel row selection.
        } else {
            return Ext.grid.ActionColumn.superclass.processEvent.apply(this, arguments);
        }
    },

    renderer : function(v, p, record){
        p.css += ' x-grid3-check-col-td'; 
        return String.format('<div class="x-grid3-check-col{0}">&#160;</div>', v ? '-on' : '');
    },

    init: Ext.emptyFn
});
Ext.preg('checkcolumn', Ext.ux.grid.CheckColumn);
Ext.grid.CheckColumn = Ext.ux.grid.CheckColumn;
Ext.grid.Column.types.checkcolumn = Ext.ux.grid.CheckColumn;


var sm = new Ext.grid.RowSelectionModel();
var <?php echo $compName;?> = new Ext.grid.EditorGridPanel({
		id:'<?php echo $compName;?>',
		store: new Ext.data.GroupingStore({
			url: '<?php echo $ajax;?>',		
			groupField: 'groupField',	
			baseParams:{
				action: 'get'
			},
			reader: new Ext.data.JsonReader({		
					root:'rows',
					totalProperty : "results"
				},
				new Ext.data.Record.create([
					{name:'id', type:'id'},
					{name:'Description', type:'string'},
					{name:'groupField', type:'string'},
					{name:'Active', type:'bool'}
				])
			)
		}),
		view: new Ext.grid.GroupingView({
            forceFit:true,
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
       	}),
		sm: sm,
		title: '<?php echo str_replace('_', ' ',$compName);?>',
		closable: true,
		columns:[{
			header: '<?php echo $LangPack->GetLabel("CRM_settings_panel", "permissions_groupField_title","Groupiranje"); ?>',
			dataIndex: 'groupField',
			hidden: true
		},{
			header: '<?php echo $LangPack->GetLabel("CRM_settings_panel", "permissions_description_title","Opis"); ?>',
			dataIndex: 'Description',
			editor: new Ext.form.TextField()
		},{
			header: '<?php echo $LangPack->GetLabel("CRM_settings_panel", "permission_enabled_title","Omogočena"); ?>',
			dataIndex: 'Active',
			width: 25,
			xtype: 'checkcolumn'
		}],
		tbar:[new Ext.ux.TreeCombo({
			height: 500,
			border: true,
			id: 'userSelectTree',
			loader: new Ext.tree.TreeLoader({
				dataUrl: '<?php echo $ajax;?>',
				baseParams:{
					action: 'getUsers'
				}
			}),
			onTreeNodeClick: function(node, e) {
				if(!node.attributes.leaf) return;
				Ext.getCmp('<?php echo $compName;?>').getStore().load({ params: { action: 'get', GroupId: node.attributes.id}});
				Ext.getCmp('selectAllButton').enable();
		        this.setRawValue(node.text);
		        this.value = node.attributes.id;
		        this.fireEvent('select', this, node);
		        this.collapse();
		    },
			hasProject: true
		}), '->',{
			xtype:'button',
			disabled: true,
			text: '<?php echo $LangPack->GetLabel("CRM_settings_panel", "select_title","Izberite"); ?>',
			id: 'selectAllButton',
			menu:{
				xtype: 'menu',
				items:[{
					xtype: 'menuitem',
					text: '<?php echo $LangPack->GetLabel("CRM_settings_panel", "select_all_title","Izberi vse"); ?>',
					handler: function(){
						var grid = Ext.getCmp('<?php echo $compName;?>');
						var store = grid.getStore();
						store.each(function(rec){ rec.set('Active', true); rec.commit(); })
						grid.getView().refresh();
						Ext.Ajax.request({
							url: '<?php echo $ajax;?>',
							params: {
								action: 'selectAllUpdate',
								userId: Ext.getCmp('userSelectTree').value,
								val: this.pressed
							}
						})
					}
				},{
					xtype: 'menuitem',
					text: '<?php echo $LangPack->GetLabel("CRM_settings_panel", "select_group_title","Izberi groupo"); ?>',
					handler: function(){
						var grid = Ext.getCmp('<?php echo $compName;?>');
						if(grid.selModel.selections.items.length > 0){
							var store = grid.getStore();
							store.each(function(rec){ if(rec.data.groupField == grid.selModel.selections.items[0].data.groupField){ rec.set('Active', true); rec.commit(); }})
							grid.getView().refresh();
							Ext.Ajax.request({
								url: '<?php echo $ajax;?>',
								params: {
									action: 'selectGroupUpdate',
									userId: Ext.getCmp('userSelectTree').value,
									group: grid.selModel.selections.items[0].data.groupField
								}
							})
						}else{
							Ext.Msg.alert('<?php echo $LangPack->GetLabel("CRM_settings_panel", "select_row_alert_title","Izberi vrstico") ?>', '<?php echo $LangPack->GetLabel("CRM_settings_panel", "select_row_alert_msg","Prosim prvo izberite groupo!"); ?>');
						}
					}
				}]
			}
			
		}],
		listeners: {
       		afteredit : function(e) {
       			Ext.Ajax.request({
       				url:'<?php echo $ajax;?>',
       				params: { 
       					action: 'update',
						id		: e.record.id,
					    field	: e.field,
						value 	: e.value,
						oldValue: e.originalValue,
						table 	:'<?php echo WARPIT_CRM."._Permissions";?>'					
       				},
					success : function(resp,opt){ 
						e.record.commit();
					}							  							
				})
			}	
		}   
	});
	Ext.getCmp('NastavitveTabPanel').add(<?php echo $compName;?>);
	Ext.getCmp('NastavitveTabPanel').setActiveTab(<?php echo $compName;?>);