Ext.onReady(function(){
    //store for customer notes grid
    var accounts_gridstore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: 'index.php?fuse=clients&action=Admin_GetClientAlternateAccounts'}),
        reader: new Ext.data.JsonReader({
            root: 'results',
            totalProperty: 'totalcount',
            id: 'id'
        }, [
            {name: 'id'},
            {name: 'email'},
            {name: 'sendnotifications'},
            {name: 'sendinvoice'},
            {name: 'sendsupport'}
        ]),
        listeners:{
         'load': function(){
            toggleButtons();
         }
        }
    });
    accounts_gridstore.setDefaultSort('email', 'asc');

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

    function renderEmail(value,p,record){
        //make description part of the popup
        if(caneditadditionalaccounts){
            name = '<a href="javascript:ShowEditAccountsWindow('+record.data.id+');" id="'+record.data.id+'" class="editbillingtype" qtip="'+lang('Click to edit this additional account')+'">'+record.data.email+'</a>';
        }else{
            name = record.data.name;
        }
        return name;
    }

    var grid1 = new Ext.grid.GridPanel({
        id :'accountsgrid',
        store: accounts_gridstore,
        disableSelection:true,
        trackMouseOver:false,
        loadMask: true,
        cm: new Ext.grid.ColumnModel({
            defaults: {
                width: 20,
                sortable: true
            },
            columns: [
                sm,
                {
                 header: lang("E-Mail"),
                 width:50,
                 dataIndex: 'email',
                 renderer: renderEmail
                 },
                {header: lang("Notifications?"), width:25, align:'center',dataIndex:'sendnotifications'},
                {header: lang("Invoices?"), width:15, align:'center',dataIndex:'sendinvoice'},
                {header: lang("Support?"), width:15, align:'center',dataIndex:'sendsupport'}
            ]
        }),
        sm: sm,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no notes available"),
            scrollOffset:1
        },
        columnLines: true,
        autoHeight:true,
        // inline buttons
        buttons: [deletebutton = new Ext.Button({
                     id:'deletebutton',
                     text:lang('Delete'),
                     disabled: true,
                     handler: function(){
                         PerformActionOnAccounts("index.php?fuse=clients&action=Admin_DeleteAlternateAccounts");
                     }
                 })
             ],
        buttonAlign:'left',
        animCollapse: false,
        title: '',
        iconCls: 'icon-grid',
        renderTo: 'accounts'
    });
    accounts_gridstore.load({params:{start:0}});

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

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

    function PerformActionOnAccounts(requesturl){
        grid1.disable();
        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                //refreshgrid
                grid1.enable();
                accounts_gridstore.load({params:{start:0}});

                var data = Ext.util.JSON.decode(xhr.responseText);
                if(data.error){
                    //we do not need to repopulate the filters if there was a validation error
                   msg(lang("There was an error performing this action"),"");
                }else if(data.message){
                    msg(data.message,"");
                }else{
                    msg(lang("Action on Accounts(s) have been performed"),"");
                }
           },
           failure: function() {
                grid1.enable();
                Ext.Msg.alert("Fail");
           },
           params: {ids: Ext.util.JSON.encode(GetSelectedRowIds())

            }
        });
    }

    var btAddAccount = new Ext.Button({
        id:"addaccount",
        renderTo:"addaccountbutton",
        text: lang('Add Account'),
        iconAlign: 'left',
        handler:function(){
            AccountsWin.CreateWindow(false,0);
            //simpleForm.getForm().reset();
        }
    })

});