Ext.Email = function(mainPanel){

	var tab = mainPanel.getComponent('docs-Email Templates');
	if(tab){
		mainPanel.setActiveTab(tab);
	}
	else{
		
	
		/********** global resources available **********/
		var emailStore = new Ext.data.Store({
	        proxy: new Ext.data.HttpProxy({url: Ext.urlScriptDir + '/application/email.php'}),
	        baseParams: { method: 'list', user_id: Ext.userId, user_level: Ext.userLevel },
	        reader: new Ext.data.JsonReader({
	            root: 'data',
	            totalProperty: 'totalCount',
	            id: 'id'
	        },
	        [
	            {name: 'id', mapping: 'id'},
	            {name: 'email_nm', mapping: 'email_nm'},
	            {name: 'email_sub', mapping: 'email_sub'},
	            {name: 'email_body', mapping: 'email_body'},
	            {name: 'br', mapping: 'br'},
	            {name: 'subject', mapping: 'subject'},
	            {name: 'body', mapping: 'body'}
	            
	        ])
	    });
	    var emailTpl = new Ext.XTemplate(
	            '<tpl for="."><div class="search-item">',
	                '<b>{email_nm}</b>{br}',
	                '<b>{subject}</b> {email_sub}{br}',
	                '<b>{body}</b> {email_body}',
	            '</div></tpl>'
	    );
	    
	    // Create the email form that is populated with the Panel display
	    var emailForm = new Ext.form.FormPanel({
	        baseCls: 'x-plain',
	        labelWidth: 130,
	        url: Ext.urlScriptDir + '/application/email.php',
	        id: 'emailFormItems',
	        defaultType: 'textfield',
	        monitorValid: true,
	
	        reader: new Ext.data.JsonReader({
	            root: 'data', // the root of the json array
	            totalProperty: 'totalCount',
	            id: 'id',
	            fields: [
	                     {name: 'id', mapping: 'id'},
	                     {name: 'email_nm', mapping: 'email_nm'},
	                     {name: 'email_sub', mapping: 'email_sub'},
	                     {name: 'email_body', mapping: 'email_body'}
	           ]
	        }),
	
	        items: [
	            new Ext.form.EmailComboBox({
	                store: emailStore,
	                id: 'emailStore',
	                fieldLabel: 'Email Templates',
	                anchor: '96%',
	            	tooltipText: "This dropdown lists all the saved email templates. You can only edit existing email templates, you cannot create nor delete anything.",
	                listeners: { render: Ext.setFormFieldTooltip },
	                tpl: emailTpl,
	                itemSelector: 'div.search-item'
	            }),
	            {
	                fieldLabel: 'Description',
	                name:'email_nm',
	                id: 'email_nm',
	                anchor:'96%',
	                disabled: true,
	            	tooltipText: "This field cannot be edited, and is only used to differentiate between unique emails.",
	                listeners: { render: Ext.setFormFieldTooltip }
	            },
	            {
	            	fieldLabel: 'Email Subject',
	            	name:'email_sub',
	            	id: 'email_sub',
	            	anchor:'96%',
	            	tooltipText: "This is the subject line of the email.",
	            	listeners: { render: Ext.setFormFieldTooltip }
	            },
		        {
		            xtype: 'textarea',
		            fieldLabel: 'Email Body',
		            name: 'email_body',
		            anchor: '96%',
		            grow: true,
		            allowBlank: false,
	                tooltipText: "This is the body text of the email. Any word that begins with % denotes a dynamic variable that is replaced with the proper text when the email is sent.",
	                listeners: { render: Ext.setFormFieldTooltip }
		        },
	            {
	                xtype: 'hidden',
	                name:'id',
	                id:'email_id',
	                value: 0
	            }
	        ],
	
	        buttons: [
	        {
	            text: 'Save',
	            type: 'submit',
	            formBind:true, // combined with monitorValid above, the submit button will remain disabled until everything is properly validated. -nk
	            handler: function(){
	    			Ext.saveResourceGlobal('emailFormItems', 'email_sub', 'emailSB', '/application/email.php', 'save', 'emailStore');
	    		}
	        },
	        {
	            text: 'Reset',
	            type: 'reset',
	            handler: function(){
	                // Clear all the values in the form
	                emailForm.getForm().reset();
	                // Set the focus to the FROM field
	                Ext.getCmp('email_nm').focus();
	            }
	        }]
	    });
	
	    // Using the generic AdminPanel ux (in rpmPanel), we will create a panel to hold our form
	    var emailPanel = new Ext.ux.AdminPanel({
	        id:'emailPanel',
	        items: [ emailForm ],
	        tbar: [
	            {
	                // SAVE
	                icon: Ext.urlScriptDir + Ext.urlIconDir + '/save.gif',
	                cls: 'x-btn-icon',
	                tooltip: '<b>Save Email Template</b><br />Save the loaded email template.',
	                handler: function(){
	    				Ext.saveResourceGlobal('emailFormItems', 'email_sub', 'emailSB', '/application/email.php', 'save', 'emailStore');
	    			}
	            }
	        ],
	        // Bottom Bar which holds the status bar for updates, etc
	        bbar: new Ext.StatusBar({
	            id: 'emailSB',
	            defaultText: 'Ready', // The default text when the status is cleared
	            defaultIconCls: 'default-icon',
	            text: 'Ready', // The default text shown when the SB is first loaded
	            iconCls: 'ready-icon'
	        })
	    });
	    // Now that we've created the Panel properly, load the component
	    rpmCom.loadComp(emailPanel, 'Email Templates', mainPanel, 0, 'icon-email-edit');
	    // Set focus to the name field
	    Ext.getCmp('email_nm').focus('', 100);
	    
	    if(Ext.isIE){
		    // Resize north panels in various calendars
		    if(Ext.getCmp('fullShowPanel')){
		    	Ext.getCmp('fullShowPanel').setHeight(120);
		    }
		    
		    if(Ext.getCmp('gridViewPanel')){
		    	Ext.getCmp('gridViewPanel').setHeight(120);
		    }
		    
		    if(Ext.getCmp('meetingCalendarViewPanel')){
		    	Ext.getCmp('meetingCalendarViewPanel').setHeight(90);
		    }
		    
		    if(Ext.getCmp('gridViewPanelDemo')){
		    	Ext.getCmp('gridViewPanelDemo').setHeight(80);
		    }
		    
		    if(Ext.getCmp('resourceAvailViewPanel')){
		    	Ext.getCmp('resourceAvailViewPanel').setHeight(70);
		    }
		    
		    if(Ext.getCmp('myViewFormPanel')){
		    	Ext.getCmp('myViewFormPanel').setHeight(50);
		    }
		    
		    if(Ext.getCmp('reportViewPanel')){
		    	Ext.getCmp('reportViewPanel').setHeight(90);
		    }
	    }
	}
}

Ext.form.EmailComboBox = Ext.extend(Ext.form.ComboBox, {
    typeAhead: false,
    displayField: 'resource_nm',
    mode: 'remote',
    triggerAction: 'all',
    loadOnTrigger: true,
    emptyText: 'Select an email template from the dropdown to edit, or search by typing...',
    selectOnFocus: true,
    minChars: 2,

    // private
    initEvents : function(){
        // Call the parent (make sure this matches the object above!)
		Ext.form.EmailComboBox.superclass.initEvents.call(this);

        // Select fires AFTER you click on a comboBox item (the list is collaspsed)
        this.on('select', this.onThisSelect, this);

    },

    onTriggerClick : function(){
        if(this.disabled){
            return;
        }
        if(this.isExpanded()){
            this.collapse();
            this.el.focus();
        }else {
            this.onFocus({});
            if(this.triggerAction == 'all') {
                this.doQuery(this.allQuery, true);
            } else {
                this.doQuery(this.getRawValue());
            }
            this.el.focus();
            if(this.loadOnTrigger){
                this.store.load({params:{query:this.getRawValue(), user_id: Ext.userId}});
            }
        }

    },

    onThisSelect: function(record){
        var rowIndex = record.selectedIndex;
        var rowData = record.store.getAt(rowIndex).data;
        var id = rowData.id;

        var loc = Ext.getCmp('emailFormItems');
        loc.getForm().load({params:{method:'list', id:String(id)}});

        loc.getForm().on('actioncomplete', function(p){
            Ext.getCmp('emailSB').setStatus({iconCls: 'x-status-accept', clear: true, text: 'Email template loaded'});
            // Manually set the id field so we can recall it later
            Ext.getCmp('email_id').setValue(id);
        }, this);
    }
});