<?php

include("_dirinfo.php");

include (PATH_TO_ROOT."init.php");
include (PATH_TO_ROOT."webcati/init.php");
include (PATH_TO_ROOT."_class/class.Extjs_tree.php");
include (PATH_TO_ROOT."_class/class.Extjs_grid.php");

/*
 * Css Styles tree
 */


$treeName = "wcdpTreeCss";
$gridEditCss = 'wcdpDesignerCssPropertyGrid';



?>

//store for adding properties
var arrStoreCssProperties = [ 

<?php 
$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
$sql = "SELECT * FROM ".WC_DESIGNER_CSS_PROPERTIES." ORDER BY name ASC ";
If ($res = $db->SQLexecute($sql)) 
{	
	$i=0;	
	while ($row = $db->fetchAssoc($res)) {
		if($i>0) echo ",";
		echo "['".$row['name']."', '".$row['id']."']";
		$i++;
	}
}else{
	echo "['Error reading sql database.', 'Contact administrator.']";
}
			
?>
 
];
<?php

$tree = new MakeTree($treeName);
$tree->SetTable(WC_DESIGNER_CSS, DB_WARPIT_WEBCATI_BASE, $treeName);
$tree->SetRootVisible('true', 'Css Styles')
	->setReqUrl('webcati/_ajax/designerPanel/ajax.cssPanel.php')
//	  ->setContEdit('Edit')
	  ->setContAddGroup('Add Group')
	  ->setContAddItem('Add Class')
//	  ->setContDelete('Delete')
	//adding a style property
	
	 ->addContItem('Add attribute',"function(item) {
	 				
					var n;
					if(item === 'd')
						n = this.getNodeById($gridEditCss.nodeId)
					else if(item)
						 n= item.parentMenu.contextNode;
					else	
					{
						n = this.getSelectionModel().getSelectedNode();
						if(!n || n.leaf == 0) return;
					}
					//we open a window with a combo of all styles to add
					var promptNameTF = new Ext.form.ComboBox({fieldLabel:'Property',id:'RMtreeAddPrompt' ,store: storeCssProperties, displayField:'name',valueField:'value', typeAhead: true, mode: 'local', triggerAction: 'all', emptyText: 'Select', selectOnFocus:true});
					new Ext.Window({title:'Add style',modal:true,width:'320px',
					items:{
						xtype:'form', buttonAlign:'center',
						frame:true,
						items: [ promptNameTF
							
						],
						keys: [{
				               key: [Ext.EventObject.ENTER], fn: function(){
				                   Ext.getCmp('promptOKBtn').fireEvent('click');
				               }
					      		 }],
							buttons:[{text:'Ok',id:'promptOKBtn',listeners:{
							click: function(){
							var text = promptNameTF.getValue();
							if(promptNameTF.isValid()   )
							{	
								//if we clicked on a question or a closed group we add it to its parent one position lower otherwise to the clicked group
								 //we make a server requst to handle addStyle
			                       $gridEditCss.RMajax.request({params:{action:'addStyle',
			                       node:n.id,propId:text
									} 
								,success:function(resp){
											if(Ext.decode(resp.responseText).success){
												//if adding was succesful we refresh the property grid
												$gridEditCss.reload(n);
												promptNameTF.findParentByType('window').close();
											} else{//else we display a warning and focus on the name field
											Ext.Msg.alert('Warning!',Ext.decode(resp.responseText).error );
											promptNameTF.focus()}},
									failure:function(){alert('failed');}	});
					}}
					}},{
		text:'Cancel',handler:function(){ 
		this.findParentByType('window').close();
	
		 }}
					
					] //eo buttons 
				},
	defaultButton:'RMtreeAddPrompt'
				}).show(n);//eo window
	
	}"
	//we hide this for groups
	,"node.leaf == 0",'icon_add_document',2)
	->setContDelete('Delete')
	  ->activateDD('t2div-webcati')
	  ->setEditable()
	  ->setTextPadding('6px')
	  ->addConfig('iconCls',"'icon-help-tab'")
	  ->addConfig('border',"false")
	  ->region('north')
	  ->setHeight(400)
	   ->listeners[] = "startdrag : function(t,n){ n.cssDrag = true;  } " ;
	
	 ;

echo $tree->CreateTree();


echo $treeName.".getSelectionModel().on('beforeselect',function(sm,node,oldNode){
		var n=node.attributes; 
		//console.log(node); 
		if(n.leaf==0){
		}else{
			$gridEditCss.nodeId = node.id;
			$gridEditCss.reload(node);
		}
		
		
	})";
?>

// simple array store
var storeCssProperties = new Ext.data.SimpleStore({
    fields: ['name', 'value'],
    data : arrStoreCssProperties
});


<?php 
//urejanje Css style


?>

var wcdpDesignerCssPropertyGrid = new Ext.grid.PropertyGrid({
        id: 'wcdpDesignerCssPropertyGrid',
        title: 'Panel properties',
        height: 250,
        region:'center',
        split:true,
        //rm ajax for requesting about properties
        RMajax : new RMajax({url:'webcati/_ajax/designerPanel/ajax.cssPanel.php'}),
        tbar:[{
        	text:'Add',
        	iconCls:'icon_add_document',
        	scope: wcdpDesignerCssPropertyGrid,
        	handler:function()
        	{
        	<?php 
        	echo "if($gridEditCss.nodeId) $tree.contextHandler_2('d') ";
        	?>
        	}
        },{
        	xtype:'button',
        	text:'Delete',
        	iconCls:'icon-delete-record',
        	scope: wcdpDesignerCssPropertyGrid,
        	handler:function(){
        		
        		var sm = wcdpDesignerCssPropertyGrid.getSelectionModel();
        		if(sm.hasSelection() )
        		{
        			var d = sm.selection.record.data;
        			wcdpDesignerCssPropertyGrid.RMajax.request({
        			params:{
        				action:'delete',
        				name:d.name,
        				node:wcdpDesignerCssPropertyGrid.nodeId
        				},
        			success:function(rsp)
        			{
        				if(Ext.decode( rsp.responseText).success )
        					wcdpDesignerCssPropertyGrid.removeProperty(d.name);
        			}
        			}); 
        			
        		}
        		//this.RMajax.request
        	}
        }]
    });

<?php

echo "$gridEditCss.reload = function(node){
	this.RMajax.request({
			params:{ 
				action:'select',RMcomp:'grid',node:node.id
			},
			success:function(resp){
				var r = Ext.decode(resp.responseText);
				$gridEditCss.customEditors = r.editors;
				$gridEditCss.setSource(r.object);
			}});
		             	
};
";

//listener for propertyGrid for updating the css values
echo $gridEditCss.".on('beforepropertychange',function(src,recId,value){
			
				 $gridEditCss.RMajax.request({
				 	params:{action:'setStyle',prop:recId,value:value,node:$gridEditCss.nodeId },
				 	success:function(resp){
				 		//now let's take some action if some special properties were changed
				 		if(lastActiveDesignerOverviewWindow && lastActiveDesignerOverviewWindow.refresh)
				 			lastActiveDesignerOverviewWindow.refresh();
				 	}
				 });
});";


/*
$gridEditCss_table = WC_DESIGNER_CSS_PROPERTIES;
$gridEditCss = new MakeGrid();
$gridEditCss->setMainTable($gridEditCss_table,DB_WARPIT_WEBCATI_BASE);
$gridEditCss->setTitle("Css");

$gridEditCss->addColumn('id')->header('Id')->hidden(TRUE);
$gridEditCss->addColumn('id_sup');
$gridEditCss->addColumn('name')->header('Name')->editor('new Ext.form.ComboBox({store: storeCssProperties, displayField:\'name\', typeAhead: true, mode: \'local\', triggerAction: \'all\', emptyText: \'Select or type css option...\', selectOnFocus:true})');
$gridEditCss->addColumn('value')->header('Value')->editor('new Ext.form.TextField()')->defaultValue('');


$gridEditCss->activateAdd('Add')
	->activateRemove('Delete')
	->setAutoExpandMax(10000)
	->setAutoExpand('name')
	->setCheckBoxSelectionModel(true)
	->region('center')
	;
	
echo $gridEditCss->createGrid();

 */

echo "
var webDesignCssPanel = new Ext.Panel({

	id:'webDesignCssPanel',
	title:'Webcati Css editor',
	defaults:{split:true,border:false},
	iconCls:'icon-webcati-tab',
	layout:'border',
	border: false,
	closable:true,
	items:[
		$treeName,
		$gridEditCss
	]
			
});";

?>

Ext.getCmp('west-panel').add(webDesignCssPanel).show();