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

var staffNotes;
var notesWin;
var showtoClients;
var associatedWithTickets;
var ticketTypes;
var groupId ;
var groupName ;
var gridgroupstore;

//var lc;
function showGroupNotes(){
    staffNotes.reset();
    showtoClients.reset();
    associatedWithTickets.reset();
    ticketTypes.hide();
  //  ticketTypes.value = "";
    notesWin.show();
    notesWin.buttons[0].setDisabled(false);
    staffNotes.focus('',300);
}

function updateNotes(){
    if(staffNotes.getValue().trim() == ""){
        Ext.Msg.alert("Please fill the notes");
        return;
    }
    var ticketTypesArr = ticketTypes.getValue().split(",");
    var visibleClients = "false";
    if(showtoClients.getValue()){
        visibleClients = showtoClients.getValue();
    }
    Ext.Ajax.request({
       url: 'index.php?fuse=clients&action=saveClientNote',
       success: function(xhr) {
                    gridgroupstore.load({params:{start:0}});
                },
       failure: function() {
            Ext.Msg.alert("Fail");
       },
       params: {customerGroup : groupId.getValue(),
                noteContent : staffNotes.getValue(),
                visibleCustomer : visibleClients,
                //visibleCustomer : false,
                associateTicketTypes : associatedWithTickets.getValue(),
                encoded : true,
                ticketTypes : Ext.util.JSON.encode(ticketTypesArr)},
       method:'post'
    });
    showtoClients.reset();
    associatedWithTickets.reset();
   // ticketTypes.reset();
    notesWin.setTitle(lang("Add staff notes for")+" \""+groupName.getValue()+"\" ");
    notesWin.buttons[0].setDisabled(true);
    notesWin.hide();
}


Ext.onReady(function(){

    var isviewingarchivednotes=0;


    //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>'
            )
        });
        groupId = document.getElementById("groupId");
        groupName = document.getElementById("groupName");
        //store for group notes grid
        gridgroupstore = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url: 'index.php?fuse=admin&action=GetCustomerGroupNotes&groupId='+groupId.getValue()}),
            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 sm = new Ext.grid.CheckboxSelectionModel({
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              }
            }
        });

        

        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,
                    sm,
                    {header: lang("Date Submitted"), width:40,dataIndex: 'datesubmitted'},
                    {header: lang("Entered By"), width:40,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:55, align:'center',dataIndex:'tickettype'}
                ]
            }),
            sm: sm,
            viewConfig: {
                forceFit:true,
                enableRowBody:true,
                emptyText:lang("There are no customer groups for this user"),
                scrollOffset:1
            },
            columnLines: true,
            autoHeight:true,
            plugins: groupnoteexpander,
            collapsible: true,
            animCollapse: false,
            title: '',
            iconCls: 'icon-grid',
            renderTo: 'groupnotes',
            buttons: [deletebutton = new Ext.Button({
                     id:'deletebutton',
                     text:lang('Delete'),
                     disabled: true,
                     handler: function(){
                         PerformActionOnNote("index.php?fuse=clients&action=deleteClientNote");
                     }
                 })]
        });

        // option button code
        function toggleButtons(count){
            if(sm.getCount()>0){
                deletebutton.setDisabled(false);
            }else{
                deletebutton.setDisabled(true);
            }
        }
        gridgroupstore.load({params:{start:0}});
    //}
    
    gridgroupstore.on('load',function(){
        var data = gridgroupstore.reader.jsonData;
//        alert("count="+data.totalcount);
    });
    var btAddNote = new Ext.Button({
        id:"addnote",
        renderTo:"addnotebutton",
        text: lang('Add Note'),
        iconAlign: 'left',
        handler:function(){
            showGroupNotes()
        }

    })
    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){
        grid2.disable();
        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {

                        //refreshgrid
                        grid2.enable();
                        gridgroupstore.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: { ids: Ext.util.JSON.encode(GetSelectedRowIds())

            }
        });
    }

    //************************ADD NOTES POPUP****************************

    //staff notes
    staffNotes = new Ext.form.TextArea({
            id:         "ce-staffnotes",
            border:     false,
            hideLabel:  true,
            anchor:     '100%',
            height:150,
            width:480,
            name:       'ce-staffnotes'
    });

    showtoClients = new Ext.form.Checkbox({
                id: 'showToClients',
                fieldLabel: lang('Visible by customer'),
                boxLabel : lang('Visible by customer'),
                name: 'showToClients'
            });
            
    associatedWithTickets = new Ext.form.Checkbox({
                id: 'associatedWithTickets',
                fieldLabel: lang('associated with tickets'),
                boxLabel : lang('associated with tickets'),
                name: 'associatedWithTickets',
                listeners : {
                    check : function(){
                        if(associatedWithTickets.checked == true){
                            ticketTypes.show();
                            ticketTypes.addSelectAllItem = true;
                            ticketTypes.allSelected = false;
                        }else{
                            ticketTypes.hide();
                        }
                    }
                }
            });
    ticketTypeStore = new Ext.data.JsonStore( {
		storeId: 'comboSubstrate_store',
		root: 'groups',
		url: 'index.php?fuse=support&action=GetTicketTypeList&addAll=1',
		idProperty: 'ticketTypeId',
		fields:  [ 'ticketTypeId', 'ticketTypeName']
	});

    ticketTypes = new Ext.ux.form.LovCombo({
    	 id:'lovcombo',
         hideOnSelect:true,
         hidden : true,
         maxHeight:200,
         value: "ALL",
       store: ticketTypeStore
    
	,displayField:'ticketTypeName'
	,valueField:'ticketTypeId'
	,triggerAction:'all'
	,mode:'remote',
    beforeBlur : Ext.emptyFn
	});//ticketTypes.initComponent();
    notesWin = new Ext.Window({
        id: "notesWindow",
        width: 500,
        height:300,
        closeAction: 'hide',
        plain: true,
        title: lang(lang("Add staff notes for")+" \""+groupName.getValue()+"\" "),

        items : [staffNotes,
                showtoClients,
                associatedWithTickets,
                ticketTypes],
        buttons: [{
            text : 'Add',
            disabled:true,
            handler:function(){
                updateNotes();
                ticketTypes.setValue("");
            }
        },{
            text: 'Close',
            handler:function(){
                notesWin.setTitle(lang("Add staff notes for")+" \""+groupName.getValue()+"\" ");
                notesWin.buttons[0].setDisabled(true);
                notesWin.hide();
                ticketTypes.setValue("");
            }
        }]
    });
});

