/*
$Id: mail.js 566 2008-07-22 04:25:20Z lukejee $
*/
Ext.namespace('NGMP.mail');

NGMP.mail.NewMessageWindow=function(B){
    this.config=B||{
        
    };
    this.guid=new NGMP.utils.GUID();
    this.addEvents({
        saved:true,
	sent:true
    });
    this.attaches=Array();
    if(this.config.messageInfo){

        if(this.config.type=="draft"){
            for(i=0;i<this.config.messageInfo.to.length;i++){
                this.to=this.config.messageInfo.to[i].mail+";";
		}
            
        }else{
            for(i=0;i<this.config.messageInfo.from.length;i++){
                this.to=this.config.messageInfo.from[i].mail+";";
            }
            
        }
        for(i=0;i<this.config.messageInfo.to.length;i++){
            this.from=this.config.messageInfo.to[i].title+";";
        }
        if(this.config.messageInfo.cc){
            for(i=0;i<this.config.messageInfo.cc.length;i++){
                this.cc=this.config.messageInfo.cc[i].mail+";";
            }
            
        }
        if(this.config.messageInfo.hasAttach&&this.config.type=="forward"){
            for(i=0;i<this.config.messageInfo.attaches.length;i++){
                var A=Array();
                A[0]=this.config.messageInfo.attaches[i].name;
                A[1]=this.config.messageInfo.attaches[i].normlink;
                A[2]=this.config.messageInfo.attaches[i].size;
                A[3]=this.config.messageInfo.attaches[i].type;
                this.attaches[i]=A;
            }
            Ext.Ajax.request({
                url:"ngmp.php",params:{
				func:'forward',
                    ix:this.config.ix,
				folder:this.config.folder,
				uid:this.guid.id
                }
                ,scope:this,
			timeout:60000
            });
        }
        
    }else{
        this.config.messageInfo={
            
        };
        
    }
	    this.tpl=new Ext.XTemplate(
	'<tpl for=".">',
	'<div class="attach-wrap" id="{name}">',
	'<table><tr><td width="32px" align="center"><img src="themes/ngmp/images/Download16.png" align="middle"/><td width="300px" align="left">',
	'{name}</td><td width="50px" align="center">{size}</td><td width="100px" align="left">{type}</td></tr></table>',
	"</tpl>",'<div class="x-clear"></div>');
	    this.messageHeaderTemplate=new Ext.XTemplate(
		'<div style="font:normal 10px tahoma, arial, helvetica, sans-serif;">',
		"<hr><table><tr>",'<td width="75px">'+LANG_from+':</td>',
		"<td>{from}</td>","</tr>","<tr>",'<td width="75px">'+LANG_sent+':</td>',
		"<td>{sent}</td>","</tr>","<tr>",'<td width="75px">'+LANG_to+':</td>',
		"<td>{to}</td>","</tr>",'<tpl if="this.isCc(cc)">',"<tr>",
		'<td width="75px">'+LANG_cc+':</td>',"<td>{cc}</td>","</tr>","</tpl>",
		"<tr>",'<td width="75px">'+LANG_subject+':</td>',"<td>{subject}</td>",
		"</tr>","</table>","</div>",
		{
	        isCc:function(C){
	            return C;
	        }
	        
	    });
	    this.messageHeaderTemplate.compile();
	    this.tpl.compile();
	    this.attachRecord=new Ext.data.Record([
		{name:"name"},
		{name:"normlink"},
		{name:"size"},
		{name:"type"}
	    ]);
	    this.attachReader=new Ext.data.ArrayReader({
	        
	    },this.attachRecord);
	    this.attachData=new Ext.data.SimpleStore({
	        fields:["name","normlink","size","type"],
		reader:this.attachReader,
		data:this.attaches
	    });
	    this.dataView=new Ext.DataView({
	        id:"dataviewAttachments_"+this.config.id,
		store:this.attachData,
		tpl:this.tpl,
		autoHeight:true,
		multiSelect:false,
		itemSelector:"div.attach-wrap",
		emptyText: LANG_no_attachments_to_display
	    });
	    if(this.config.preferences.editorMode=="html"){
		if (this.config.type == 'draft')
			this.bodyValue = this.config.messageBody;
		else
	        this.bodyValue=this.config.messageBody?"<br><br><br>"+(this.config.id?"":(this.config.preferences.addSig?"<p>"+this.config.preferences.signature+"</p><br><br>":""))+this.messageHeaderTemplate.apply({
	   	         from:Ext.util.Format.htmlEncode(this.config.messageInfo.from[0].title),
				to:Ext.util.Format.htmlEncode(this.from),
				cc:Ext.util.Format.htmlEncode(this.cc),
				subject:this.config.messageInfo.subject,
				sent:this.config.messageInfo.sent
	   	     }
	        )+"<br>"+this.config.messageBody:"<br><br><br>"+(this.config.preferences.addSig?"<p>"+this.config.preferences.signature+"</p><br><br>":"");
	    }
	    else{
	        this.bodyValue=this.config.messageBody?"\n\n\n"+(this.config.id?"":(this.config.preferences.addSig?Ext.util.Format.stripTags(this.config.preferences.signature)+"\n\n":""))+this.config.messageBody:"";
	    }
	    switch(this.config.type){
	        case"reply":
			this.cc="";
	        	break;
	        case"forward":
			this.to="";
	        	this.cc="";
	        	break;
			default:
				break;
	    } 
	   this.form=new Ext.form.FormPanel({
	        id:"formNewMessage_"+this.config.id,
		url:"ngmp.php",
		baseParams:{
	            is_html:this.config.preferences.editorMode=="html"?true:false,
			func: 'sendmail'
	        },
	        baseCls:"x-plain",
		border:false,
		items:[{
	            id:"panelFormBorderPanel_"+this.config.id,
			layout:"border",
			border:false,
			anchor:"100% 100%",
			items:[{
				id:'panelFormBorderPanelNorth_' + this.config.id,
				region: 'north',
				height: 150,
				layout: 'form',
				labelWidth: 55,
				bodyStyle:'padding:5px;',
				baseCls:'x-plain',
				border: false,
				items:[{
					id:'addressfieldTo_'+this.config.id,
					xtype:'addressfield',
					type:'To',
					fieldLabel:LANG_to,
					name: 'to',
					value: this.to?this.to:'',
					contactsStore: this.config.contactsStore,
					anchor: '100%'
				}, {
					id:'addressfieldCc_'+this.config.id,
					xtype:'addressfield',
					type:'Cc',
					fieldLabel:LANG_cc,
					name: 'cc',
					value: this.cc?this.cc:'',
					contactsStore: this.config.contactsStore,
					anchor: '100%'				
				}, {
					id:'addressfieldSubject_'+this.config.id,
					xtype:'textfield',
					fieldLabel:LANG_subject,
					name: 'subject',
					value: this.config.messageInfo.subject?this.config.messagePrefix+this.config.messageInfo.subject:'',
					anchor: '100%'
				}, {
					id: 'panelAttachmentsTitle_' + this.config.id,
					html: '<a style="font-size:10pt">'+LANG_attachment+':</a>',
					baseCls:'x-plain',
					border:false
				}, this.dataView]
			}, {
				id:'panelFormBorderCenter_' + this.config.id,
				region:'center',
				layout:'anchor',
				border: false,
				items:[{
					id:(this.config.preferences.editorMode=='html'?'htmleditor':'textarea')+'Body_'+this.config.id,
					xtype:this.config.preferences.editorMode=='html'?'htmleditor':'textarea',
					hideLabel: true,
					name: 'body',
					value: this.bodyValue,
					anchor:'100% 100%'
				}]
			}]
	        }
	        ]
	    });
	
	    this.priorityData=new Ext.data.SimpleStore({
	        fields:["display","value"],
		data:[[LANG_priority_low,5],
		[LANG_priority_normal,3],
		[LANG_priority_high,1]]
	    }
	    );
	    this.comboPriority=new Ext.form.ComboBox({
	        id:"comboPriority_"+this.config.id,
		store:this.priorityData,
		displayField:"display",
		typeAhead:true,mode:"local",
		triggerAction:"all",
		selectOnFocus:true,
		resizable:false,
		listWidth:100,
		width:100,
		valueField:"value",
		value:3
	    });
	    this.tb=new Ext.Toolbar({
	        id:"toolbarNewMessage_"+this.config.id,items:[{
	            id:"tbbuttonAttach_"+this.config.id,
			iconCls:"icon-attachment",
			cls:"x-btn-text-icon",
			text:LANG_attach,
			tooltip:LANG_attach_tooltip,
			enableToggle:false,
			pressed:false,
			handler:function(){
	                var C=new NGMP.dialog.UploadDialog.Dialog({
	                    url:"ngmp.php",
					iconCls:"icon-upload",base_params:{
						func:'upload',
	                        uid:this.guid.id
	                    },
	                    reset_on_hide:false,
					allow_close_on_upload:false,
					modal:true
	                });
	                C.on("uploadsuccess",function(H,G,F){
	                    var I=G.split(/\/|\\/);
	                    if(I.length==1){
	                        G=I[0];
	                    }
	                    else{
	                        G=I.pop();
	                    }
	                    var E=Array();
	                    E[0]=G;
	                    E[1]="";
	                    E[2]="";
	                    E[3]=F.size;
	                    E[4]=F.type;
	                    var D=Array();
	                    D[0]=E;
	                    this.attachData.loadData(D,true);
	                },this);
	                C.show(this.getEl());
	            },
	            scope:this
	        },
	        {
	            id:"tbbuttonSaveDraft_"+this.config.id,
			iconCls:"icon-draft",
			cls:"x-btn-text-icon",
			text:LANG_save_draft,
			tooltip:LANG_save_draft_tooltip,
			enableToggle:false,
			pressed:false,
			handler:function(){
	                this.form.getForm().submit({
	                    url:"ngmp.php",params:{
						func:'savemsg',
						uid: this.guid.id,
	                        priority:this.comboPriority.getValue()
	                    },
	                    waitMsg:LANG_saving_message+"...",
					success:function(C,D){
	                        Ext.Msg.alert(LANG_save_message,LANG_message_saved_to_drafts_folder,function(){
	                            this.fireEvent("saved",this);
	                            this.close();
	                        }
	                        ,this);
	                    }
	                    ,failure:function(C,D){
	                        Ext.Msg.alert(LANG_error_saving_message,D.result.errormessage);
	                    },
					scope:this
	                });
	            },
	            scope:this
	        }
	        ,"-",LANG_priority+':',{
	            id:"tbspacerPriority_"+this.config.id,
			xtype:"tbspacer"
	        }
	        ,this.comboPriority]
	    });
	    this.cascadeOnFirstShow=20;    
    NGMP.mail.NewMessageWindow.superclass.constructor.call(this,{
        id:this.config.id?this.config.id:"NewMessage",
		title:Ext.util.Format.ellipsis(this.config.messageInfo.subject?this.config.messagePrefix+this.config.messageInfo.subject:LANG_new_message,30),
		width:500,
		height:400,
		minWidth:300,
		minHeight:200,
		bodyBorder:false,
		layout:"fit",
		plain:true,
		constrain:true,
		iconCls:"newmessage-icon-cls",
		stateful:false,
		buttonAlign:"right",
		maximizable:true,
		minimizable:true,
		manager:this.config.windowGroup,
		plugins:[new NGMP.plugins.IconMenu({
            
        }
        )],
		items:[this.form],
		buttons:[{
		            id:"buttonSendNewMessage_"+this.config.id,
			text:LANG_send,
			handler:function(){
		                var C;
		                if(this.config.ix){
		                    C={
		                        priority:this.comboPriority.getValue(),
						ix:this.config.ix,folder:this.config.folder,
						uid:this.guid.id
		                    };
		                    
		                }
		                else{
		                    C={
		                        priority:this.comboPriority.getValue(),
						uid:this.guid.id
		                    };
		                    
		                }
		                this.form.getForm().submit({
		                    params:C,
					waitMsg:LANG_sending_message+"...",
					success:function(D,E){
		                    	this.fireEvent("sent",this);
								this.close();
		                    }
		                    ,failure:function(D,E){
		                        Ext.Msg.alert(LANG_error_sending_message,E.result.feedback);
		                    }
		                    ,scope:this
		                });
		            }
		            ,scope:this
		        }
		        ,{
		            id:"buttonCancelNewMessage_"+this.config.id,
			text:LANG_cancel,
			handler:function(){
		                this.close();
		            }
		            ,scope:this
		        }
		        ],tbar:this.tb 
    });
};
Ext.extend(NGMP.mail.NewMessageWindow,Ext.Window,{
    beforeShow:function(){
        delete this.el.lastXY;
        delete this.el.lastLT;
        if(this.x===undefined||this.y===undefined){
            var B=this.el.getAlignToXY(this.container,"tl-tl",[5,5]);
            var C=this.el.translatePoints(B[0],B[1]);
            this.x=this.x===undefined?C.left:this.x;
            this.y=this.y===undefined?C.top:this.y;
            if(this.cascadeOnFirstShow){
                var A;
                this.manager.each(function(D){
                    if(D==this){
                        if(A){
                            var F=(typeof this.cascadeOnFirstShow=="number")?this.cascadeOnFirstShow:20;
                            var E=this.el.translatePoints(A.getPosition()[0],A.getPosition()[1]);
                            this.x=E.left+F;
                            this.y=E.top+F;
                        }
                        return false;
                    }
                    if(D.isVisible()){
                        A=D;
                    }
                   	return true; 
                } ,this);
            }
            
        }
        this.el.setLeftTop(this.x,this.y);
        if(this.expandOnShow){
            this.expand(false);
        }
        if(this.modal){
            Ext.getBody().addClass("x-body-masked");
            this.mask.setSize(Ext.lib.Dom.getViewWidth(true),
			Ext.lib.Dom.getViewHeight(true));
            this.mask.show();
        }
        
    }
    ,afterShow:function(){
        NGMP.mail.NewMessageWindow.superclass.afterShow.call(this);
//        this.form.items.item(0).setWidth(this.form.ownerCt.getInnerWidth())
    }
    ,handleResize:function(A){
        NGMP.mail.NewMessageWindow.superclass.handleResize.call(this,A);
 //       this.form.items.item(0).setWidth(this.form.ownerCt.getInnerWidth())
    }
    ,maximize:function(){
        NGMP.mail.NewMessageWindow.superclass.maximize.call(this);
//        this.form.items.item(0).setWidth(this.form.ownerCt.getInnerWidth())
    }
    ,restore:function(){
        NGMP.mail.NewMessageWindow.superclass.restore.call(this);
//        this.form.items.item(0).setWidth(this.form.ownerCt.getInnerWidth())
    }
    
});
NGMP.mail.MessageWindow=function(B){
    this.config=B||{
        
    };
    this.addEvents({
        refresh:true
    });
    for(i=0;i<this.config.messageInfo.to.length;i++){
        this.to=this.config.messageInfo.to[i].title+";";}
    for(i=0;i<this.config.messageInfo.cc.length;i++){
        this.cc=this.config.messageInfo.cc[i].title+";";}
    this.attaches=Array();
    if(this.config.messageInfo.hasAttach){
        for(i=0;i<this.config.messageInfo.attaches.length;i++){
            var A=Array();
            A[0]=this.config.messageInfo.attaches[i].name;
            A[1]=this.config.messageInfo.attaches[i].normlink;
            A[2]=this.config.messageInfo.attaches[i].size;
            A[3]=this.config.messageInfo.attaches[i].type;
            this.attaches[i]=A;
        }
        
    }
    this.containsImages=this.config.messageInfo.containsImages;
    this.showImages=this.config.messageInfo.showImages;
    this.tpl=new Ext.XTemplate(
	'<tpl for="."><div class="attach-wrap" id="{name}"><table><tr><td width="32px" align="center"><a href="{normlink}" target="_blank">',
	'<img src="themes/ngmp/images/Download16.png" align="middle"/></a><td width="150px" align="left"><a href="{normlink}" target="_blank">',
	'{name}</a></td><td width="50px" align="center">{size}</td><td width="100px" align="left">{type}</td></tr></table>',
	'</tpl><div class="x-clear"></div>');
    this.tpl.compile();
    this.attachData=new Ext.data.SimpleStore({
        fields:["name","normlink","size","type"],
		data:this.attaches
    });
    this.dataView=new Ext.DataView({
        id:"dataviewAttachments_"+this.config.id,
		store:this.attachData,
		tpl:this.tpl,
		autoHeight:true,
		multiSelect:false,
		itemSelector:"div.attach-wrap",
		emptyText:LANG_no_attachments_to_display
    });
    this.form=new Ext.form.FormPanel({
        id:"formMessage_"+this.config.id,
		autoHeight:true,
		region:"north",
		baseCls:"x-plain",
		bodyStyle:"padding:10px;",
		labelWidth:55,items:[{
            id:"textfieldFrom_"+this.config.id,
			xtype:"textfield",
			readOnly:true,
			fieldLabel:LANG_from,
			name:"from",
			value:this.config.messageInfo.from[0].title,
			anchor:"100%"
        },
        {
            id:"textfieldTo_"+this.config.id,
			xtype:"textfield",
			readOnly:true,
			fieldLabel:LANG_to,
			name:"to",
			value:this.to,
			anchor:"100%"
        },
        {
            id:"textfieldCc_"+this.config.id,
			xtype:"textfield",
			readOnly:true,
			fieldLabel:LANG_cc,
			name:"cc",
			value:this.cc,
			anchor:"100%"
        },
        {
            id:"textfieldSubject_"+this.config.id,
			xtype:"textfield",
			fieldLabel:LANG_subject,
			readOnly:true,
			name:"subject",
			value:this.config.messageInfo.subject,
			anchor:"100%"
        },
        {
            id:"panelAttachmentsTitle_"+this.config.id,
			html:'<a style="font-size:10pt">'+LANG_attachment+':</a>',
			baseCls:"x-plain",
			border:false
        }
        ,this.dataView]
    }
    );
    this.imagesShow=function(){
        this.showImages=true;
        this.imagesNorth.hide();
        this.bodyPanel.load({
            url:"ngmp.php",
			baseParams:{
				func:'mailGetBody',
                ix:this.config.ix,
				folder:this.config.folder,
				block_images:false,
				text:false
            },
           // ,method:"GET",
			nocache:false
        });
        this.doLayout();
    };
    this.imagesNorth=new Ext.FormPanel({
        id:"formImagesNorth_"+this.config.id,
		region:"north",
		autoShow:true,
		split:false,
		height:80,
		minSize:40,
		maxSize:40,
		border:false,
		collapsible:false,
		margins:"0 0 0 0",
		bodyStyle:"padding: 5px;background-color: #fff59f",
		items:[{
            id:"panelContainsImagesText_"+this.config.id,
			border:false,
			bodyStyle:"padding: 5px;background-color: #fff59f",
			html:'<a><img src="images/Images32.png" align="middle" />'+LANG_this_message_contains_blocked_images+' </a>'
        }
        ],buttons:[{
            id:"buttonShowImages_"+this.config.id,
			text:LANG_show_images,
			handler:this.imagesShow,
			scope:this
        }
        ]
    });
    this.bodyPanel=new NGMP.panel.ManagedIframePanel({
        id:"iframepanelBodyPanel_"+this.config.id,
		region:"center",
		autoShow:true,
		split:false,
		border:false,
		collapsible:false,
		margins:"0 0 0 0",
		autoLoad:{
            url:"ngmp.php",
			params:{
				func:'mailGetBody',
                ix:this.config.ix,
				folder:this.config.folder,
				block_images:!this.showImages,text:false
            }
            ,method:"GET",
			nocache:false
        }
        
    });
    this.tb=new Ext.Toolbar({
        id:"toolbarMessage_"+this.config.id,items:[{
            id:"tbbuttonReply_"+this.config.id,
			iconCls:"icon-reply",
			cls:"x-btn-text-icon",
			text:LANG_reply_to_message,
			tooltip:LANG_reply_to_message_tooltip,
			enableToggle:false,
			pressed:false,
			handler:function(){
                var D=this.config.messageInfo;
                var C=new NGMP.mail.NewMessageWindow({
                    type:"reply",
					messageInfo:D,
					messageBody:this.bodyPanel.body.dom.innerHTML,messagePrefix:LANG_re+': ',
					folder:this.config.folder,
					ix:this.config.ix,
					windowGroup:this.config.windowGroup,
					id:Ext.id(),
					preferences:this.config.preferences,
					contactsStore:this.config.contactsStore
                });
                C.on("sent",function(E){
                    this.fireEvent("refresh",this);
                },this);
                C.render(this.container);
                this.config.windowPanel.addWindow(C);
                C.show();
                C.on("close",function(E){
                    this.config.windowPanel.removeWindow(C);
                },this);
                C.show();
            },scope:this
        }
        ,{
            id:"tbbuttonReplyAll_"+this.config.id,
			iconCls:"icon-reply-all",
			cls:"x-btn-text-icon",
			text:LANG_reply_to_all_message,
			tooltip:LANG_reply_to_all_message_tooltip,
			enableToggle:false,
			pressed:false,
			handler:function(){
                var D=this.config.messageInfo;
                var C=new NGMP.mail.NewMessageWindow({
                    type:"replyall",
					messageInfo:D,
					messageBody:this.bodyPanel.body.dom.innerHTML,
					messagePrefix:LANG_re+': ',
					folder:this.config.folder,
					ix:this.config.ix,
					windowGroup:this.config.windowGroup,
					id:Ext.id(),
					preferences:this.config.preferences,
					contactsStore:this.config.contactsStore
                });
                C.on("sent",function(E){
                    this.fireEvent("refresh",this);
                },this);
                C.render(this.container);
                this.config.windowPanel.addWindow(C);
                C.show();
                C.on("close",function(E){
                    this.config.windowPanel.removeWindow(C);
                },this);
                C.show();
            },scope:this
        }
        ,{
            id:"tbbuttonForward_"+this.config.id,
			iconCls:"icon-forward",
			cls:"x-btn-text-icon",
			text:LANG_forward_message,
			tooltip:LANG_forward_message_tooltip,
			enableToggle:false,
			pressed:false,
			handler:function(){
                var D=this.config.messageInfo;
                var C=new NGMP.mail.NewMessageWindow({
                    type:"forward",
					messageInfo:D,
					messageBody:this.bodyPanel.body.dom.innerHTML,
					messagePrefix:LANG_re+': ',
					folder:this.config.folder,
					ix:this.config.ix,
					windowGroup:this.config.windowGroup,
					id:Ext.id(),
					preferences:this.config.preferences,
					contactsStore:this.config.contactsStore
                });
                C.on("sent",function(E){
                    this.fireEvent("refresh",this);
                },this);
                C.render(this.container);
                this.config.windowPanel.addWindow(C);
                C.show();
                C.on("close",function(E){
                    this.config.windowPanel.removeWindow(C);
                },this);
                C.show();
            },scope:this
        }
        ,{
            id:"tbbuttonPrint_"+this.config.id,
			iconCls:"icon-print",
			cls:"x-btn-text-icon",
			text:LANG_print_message,
			tooltip:LANG_print_message_tooltip,
			enableToggle:false,
			pressed:false,
			handler:function(){
                var C=window.open();
                self.focus();
                C.document.open();
                C.document.write(this.config.printTemplate.apply({
                    from:Ext.util.Format.htmlEncode(this.config.messageInfo.from[0].title),
					to:Ext.util.Format.htmlEncode(this.to),
					cc:Ext.util.Format.htmlEncode(this.cc),
					subject:this.config.messageInfo.subject,
					body:this.bodyPanel.getFrameDocument().body.innerHTML
                }
                ));
                C.document.close();
                C.print();
                C.close();
            },scope:this
        }
        ]
    });
    this.cascadeOnFirstShow=20;
    NGMP.mail.MessageWindow.superclass.constructor.call(this,{
        id:this.config.id,
		title:Ext.util.Format.ellipsis(this.config.messageInfo.subject,30),
		width:500,
		height:400,
		minWidth:300,
		minHeight:200,
		layout:"border",
		constrain:true,
		bodyBorder:false,
		plain:true,
		stateful:false,
		bodyStyle:"padding:5px;",
		buttonAlign:"center",
		maximizable:true,
		minimizable:true,
		iconCls:"message-icon-cls",
		manager:this.config.windowGroup,
		plugins:[new NGMP.plugins.IconMenu({})],
		items:[this.form,new Ext.Panel({
            id:"panelCenter_"+this.config.id,
			region:"center",
			layout:"border",
			items:[this.imagesNorth,this.bodyPanel]
        }
        )],tbar:this.tb
    });
};
Ext.extend(NGMP.mail.MessageWindow,Ext.Window,{
    beforeShow:function(){
        delete this.el.lastXY;
        delete this.el.lastLT;
        if(this.x===undefined||this.y===undefined){
            var B=this.el.getAlignToXY(this.container,"tl-tl",[5,5]);
            var C=this.el.translatePoints(B[0],B[1]);
            this.x=this.x===undefined?C.left:this.x;
            this.y=this.y===undefined?C.top:this.y;
            if(this.cascadeOnFirstShow){
                var A;
                this.manager.each(function(D){
                    if(D==this){
                        if(A){
                            var F=(typeof this.cascadeOnFirstShow=="number")?this.cascadeOnFirstShow:20;
                            var E=this.el.translatePoints(A.getPosition()[0],A.getPosition()[1]);
                            this.x=E.left+F;
                            this.y=E.top+F;
                        }
                        return false;
                    }
                    if(D.isVisible()){
                        A=D;
                    }
                  	return 0;  
                }
                ,this);
            }
            
        }
        this.el.setLeftTop(this.x,this.y);
        if(this.expandOnShow){
            this.expand(false);
        }
        if(this.modal){
            Ext.getBody().addClass("x-body-masked");
            this.mask.setSize(Ext.lib.Dom.getViewWidth(true),Ext.lib.Dom.getViewHeight(true));
            this.mask.show();
        }
        
    }
    ,afterShow:function(){
        NGMP.mail.MessageWindow.superclass.afterShow.call(this);
        if(!this.containsImages||this.showImages){
            this.imagesNorth.hide();
            this.doLayout();
        }
        
    }
    
});


mailPrintTemplate = new Ext.XTemplate(
	"<html><head><style>body, td {font-family: Verdana;font-size: 10pt;}</style></head>",
	'<body><div><table><tr><td width="75px">'+LANG_from+':</td><td>{from}</td></tr><tr><td width="75px">'+LANG_to+':</td><td>{to}</td></tr>',
	'<tr><td width="75px">'+LANG_cc+':</td><td>{cc}</td></tr><tr><td width="75px">'+LANG_subject+':</td><td>{subject}</td></tr></table><hr></div>',
	'<div>{body}</div></body></html>');
mailPrintTemplate.compile();

NGMP.mail.MailboxTreePanel=function(A){
    this.config=A||{
        };
    this.addEvents({
        refreshtree:true,
		refresh:true,
		reloadtree:true
    });
    this.tree=new Ext.tree.TreePanel({
        id:"treepanelMailboxTree",
		region:"center",
		autoShow:true,
		iconCls:"icon-mail",
		margins:"0 0 0 0",
		animate:true,
		useArrows: true,
		autoScroll:true,
		loader:new Ext.tree.TreeLoader({
            dataUrl:"ngmp.php?func=mailboxtree",
			preloadChildren:true
        }),
		enableDrag:false,
		hideMode:"visibility",
		enableDrop:false,
		containerScroll:true,
		border:false,
		bodyStyle:"background-color: white",
		pathSeparator:"|"
    });
    this.tree.getLoader().requestMethod="POST";
    this.tree.on("beforeexpandnode",function(B){
        if(B.id=="mailbox" || B.id=='tags'){
            return true;
        }
        else{
            return false;
        }
        
    },this);
    this.sroot=new Ext.tree.AsyncTreeNode({
        text:LANG_mailbox + " - "+this.config.username,
		draggable:false,
		id:"mailbox"
    });
    this.tree.setRootNode(this.sroot);
    this.quotaPanel=new Ext.Panel({
        id:"panelQuotaPanel",
		region:"south",
		height:185,
		minHeight:120,
		maxHeight:120,
		collapsible:true,
		bodyStyle:"background-color: transparent;",
		split:false,
		title:LANG_mailbox_quota,
		border:true,
		frame:true,
     	titleCollapse: true,
		autoLoad: {
			url:'ngmp.php?func=mailQuota',
			scripts:false,
			scope:this,
			nocache:true
		}
    });
    NGMP.mail.MailboxTreePanel.superclass.constructor.call(this,{
        id:"panelMailboxTreePanel",
		title: LANG_btn_mail,
		iconCls: 'icon-mail',
		layout:"border",
		bodyStyle:"background-color: transparent",
		items:[this.tree,this.quotaPanel]
    });
};
Ext.extend(NGMP.mail.MailboxTreePanel,Ext.Panel,{
    afterRender:function(){
        NGMP.mail.MailboxTreePanel.superclass.afterRender.call(this);
        this.sroot.expand(false,false);
    },
	refreshTree:function(){
//		console.log('mailboxtreepanel refreshTree');
   //     this.sroot.reload();
    },
    reloadTree:function(){
        this.tree.getLoader().on("beforeload",this.reloadParams,this);
        this.sroot.reload();
        if(this.tree.getLoader().baseParams.refresh){
            delete this.tree.getLoader().baseParams.refresh;
        }
        this.tree.getLoader().un("beforeload",this.reloadParams,this);
    },
    refreshQuota:function(A){
        this.quotaPanel.getUpdater().refresh();
    },
    reloadParams:function(A,B){
        this.getLoader().baseParams.refresh=true;
    },
    selectNode:function(A){
        if (this.tree.rendered) {
			this.tree.getNodeById(A).select();
		}
    }
    
});

NGMP.mail.MailBoxPanel = function(A) {
	this.config = A || {};

	switch (this.config.groupField) {
		case 'from':
			this.config.groupFieldHeader = LANG_from;
			break;
		case 'to':
			this.config.groupFieldHeader = LANG_to;
			break;
		case 'subject':
			this.config.groupFieldHeader = LANG_subject;
			break;
		default:
			this.config.groupFieldHeader = this.config.groupField;
			break;
	}

	
	function D(G,F,E) {
		if (!E.get('read')) {
			F.css='x-grid3-cell-read';
		}
	    return G?G.dateFormat(NGMP.preferences.settings.datetime_format):"";
       
	}
    function B(G,F,E){
        if(!E.get("read")){
            F.css="x-grid3-cell-read";
        }
        return G?G+"KB":"";
    }
    function C(G,F,E){
        if(!E.get("read")){
            F.css="x-grid3-cell-read";
        }
        return G?G:"";
    }

	this.addEvents({
		refreshtree: true,
		refresh: true,
		selectnode: true
	});
	
	this.previewInfo = new Ext.Panel({
		id:'panelPreviewInfo_'+this.config.folder,
		region:'north',
		split: false,
		autoHeight: true,
		minHeight: 85,
		maxHeight:85,
		bodyStyle:'padding: 5px; background-color:#FFFFFF;',
		border:false,
		frame:false,
		hideMode:'offsets',
		autoScroll:true
	});
	
	this.previewBody = new NGMP.panel.ManagedIframePanel({
		id:'iframepanelPreviewBody_' + this.config.folder,
		region:'center',
		split: false,
		bodyStyle:'padding:5px;background-color:#FFFFFF',
		border:false,
		frame: false,
		hideMode: 'offsets',
		autoScroll: true
	});
	
	

	this.tbar = new Ext.Toolbar({
		id: 'toolbarMailTopMailboxPanel_' + this.config.folder,
		items:[
			{
				id: 'tbbuttonNewMessage_'+this.config.folder,
				iconCls:'icon-new-message',
				cls:'x-btn-text-icon',
				text: LANG_new_message,
				disabled: false,
				tooltip: LANG_new_message_tooltip,
				enableToggle: false,
				pressed: false,
				handler: function() {
    				var E = new NGMP.mail.NewMessageWindow({
						type: 'new',
						folder: this.config.folder,
						windowGroup: this.windowGroup,
						id: Ext.id(),
						preferences: NGMP.preferences.settings,
						contactsStore: this.config.contactsStore
					});
    				E.on('sent', function(F) {
						this.fireEvent('refresh', this);
						this.fireEvent('refreshtree', this);
					}, this);
					E.render(this.mailboxPane.body);
					this.windowPanel.addWindow(E);
					E.show();
					E.on('close', function(F) {
						this.windowPanel.removeWindow(E);
					},this);
				},
				scope: this
			}, '-', {
				id: 'tbbuttonDeleteMessage_' + this.config.folder,
				iconCls: 'icon-trash',
				cls: 'x-btn-text-icon',
				text: LANG_delete_message,
				disabled: true,
				tooltip: LANG_delete_message_tooltip,
				enableToggle: false,
				pressed: false,
				handler: function() {
					Ext.Ajax.request({
						url:'ngmp.php',
						params:{
							func: 'mailDeleteMessage',
							id: Ext.encode(this.mailbox.selModel.selections.keys),
							folder: this.config.folder
						},
						method: 'POST',
						success: function(G,H) {
							var I = Ext.util.JSON.decode(G.responseText);
							if (I.success) {
								this.fireEvent('refresh', this);
								this.fireEvent('refreshtree', this);
							} else {
								Ext.Msg.alert(LANG_error, LANG_unable_to_delete_messages);
							}
						},
						failure: function(G,H) {
							Ext.Msg.alert(LANG_error, LANG_unable_to_delete_messages);
						},
						scope: this
					});
				},
				scope: this
			}, '-', {
				id: 'tbbuttonReplyToMessage_' + this.config.folder,
				iconCls: 'icon-reply',
				cls:'x-btn-text-icon',
				text: LANG_reply_to_message,
				disabled:true,
				tooltip:LANG_reply_to_message_tooltip,
				enableToggle: false,
				pressed: false,
				handler: function() {
					var E = this.mailbox.getSelectionModel().getSelected().get('msgidx');
					Ext.Ajax.request({
						url:'ngmp.php',
						params: {
							func: 'readmsg',
							folder: this.config.folder,
							ix: E
						},
						success: function(F,G) {
							var H = Ext.util.JSON.decode(F.responseText);
							Ext.Ajax.request({
								url:'ngmp.php',
								params: {
									func: 'showbody',
									ix: E,
									folder: this.config.folder,
									block_images:!H.showImages,
									text:NGMP.preferences.settings.editorMode=='text'?true:false
								},
								success: function(J,K) {
									var L = J.responseText;
									var I = new NGMP.mail.NewMessageWindow({
										type:'reply',
										messageInfo: H,
										messageBody:L,
										messagePrefix: LANG_re + ':',
										folder: this.config.folder,
										ix: E,
										windowGroup:this.windowGroup,
										id:Ext.id(),
										preferences:NGMP.preferences.settings,
										contactsStore: this.config.contactsStore
									});
									I.on('sent', function(M) {
										this.fireEvent('refresh', this);
									}, this);
									I.render(this.mailboxPane.body);
									this.windowPanel.addWindow(I);
									I.show();
									I.on('close', function(M) {
										this.windowPanel.removeWindow(I);
									}, this);
								},
								failure: function(I, J) {
									Ext.Msg.alert(LANG_error, LANG_unable_to_reply_to_message+'!');
								},
								scope:this
							});
						},
						scope: this
					});
				},
				scope: this
			}, '-', {
				id: 'tbbuttonReplyAll_' + this.config.folder,
				iconCls: 'icon-reply-all',
				cls: 'x-btn-text-icon',
				text: LANG_reply_to_all_message,
				disabled: true,
				tooltip: LANG_reply_to_all_message_tooltip,
				enableToggle: false,
				pressed: false,
				handler: function() {
	                var E=this.mailbox.getSelectionModel().getSelected().get("msgidx");
	                Ext.Ajax.request({
	                    url:"ngmp.php",params:{
	                        func:'readmsg',
							folder:this.config.folder,
							ix:E
	                    },
	                    success:function(F,G){
	                        var H=Ext.util.JSON.decode(F.responseText);
	                        Ext.Ajax.request({
	                            url:"ngmp.php",params:{
									func: 'mailGetBody',
	                                ix:E,
									folder:this.config.folder,
									block_images:!H.showImages,
									text:NGMP.preferences.settings.editorMode=="text"?true:false
	                            },
	                            success:function(J,K){
	                                var L=J.responseText;
	                                var I=new NGMP.mail.NewMessageWindow({
	                                    type:"replyall",
										messageInfo:H,
										messageBody:L,
										messagePrefix:LANG_re+': ',
										folder:this.config.folder,
										ix:E,
										windowGroup:this.WindowGroup,
										id:Ext.id(),
										preferences:NGMP.preferences.settings,
										contactsStore:this.config.contactsStore
	                                });
	                                I.on("sent",function(M){
	                                    this.fireEvent("refresh",this);
	                                },this);
	                                I.render(this.mailboxPane.body);
	                                this.windowPanel.addWindow(I);
	                                I.show();
	                                I.on("close",function(M){
	                                    this.windowPanel.removeWindow(I);
	                                },this);
	                            },
	                            failure:function(I,J){
	                                Ext.Msg.alert(LANG_error,LANG_unable_to_reply_to_message + '!');
	                            },
	                            scope:this,
								method:"GET",
								nocache:false
	                        });
	                    },
	                    failure:function(F,G){
	                        Ext.Msg.alert(LANG_error,LANG_unable_to_reply_to_message+'!');
	                    },
	                    scope:this
	                });
				},
				scope: this
			}, '-',	{
				id: 'tbbuttonForwardMessage_' + this.config.folder,
				iconCls: 'icon-forward',
				cls: 'x-btn-text-icon',
				text: LANG_forward_message,
				disabled: true,
				tooltip: LANG_forward_message_tooltip,
				enableToggle: false,
				pressed: false,
				handler: function() {
	                var E=this.mailbox.getSelectionModel().getSelected().get("msgidx");
	                Ext.Ajax.request({
	                    url:"ngmp.php",params:{
	                        func:'readmsg',
							folder:this.config.folder,
							ix:E
	                    },
	                    success:function(F,G){
	                        var H=Ext.util.JSON.decode(F.responseText);
	                        Ext.Ajax.request({
	                            url:"ngmp.php",params:{
									func: 'mailGetBody',
	                                ix:E,
									folder:this.config.folder,
									block_images:!H.showImages,
									text:NGMP.preferences.settings.editorMode=="text"?true:false
	                            },
	                            success:function(J,K){
	                                var L=J.responseText;
	                                var I=new NGMP.mail.NewMessageWindow({
	                                    type:"forward",
										messageInfo:H,
										messageBody:L,
										messagePrefix:LANG_fw+': ',
										folder:this.config.folder,
										ix:E,
										windowGroup:this.WindowGroup,
										id:Ext.id(),
										preferences:NGMP.preferences.settings,
										contactsStore:this.config.contactsStore
	                                });
	                                I.on("sent",function(M){
	                                    this.fireEvent("refresh",this);
	                                },this);
	                                I.render(this.mailboxPane.body);
	                                this.windowPanel.addWindow(I);
	                                I.show();
	                                I.on("close",function(M){
	                                    this.windowPanel.removeWindow(I);
	                                },this);
	                            },
	                            failure:function(I,J){
	                                Ext.Msg.alert(LANG_error,LANG_unable_to_forward_to_message + '!');
	                            },
	                            scope:this,
								method:"GET",
								nocache:false
	                        });
	                    },
	                    failure:function(F,G){
	                        Ext.Msg.alert(LANG_error,LANG_unable_to_forward_to_message+'!');
	                    },
	                    scope:this
	                });
				},
				scope: this
		 	}, '-', {
				id: 'tbbuttonPrintMessage_' + this.config.folder,
				iconCls: 'icon-print',
				cls: 'x-btn-text-icon',
				text: LANG_print_message,
				disabled: true,
				tooltip: LANG_print_message_tooltip,
				enableToggle: false,
				pressed: false,
				handler: function() {
	                if(this.bottom.isVisible()||this.right.isVisible()){
	                    var E=window.open();
	                    self.focus();
	                    E.document.open();
	                    E.document.write(this.config.printTemplate.apply({
	                        from:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("from")),
							to:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("to")),
							cc:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("cc")),
							subject:this.mailbox.getSelectionModel().getSelected().get("subject"),
							body:this.preview.getFrameDocument().body.innerMTML
	                    }));
	                    E.document.close();
	                    E.print();
	                    E.close();
	                } else {
	                    Ext.Ajax.request({
	                        url:"ngmp.php",
							params:{
								func: 'mailGetBody',
	                            ix:this.mailbox.getSelectionModel().getSelected().get("msgidx"),
								folder:this.config.folder,
								block_images:!this.mailbox.getSelectionModel().getSelected().get("showimages"),
								text:false
	                        },
	                        success:function(F,G){
	                            var H=window.open();
	                            self.focus();
	                            H.document.open();
	                            H.document.write(this.config.printTemplate.apply({
	                                from:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("from")),
									to:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("to")),
									cc:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("cc")),
									subject:this.mailbox.getSelectionModel().getSelected().get("subject"),
									body:F.responseText
	                            }));
	                            H.document.close();
	                            H.print();
	                            H.close();
	                        },
	                        failure:function(F,G){
	                            Ext.Msg.alert(LANG_error, LANG_unable_to_print_message + '!');
	                        },
	                        scope:this,
							method:"GET",
							nocache:false
	                    });
	                }

				},
				scope: this
			}, '-', {
				xtype:'cycle',
				id:'tbbuttonPreviewMessage_' + this.config.folder,
				prependText: LANG_preview_message,
				cls:'x-btn-text-icon',
				showText: true,
				disabled: false,
				tooltip: LANG_preview_message_tooltip,
				items:[
					{text:LANG_preview_message_bottom, iconCls:'icon-preview-bottom'},
					{text:LANG_preview_message_right, iconCls:'icon-preview-right'},
					{text:LANG_preview_message_hide, iconCls:'icon-preview-hide', checked: true}
				],
				changeHandler: function(E,F) {
					switch(F.text) {
						case LANG_preview_message_bottom:
							this.right.hide();
							this.bottom.add(this.preview);
    						this.bottom.show();
							break;
						case LANG_preview_message_right:
							this.bottom.hide();
							this.right.add(this.preview);
							this.right.show();
							break;
						case LANG_preview_message_hide:
							this.preview.ownerCt.hide();
							break;
						default:
							break;
					}
    				this.doLayout();
					this.mailboxPane.doLayout();
					this.mailbox.doLayout();
					if (F.text == LANG_preview_message_hide) {
						this.previewInfo.body.update('');
						this.previewBody.getFrame().update('');
					} else {
						if (this.mailbox.getSelectionModel().getCount()>0) {
    				  		this.previewInfo.body.update(this.previewTemplate.apply({
								from:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("from")),
	    						to:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("to")),
	    						cc:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("cc")),
		    					subject:this.mailbox.getSelectionModel().getSelected().get("subject")
			    		 		}));
						  	this.previewBody.load({
								url:'ngmp.php',
								params:{
									func:'mailGetBody',
									ix:this.mailbox.getSelectionModel().getSelected().get('msgidx'),
									folder:this.config.folder,
									block_images:!this.mailbox.getSelectionModel().getSelected().get('showimages'),
									text: false
								},
								method:'GET',
								nocache: false
							});
					  	}
    				}
				    this.preview.doLayout();
				},
				scope: this
			}, '-', {
				id: 'tbbuttonAutoPreviewMessage_' + this.config.folder,
				iconCls:'icon-auto-preview',
				cls: 'x-btn-text-icon',
				text: LANG_auto_preview,
				disabled: false,
				enableToggle: true,
				pressed: false,
				tooltip: LANG_auto_preview_tooltip,
				toggleHandler: function(F,G) {
					var E = this.mailbox.getView();
					E.showPreview = G;
					if (this.previewsLoaded) {
						E.refresh();
					} else {
						this.store.reload();
					}
				},
				scope: this
			}
		]
	});

    
	this.previewsLoaded = false;

    this.message=Ext.data.Record.create([
		{name:"seen",type:"boolean"},
		{name:"msgidx",type:"string"},
		{name:"from",type:"string"},
		{name:"to",type:"string"},
		{name:"subject",type:"string"},
		{name:'starred', type:'boolean'},
		{name:'archived', type:'boolean'},
		{name:'attach', type:'boolean'},
    	{name:"date",type:"date", dateFormat: 'timestamp'},
		{name:"size",type:"int"},
		{name:"flagimg"},
		{name:"showimages",type:"boolean"},
		{name:"body"}
    ]);
	
	this.jsonReader = new Ext.data.JsonReader({
		totalProperty:'nummsg',
		root: 'messages',
		id: 'msgidx'
	}, this.message);
	
    this.store=new Ext.data.GroupingStore({
	   	proxy:new Ext.data.HttpProxy({
        	url:"ngmp.php",
			disableCaching:true
        }),
		baseParams:{
			start:0,
			limit:Number(NGMP.preferences.settings.rpp),
			func:'msglist',
            folder:this.config.folder,
			refr:true
        },
        remoteGroup:true,
		remoteSort:true,
		reader:this.jsonReader,
		storeId:this.config.folder,
		id:'msgidx',
		sortInfo:{
            field:"received",direction:"DESC"
        }
        
    });

	
	this.refresh = {
		run: function() {
			this.store.reload({
				params:{
					start: 0,
					limit: Number(NGMP.preferences.settings.rpp)
				}
			});
		},
		interval: 60000*NGMP.preferences.settings.refreshTime,
		scope: this
	};
	
    this.store.on("beforeload",function(E,F){
        this.fireEvent("refreshtree",this);

        if(E.baseParams.groupBy){
            delete E.baseParams.groupBy;
        }
        if(F.params){
            if(F.params.groupBy){
                delete F.params.groupBy;
            }
            
        }
        if(E.groupField){
            Ext.apply(E.baseParams,{
                groupBy:E.groupField
            });
        }
        if(E.baseParams.getbody){
            delete E.baseParams.getbody;
        }
        if(F.params){
            if(F.params.getbody){
                delete F.params.getbody;
            }
            
        }

    	if (this.rendered) {
	        if(this.getTopToolbar()){
	            if(this.getTopToolbar().items.item("tbbuttonAutoPreviewMessage_"+this.config.folder).pressed){
	                Ext.apply(E.baseParams,{
	                    getbody:true
	                });
	                this.previewsLoaded=true;
	            }
	            else{
	                this.previewsLoaded=false;
	            }
            
	        }
	   }
    },this);
	
	this.store.on('load', function() {
		Ext.TaskMgr.stop(this.refresh);
		this.itemCount.el.innerHTML = this.store.getCount() + " " + LANG_items;
		this.fireEvent('selectnode', this);
		try {
			this.mailbox.getSelectionModel().selectFirstRow();
			if (this.right.isVisible() || this.bottom.isVisible()) {
				this.previewBody.load({
					url:'ngmp.php',
					params: {
						func: 'mailGetBody',
						ix: this.mailbox.getSelectionModel().getSelected().get('msgidx'),
						folder: this.config.folder,
						block_images:!this.mailbox.getSelectionModel().getSelected().get('showimages'),
						text: false
					},
					method:'GET',
					nocache: false
				});
				this.previewInfo.body.update(this.previewTemplate.apply({
					from: Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get('from')),
					to: Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get('to')),
					cc: Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get('cc')),
					subject: Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get('subject'))
					
				}));
			}
		} catch (E) {

		}
		Ext.TaskMgr.start(this.refresh);
	}, this);
	
	this.store.on('datachanged', function() {
		if (this.itemCount) {
			this.itemCount.el.innerHTML = this.store.getCount() + " " + LANG_items;
		}
	},this);
	
	this.store.on('update', function(A,B,C) {
		if (C == 'commit') {
            Ext.Ajax.request({
                url:"ngmp.php",params:{
					func: 'flag_mail',
					idx:B.get('msgidx'),
					seen: B.get('seen')===true?1:0,
					starred: B.get('starred')===true?1:0,
					archived: B.get('archived')===true?1:0
                },
                success:function(G,H){
               	},
                failure:function(G,H){
                },
                scope:this
            });
		}
	},this);

    this.itemCount=new Ext.Toolbar.TextItem(LANG_unknown + ' ' + LANG_items);
	this.tb = new Ext.Toolbar({
        id:"toolbarBottomMailboxPanel_"+this.config.folder,
		height:24,
		items:[this.itemCount,{
            xtype:"tbseparator"
        }
        ]
	});
	
	this.previewTemplate = new Ext.XTemplate(
    	'<div style="font:normal 12px tahoma, arial, helvetica, sans-serif;overflow=hidden">',
    	'<div style="font:bold 16px tahoma, arial, helvetica, sans-serif;">{subject}</div>',
    	'<table><tr><td colspan=2 style="font:normal 14px tahoma, arial, helvetica, sans-serif;">{from}',
    	'</td></tr><tr><td width="75px">'+LANG_to+':</td><td>{to}</td></tr><tr><td width="75px">'+LANG_cc+':</td>',
    	'<td>{cc}</td></tr></table><hr></div>');
	this.previewTemplate.compile();
	
	
	this.preview = new Ext.Panel({
		id:'panelMailPreview_'+this.config.folder,
		border: false,
		layout:'border',
		frame: false,
		autoScroll: false,
		hideMode: 'offsets',
		items:[this.previewInfo, this.previewBody],
		statefull: false
	});
	
	this.bottom = new Ext.Panel({
		id:'panelMailBottom_'+this.config.folder,
		region: 'south',
		split: true,
		height: 300,
		minHeight: 200,
		bodyStyle: 'padding: 5px',
		border: true,
		layout: 'fit',
		frame: false,
		autoScroll: false,
		stateful: false,
		hideMode: 'offsets',
		hidden: true,
		items: [this.preview]
	});
	
	this.right = new Ext.Panel({
		id:'panelMailRight_'+this.config.folder,
		region:'east',
		split: true,
		width: 300,
		minWidth: 200,
		bodyStyle: 'padding: 5px',
		border: true,
		layout: 'fit',
		frame: false,
		hidden: true,
		hideMode: 'offsets',
		autoScroll: false,
		stateful: false
	});
	
	
	this.sm = new Ext.grid.RowSelectionModel({
		singleSelect: false
	});
	
	this.cm = new Ext.grid.ColumnModel([
//		{
//			header:"&nbsp<img src=themes/ngmp/images/Priority16.png border=0>",
//			width:30,
//			sortable:false,
//			resizable:false,
//			groupable:false
//	    },
//	    {
//	        header:"<img src=themes/ngmp/images/Status16.png border=0>",
//			dataIndex:"statusimg",
//			width:30,
//			sortable:false,
//			resizable:false,
//			groupable:false
//	    },
		{
			header:"&nbsp;",
			dataIndex:"seen",
			width:20,
			sortable:true,
			resizable:false,
			groupable:false,
			renderer:function(value) {
				return (value === true)?'':'<img src="themes/ngmp/images/seen.png" border="0"/>';
			}
		},
		{
			header:"&nbsp;",
			dataIndex:"starred",
			width:24,
			sortable:true,
			resizable:false,
			groupable:false,
			renderer:function(value) {
				return (value===true)?'<img src="themes/ngmp/images/16x16/starred.png" border="0"/>':'<img src="themes/ngmp/images/star_off.png" border="0"/>';
			}
		},
	    {
			header: this.config.groupFieldHeader,
			dataIndex:this.config.groupField,
			renderer:C,
			width:200,
			sortable:true
	    },
	    {
	        id:"subject",
			header:LANG_subject,
			dataIndex:"subject",
			renderer:C,
			width:200,
			sortable:true
	    },
		{
			header:"&nbsp;",
			dataIndex:"attach",
			width:25,
			sortable:false,
			resizable:false,
			groupable:false,
			renderer:function(value) {
				return (value === true)?'<img src="themes/ngmp/images/Mail-attachment.png" border="0"/>': '';
			}
		},
	    {
	        header:this.config.dateTitle,
			dataIndex:"date",
		    renderer:D,
			width:120,
			sortable:true
	    }
//	    {
//	        header:LANG_size,
//			dataIndex:"size",
//			renderer:B,
//			width:70,
//			sortable:true,
//			align:"right",
//	    }		
	]);
	
	this.mailbox = new NGMP.grid.GridPanel({
		id: 'gridMailbox_' + this.config.folder,
		folder: this.config.folder,
		layout: 'fit',
		region: 'center',
		autoExpandColumn: 'subject',
		deferredRender: true,
		monitorResize: true,
		ddGroup: 'MsgDD',
		enableDragDrop: false,
		store: this.store,
		cm: this.cm,
		view: new Ext.grid.GroupingView({
			forceFit: false,
			groupTextTpl: '{text}({[values.rs.length]}{[values.rs.length>1?"'+LANG_items+'" : "'+LANG_item+'"]})',
			hideGroupedColumn: true,
			showGroupName: true,
			enableNoGroups: true,
			emptyText: LANG_there_are_no_messages_in_this_mailbox,
			enableRowBody: true,
			showPreview: false,
			getRowClass: function(E,H,G,F) {
				if (this.showPreview) {
					G.body='<div style="padding-left:100px">'+E.get("body")+"</div>";
					G.bodyStyle="padding-left:25px !important;color:blue";
					return"x-grid3-row-expanded";
				}
				return "x-grid3-row-collapsed";
			}
		}),
		loadMask: {
			msg: LANG_loading_messages
		},
		sm: this.sm,
		frame: false,
		border: true,
		hideMode:'offsets',
		stateful: false,
		tbar:this.tbar,
		bbar: new Ext.PagingToolbar({
			id:'paggingMailbox_' + this.config.folder,
			pageSize:Number(NGMP.preferences.settings.rpp),
			store: this.store,
			displayInfo: true,
			displayMsg: LANG_displaying_messages + ' {0} - {1} @ {2}',
			emptyMsg: LANG_no_messages_to_display,
			plugins:[new NGMP.plugins.PageSizePlugin()]
		})
	});
	
	this.mailboxPane = new Ext.Panel({
		id:'panelMaiboxPane_'+this.config.folder,
		region: 'center',
		border: false,
		frame: false,
		autoScroll: false,
		layout: 'border',
		hideMode: 'offsets',
		items: [this.mailbox, this.bottom, this.right]
	});
	
	this.windowGroup = new Ext.WindowGroup();

	this.windowPanel = new NGMP.panel.WindowPanel(this.windowGroup, {
		id:'windowpanelWindowPanel_' + this.config.folder,
		region: 'south',
		bodyCls:'x-plain',
		border: false,
		split: true,
		minHeight: 85,
		height:85,
		maxHeight: 85,
		hideMode: 'offsets',
		hidden: true
	});
	
	NGMP.mail.MailBoxPanel.superclass.constructor.call(this,{
		id: 'panelMailboxPanel_'+this.config.folder,
		autoShow: true,
		title: this.config.title,
		border: false,
		layout: 'border',
		bodyStyle:'background-color:#DFE8F6',
		iconCls: this.config.iconCls,
		closable: true,
		stateful: false,
		hideMode:'offsets',
		bbar:this.tb,
		items: [this.mailboxPane, this.windowPanel]
	});
	
	this.mailbox.on('render', function(){
		var E = this.mailbox.getColumnModel();
//	      E.setColumnWidth(0, 20 ,false),
 //         E.setColumnWidth(1, 20, false),
	 //   E.setColumnWidth(2, 35, false),
		E=this.mailbox.getView();
		E.autoExpand();
	}, this, {
		delay: 10
	});
	
    this.mailbox.getTopToolbar().on("render",function(){
        if(this.config.folder=="inbox"){
            this.mailbox.getTopToolbar().insertButton(3,{
                id:"tbbuttonSpam_"+this.config.folder,
				iconCls:"icon-spam",
				cls:"x-btn-text-icon",
				text:LANG_spam,
				disabled:true,
				tooltip: LANG_spam_tooltip,
				enableToggle:false,
				pressed:false,
				handler:function(){
                    Ext.Ajax.request({
                        url:"ngmp.php",params:{
							func: 'mailMarkAsSpam',
                            folder:this.config.folder,
							id:Ext.encode(this.mailbox.selModel.selections.keys)
                        },
                        success:function(G,H){
                            var I=Ext.util.JSON.decode(G.responseText);
                            if(I.success){
                           		this.fireEvent("refresh",this);
                                this.fireEvent("refreshtree",this);
                            } else{
                                Ext.Msg.alert(LANG_error,E.length>1?LANG_unable_to_mark_messages_as_spam:LANG_unable_to_mark_messages_as_spam);
                            }
                            
                        },
                        failure:function(G,H){
                            Ext.Msg.alert(LANG_error,E.length>1?LANG_unable_to_mark_messages_as_spam:LANG_unable_to_mark_messages_as_spam);
                        },
                        scope:this
                    });
                },
                scope:this
            });
        }
	    if(this.config.folder=="inbox"){
	            this.mailbox.getTopToolbar().insertButton(3,{
	                id:"tbbuttonArchive_"+this.config.folder,
					iconCls:"icon-archive",
					cls:"x-btn-text-icon",
					text:LANG_archive,
					disabled:true,
					tooltip:LANG_archive_tooltip,
					enableToggle:false,
					pressed:false,
					handler:function(){
 					 	this.mailbox.getSelectionModel().getSelected().set('archived', true);
						this.mailbox.getSelectionModel().getSelected().commit();
						this.store.remove(this.mailbox.getSelectionModel().getSelected());
						this.store.commitChanges();
	                },
	                scope:this
	            });
	  	}
	    if(this.config.folder=="archive"){
	            this.mailbox.getTopToolbar().insertButton(3,{
	                id:"tbbuttonUnArchive_"+this.config.folder,
					iconCls:"icon-unarchive",
					cls:"x-btn-text-icon",
					text:LANG_unarchive,
					disabled:true,
					tooltip:LANG_unarchive_tooltip,
					enableToggle:false,
					pressed:false,
					handler:function(){
 					 	this.mailbox.getSelectionModel().getSelected().set('archived', false);
						this.mailbox.getSelectionModel().getSelected().commit();
						this.store.remove(this.mailbox.getSelectionModel().getSelected());
						this.store.commitChanges();

	                },
	                scope:this
	            });
	  	}
        if(this.config.folder=="spam"){
            this.mailbox.getTopToolbar().insertButton(4,{
                id:"tbbuttonNoSpam_"+this.config.folder,
				iconCls:"icon-nospam",
				cls:"x-btn-text-icon",
				text:LANG_not_spam,
				disabled:true,
				tooltip:LANG_not_spam_tooltip,
				enableToggle:false,
				pressed:false,
				handler:function(){
                    Ext.Ajax.request({
                        url:"ngmp.php",params:{
							func:'mailMarkAsNotSpam',
                            folder:this.config.folder,
							id:Ext.encode(this.mailbox.selModel.selections.keys)
                        },
                        success:function(G,H){
                            var I=Ext.util.JSON.decode(G.responseText);
                            if(I.success){
                                this.fireEvent("refresh",this);
                                this.fireEvent("refreshtree",this);
                            }
                            else{
                                Ext.Msg.alert(LANG_error,E.length>1?LANG_unable_to_mark_messages_as_not_spam:LANG_unable_to_mark_messages_as_not_spam);
                            }
                            
                        }
                        ,failure:function(G,H){
                            Ext.Msg.alert(LANG_error,E.length>1?LANG_unable_to_mark_messages_as_not_spam:LANG_unable_to_mark_messages_as_not_spam);
                        },
                        scope:this
                    });
                },
                scope:this
            });
        }
        
    },
	this,
	{
        delay:1000
    });
    this.on("beforedestroy",function(){
        this.windowGroup.each(function(E){
            E.close();
        },this);
    });	

    this.mailbox.on("rowdblclick",function(G,J,H){
        var E=this.store.getAt(J).get("msgidx");
        var I=this.id+"_"+E;
        var F=this.windowGroup.get(I);
        if(F){
            F.setActive(true);
            this.windowGroup.bringToFront(F);
        } else {
            if(!this.config.drafts){
                Ext.Ajax.request({
                    url:"ngmp.php",
					params:{
						func:'readmsg',
                        folder:this.config.folder,
						ix:E
                    }
                    ,success:function(K,L){
                        var M=Ext.util.JSON.decode(K.responseText);
                        F=new NGMP.mail.MessageWindow({
                            id:I,
							ix:E,
							folder:this.config.folder,
							messageInfo:M,
							windowPanel:this.windowPanel,
							windowGroup:this.windowGroup,
							preferences:NGMP.preferences.settings,
							printTemplate:this.config.printTemplate,
							contactsStore:this.config.contactsStore
                        });
                        F.render(this.mailboxPane.body);
                        this.windowPanel.addWindow(F);
                        F.show();
                        this.store.getAt(J).set("read",true);
                        F.on("close",function(N){
                            this.windowPanel.removeWindow(F);
                        },this);
                    },
					failure:function(K,L){
                        Ext.Msg.alert(LANG_error, LANG_unable_to_show_message+'!');
                    },
					scope:this
                });
            }
            else{
                Ext.Ajax.request({
                    url:"ngmp.php",params:{
						func:'readmsg',
                        folder:this.config.folder,
						ix:E
                    }
                    ,success:function(K,L){
                        var M=Ext.util.JSON.decode(K.responseText);
                        Ext.Ajax.request({
                            url:"ngmp.php",params:{
								func: 'mailGetBody',
                                ix:E,folder:this.config.folder,
								block_images:!M.showImages,
								text:false
                            }
                            ,success:function(O,P){
                                var Q=O.responseText;
                                var N=new NGMP.mail.NewMessageWindow({
                                    type:"draft",
									id:I,messageInfo:M,
									messageBody:Q,
									messagePrefix:"",
									windowGroup:this.WindowGroup,
									folder:this.config.folder,
									ix:E,
									preferences:NGMP.preferences.settings,
									contactsStore:this.config.contactsStore
                                });
                                N.on("sent",function(R){
                                    this.fireEvent("refresh",this);
                                    this.fireEvent("refreshtree",this);
                                }
                                ,this);
                                N.render(this.mailboxPane.body);
                                this.windowPanel.addWindow(N);
                                N.show();
                                N.on("close",function(R){
                                    this.windowPanel.removeWindow(N);
                                }
                                ,this);
                            }
                            ,failure:function(N,O){
                                Ext.Msg.alert(LANG_error, LANG_unable_to_reply_to_message+"!");
                            }
                            ,scope:this,method:"GET",nocache:false
                        });
                    }
                    ,failure:function(K,L){
                        Ext.Msg.alert(LANG_error,LANG_unable_to_reply_to_message+"!");
                    }
                    ,scope:this
                });
            }
            
        }
        
    }
    ,this);	
	
	this.mailbox.on('cellclick', function(grid, rowIndex, columnIndex, e) {
		if (columnIndex == 1) {
			this.mailbox.getSelectionModel().getSelected().set('starred', !this.mailbox.getSelectionModel().getSelected().get('starred'));
	  		this.store.commitChanges();
		}
	}, this);
	
	this.mailbox.getSelectionModel().on('selectionchange', function(F) {
		var E = this.mailbox.getTopToolbar().items;
		if (F.getCount() == 1 && (this.right.isVisible() || this.bottom.isVisible())) {
			this.previewBody.load({
				url:'ngmp.php',
				params:{
					func: 'mailGetBody',
					ix: this.mailbox.getSelectionModel().getSelected().get('msgidx'),
					folder: this.config.folder,
					block_images:!this.mailbox.getSelectionModel().getSelected().get('showimages'),
					text: false
				},
				method: 'GET',
				nocache:false
			});
		 	this.mailbox.getSelectionModel().getSelected().set('seen', true);
	  		this.store.commitChanges();
			this.previewInfo.body.update(this.previewTemplate.apply({
				from:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("from")),
				to:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("to")),
				cc:Ext.util.Format.htmlEncode(this.mailbox.getSelectionModel().getSelected().get("cc")),
				subject:this.mailbox.getSelectionModel().getSelected().get("subject")	
			}));
		}
		if (F.getCount()>0) {
			E.get('tbbuttonDeleteMessage_'+this.config.folder).enable();
			E.get('tbbuttonReplyToMessage_'+this.config.folder).enable();
			E.get('tbbuttonReplyAll_'+this.config.folder).enable();
			E.get('tbbuttonForwardMessage_'+this.config.folder).enable();
			if (E.get('tbbuttonSpam_'+this.config.folder)) {
				E.get('tbbuttonSpam_'+this.config.folder).enable();
			}
			if (E.get('tbbuttonNoSpam_'+this.config.folder)) {
				E.get('tbbuttonNoSpam_'+this.config.folder).enable();
			}
			if (E.get('tbbuttonArchive_'+this.config.folder)) {
				E.get('tbbuttonArchive_'+this.config.folder).enable();
			}
			if (E.get('tbbuttonUnArchive_'+this.config.folder)) {
				E.get('tbbuttonUnArchive_'+this.config.folder).enable();
			}
			E.get('tbbuttonPrintMessage_'+this.config.folder).enable();
			if (F.getCount()>1) {
				E.get('tbbuttonReplyToMessage_'+this.config.folder).disable();
				E.get('tbbuttonForwardMessage_'+this.config.folder).disable();
				E.get('tbbuttonPrintMessage_'+this.config.folder).disable();
			}
		} else {
            E.get("tbbuttonDeleteMessage_"+this.config.folder).disable();
            E.get("tbbuttonReplyToMessage_"+this.config.folder).disable();
            E.get("tbbuttonReplyAll_"+this.config.folder).disable();
            E.get("tbbuttonForwardMessage_"+this.config.folder).disable();
            if(E.get("tbbuttonSpam_"+this.config.folder)){
                E.get("tbbuttonSpam_"+this.config.folder).disable();
            }
            if(E.get("tbbuttonNoSpam_"+this.config.folder)){
                E.get("tbbuttonNoSpam_"+this.config.folder).disable();
            }
            E.get("tbbuttonPrintMessage_"+this.config.folder).disable();
		}
	}, this);
	
	this.mailbox.on('keypress', function(e) {
		if (e.keyCode == 38 || e.keyCode == 40) {
	   // 	console.log(this.mailbox.getSelectionModel().getSelected().get('from'));
		}
	}, this);

	this.on('activate', function(A) {
		this.store.reload();
	},this, {delay:20});
};
Ext.extend(NGMP.mail.MailBoxPanel,Ext.Panel,{
	afterRender: function (){
		NGMP.mail.MailBoxPanel.superclass.afterRender.call(this);
   	},
    refreshMailbox:function(){
        this.store.reload();
    }
});

mailContactsStore = new NGMP.data.JsonStore({
	autoLoad: false,
	url:'quick_address.php',
	root:'addresses',
	fields: [
		'name',
		'email',
		'street',
		'city',
		'state',
		'work'
	],
	method: 'POST'
});

NGMP.mail.MailPrintTemplate = new Ext.XTemplate(
	"<html><head><style>body, td {font-family: Verdana;font-size: 10pt;}</style></head>",
	'<body><div><table><tr><td width="75px">'+LANG_from+':</td><td>{from}</td></tr><tr><td width="75px">'+LANG_to+':</td><td>{to}</td></tr>',
	'<tr><td width="75px">'+LANG_cc+':</td><td>{cc}</td></tr><tr><td width="75px">'+LANG_subject+':</td><td>{subject}</td></tr></table><hr></div>',
	'<div>{body}</div></body></html>');
NGMP.mail.MailPrintTemplate.compile();


NGMP.mail.MailModule = function(A) {
	if (!A) { A = {};}
	this.mailboxTree = new NGMP.mail.MailboxTreePanel({
		username: NGMP.preferences.settings.account
	});
	this.mailboxTree.on('refresh', function(){
		//this.refreshMailboxes();
	}, this);
		
	this.mailboxTree.on('refreshtree', function(){
		//this.refreshMailboxTree();
	}, this);
		
	this.mailboxTree.on('reloadtree',function() {
	}, this);
				
	this.mailboxTree.on('expand', function(A) {
		if (this.centerPanel.rendered) {
			this.centerPanel.getLayout().setActiveItem(0);
		}
	}, this);
					
	this.mailboxTree.tree.on('click', function(B, C) {
		if (B.isLeaf()) {
			var A = Ext.getCmp('panelMailboxPanel_' + B.id);
			if (!A) {
				newComp = this.centerTabPanel.add(new NGMP.mail.MailBoxPanel({
					folder: B.id,
					title: B.text,
					iconCls: B.attributes.iconCls,
					preferences: Ext.state.Manager.get('preferences'),
					printTemplate: mailPrintTemplate,
					contactsStore: mailContactsStore,
					system: B.attributes.system,
   					groupField: B.attributes.groupField,
					drafts: B.attributes.drafts,
   					dateTitle: B.attributes.dateTitle
				}));
				this.centerTabPanel.setActiveTab(newComp);
				if (this.centerTabPanel.hidden) {
					this.centerTabPanel.show();
					this.centerTabPanel.doLayout();
					this.centerPanel.getLayout().setActiveItem(0);
					this.centerPanel.doLayout();
				}
				this.mailboxTree.selectNode(B.id);
	//			newComp.on('activate', function(){ 
	//				console.log(B.id + ' activate')
	//			//o	this.refreshMailboxes();
	//				this.mailboxTree.selectNode(B.id);
	//			}, this);
				newComp.on('refresh', function() {
					this.refreshMailboxes();
				}, this);
				newComp.on('refreshtree', function() {
					this.refreshMailboxTree();
				}, this);
				newComp.on('selectnode', function(D) {
					this.mailboxTree.selectNode(D.config.folder);
				}, this);
			} else {
				this.centerTabPanel.setActiveTab(A);
			}
		}
	}, this);

	this.accordion = new Ext.Panel({
		id:"panelMailAccordion",
		region:'west',
		layout: 'accordion',
		width: 250,
		minSize: 150,
		maxSize: 300,
		split: false,
		frame: false,
		collapsible: true,
		defaults: {
			bodyStyle: 'background: transparent;',
			border:true,
			frame:true
		},
		layoutConfig: {
			titleCollapse: true,
			hideCollapseTool: false,
			animate: true,
			activeOnTop: true,
			renderHidden: false,
			border: true
		},
		items: [this.mailboxTree]
	});

	this.inboxPanel = new NGMP.mail.MailBoxPanel({
		folder:'inbox',
		title: LANG_inbox,
		iconCls:'icon-inbox',
		preferences: NGMP.preferences.settings,
		printTemplate: NGMP.mail.MailPrintTemplate,
		contactsStore: mailContactsStore,
		system: true,
		groupField: 'from',
		drafts: false,
		dateTitle: LANG_date_received
	});
   
 
	this.inboxPanel.on('activate', function() {
		if (this.mailboxTree.rendered) {
			this.mailboxTree.selectNode('inbox');
		}
	}, this);
	
	this.inboxPanel.on('refresh', function() {
		this.refreshMailboxes();
	}, this);
	this.inboxPanel.on('refreshtree', function() {
		this.refreshMailboxTree();
	}, this);
	this.inboxPanel.on('selectnode', function(A) {
		this.mailboxTree.selectNode(A.config.folder);
	}, this);

	
	this.centerTabPanel = new Ext.TabPanel({
		id:'tabpanelMailboxes',
		autoShow: true,
		deferredRender: true,
		enableTabScroll: true,
		monitorResize: true,
		border: true,
		activeTab: 0,
		hideMode:'offsets',
		items:[this.inboxPanel]
	});

	this.centerTabPanel.on('remove', function() {
		if (this.centerTabPanel.items.getCount() === 0) {
			this.centerTabPanel.hide();
		}
	},this);
	
	
	this.centerPanel = new Ext.Panel({
		id:"panelMailCenterPanel",
		baseCls:'x-plain',
		deferredRender:false,
		region: 'center',
		autoShow: true,
		activeItem: 0,
		border: false,
		layout: 'card',
		hideMode:'offsets',
		items: [this.centerTabPanel]
	});

	this.centerPanel.on('show', function() {
		this.centerPanel.doLayout();
	},this);



	A.layout = 'border';
	A.items = [this.accordion,this.centerPanel];
	NGMP.mail.MailModule.superclass.constructor.call(this,A);
};
Ext.extend(NGMP.mail.MailModule,Ext.Panel, {
	refreshMailboxes: function() {
		this.centerTabPanel.items.each(function(C,A,B) {
			C.refreshMailbox();
		},this);
	},
	refreshMailboxTree:function() {
		this.mailboxTree.refreshQuota();
		this.mailboxTree.refreshTree();
	},
	reloadMailboxTree: function() {
		this.mailboxTree.refreshQuota();
		this.mailboxTree.reloadTree();
	}
});
NGMP.moduleManager.addModule('mail', NGMP.mail.MailModule, {
	title:LANG_btn_mail,
	iconCls:'icon-mail'
});
