var ticketTypeId = -1;

Ext.onReady(function(){

    // Handle the Add Ticket Type Button
    new Ext.Button({
        id:"addTicketType",
        renderTo:"addtickettype",
        text: lang('Add Ticket Type'),
        iconAlign: 'left',
        disabled : (!canedittickettypes) ? true : false,
        handler:function(){
            addTicketType();
        }
    });
    

    // Function to process the window request
    function TicketTypeWindow(update){
        if(this instanceof TicketTypeWindow){
            //this.update = update;
            this.CreateWindow = createWindow;
            this.LoadFields = loadFields;
            this.SetForNewEntry = setForNewEntry;
        }else{
            return new TicketTypeWindow();
        }
    }
    TicketTypeWin = new TicketTypeWindow();


    // Set the window options & decide if we are adding or editing
    function createWindow(update, id, winheight) {
        if (update) {
            buttonText = lang('Update');
            titleText = '&nbsp;&nbsp;'+lang('Edit Ticket Type');
            ticketTypeId = id;
            requesturl = 'index.php?fuse=support&action=UpdateTicketType';

        } else {
            buttonText = lang('Save');
            titleText = '&nbsp;&nbsp;'+lang('Add Ticket Type');
            ticketTypeId = id;
            requesturl = 'index.php?fuse=support&action=AddTicketType';
        }

        // Load the info for the dropdown
        var groupstore = new Ext.data.JsonStore({
            id: "groupstore",
            root: 'groups',
            totalProperty: 'totalcount',
            idProperty: 'id',
            remoteSort: true,
            baseParams: {
                filter: "",
                customerid: "0"
            },
            fields: ['assigneeId','assigneeLabel',
            {
                name :"indentClass",
                type: 'string',
                mapping: 'indentClass'
            }
            ],
            proxy: new Ext.data.HttpProxy({
                url: 'index.php?fuse=support&action=GetDepartmentList&getDepartmentsWithMembers=1&additionalOptions=1'
            })
        });
        groupstore.setDefaultSort('id', 'asc');
        groupstore.on('load',function(){

            if (TicketTypeWin.update==null || TicketTypeWin.update==false) {
                clientFieldGroup.setValue('Leave unassigned');
            }
        });

        // Custom rendering Template
        var resultTpl = new Ext.XTemplate(
            '<tpl for="."><div class="combo-value {indentClass}"><span>{assigneeLabel}</span></div></tpl>'
            );

        // Create the dropdown
        clientFieldGroup = new Ext.form.ComboBox({
            name: 'deptid_staffid1',
            typeAhead: true,
            triggerAction: 'all',
            /*lazyRender:true,*/
            mode: 'local',
            validationEvent:false,
            fieldLabel: lang("Default Assignee"),
            /*labelStyle: 'font-weight:bold;font-size:11px;',*/
            /*anchor:     '100%',*/
            store: groupstore,
            valueField: 'assigneeId',
            hiddenName : 'deptid_staffid',
            displayField: 'assigneeLabel',
            /*displayField: 'groupname',*/
            allowBlank: false,
            blankText:  lang("This field is required"),
            forceSelection: true,
            editable: false,
            iconCls: 'no-icon',
            tpl: resultTpl,
            labelStyle: "font-weight: bold;",
            itemSelector: 'div.combo-value'


        });

        // Load the groupstore
        groupstore.load();

        // Create the form
        simpleForm = new Ext.FormPanel({
            /*labelWidth: 75,*/ // label settings here cascade unless overridden
            frame:true,
            border:false,
            bodyStyle:'padding:8px 8px 8px 8px',
            labelStyle: "font-weight: bold;",
            items: [{
                xtype:'fieldset',
                id: "cantDeleteFieldset",
                title: '',
                autoHeight:true,
                defaults: {
                    width: 240
                },
                defaultType: 'textfield',
                labelAlign: 'top',
                items :
                [
                {
                    text: 'Notice: You must reassign all tickets and routing rules with this ticket type to another ticket type before deleting this ticket type.',
                    name: 'cantDelete',
                    xtype: "label",
                    style: "font-weight: bold;"
                }
                ]
                },{
                xtype:'fieldset',
                title: '',
                defaults: {
                    width: 240
                },
                defaultType: 'textfield',
                labelAlign: 'top',
                items :[{
                    fieldLabel: 'Id',
                    name: 'id',
                    xtype: "hidden"
                },{
                    id: 'enable_delete',
                    name: 'enable_delete',
                    xtype: "hidden"
                },{
                    fieldLabel: 'Name',
                    id: 'name',
                    name: 'name',
                    selectOnFocus: true,
                    labelStyle: "font-weight: bold;",
                    allowBlank:false
                },{
                    xtype: "textarea",
                    fieldLabel: 'Description',
                    id: 'description',
                    name: 'description',
                    selectOnFocus: true,
                    labelStyle: "font-weight: bold;",
                    height: 110
                },clientFieldGroup
                ]
            }, {
                xtype:'fieldset',
                title: '',
                autoHeight:true,
                defaults: {
                    width: 240
                },
                defaultType: "checkbox",
                columns: 2,
                hideLabel: true,
                items :[{
                    boxLabel: 'Enabled',
                    id: 'enabled1',
                    name: 'enabled',
                    xtype: "checkbox" ,
                    labelStyle: "font-weight: bold;",
                    hideLabel: true,
                    checked: false
                },{
                    boxLabel: 'Enabled in the public section',
                    id: 'enabled_public1',
                    name: 'enabled_public',
                    xtype: "checkbox",
                    labelStyle: "font-weight: bold;",
                    hideLabel: true,
                    checked: false
                },{
                    boxLabel: 'Associate to billing events',
                    id: 'is_billing_type1',
                    name: 'is_billing_type',
                    xtype: "checkbox",
                    labelStyle: "font-weight: bold;",
                    hideLabel: true,
                    checked: false
                }
                ]
            }]
        });

        // Create the window
        win = new Ext.Window({
            layout:'fit',
            title:titleText,
            width:310,
            y:25,
            height:winheight,
            modal:true,
            closeAction:'hide',
            plain: true,
            items: [simpleForm],
            buttons:
            [
            {
                text: 'Close',
                handler: function()
                {
                    win.hide();
                }
            },
            {
                id: 'deleteButton',
                text: 'Delete',
                hidden: true,
                onClick: function(record)
                {
                    requesturl = "index.php?fuse=support&action=DeleteTicketType&ticketTypeId=" + ticketTypeId;
                    Ext.Msg.show ({
                        title : "Delete?" ,
                        msg: "Are you sure you want to delete this ticket type?",
                        buttons: Ext.Msg.YESNO,
                        fn: function(btn, text)
                        {
                            if (btn == 'yes')
                            {
                                DeleteTicketType(requesturl);
                            }
                        },
                        icon: Ext.MessageBox.QUESTION

                    })
                }
            }],
            listeners: {
                hide: function() {
                    simpleForm.destroy();
                }
            }
        });

        // Add the Save button
        win.addButton(buttonText, function(){
            simpleForm.getForm().submit({
                clientValidation: true,
                url: requesturl,
                success: function(form, action) {
                    win.hide();
                    tickettypes.gridstore.load();
                },
                failure: function(form, action) {
                    switch (action.failureType) {
                        case Ext.form.Action.CLIENT_INVALID:
                            Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                            break;
                        case Ext.form.Action.CONNECT_FAILURE:
                            Ext.Msg.alert('Failure', 'Ajax communication failed');
                            break;
                        case Ext.form.Action.SERVER_INVALID:
                            Ext.Msg.alert('Failure', action.result.msg);
                    }
                }
            });
        });

        // Show the window
        win.show(this);

    }

    // Function to load the fields
    function loadFields(id){

        // Make the on load function
        simpleForm.getForm().load({
            waitMsg:lang('Loading'),
            url: 'index.php?fuse=support&action=GetTicketTypes&id=' + id,
            timeout: 60,
            success: function(form, action) {
                
            },
            failure: function(form, action) {
                Ext.Msg.alert("Failed to retrieve registrar data", action.result.errorMessage);
            }
        });
    }

    // Not sure what this does yet
    function setForNewEntry(){
    }
});

// Function to load the Edit Ticket Type Window
function editTicketType(id, candelete)
{
    // Calculate the height
    if(candelete) {
        var winheight = '470';
    } else {
        var winheight = '560';
    }

    // Create the window
    TicketTypeWin.CreateWindow(true,id, winheight);

    // Hide the revelevant Options
    if(candelete) {
        Ext.getCmp('cantDeleteFieldset').hide();
        Ext.getCmp('deleteButton').show();
    }

    // Load the fields
    TicketTypeWin.LoadFields(id);
}

// Function to load the Add Ticket Type Window
function addTicketType()
{
    // Create the window
    TicketTypeWin.CreateWindow(false, '-1', '470');

    // Hide the warning message
    Ext.getCmp('cantDeleteFieldset').hide();

    // Set for new entry
    TicketTypeWin.SetForNewEntry();

}

// Function to process the deletion
function DeleteTicketType(requesturl){

    simpleForm.getForm().submit({
        clientValidation: true,
        url: requesturl,
        params: {
            newStatus: 'Deleted'
        },
        waitMsg:'Deleting',
        success: function(form, action) {
            win.hide();
            tickettypes.gridstore.load();
        },
        failure: function(form, action) {
            switch (action.failureType) {
                case Ext.form.Action.CLIENT_INVALID:
                    Ext.Msg.alert('Failure', 'Unable to delete the ticket type.');
                    break;
                case Ext.form.Action.CONNECT_FAILURE:
                    Ext.Msg.alert('Failure', 'Ajax communication failed');
                    break;
                case Ext.form.Action.SERVER_INVALID:
                    Ext.Msg.alert('Failure', action.result.msg);
            }
        }
    })
}