<?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_form.php");
include_once(PATH_TO_ROOT."_class/class.Extjs_grid.php");
include_once(PATH_TO_ROOT."config.php");
include (PATH_TO_ROOT."/_support/repository.php");

loadPlugin($_repository,'fileUpload');

if($_POST['capi'])
	$capi = 1;
	else 
	$capi = 0;

$tablePrefix = $capi ? '_Capi' : '_Telephone';
$telTablePrefix = $capi ? '_capi___' : 'tel___';

$reqUrl = "webcati/_ajax/telNumberManagment/ajax.telNumberManagment.php";

$tabId = $_POST['uniqueTabId'];

$tableName = $tablePrefix.'Tables';

//the stores for the both comboboxes (they're used in grid and forms)
$storeDataType = $tabId.'_dataTypeStore';
$storeFieldType = $tabId.'_dataFieldStore';

$treeName = $tabId.'_tree';
$tree = new MakeTree($treeName);


$projGrid = new MakeGrid("proj_".$tabId);

//the grid to show all the fields
$fieldGrid = new MakeGrid($tabId.'_fieldGrid');

$tree->SetTable($tableName,DB_WARPIT_WEBCATI_BASE);
$tree->SetRootVisible('true','Telephone tables')
	->setWidth('300')
;
$tree->setTextPadding('1px');
$tree
	->addConfig('region',"'center'")
	->activateDD(null,"	
	isValidDropPoint : function(n, pt,dd, e, data){
		var dragNode = dd.dragData.node;
		var dropNode = n.node;
			if(dragNode.attributes.isField)
			{
				if(dropNode.attributes.isField && dropNode.parentNode.id == dragNode.parentNode.id)
					return Ext.tree.TreeDropZone.prototype.isValidDropPoint.call(this,n,pt,dd,e,data);
				else
					return false;
			}
			if(dropNode.attributes.isField || dropNode.attributes.isTable && pt == 'append')
				return false;
				
			return Ext.tree.TreeDropZone.prototype.isValidDropPoint.call(this,n,pt,dd,e,data);
	}
	", //we add our custom beforedrop listener, becouse we must reorder fields differently!
	"function(e){
		if(!e.dropNode)
		{
			return;
		}
		if(e.target.ownerTree !== e.dropNode.ownerTree)
		{
			alert('Move only inside this tree, please');
			e.cancel = true;
			return;
		}
		
		var nodeId = e.dropNode.attributes.origId;
		var targetId = e.target.attributes.origId;
		this.RMconn.request({params:{ isField : e.dropNode.attributes.isField ? 1 : 0,
		action:'moveNode',nodeId: nodeId,targetId:targetId,movePoint:e.point},
			success:function(){
				if(	e.dropNode.attributes.isField ) $fieldGrid.getStore().reload();
			}
		});}"
	)
	->setReqUrl($reqUrl)
	
	
	
			  
			  
	//context function for adding groups	
		->addContItem('Add Folder',"function(item){ 
		var n;
	    if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $tree.getSelectionModel().getSelectedNode();
				if(!n)
					n = $tree.getRootNode();
			}
		if(n.attributes.isField) return;	
		Ext.Msg.prompt('Add Folder','Folder name:',function(btn,text){ if(btn == 'ok' ){
		
		var par;
		//the group gets added after the clicked node
		var closed = !n.isExpanded();
		if( (n.attributes.leaf == true || closed || n.attributes.isTable ) && n.parentNode  )
			{par = n.parentNode; } 
		else{ par = n;   }
		$treeName.RMconn.request({params:{
		action:'insertItem',nodeText:text,addLeaf:false,
		parId:par.id,nodeId:n.id , closed:closed
		,isTargetF:(n.attributes.leaf || n.attributes.isTable ) ? 1 : 0 },success:function(resp){
		if(Ext.decode(resp.responseText).success){ 
		$treeName.getLoader().load($treeName.getRootNode(),function(){ $treeName.getRootNode().expand();});  
		}
		 }  }); }  } );   }",'node.attributes.isField','icon-add-folder',2)
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!CONTEXT MENU FOR ADDING TABLES !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!		  
	
		->addContItem('Add Table'," function(item) {
		var n;
	    if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $tree.getSelectionModel().getSelectedNode();
				if(!n)
					n = $tree.getRootNode();
			}
		if(n.attributes.isField) return;
		//we open a window to get question name and question type
		new Ext.Window({title:'Add Table',modal:true,width:'380px',
		items:{
		xtype:'form', buttonAlign:'center',labelWidth:180,labelAlign:'right',
		frame:true,
		items: [
		//textfield with filter for questions (start with letter, only numbers and letterz )
		{xtype:'textfield',id:'wupAddPrompt' , fieldLabel:'Table name',vtype:'fieldName',width: 140,allowBlank:false,labelWidth:100}
		". ($capi ? "" : ",
		//a checkbox for unique telephone numbers!
		{xtype:'checkbox',id:'wcbqCheckUnique',fieldLabel:'Unique telephone numbers' ,checked:true },
		//a checkbox for numbers as text!
		{xtype:'checkbox',id:'wcbqCheckAsText',fieldLabel:'Telephone numbers as text' }
		")."
		]//eof form items
		 ,
		keys: [{
               key: [Ext.EventObject.ENTER], fn: function(){
                   Ext.getCmp('promptOKBtn').fireEvent('click');
               }
      		 }],
		buttons:[{text:'Ok',id:'promptOKBtn',listeners:{
		click: function(){ 
			var text = Ext.getCmp('wupAddPrompt').getValue();
			if(Ext.getCmp('wupAddPrompt').isValid()   )
			{	
				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( (n.attributes.leaf==true || closed || n.attributes.isTable) && n.parentNode )
				{par = n.parentNode; }
				 else {par = n;}
				 //we make a server requst to handle insertQuestion
				 //we send the parent node ID the text and type
		         $treeName.RMconn.request({params:{
		         action:'insertTable',
		         parId:par.id,
		         nodeText:text,
		         ".($capi ? "" :"
		         uniqueTelNum :Ext.getCmp('wcbqCheckUnique').getValue(),
		         telNumAsText :Ext.getCmp('wcbqCheckAsText').getValue(),
		         ")."
		         nodeId:n.attributes.id , closed:closed,
		         isTargetF:(n.attributes.leaf || n.attributes.isTable) ? 1 : 0 } 
				,success:function(resp){
				if(Ext.decode(resp.responseText).success){
					//if adding was succesful we refresh the parent and open the location
					//NOTE: all other groups get closed
					var p = par.getPath()+'/'+Ext.decode(resp.responseText).insertId;
					$treeName.getLoader().load($treeName.getRootNode(),function(){ $treeName.selectPath(p); } );
					$fieldGrid.getStore().reload();
					Ext.getCmp('wupAddPrompt').findParentByType('window').close();
				} else{//else we display a warning and focus on the name field
				Ext.Msg.alert('Warning!',Ext.decode(resp.responseText).error );
				Ext.getCmp('wupAddPrompt').focus()}},
					
				failure:function(){alert('failed');}	});    
				
			}
		}
	}
			  },
		{
		text:'Cancel',handler:function(){ 
		this.findParentByType('window').close();
	
	
		 }
		 }
			  ] },
	defaultButton:'wupAddPrompt'
			   } ).show(n); 
			    }" //eof handler
			  ,'node.attributes.isField','icon_database_add',2 )
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!CONTEXT MENU FOR ADDING FIELDS INTO TABLE (SHOWS ONLY ON TABLES AND FIELDS)!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!		  
	->addContItem('Add Field'," function(item) {
		var n;
	    if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $tree.getSelectionModel().getSelectedNode();
				if(!n)
					n = $tree.getRootNode();
			}
		if(!n.attributes.isTable && !n.attributes.isField) return;	
		
		//we open a window to get question name and question type
		new Ext.Window({title:'Add Field',iconCls:'icon-add-record',modal:true,width:'300px',
		items:{
		xtype:'form', buttonAlign:'center',labelAlign:'right',
		frame:true,
		items: [
		//textfield with filter for questions (start with letter, only numbers and letterz )
		{xtype:'textfield',id:'wupAddPrompt' , fieldLabel:'Field name',vtype:'fieldName',width: 140,allowBlank:false,labelWidth:100},
		//a combobox taken from the grid, with variable types
		{xtype:'combo',id:'wcbqComboPrompt', store: $storeDataType ,fieldLabel:'Field type',displayField:'displayText',mode:'local',
		triggerAction:'all',width: 140,valueField:'myId',editable:false}
		
		]//eof form items
		 ,
		keys: [{
               key: [Ext.EventObject.ENTER], fn: function(){
                   Ext.getCmp('promptOKBtn').fireEvent('click');
               }
      		 }],
		buttons:[{text:'Ok',id:'promptOKBtn',listeners:{
		click: function(){ 
			var text = Ext.getCmp('wupAddPrompt').getValue();
			if(Ext.getCmp('wupAddPrompt').isValid()   )
			{	
				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(n.attributes.isField )
				{par = n.parentNode; }
				 else {par = n;}
				 //we make a server requst to handle insertQuestion
				 //we send the parent node ID the text and type
		         $treeName.RMconn.request({params:{
		         action:'insertField',
		         parId:par.id,
		         nodeText:text,
		         dataType :Ext.getCmp('wcbqComboPrompt').getValue(),
		         nodeId:n.attributes.origId , closed:closed,
		         parText:par.text,
		         isTargetF:(n.attributes.leaf) ? 1 : 0 } 
				,success:function(resp){
				if(Ext.decode(resp.responseText).success){
					//if adding was succesful we refresh the parent and open the location
					//NOTE: all other groups get closed
					var p = par.getPath()+'/'+Ext.decode(resp.responseText).insertId+'_field';
					$treeName.getLoader().load(par,function(){ $treeName.selectPath(p); } );
					$fieldGrid.getStore().reload();
					Ext.getCmp('wupAddPrompt').findParentByType('window').close();
				} else{//else we display a warning and focus on the name field
				Ext.Msg.alert('Warning!',Ext.decode(resp.responseText).error );
				Ext.getCmp('wupAddPrompt').focus()}},
					
				failure:function(){alert('failed');}	});    
				
			}
		}
	}
			  },
		{
		text:'Cancel',handler:function(){ 
		this.findParentByType('window').close();
	
	
		 }
		 }
			  ] },
	defaultButton:'wupAddPrompt'
			   } ).show(n); 
			   Ext.getCmp('wcbqComboPrompt').setValue(0); 
			    }" //eof handler
			  ,'!node.attributes.isTable && !node.attributes.isField','icon-add-record',2 )
	->addContSeparator(true)		  
	
	->addContItem('Delete Folder',"function(item){
		var n;
	    if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $tree.getSelectionModel().getSelectedNode();
				if(!n)
					n = $tree.getRootNode();
			}
		if((n.hasChildNodes() )|| n.attributes.isField || n.attributes.isTable) return;	
		
		 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,isTargetF:(n.attributes.leaf || n.attributes.isTable ) ? 1 : 0,
			nodeText:n.text
			},success:function(resp){
			if(Ext.decode(resp.responseText).success){
			n.remove();
			$fieldGrid.getStore().reload();  }
			 }  }); 
		  }} });
		 }"
		 ,"node.hasChildNodes() || node.attributes.isField || node.attributes.isTable",'icon_delete_folder',2)
	->addContItem('Delete Table',"function(item){
		var n;
	    if(item)
			n = item.parentMenu.contextNode;
		else
			{
				n = $tree.getSelectionModel().getSelectedNode();
				if(!n)
					n = $tree.getRootNode();
			}
		if(!n.attributes.isTable ) return;	
		
		 Ext.Msg.show({ title:'Remove table',buttons: Ext.MessageBox.YESNO,msg: 'Are you sure?',
		fn: function(btn){if(btn == 'yes'){
			$treeName.RMconn.request({params:{
			action:'delete',
			nodeId:n.id,isTargetF:(n.attributes.leaf || n.attributes.isTable ) ? 1 : 0,
			nodeText:n.text
			},success:function(resp){
			if(Ext.decode(resp.responseText).success){
			n.remove();
			$fieldGrid.getStore().reload();  }
			 }  }); 
		  }} });
		 }"
		 ,"!node.attributes.isTable ",'RMicon_delete_database',2)
	->baseParams = "nameField : 'name',isCapi:$capi"
;

	 $labelGrid = new MakeGrid();

	
	$fieldGrid->setMainTable($tableName.'Addon',DB_WARPIT_WEBCATI_BASE)
	->setReqUrl($reqUrl)
	->setTitle('Fields')
	->setSort('orderBy')
	//we will create or own afteredit listener, so that we can update the column structure
	->setEditable(false)
	->listeners[]="afteredit:function(e){
				var p = {};
				p.field = e.field;
				p.action = 'update';
				p.tableId = e.grid.selectedId;
				p.id = e.record.id;
				p.value = e.value;
				if(e.field == 'name')
				{
					p.oldName = e.originalValue;
					p.dataType = e.record.data.type;
				}
				else
				{
					p.fieldName = e.record.data.name;
					p.oldName = p.fieldName;
				}
				
				$fieldGrid.RMconn.request({
					params: p,
					success : function(resp,opt){
					
						if(Ext.decode(resp.responseText).success){ e.record.commit();
								if(e.field == 'use_as_labels')
									{
										$labelGrid.store.reload();
									}
						 
						 } else {e.record.reject();
						Ext.Msg.alert('Warning!',Ext.decode(resp.responseText).error);
					}},
					failure: function(){e.record.reject();}
				});
			}"
	;
	$fieldGrid->baseParams = "isCapi:$capi";
	
	//$fieldGrid->selectSQL = "SELECT a.id,b.id AS id_order,a.field_name,a.data_type,field_text,field_type,is_hidden FROM _InterviewerStructure as a INNER JOIN _InterviewerFieldOrder as b ON a.id = b.field_id AND b.user_id = 0";
	
	$fieldGrid->addColumn('id');
	$fieldGrid->addColumn('id_telbaza')->defaultValue("\"+$fieldGrid.selectedId+\"");
	$fieldGrid->addColumn('orderBy');
	$fieldGrid->addColumn('name','Name')->editor("new Ext.form.TextField()");
	
	$comboArray = $configCombo['DataType'][$_SESSION['UserInfo']['lng_admin'] ]; 
	for ($i=0;$i< count($comboArray);$i++ )
	{
		$comboStr[] = "['$i','".$comboArray[$i]."']";
	}
	
	echo "var $storeDataType = new Ext.data.ArrayStore({
        fields: [
            'myId',
            'displayText'
        ],
        data: [".implode(',',$comboStr).  "]
	});";
	
	
	$fieldGrid->addColumn('type','Variable type')
	->editor("new Ext.form.ComboBox({store:$storeDataType,
		valueField:'myId',
	displayField:'displayText',
	mode:'local',
	triggerAction:'all'
	})")
	->renderer("function(val){
		var idx =$storeDataType.find('myId', val);
		if(idx==-1)	return 'Select';
		var rec = $storeDataType.getAt(idx);
		return rec.get('displayText');
	}"  );

	$fieldGrid->region('center')
	->activateRemove('Remove','icon-delete-record',"$treeName.getRootNode().reload();");
	if(!$capi)
	
	$fieldGrid->addTbarItem("{iconCls:'RMicon_undo',text:'Reset statuses',handler:function(){
		Ext.Msg.confirm('Reset database','Are you sure?',function(btn){
			if(btn == 'yes')
			{
				$fieldGrid.RMconn.request({params:{action:'resetDatabase',telTable:'tel___'+$fieldGrid.selectedName }});
			}
		});
	} }");
	
	//Section #1 20150305 Tanis
    $copyTree = new MakeTree($treeName . "_copy");
    
    
    $copyTree->SetTable($tableName,DB_WARPIT_WEBCATI_BASE);
    $copyTree->SetRootVisible('true','Telephone tables')
        ->setWidth('300')
    ;
    $copyTree->setTextPadding('1px');
    $copyTree->setReqUrl($reqUrl);
  //  echo $copyTree->createTree();
    
    	
	$fieldGrid->addTbarItem("{iconCls:'RMicon_copy',text:'Copy to',handler:function(a,b,c){
           
       " . $copyTree->createTree() . "
       $copyTree.getLoader().on('beforeload',function(loader,node){
        if(!node.attributes.isTable)
            delete loader.baseParams.isTable;
        });
        

        var win = new Ext.Window({
            //    applyTo:'hello-win',
                layout:'fit',
                width:500,
                height:300,
                title: 'Copy fields',
                items: [$copyTree],
 
                buttons: [{
                    text:'Copy',
                    handler: function()
                    {
                       if($copyTree.getSelectionModel().getSelectedNode().id != $fieldGrid.selectedId)
                       {
                           $copyTree.RMconn.request({
                                params: {
                                    action:'copy', 
                                    id_from: $fieldGrid.selectedId, 
                                    id_to: $copyTree.getSelectionModel().getSelectedNode().id,
                                    parText: $copyTree.getSelectionModel().getSelectedNode().attributes.text
                                },
                                success:function(fp, o)
                                {
                                    ///console.log($tree.getLoader());
                                    $treeName.getLoader().load($treeName.getRootNode(),function(){ $treeName.getRootNode().expand();});  
                                    win.close();
                                }                               
                           });
                       }
                        
                    }
                },{
                    text: 'Close',
                    handler: function(){
                        win.close();
                    }
                }]
            });
            win.show();
    } }");
    //End Section #1 20150305
    
    $form2 = new MakeForm($tableName. 'sampleRules');
    $form2->padding(15)
    //->setAutoUpdate()
    ->setReqUrl($reqUrl)
   // ->flex(2)
  //  ->region('east')
 //   ->setHeight(280)
 //   ->setMainTable('_ProjectProperties',DB_WARPIT_WEBCATI_BASE)
    ->addConfig('labelWidth',150)
    ->addConfig('border', 'false')
    ->addConfig('autoScroll',true);
    //->id = $projectId;
    
    $form2->addField('sample_parameter','Set sample parameter','textfield')->width(180);
    $form2->addField('rules_by_id','Set rules by ID','textfield')->width(180);
    
    //Section #2 20150522
        $fieldGrid->addTbarItem("{/*iconCls:'RMicon_copy',*/text:'Set sample rules',handler:function(a,b,c){
             " .  $form2->createForm() . "
        if($fieldGrid.getSelectionModel().getSelected())
        {
            var win = new Ext.Window({
            //    applyTo:'hello-win',
                layout:'fit',
                width:400,
                modal:true,
                height:150,
                title: 'Set sample rules',
                items: [$form2],
 
                buttons: [{
                    text:'OK',
                    handler: function()
                    {
                        var dbName = $fieldGrid.selectedName;
                        $form2.getForm().submit({
                            params: {
                                action: 'setSampleRules',
                                RMtable: 'tel___' + dbName,
                                database: '" . DB_WARPIT_WEBCATI_BASE . "',
                                field: 'tel_' + $fieldGrid.getSelectionModel().getSelected().get('name')
                            },
                            success: function(cmp, form)
                            {
                                if(form.result.error.length == 0)
                                {
                                    win.close();
                                }
                                else
                                {
                                    Ext.Msg.show({ title:'Error', msg: form.result.error, icon: Ext.MessageBox.INFO, buttons: Ext.Msg.OK});
                                }
                            }
                        });
                        //console.log($fieldGrid.getSelectionModel().getSelected().get('name'));
                    }
                },{
                    text: 'Close',
                    handler: function(){
                        win.close();
                    }
                }]
            });
            win.show();
        }
        else
        {
            Ext.Msg.show({ title:'Info', msg: 'You have to select field!', icon: Ext.MessageBox.INFO, buttons: Ext.Msg.OK});
        }
        
    } }");
    // End Section #2 20150522
    
	$fieldGrid->addColumn('is_default','Default')->type('checkColumn');
	$fieldGrid->addColumn('use_as_labels','With Labels')->type('checkColumn');
//grid that shows all posiible records and let's you label them
$labelGrid->setMainTable($tablePrefix.'LabelsDef',DB_WARPIT_WEBCATI_BASE)
->setReqUrl($reqUrl)
->setAutoLoad(false)
->region('south')
->setTitle('Define labels')
->setGrouping('varLabel','{startCollapsed:true}')
->addConfig('clicksToEdit',1)
->setEditable(false)
->setHeight('mainTabPanel.getHeight()/2')
->listeners[] = "afteredit:function(e){
	$labelGrid.RMconn.request({
		params: Ext.apply({action:'update',RMcomp:'labelGrid'},e.record.data),
		success:function(){e.record.commit()}
	});
}";
$labelGrid->addColumn('id_telname');
$labelGrid->addColumn('is_addon');
$labelGrid->addColumn('id_var');
$labelGrid->addColumn('varLabel','Group')->hidden(true);
$labelGrid->addColumn('reg_code','Code');
$labelGrid->addColumn('reg_label','Label','new Ext.form.TextField()');


echo $labelGrid->createGrid();
	
	
//grid that shows all succeded imports
$importGrid = new MakeGrid();
$importGrid->setMainTable('notSet',DB_WARPIT_WEBCATI_BASE)
->activateRemove()
->addTbarItem("{
	text:'Edit records',
	iconCls:'RMicon_edit_record',
	handler: function(){
		addTabAuto('manageTelTable_'+$fieldGrid.selectedId,'webcati/_forms/".($capi ? "capiManagment/forms.manageCapiTable.php" :  "telNumberManagment/forms.manageTelTable.php")."',
			{
				id_table: $fieldGrid.selectedId,
				capi:$capi
			}
		);
	}
}")
->setAutoLoad(false)
->region('center')
->setTitle('Previous imports')
->baseParams= "idField:'id_import',isCapi:$capi";

$importGrid->addColumn('id','Id');
$importGrid->addColumn('number','Records');

echo $importGrid->createGrid();
	
$cardFieldsName = $tabId.'_fieldsCard';
echo $tree->createTree();
echo $fieldGrid->createGrid();
/*echo $form->createForm();
echo $grid->createGrid();
echo $propForm->createForm();
*/
echo  $treeName.".getSelectionModel().on('beforeselect',function(sm,n){
	if(n.isLeaf() || n.attributes.isTable)
	{
		if(!n.attributes.isTable)
			n = n.parentNode;
	
		$fieldGrid.selectedId = n.id;
		$fieldGrid.selectedName = n.text;
		var st = $fieldGrid.getStore();
		$fieldGrid.setTitle('Fields: '+n.text);
		st.baseParams.SQLwhere = 'id_telbaza = '+n.id;
		st.reload();
		$importGrid.RMconn.baseParams.RMtable = '$telTablePrefix'+n.text;
		$importGrid.getStore().reload({params:{
			SQL:'SELECT id_import as id,count(*) as number FROM $telTablePrefix'+n.text+' GROUP BY id_import'}});
			
		$labelGrid.getStore().reload({params:{id_telname:n.id,RMcomp:'labelGrid',telTable:'$telTablePrefix'+n.text } });

		$projGrid.telTableName = '$telTablePrefix'+n.text;
		$projGrid.getStore().reload({ params: { telTable: '$telTablePrefix'+n.text  } });
		$cardFieldsName.getLayout().setActiveItem(0);
	}
	else 
	{
		$cardFieldsName.getLayout().setActiveItem(1);
	}
}); 
	$treeName.getLoader().on('beforeload',function(loader,node){
		if(node.attributes.isTable)
			loader.baseParams['isTable'] = true; 
		else 
			delete loader.baseParams.isTable;
	});

";

	
	$projGrid->setMainTable('projView',DB_WARPIT_WEBCATI_BASE)->setTitle('Reserved samples')
	->setReqUrl("webcati/_ajax/telNumberManagment/ajax.manageTelTable.php");
	$projGrid->addColumn('id','Id')->width(50);
	$projGrid->addColumn('project','Project');
	$projGrid->addColumn('count','Number')->width(60);
	$projGrid->addRowAction('icons',"new Ext.ux.grid.RowActions({
	
	actions:[
		{
		iconCls:'RMicon_edit_record',
		tooltip:'Edit index table'
		},
		{
		iconCls:'icon_red_delete',
		tooltip:'Remove sample'
		}
	],
	listeners: {
		action: function(g,r,a){
			var act;
			if(a == 'RMicon_edit_record')
			{
				if(r.data.project != 'not exists' && r.data.project != 'Available')
				addTabAuto('manageSamples_'+ r.id,'webcati/_forms/sampler/forms.manageSamples.php',
				{
					id_proj:r.id
					,id_telTable:$fieldGrid.selectedId 
				});
			}
			else if(a == 'icon_red_delete') 
			{
				var confirmText = RMrandomString();		
				Ext.Msg.prompt('Warning','This will delete all samples for this project!'+
			'<br>Enter following code and confirm<br>'+confirmText,
				function(btn,text){
					if(btn=='ok')
					{
						if(text == confirmText )
						{
						$projGrid.RMconn.request({params:{
							action: 'deleteSamples',
							telTable: $projGrid.telTableName,
							id:r.id},
							success:function(){ $projGrid.getStore().reload();}
						});
						}else 
							Ext.Msg.alert('Error','Wrong code!');
					 }
					else return false;
					 }
				)
			}	
		}
	}
})");

	$projGrid->region('south')->setHeight(200)
	//->baseParams = "telTable : '$tableName'"
	;
 
	
echo $projGrid->createGrid();
	
	
	
?>
	var <?php echo $tabId; ?> = new Ext.Panel({
		id:'<?php echo $tabId; ?>',
		title:'Prepare <?php echo $capi ? 'CAPI':"CATI"; ?> numbers',
		iconCls:'RMicon_prepare_cati',
		defaults:{split:true,border:false},
	
		layout:'border',
		border: false,
		closable:true,
		items:[<?php echo "
		{
			layout:'border',
			region:'west',
			items:[ $tree,$projGrid ],
			width:300
		} 
		 ,$cardFieldsName = new Ext.Panel({layout:'card',width:400,activeItem:1, region:'center',items:[{layout:'border',border:false,defaults:{split:true,border:false},
		  items:[
		  {layout:'border',region:'center',defaults:{split:true,border:false}, items:[ $fieldGrid,$labelGrid] },
		  {region:'east',layout:'border',width:350,
		  items:[
		//form with import button
		  {xtype:'form',title:'Upload1233',region:'north',height:200,padding:'15',enctype:'multipart/form-data',
      			  fileUpload: true,labelWidth:60,
						items: [{
							xtype:'combo',
							store: new Ext.data.ArrayStore({
								        fields: [
								            'myId'
								        ],
								        data: [ ['iso-8859-1'],['iso-8859-2'],['iso-8859-3'],['iso-8859-4'],['iso-8859-5'],['iso-8859-6'],['iso-8859-7'],['iso-8859-8'],['iso-8859-9'],['iso-8859-10'],['iso-8859-11'],['iso-8859-12'],['iso-8859-13'],['iso-8859-14'],['iso-8859-15'],['windows-1250'],['windows-1251'],['windows-1252'],['windows-1256'],['windows-1257'],['koi8-r'],['big5'],['gb2312'],['utf-16'],['utf-8'],['utf-7'],['x-user-defined'],['euc-jp'],['ks_c_5601-1987'],['tis-620'],['SHIFT_JIS']
								         ]
											}),
									fieldLabel:'Encoding',displayField:'myId',mode:'local',
						triggerAction:'all',width: 140,valueField:'myId',editable:false,
						name:'encoding',
						value:'utf-8'
						
						},{
			            xtype: 'fileuploadfield',
			            id: 'tm-form-file',
			            width:260,
			            emptyText: 'Select file',
			            fieldLabel: 'File',
			            name: 'csvfilepath',
			            buttonText: '',
			            buttonCfg: {
			                iconCls: 'upload-icon'
			            }
			        }
			   ,{xtype:'button',
	            text: 'Upload',
	            handler: function(){
	              
		                this.findParentByType('form').getForm().submit({
		                    url: 'webcati/_ajax/telNumberManagment/ajax.import.php',
		                    method : 'post',
		                    params:{tableSel : $fieldGrid.selectedName,tableId : $fieldGrid.selectedId,capi:$capi },
		                    waitMsg: 'Uploading your file...',
		                    success: function(fp, o){	                      
		                      var respStatus = Ext.decode(o.response.responseText);
		                      Ext.Msg.alert('Success','Upload succesful!');
		                      $importGrid.store.reload();
		                    },
		                    failure: function(fp, o){	                      
		                      var respStatus = Ext.decode(o.response.responseText);
		                      Ext.Msg.alert('Error',respStatus.error);
		                    }
		                });
	              
	            }
	        }],
			tbar: [{text: 'Example',iconCls:'RMicon_example',handler: function(){
				Ext.util.FileOps.downloadFile('$reqUrl',{
					action: 'example'
				});
			}  }]
	         },$importGrid]} //eo east border layout

        ] } 
		  ,//blank page to show while no table is selected!!!!
		  {}  ]  }) 
		" ;  ?>   ]
	});
	mainTabPanel.add(<?php echo $tabId; ?>).show();
