<?php 
include("_dirinfo.php");
include_once (PATH_TO_ROOT."init.php");

include (PATH_TO_ROOT."webuserspool/UsersPoolinit.php");
include (PATH_TO_ROOT."_class/class.Extjs_form.php");
include (PATH_TO_ROOT."_class/class.Extjs_grid.php");

if( !$UserSession->isLoggedin() )
{
	echo "alert('Not logged in!')";
	exit;
}

$tabId = $_POST['uniqueTabId'];
$templateId = $_POST['node_id'];
$treeName = 'PoolMenu';
$attachName = $tabId.'_attachFS';
$name = $db->get('_Emails',$templateId,'idLab',DB_WARPIT_USERSPOOL);
$urlAjax = 'webuserspool/_ajax/ajax.fileTree.php';

$fileTName = $tabId.'_fileTree';

$form = new MakeForm($tabId.'_form');
$formName = $form->getName();
$form->setMainTable('_Emails',DB_WARPIT_USERSPOOL)
	->addConfig('padding','20')
	->addConfig('autoScroll','true')
	//->labelAlign('top')
	->id = $_POST['node_id']
	;
//$form->addField('oseba_id','First name');
//we add some anchor to all the fields becouse IE doesn't go well with autoscroll
$acnhor = '98%';

	
/*
$form->addField('loadTemplate','Load Template','compositefield')
	->anchor($acnhor)
	->setProperty('submitValue','false')
	->setProperty('items',"[
	{xtype:'combo',name:'loadTemplateCombo',submitValue:false,
	store:new Ext.data.JsonStore({url:'_ajaxManipulators/gridDataManipulator.php',
				baseParams:{action:'select',database:'".DB_WARPIT_USERSPOOL."',RMtable:'_MailTemplates'},
				root:'rows',autoLoad:true,
				fields:['id','name','subject','content']}),
	fieldLabel:'programer',
	displayField:'name',
	valueField:'id',
	mode:'local',
	triggerAction:'all' 
	
	},
	{xtype:'button',text:'Load',handler:function(){
		var cb =  $formName.getForm().findField('loadTemplateCombo');
		var data = cb.getStore().getById (cb.getValue() ) ;
		if(data)  
			//$formName.getForm().findField('podatki[content]').setValue( data.data.content  );
			$formName.getForm().load({params:{action:'load',RMtable:'_MailTemplates',id:data.data.id}});
		cb.setValue('');
	} }	
]")
	
;*/
/*
$form->addField('sendMail','Send test mail','compositefield')
	->anchor($acnhor)
	->setProperty('submitValue','false')
	->setProperty('items',"[
	{xtype:'combo',submitValue:false,
	store:new Ext.data.JsonStore({url:'_ajaxManipulators/gridDataManipulator.php',
				baseParams:{action:'select',database:'".DB_WARPIT_USERSPOOL."',RMtable:'_TestMails'
				,SQL : 'SELECT a.id,b.id AS intId,b.email FROM _TestMails a INNER JOIN _Interviewer b ON a.interViewerId = b.id'
				},
				root:'rows',autoLoad:true,
				fields:['id','email','intId']}),
	name:'sendTestMail',
	displayField:'email',
	valueField:'id',
	mode:'local',
	triggerAction:'all' 
	
	},
	{xtype:'button',text:'Send',handler:function(){
		var cb = $formName.getForm().findField('sendTestMail');
		var data = cb.getStore().getById (cb.getValue() ) ;
		if(!data) return;
		Ext.Ajax.request({url:'webuserspool/_ajax/ajax.showgroup.php',params:{action:'sendMail',
		ids:'['+data.data.intId+']',
		emails:'[\"'+data.data.email+'\"]',
		immideately : true, schTime :'0000-00-00 00:00:00',
		templateId:$templateId
		 },
				success: function(resp){
						var statGrid = Ext.getCmp('WUPMailStatisticsGrid');
					 		if(  statGrid )
					 			statGrid.getStore().reload();
				  }
					});
	} }	
]");
*/
/*
$form->addField('test','','fieldset')
	->anchor($acnhor)
	->setProperty('defaults',"{anchor:'80%'}")
	->setProperty('collapsible',"true")
	->setProperty('title',"'Mail options'")
	->setProperty('items',"[{xtype:'textfield',
	        	name:'podatki[mail_from]',fieldLabel:'Mail from'
	        },{xtype:'textfield',
	        	name:'podatki[subject]',fieldLabel:'Subject'
	        }]")*/
/*	->setProperty('listeners',"{
		collapse:function(){ //when the size of the form changes, we adjust the anchor 
		$formName.getForm().findField('podatki[content]').anchor = '100% -130';
						//we must delete some anchor buffer in order, for the changes to take effect!!!
							delete $formName.getForm().findField('podatki[content]').anchorSpec;
							$formName.doLayout();
		  },
		expand:function(){ $formName.getForm().findField('podatki[content]').anchor = '100% -190';
					delete $formName.getForm().findField('podatki[content]').anchorSpec;
					$formName.doLayout(); }
	}")*/
	;
	
//grid for showing attachments
$grid = new MakeGrid();
$gridName = $grid->getName();
$grid->setMainTable(WUP_MAILATTACHMENTS,DB_WARPIT_USERSPOOL)
	->setWidth(300)
	->baseParams = "SQLwhere : 'template_id = $templateId'";
	;
$grid->addColumn('id');
$grid->addColumn('fileName','File');
$grid->addColumn('fileSize','Size')->type('int')->width(90);
$grid->addColumn('embeded','Embedded')->type('checkColumn')->width(70);

$grid->setCheckBoxSelectionModel()
	->addTbarItem("{
		text:'Attach',iconCls:'RMicon_add_attach',handler:function(){
			//attaching files to this template
			var files = [];
			 Ext.each( $fileTName.getChecked(),function(n){
			 		var attr = n.attributes;
			 		var fInfo = {
			 			name : n.text,
			 			path : attr.filePath
			 		};
			 		files.push(fInfo);
			 		
			 } );
			 Ext.Ajax.request({
				url:'$urlAjax',
				params: { //becouse filetree sends cmd instead of action!
					cmd:'insertAttachments', files: Ext.encode( files),template:$templateId
				},
				success:function(resp,opt)
				{
					var r = Ext.decode(resp.responseText);
					if(r.success){ $gridName.getStore().reload();   }
					else { alert(r.error);  }
				}
			});
		}
	} ")
	->activateRemove('Remove','RMicon_delete_attach')
	
	;
	


echo 	"var   $fileTName= new Ext.ux.FileTreePanel({
		width:400
		,region:'west'
		,rootVisible:false
		,readOnly:true
		,enableDD:false
		//,enableDrag:true
		,ddGroup:'wbluFileTree'
		//settable in RMconfigfile!!!
		,rootPath:''
		,url: '$urlAjax'
		,autoScroll:true
		,enableProgress:false
	//	,baseParams:{action:'select'}
	//	,singleUpload:true
		,topMenu : false
		,tbar :[{text:'Upload',iconCls:'upload-icon',handler:function(){
		  mcFileManager.browse( {rootpath:'".USERSPOOL_ATTACHMENTS."', onClose: function(u,d){ console.log(u,d);  }   });
	}  }, {iconCls:' x-btn-text x-tbar-loading',handler:function(){ $fileTName.getRootNode().reload();  }  }]
	});
	$fileTName.getLoader().on('beforeload',function(tl,n){ 
	tl.baseParams.fileType = n.attributes.fileType;
	tl.baseParams.RMpath = n.attributes.filePath;
	   } );";

echo $grid->createGrid();
	
echo "$gridName.getStore().on('load',function(st,recs){
	var rNames = new Array();
	Ext.each(recs,function(r){
		rNames.push(r.data.fileName);
	});
	Ext.getCmp('$attachName').setTitle('Attachments: '+rNames.join()  );
});";
	
$form->addField('test2','','fieldset')
	->anchor($acnhor)
	->setProperty('id',"'$attachName'")
	->setProperty('collapsible',"true")
	->setProperty('collapsed','true')
	->setProperty('title',"'Attachments'")
	->setProperty('items',"
	{xtype:'panel',defaults:{flex:1},border:false, layout:{type:'hbox',align:'stretch'},height:250,buttonAlign:'left',
	items:[$gridName,$fileTName] }
	")
	;
if($_SESSION['UserInfo']['mc_rootpath'] == 'tinymce')
	$form->addField('content','lalala','tinymce')->anchor($acnhor.' 90%')
			->hideLabel(true)
			//->width(800)->height(400)
			//properties for tincMCE editor...since there is a bug in IE html editor is used for now!
			//back to tinyMCE since htmleditor is kinda crappy!
				->setProperty('tinymceSettings','{
						theme : "advanced", 
						plugins: "pagebreak,style,layer,table,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
						theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
						theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code,forecolor,backcolor",
						
						//theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
						theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,media,advhr,|,linkProject",
						//theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
						theme_advanced_toolbar_location : "top",
						theme_advanced_toolbar_align : "left",
						theme_advanced_statusbar_location : "bottom",
						setup: function(ed){
							ed.addButton("linkProject",{
								title:"Project link",
								image: "_img/WebLink16.gif",
								onclick : function(){
									ed.focus();
									console.log(ed);
									ed.selection.setContent("[!catiLink]Link[/catiLink]");
								}
								
							});
						},
					//	theme_advanced_resizing : false,
						extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]",
						template_external_list_url : "example_template_list.js",
						autoresize_min_height:"600px"
					}')
;
else
	$form->addField('content','test','htmleditor')->hideLabel(true)->anchor($acnhor.' 90%');

//$form->addConfig('frame:true');
$form
	->addtBarItem("{text:'Save as',iconCls:'RMicon_save_as',handler: function(){
		var wup2 = Ext.getCmp('PoolMenu_2');
		if(!wup2)
		{
			Ext.Msg.alert('Warning!','Please select a template in the tree');
			addTabAuto('webUserspoolUniqePanel','webuserspool/_forms/tree.groups.php',{treeName : 'PoolMenu', tree:'_ProgramMenu'},
			function(){ Ext.getCmp('PoolMenu_2').show(); });
		    return;        	
		}
	
		var n = wup2.getSelectionModel().getSelectedNode();
		if(!n || !n.isLeaf() || n.id == $templateId ) {
			Ext.Msg.alert('Warning!','Please select a template in the tree');
			Ext.getCmp('webUserspoolUniqePanel').show();
			wup2.show();
			return;			
		}
		Ext.Msg.confirm('Save to '+n.text,'Are you sure?',function(btn){
			if(btn == 'yes')
			{
				$formName.getForm().doAction('oosubmit',{params:{ id:n.id }, success : function(f,a)
				{ 
				addTabAuto('wupMailTemplate_'+n.id,'webuserspool/_forms/mails/forms.mailTemplate.php',{node_id: n.id,name:n.text});
				},failure : function(f,a){ alert( Ext.decode(a.response.responseText).error ); }   });
			} 
		});
		
		
		
	}}")
	->addSaveCancel('Save','Cancel',$tabId,false)
	/*removed, becouse a option form was added under the mails in the right tab panel
	 * ->addtBarItem("{text:'Options',iconCls:'icon-options-3',handler:function(){
		addTabAuto('wupMailTemplateOptions_$templateId' ,'webuserspool/_forms/mails/forms.mailOptions.php',{node_id: $templateId,parId:{$_POST['parId']},tree:'{$_POST['tree']}' });
	}}")*/
	->region('center')
	//->labelAlign('top')
;


	
echo $form->createForm();

echo $form->getName().".getForm().load({params:{action:'load'}});
	
";

echo "
	var $tabId = new Ext.Panel({
		id:'$tabId',
		autoSroll:true,
		iconCls : 'RMicon_emails',
		//so we can get name when we set options in tree menu!
		tmpName: '$name',
		title:'Mail Temp: $name',
		listeners:{
			show:function(){
				//we add the tree to the west-panel, and set it to use this field for adding
				/*addTabAuto('webUserspoolUniqePanel','webuserspool/_forms/tree.groups.php',{treeName : 'PoolMenu', tree:'_ProgramMenu'},
				function(){ 
					*/
					Ext.getCmp('PoolMenu').templateComp = $formName;
					//console.log(Ext.getCmp('PoolMenu').getNodeById(4));
					var n = Ext.getCmp('PoolMenu').getNodeById(4);
					//console.log(n);
					if(n && n.childNodes.length == 0) n.expand();
					
					 var mOp = Ext.getCmp('wupMailOptionsPanel');
					// console.log(Ext.getCmp('wupMailOptionsPanel'));
					//console.log(mOp.ownerCt);
					  if( mOp.ownerCt)
					 		{
							 //console.log('noter sem');
							 mOp.getForm().reset();
							 mOp.selectedId = $templateId;
							 mOp.getForm().baseParams.id = $templateId;
							 mOp.setTitle('Options: $name');
							 mOp.getForm().load({ params:{action:'load' },success:function(){ }  });
							  mOp.show();
							 mOp.ownerCt.getLayout().layout();
							}
							
					// }   );
					 
					
			 },
			hide:function(){var tmpTree = Ext.getCmp('$treeName');if(tmpTree)delete tmpTree.templateComp;
						 var mOp = Ext.getCmp('wupMailOptionsPanel');
						 if(mOp && mOp.rendered)
						 {
							 mOp.hide();
							 mOp.ownerCt.getLayout().layout();
						 }
			},
			removed:function(){	var tmpTree = Ext.getCmp('$treeName');if(tmpTree)delete tmpTree.templateComp;
			var mOp = Ext.getCmp('wupMailOptionsPanel');
						 if(mOp && mOp.rendered)
						 {
							 mOp.hide();
							 mOp.ownerCt.getLayout().layout();
						 }}
		},
		layout:'fit',
		closable:true,
		items:[$formName ]
	});
mainTabPanel.add($tabId).show();";
?>

   

