var gridstore;

Ext.onReady(function(){
    if(document.getElementById('addemailtemplatebutton') != null){
        new Ext.Button({
            id:"addemailtemplatebutton",
            renderTo:"addemailtemplatebutton",
            text: lang('Add Template'),
            iconAlign: 'left',
            handler:function(){
                ShowEditEmail(0);
            }
        });
     }

     var emailtypestore = new Ext.data.JsonStore({
            id: "emailtypestore",
            root: 'types',
            totalProperty: 'totalcount',
            idProperty: 'id',
            remoteSort: true,
            baseParams: {
            filter: "",
            customerid: "0"
        },
        fields: [
                'id','name'
        ],
        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
                url: 'index.php?fuse=admin&action=Admin_GetEmailTypes'
        })
    });

     var emailtypecombo = new Ext.form.ComboBox({
        triggerAction: 'all',
        id:"emailtypecombo",
        lazyRender:true,
        editable:false,
        value:"Support E-Mails",
        mode: 'local',
        store: emailtypestore,
        valueField: 'id',
        width: 220,
        displayField: 'name',
        applyTo: 'emailtypes',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                 gridstore.setBaseParam('templatetype',record.data.id);
                 gridstore.load({params:{start:0}});
                return true;
             }
        }
    });
    emailtypestore.load({params:{start:0}});

     gridstore = new Ext.data.JsonStore({
            id: "gridstore",
            root: 'templates',
            totalProperty: 'totalcount',
            idProperty: 'templateId',
            remoteSort: true,
            baseParams: {
            filter: ""
        },
        fields: [
                'templateId','templateName','templateDescription','templateCanDelete','templateType','templateTypeName','templateRuleNames','templateNumberOfRules'],
        // load using script tags for cross domain, if the data in on the same domain as
        // this page, an HttpProxy would be better
        proxy: new Ext.data.HttpProxy({
                method: 'GET',
                url: 'index.php?fuse=admin&action=Admin_GetEmailTemplates'
        })
    });
    gridstore.on("load",function(){
        toggleButtons(0);
        if(gridstore.baseParams.templatetype==1){
            colindex = grid.getColumnModel().getIndexById('rulecol');
            grid.getColumnModel().setHidden(colindex,false);
        }else{
            colindex = grid.getColumnModel().getIndexById('rulecol');
            grid.getColumnModel().setHidden(colindex,true);
        }
    });
    gridstore.setDefaultSort('templateId', 'asc');
    gridstore.setBaseParam('templatetype',7);

    var sm = new Ext.grid.CheckboxSelectionModel({
        id:'emails-sm',
        width: 30,
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              }
        }
    });

    function renderName(value,p,record){
        tooltip = "<b>Description</b>: "+record.data.templateDescription;
        name = '<a href="javascript:ShowEditEmail('+record.data.templateId+');" title="'+tooltip+'">'+record.data.templateName+'</a>';
        return name;
    }
    function renderRuleInfo(value,p,record){
        tooltip = "<b>Description</b>: "+record.data.templateRuleNames;
        name = '<span ext:qwidth="200" qtip="'+tooltip+'">'+record.data.templateNumberOfRules+'</span>';
        return name;
    }

    var grid = new Ext.grid.GridPanel({
        id: 'emails-grid',
        el: 'emails-grid',
        autoHeight:true,
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        autoExpandColumn: 'name',
        loadMask: true,
        viewConfig: {
            enableRowBody:true,
            scrollOffset:1,
            emptyText: lang("There are no templates available to view at this time")
        },
        autoExpandColumn: "name",
        // grid columns
        columns:[
        sm,{
            id: 'name',
            header: lang("Name"),
            renderer: renderName,
            dataIndex : "templateName",
            sortable: false
        },{
            id: 'rulecol',
            header: lang("# of Rule"),
            width: 100,
            hidden:true,
            align:'center',
            dataIndex : "templateNumberOfRules",
            renderer: renderRuleInfo,
            sortable: false
        },
        {
            id: 'type',
            header: lang("Type"),
            width: 160,
            align:'center',
            dataIndex : "templateTypeName",
            sortable: false
        }

        ],
        stripeRows: true,
        sm: sm,
        // inline buttons
        buttons:[deletebutton = new Ext.Button({
                     id:'actionbuttons',
                     autoHeight:true,
                     xtype:'button',
                     text:'Delete',
                     disabled: true,
                     onClick: function(record){
                            if(!deletebutton.disabled){
                                ProcessAction("delete");
                            }
                        }
                     })
                ],
        buttonAlign:'left'

    });

    // render it
    grid.render();

	//check to see if I'm looking at archived or active coupons.
    gridstore.setBaseParam('limit', 50);
    gridstore.load({params:{start:0}});

    function ProcessAction(action){
        switch(action){
            case "delete":
                requesturl = "index.php?fuse=admin&action=Admin_DeleteEmailTemplate";
                break;
            default:
                return;
        }
        
        var rows = sm.getSelections();
        var defaultTemps = false;
        var otherTemps = false;
        for(x=0;x<rows.length;x++){
            var type = rows[x].data.templateType;
            if(type != 1 && type != 2 && type != 8){
               defaultTemps = true;
            }else{
                otherTemps = true;
            }
        }
        if(defaultTemps == true){
            Ext.MessageBox.alert(lang("Warning"),lang("Sorry! You can not delete default templates."));
        }
        if(otherTemps == false){
            grid.enable()
            gridstore.load();
            return;
        }
        grid.disable();
        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                        //refreshgrid
                        grid.enable();
                        gridstore.load();
                        msg("E-Mail template(s) deleted");
                    },
           failure: function() {
                grid.enable();
           },
           params: { ids: Ext.util.JSON.encode(GetSelectedRowIds())}
        });
    }

    function GetSelectedRowIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
	    for(x=0;x<rows.length;x++){
	       arrayofids[x] = rows[x].data.templateId;
	    }
	    return arrayofids;
    }

    // option button code
    function toggleButtons(count){
        if(count == undefined){
            count = sm.getCount();
        }
        if(count>0){
            deletebutton.setDisabled(false);
            //archivebutton.setDisabled(false);
        }else{
            deletebutton.setDisabled(true);
            //archivebutton.setDisabled(true);
        }
    }

});