<?php

include("_dirinfo.php");
include (PATH_TO_ROOT."init.php");


$db->ChangeDatabase(DB_WARPIT_USERSPOOL);
if($_POST['groupId'])
{
		$sql = "SELECT DISTINCT id_project FROM _SendMailSet WHERE id_project > 0 AND id_group = ".$_POST['groupId'];
		$res = $db->SQLexecute($sql);
		$hasProj = $db->NumRows($res) > 0;
}		

?>

//the tree for groups
var sendMailTemplateCombo = new Ext.ux.TreeCombo({
		autoHeight:true,
		loader : new Ext.tree.TreeLoader({
		 	dataUrl   	:'_ajaxManipulators/treeDataManipulator.php', 
		 	baseParams	: {
		 		RMtable:'_Emails',
		 		database:'<?php echo DB_WARPIT_USERSPOOL; ?>',
		 		action:'select',
		 		RMcomp:'tree',
		 			//custom SQL to get info if template contains catiLink
		 		SQL:"SELECT *,(content LIKE '%[!catiLink]%[/catiLink]%') as hasCatiLink,(content LIKE '%[!redirection]%[/redirection]%') as hasRedirectLink FROM `_Emails`",
		 		attr:'hasCatiLink,hasRedirectLink'
		 	},
		 
			listeners: { 
				load : function(a,b,resp){ 
					var r = Ext.decode(resp.responseText); 
					if(r!= null && r.success === false)	{ 
						alert('Tree load error: '+r.error,'Error'); 
					}  
				}
		 	} 
		}) //end of treeLoader
		
		,fieldLabel:'Mail Template'
		,onTreeNodeClick: function(node, e) {
						if(!node.attributes.leaf) return;
				        this.setRawValue(node.text);
				        this.value = node.id;
				        this.fireEvent('select', this, node);
				        this.collapse();
			},
			listeners:{
				select:function(ct,node)
				{  //if template has catiLink we show the project combo!
					if(node.attributes.hasCatiLink == 1)
					{
						sendMailProjectsCombo.setVisible(true);
						sendMailProjectsCombo.treePanel.getLoader().baseParams.showAll = true;
						sendMailProjectsCombo.treePanel.getLoader().baseParams.showRedirect = false;
						sendMailProjectsCombo.treePanel.getRootNode().reload();
						sendMailTemplateCombo.hasLink = 1;
					}
					else if(node.attributes.hasRedirectLink == 1)
					{
						sendMailProjectsCombo.setVisible(true);
						sendMailProjectsCombo.treePanel.getLoader().baseParams.showRedirect = true;
						sendMailProjectsCombo.treePanel.getLoader().baseParams.showAll = false;
						sendMailProjectsCombo.treePanel.getRootNode().reload();
						sendMailTemplateCombo.hasLink = 2;
					}
					else
					{
						//if some mails have already be send to a project...
						//we must leave the option to select a project and select a status!
						if(sendMailProjectsCombo.hasProject)
						{
							sendMailProjectsCombo.treePanel.getLoader().baseParams.showAll = false;
							sendMailProjectsCombo.treePanel.getLoader().baseParams.showRedirect = false;
							sendMailProjectsCombo.treePanel.getRootNode().reload();
						}
						else
						{
							sendMailProjectsCombo.setVisible(false);
							
						}
						sendMailTemplateCombo.hasLink = 0;
					}
				}
			}
	});	

var sendMailProjectsCombo = new Ext.ux.TreeCombo({autoHeight:true,loader : new Ext.tree.TreeLoader({
 dataUrl   	:'webuserspool/_ajax/ajax.sendMailWizard.php', 
 baseParams	: {RMtable:'_ProjectsTree',database:'<?php echo DB_WARPIT_WEBCATI_BASE; ?>',action:'select',RMcomp:'tree',id_group: <?php echo $_POST['groupId'] ?>,attr:'id_project'} 
,listeners: { load : function(a,b,resp){ var r = Ext.decode(resp.responseText); if(r!= null && r.success === false){ alert('Tree load error: '+r.error,'Error'); }  }
				 } 
				}) //eo treeLoader
			,fieldLabel:'Project'
			,hidden:<?php echo $hasProj ? 'false':'true' ?>
			,hasProject : <?php echo $hasProj ? 'true':'false' ?>
			,onTreeNodeClick: function(node, e) {
						if(!node.attributes.leaf) return;
				        this.setRawValue(node.text);
				        this.value = node.attributes.id_project;
				        this.fireEvent('select', this, node);
				        this.collapse();
				    },
			listeners:{
				select:function(ct,node)
				{
					if(node.attributes.sendAlready)
					{
						
						sendMailReceiverCombo.setVisible(true);
						sendMailReceiverCombo.sendAlready = true;
						
						//we need to load reciever options and info
						new RMajax().request(
						{
							url:'webuserspool/_ajax/ajax.sendMailWizard.php',
							params: {
								action: 'getStatus',
								id_project: node.attributes.id_project,
								id_group: <?php echo $_POST['groupId'] ?>
							},
							success: function(resp)
							{
								var data =  Ext.decode(resp.responseText);
								sendMailReceiverCombo.bindStore(data);
								sendMailReceiverCombo.setValue(1);
							}
						})
					}
					else
					{
						sendMailReceiverCombo.setVisible(false);
						sendMailReceiverCombo.sendAlready = false;
					}
				}
			}
				});

var sendMailReceiverCombo = new Ext.form.ComboBox({
	store:[[1,'All']],
	editable:false,
	triggerAction:'all',
	value:1,
	hidden: true,
	fieldLabel: 'Send to'
});

var sendMailTemplateForm = new Ext.FormPanel({
      
        width: 350,
        frame: false,
        autoHeight: true,
        padding: '10',
        labelWidth: 100,
        defaults: {
            anchor: '95%',
            allowBlank: false
        },
        items: [
        	sendMailTemplateCombo,
        	sendMailProjectsCombo,
        	sendMailReceiverCombo,
        	new Ext.form.TextField({
        	 	fieldLabel:'# of mails',
        	 	id: 'NumberOfmails'
        	
        	})
        	,
        	{xtype:'checkbox',name:'cbField',
        	 fieldLabel:'Send immediately',checked:true,
        	  listeners:{check:function(cb,val){
        	  	sendMailTemplateForm.getForm().findField('dtfield').setDisabled(val);
        	  } }
        	  }
        	,{xtype:'datetimefield',
        	fieldLabel: 'Send time'
        	,name:'dtfield'
        	,value : new Date(),disabled:true
        	}
        	
        ],
        buttons: [{
            text: 'Send',
            handler: function(){
            	var templateId = sendMailTemplateCombo.getValue();
            	if(!templateId) return false;
            	var id_project = 0;
            	var id_status = 1;
            	if(sendMailTemplateCombo.hasLink )
            	{//if template has link a project MUST be selected
            		id_project = sendMailProjectsCombo.getValue();
            		if(	!id_project)
            			return false;
            		
            		if(sendMailReceiverCombo.sendAlready)
            		{
            			id_status = sendMailReceiverCombo.getValue();
            			
            		}
            	}
            	
            	var gridTmp = Ext.getCmp('<?php echo $_POST['groupGridName']?>');
            	var sm = gridTmp.getSelectionModel();
            	//let's set the params
            	var p = {templateId:templateId,id_group: <?php echo $_POST['groupId'] ?> };
            	p.id_project = id_project;
            	p.project_type = sendMailTemplateCombo.hasLink;
            	p.id_status = id_status;
            	
            	p.numberOfMails =  Ext.getCmp('NumberOfmails').getValue();
            	
            	if( sendMailTemplateForm.getForm().findField('cbField').getValue() )
            	{//if immediately is checked
            		
            		p.immideately = true;
            		p.schTime = '0000-00-00 00:00:00';
            	}
            	else
            	{
            		p.schTime = sendMailTemplateForm.getForm().findField('dtfield').getValue();
            	}
            	var numSendTo=0;
            	
            	if(sm.hasSelection())
            	{//if some rows were checked on the group grid, we send only those! other wise the whole store
	            	var selId = [];
	            		var selMails = [];
	            		Ext.each( sm.getSelections() , function(rec){
	            			if(rec.data.email && rec.data.email != '')
	            			{
	            			numSendTo++;
	            			selId.push(rec.data.<?php echo $_POST['sendProjUsers'] ? 'id_user' : 'id' ?>);
	            			selMails.push(rec.data.email); } 
	            		} );
	            		
            		
            		p.ids = Ext.encode(selId);
            		p.emails = Ext.encode(selMails);
            	}
            	else
            	{
            		Ext.apply(p,gridTmp.getStore().lastOptions.params);
            		numSendTo = <?php echo $_POST['numSendTo'] ? $_POST['numSendTo'] : "gridTmp.getStore().totalLength" ?>;
            	}
            	
            	// show correct number of sending emails for send
            	if ( id_status > 1 && sendMailReceiverCombo ) numSendTo = sendMailReceiverCombo.getRawValue(); 
            	
            	Ext.Msg.confirm('Warning','Send '+numSendTo+' mails<br>Are you sure?',function(btn){
            		if(btn == 'yes')
            		{
            		p.action = 'sendMail';
            		new RMajax().request({url:'webuserspool/_ajax/ajax.showgroup.php',
            		params:p
					,success:function(resp){
					  var rsp = Ext.decode(resp.responseText)
					 if( !rsp.success)	
					 	Ext.Msg.alert('Warning','Error: '+rsp.error );
					 else
					 	{
					 		var statGrid = Ext.getCmp('WUPMailStatisticsGrid');
					 		if(  statGrid )
					 			statGrid.getStore().reload();
					 		if(	p.immideately == true)
					 		{
						 		new RMajax().request({url:'webuserspool/_ajax/ajax.sendMail.php',
						 		params:{mailStatus:1, mailSet:rsp.set },
								success:function(r,opt){},
								failure:function(r,opt){},
								timeout : 100000
								});
							}	
					 	}
					  }
					});
            		
            	}} );
            	
	            win1.close();
	                  
              
            }
        },{
            text: 'Cancel',
            handler: function(){
                 win1.close();
            }
        }]
    });


	var win1 = new Ext.Window({
		width:365,
       modal:true,
 		title: 'Send mail (to '+ ( Ext.getCmp('<?php echo $_POST['groupGridName']?>').getSelectionModel().hasSelection() ? Ext.getCmp('<?php echo $_POST['groupGridName']?>').getSelectionModel().getCount() : <?php echo $_POST['numSendTo'] ? $_POST['numSendTo'] : "Ext.getCmp('".$_POST['groupGridName']."').getStore().totalLength" ?> )+' users)' ,
        closeAction:'close',
        plain: true,
		items: sendMailTemplateForm

    }).show();

    

