/*!
 * Ext JS Library 3.0.0
 * Copyright(c) 2006-2009 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */

var notes_gridstore;

Ext.onReady(function(){

    var isviewingarchivednotes=0;

    var expander = new Ext.ux.grid.RowExpander({
        tpl : new Ext.Template(
            '<p style="padding-top:0px;padding-left:22px;">',
            '<br/><b>'+lang('Associated to Ticket Type')+':</b> <b>&nbsp;&nbsp;{tickettype}&nbsp;&nbsp;</b>',
            '<br/><br/><b>'+lang('Note')+':</b> {desc}</p>'
        )
    });
    
    //store for customer notes grid
        notes_gridstore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: 'index.php?fuse=clients&action=adminGetClientNotes'}),
        reader: new Ext.data.JsonReader({
            root: 'results',
            totalProperty: 'totalcount',
            id: 'id'
        }, [
            {name: 'id'},
            {name: 'staff'},
            {name: 'tickettype'},
            {name: 'datesubmitted'},
            {name: 'visablebycustomer'},
            {name: 'tickettype'},
            {name: 'desc'}
        ]),
        listeners:{
         'load': function(){
            toggleButtons();
         }
        }
    });
    notes_gridstore.setDefaultSort('datesubmitted', 'asc');
    notes_gridstore.setBaseParam('archived', 0);

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

    var grid1 = new Ext.grid.GridPanel({
        store: notes_gridstore,
        disableSelection:true,
        trackMouseOver:false,
        loadMask: true,
        cm: new Ext.grid.ColumnModel({
            defaults: {
                width: 20,
                sortable: true
            },
            columns: [
                expander,
                sm,
                {header: lang("Date Submitted"), width:20,dataIndex: 'datesubmitted'},
                {header: lang("Entered By"), width:50,dataIndex: 'staff'},
                {header: lang("Visible By Customer?"), width:25, align:'center',dataIndex:'visablebycustomer'},
                {header: lang("Ticket Type"), width:15, align:'center',dataIndex:'tickettype'}
            ]
        }),
        sm: sm,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no notes available"),
            scrollOffset:1
        },
        columnLines: true,
        autoHeight:true,
        plugins: expander,
        // inline buttons
        buttons: [deletebutton = new Ext.Button({
                     id:'deletebutton',
                     text:lang('Delete'),
                     disabled: true,
                     handler: function(){
                         PerformActionOnNote("index.php?fuse=clients&action=deleteClientNote");
                     }
                 }),
                 archivebutton = new Ext.Button({
                     id:'archivebutton',
                     text:lang('Archive'),
                     disabled: true,
                     handler:function(){
                         PerformActionOnNote("index.php?fuse=clients&action=archiveClientNotes");
                     }
                 })
             ],
        buttonAlign:'left',
        animCollapse: false,
        title: '',
        iconCls: 'icon-grid',
        renderTo: 'notes'
    });
    notes_gridstore.load({params:{start:0}});

    var filtercombo = new Ext.form.ComboBox({
        typeAhead: false,
        editable:false,
        triggerAction: 'all',
        transform:'archivednotesfilter',
        width:135,
        forceSelection:true,
        listeners:{
         'select': function(cb,record){
            notes_gridstore.setBaseParam('archived', record.data.value);
            if(record.data.value==0){
                isviewingarchivednotes = 0;
                archivebutton.setText(lang('Archive'));
            }else{
                isviewingarchivednotes = 1;
                archivebutton.setText(lang('Un-Archive'));
            }
            notes_gridstore.load({params:{start:0}});
         }
        }
    });



    // option button code
    function toggleButtons(count){
        if(sm.getCount()>0){
            deletebutton.setDisabled(false);
            archivebutton.setDisabled(false);
        }else{
            deletebutton.setDisabled(true);
            archivebutton.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 PerformActionOnNote(requesturl){
        grid1.disable();
        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                    //refreshgrid
                    grid1.enable();
                    notes_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 Note(s) have been performed"));
                    }
            },
           failure: function() {
                grid1.enable();
                Ext.Msg.alert("Fail");
           },
           params: { isviewingarchived: isviewingarchivednotes,
                     ids: Ext.util.JSON.encode(GetSelectedRowIds())
                     
            }
        });
    }


    //only show if we have group notes
    //if(hasgroupnotes){
        var groupnoteexpander = new Ext.ux.grid.RowExpander({
            tpl : new Ext.Template(
                '<p style="padding-top:0px;padding-left:8px;">',
                '<br/><b>'+lang('Associated to Group')+':</b> <b>&nbsp;&nbsp;{group}&nbsp;&nbsp;</b>',
                '<br/><b>'+lang('Associated to Ticket Type')+':</b> <b>&nbsp;&nbsp;{tickettype}&nbsp;&nbsp;</b>',
                '<br/><br/><b>'+lang('Note')+':</b> {desc}</p>'
            )
        });

        //store for group notes grid
        var gridgroupstore = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url: 'index.php?fuse=clients&action=adminGetGroupNotes'}),
            reader: new Ext.data.JsonReader({
                root: 'results',
                totalProperty: 'totalcount',
                id: 'id'
            }, [
                {name: 'id'},
                {name: 'staff'},
                {name: 'tickettype'},
                {name: 'group'},
                {name: 'datesubmitted'},
                {name: 'visablebycustomer'},
                {name: 'tickettype'},
                {name: 'desc'}
            ])
        });
        gridgroupstore.setDefaultSort('datesubmitted', 'asc');

        var grid2 = new Ext.grid.GridPanel({
            store: gridgroupstore,
            disableSelection:true,
            trackMouseOver:false,
            loadMask: true,
            cm: new Ext.grid.ColumnModel({
                defaults: {
                    width: 20,
                    sortable: true
                },
                columns: [
                    groupnoteexpander,
                    {header: lang("Date Submitted"), width:20,dataIndex: 'datesubmitted'},
                    {header: lang("Entered By"), width:50,dataIndex: 'staff'},
                    {header: lang("Group"), align:'center',dataIndex:'group'},
                    {header: lang("Visable By Customer?"), width:25, align:'center',dataIndex:'visablebycustomer'},
                    {header: lang("Ticket Type"), width:15, align:'center',dataIndex:'tickettype'}
                ]
            }),
            viewConfig: {
                forceFit:true,
                enableRowBody:true,
                scrollOffset:1
            },
            columnLines: true,
            autoHeight:true,
            plugins: groupnoteexpander,
            collapsible: true,
            animCollapse: false,
            title: '',
            iconCls: 'icon-grid',
            renderTo: 'groupnotes'
        });

    
        gridgroupstore.load({params:{start:0}});
    //}

    if ($('#addnotebutton')) {
        var btAddNote = new Ext.Button({
            id:"addnote",
            renderTo:"addnotebutton",
            text: lang('Add Note'),
            iconAlign: 'left',
            handler:function(){
                 ce.addNote();
            }

        })
    }



});