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

var getCurrentEscalationRule;

var escalationWin;
var escalationFieldEscalationId;
var escalationFieldName;
var escalationFieldAssignedDepartments;
var escalationFieldTimeElapsed;
var escalationFieldTicketStatus;
var escalationFieldTicketPriority;
var escalationFieldNewTag;
var escalationFieldNewPriority;
var escalationFieldReassign;
var escalationFieldOnlyApplyOnce;
var escalationFieldTranscriptionDestinataries;

Ext.onReady(function(){
    
    var defaultWidth = 180;
    
// escalationId
    escalationFieldEscalationId = new Ext.form.Hidden({
        id:               'escalationFieldEscalationId',
        name:             'escalationFieldEscalationId',
        value:            0,
        validationEvent:  false
    });
    
//  name
    escalationFieldName = new Ext.form.TextField({
        id:               'escalationFieldName',
        name:             'escalationFieldName',
        fieldLabel:       lang("Escalation Name"),
        validationEvent:  false,
        anchor:           '100%',
        border:           false,
        value:            '',
        allowBlank:       true
    });
    
//  assignedDepartments[]
    var departmentstore = new Ext.data.JsonStore({
        id:             "departmentstore",
        root:           'groups', //'departments',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
                            filter: "",
                            customerid: "0"
                        },
        fields:         [
                            'departmentId',
                            'departmentName'
                        ],
        proxy:          new Ext.data.HttpProxy({
                            url:  'index.php?fuse=support&action=GetDepartmentList'
                        })
    });
    
    departmentstore.setDefaultSort('id', 'asc');
    
    departmentstore.load();
    
    escalationFieldAssignedDepartments = new Ext.ux.form.LovCombo({
        id:               'escalationFieldAssignedDepartments',
        name:             'escalationFieldAssignedDepartments',
        fieldLabel:       lang("Assigned to departments"),
        validationEvent:  false,
        width:            defaultWidth,
        hideOnSelect:     true,
        //hidden :          true,
        maxHeight:        200,
        //allowBlank:       false,
        store:            departmentstore,
        valueField:       'departmentId',
        displayField:     'departmentName',
        value:            '',
        triggerAction:    'all',
        mode:             'local',
        beforeBlur:       Ext.emptyFn
    });
    
//  timeElapsed
    escalationFieldTimeElapsed = new Ext.form.TextField({
        id:               'escalationFieldTimeElapsed',
        name:             'escalationFieldTimeElapsed',
        fieldLabel:       lang("Time elapsed since last reply") + ' (' + lang("Hours") + ')',
        validationEvent:  false,
        width:            defaultWidth,
        border:           false,
        value:            '',
        allowBlank:       true
    });
    
//  ticketStatus
    escalationFieldTicketStatus = new Ext.form.ComboBox({
        id:               'escalationFieldTicketStatus',
        name:             'escalationFieldTicketStatus',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Ticket status"),
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'ticketstatusname'
                                        ],
                              data:     [
                                            [
                                                1,
                                                lang("Open")
                                            ],
                                            [
                                                2,
                                                lang("Waiting on tech")
                                            ],
                                            [
                                                3,
                                                lang("Waiting on customer")
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'ticketstatusname',
        value:            1,
        hiddenId:         'escalationFieldTicketStatusValue',
        hiddenName:       'escalationFieldTicketStatusValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
//  ticketPriority[]
    escalationFieldTicketPriority = new Ext.ux.form.LovCombo({
        id:               'escalationFieldTicketPriority',
        name:             'escalationFieldTicketPriority',
        fieldLabel:       lang("Tickets of priority"),
        validationEvent:  false,
        width:            defaultWidth,
        hideOnSelect:     true,
        //hidden :          true,
        maxHeight:        200,
        allowBlank:       false,
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'ticketpriorityname'
                                        ],
                              data:     [
                                            [
                                                1,
                                                lang("High")
                                            ],
                                            [
                                                2,
                                                lang("Medium")
                                            ],
                                            [
                                                4,
                                                lang("Low")
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'ticketpriorityname',
        value:            '',
        triggerAction:    'all',
        mode:             'local',
        beforeBlur:       Ext.emptyFn
    });
    
//  newTag
    escalationFieldNewTag = new Ext.form.ComboBox({
        id:               'escalationFieldNewTag',
        name:             'escalationFieldNewTag',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Change Ticket Tag"),
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'tagname'
                                        ],
                              data:     [
                                            [
                                                '',
                                                lang("Don't change")
                                            ],
                                            [
                                                'clear',
                                                lang("Clear")
                                            ],
                                            [
                                                'red',
                                                lang("Red")
                                            ],
                                            [
                                                'green',
                                                lang("Green")
                                            ],
                                            [
                                                'blue',
                                                lang("Blue")
                                            ],
                                            [
                                                'yellow',
                                                lang("Yellow")
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'tagname',
        value:            '',
        hiddenId:         'escalationFieldNewTagValue',
        hiddenName:       'escalationFieldNewTagValue',
        forceSelection:   true,
        editable:         false
    });
    
//  newPriority
    escalationFieldNewPriority = new Ext.form.ComboBox({
        id:               'escalationFieldNewPriority',
        name:             'escalationFieldNewPriority',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Change Priority"),
        store:            new Ext.data.ArrayStore({
                              idIndex:  0,
                              fields:   [
                                            'id',
                                            'ticketpriorityname'
                                        ],
                              data:     [
                                            [
                                                0,
                                                lang("Don't change")
                                            ],
                                            [
                                                1,
                                                lang("High")
                                            ],
                                            [
                                                2,
                                                lang("Medium")
                                            ],
                                            [
                                                4,
                                                lang("Low")
                                            ]
                                        ]
                          }),
        valueField:       'id',
        displayField:     'ticketpriorityname',
        value:            0,
        hiddenId:         'escalationFieldNewPriorityValue',
        hiddenName:       'escalationFieldNewPriorityValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
//  reassign
    var staffstore = new Ext.data.JsonStore({
        id:             "staffstore",
        root:           'groups', //'staff',
        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=2'
                        })
    });
    
    staffstore.setDefaultSort('id', 'asc');
    
    staffstore.load();
    
    // Custom rendering Template
    var resultTpl = new Ext.XTemplate(
        '<tpl for="."><div class="combo-value {indentClass}"><span>{assigneeLabel}</span></div></tpl>'
    );
    
    escalationFieldReassign = new Ext.form.ComboBox({
        id:               'escalationFieldReassign',
        name:             'escalationFieldReassign',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Reassign to"),
        store:            staffstore,
        valueField:       'assigneeId',
        displayField:     'assigneeLabel',
        value:            'dep_0_staff_0',
        hiddenId:         'escalationFieldReassignValue',
        hiddenName:       'escalationFieldReassignValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false,
        tpl:              resultTpl,
        itemSelector:     'div.combo-value'
    });
    
//  onlyApplyOnce
    var helpOnlyApplyOnce = lang('Tick if you wish that, after a ticket is escalated by this rule, it doesn\'t get escalated again later by this same rule.<br />\nIt will be able to be escalated by this rule again only after the assignee, status or priority have changed.');
    
    escalationFieldOnlyApplyOnce = new Ext.form.Checkbox({
        id:               'escalationFieldOnlyApplyOnce',
        name:             'escalationFieldOnlyApplyOnce',
        value:            true,
        validationEvent:  false,
        hideLabel:        true,
        //boxLabel :        lang('Only apply once') + " <img class='tip-target' src='../templates/admin/images/information-button.png' qtip='" + helpOnlyApplyOnce.replace(/'/g, "&#39;") + "'/>"
        boxLabel :        "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpOnlyApplyOnce.replace(/'/g, "&#39;") + "'>" + lang('Only apply once') + "</span>"
    });
    
//  transcriptionDestinataries
    var helpTranscriptionDestinataries = lang('Enter one E-mail per line.');
    
    escalationFieldTranscriptionDestinataries = new Ext.form.TextArea({
        id:               'escalationFieldTranscriptionDestinataries',
        name:             'escalationFieldTranscriptionDestinataries',
        //fieldLabel:       lang("Send Transcription To") + " <img class='tip-target' src='../templates/admin/images/information-button.png' qtip='" + helpTranscriptionDestinataries.replace(/'/g, "&#39;") + "'/>",
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpTranscriptionDestinataries.replace(/'/g, "&#39;") + "'>" + lang("Send Transcription To") + "</span>",
        border:           false,
        validationEvent:  false,
        anchor:           '100%',
        height:           140,
        value:            ''
    });
    
// tabed form
    var simpleForm = new Ext.FormPanel({
        labelAlign:   'top',
        frame:        true,
        hideBorders:  true,
        shadow:       false,
        floating:     false,
        autoHeight:   true,
        title:        '',
        bodyStyle:    'padding:5px 5px 0',
        width:        600,
        items:        [
                          {
                              layout: 'column',
                              border: false,
                              items:  [
                                          {
                                              columnWidth:  1,
                                              layout:       'form',
                                              border:       false,
                                              items:        [
                                                                escalationFieldEscalationId,
                                                                escalationFieldName
                                                            ]
                                          }
                                      ]
                          },
                          {
                              id:             'escalationTabPanels',
                              xtype:          'tabpanel',
                              plain:          true,
                              activeTab:      'tabPanelConditions',
                              //deferredRender: false,
                              height:         210,
                              defaults:       {bodyStyle:'padding:10px; background-color:WhiteSmoke'},
                              items:          [
                                                  {
                                                      id:     'tabPanelConditions',
                                                      title:  lang("Conditions"),
                                                      layout: 'form',
                                                      items:  [
                                                                  {
                                                                      layout: 'column',
                                                                      border: false,
                                                                      items:  [
                                                                                  {
                                                                                      columnWidth:  .5,
                                                                                      layout:       'form',
                                                                                      border:       false,
                                                                                      items:        [
                                                                                                        escalationFieldTimeElapsed,
                                                                                                        escalationFieldAssignedDepartments
                                                                                                    ]
                                                                                  },
                                                                                  {
                                                                                      columnWidth:  .5,
                                                                                      layout:       'form',
                                                                                      border:       false,
                                                                                      items:        [
                                                                                                        escalationFieldTicketStatus,
                                                                                                        escalationFieldTicketPriority
                                                                                                    ]
                                                                                  }
                                                                              ]
                                                                  }
                                                              ]
                                                  },
                                                  {
                                                      id:     'tabPanelAppearanceActions',
                                                      title:  lang("Appearance Actions"),
                                                      layout: 'form',
                                                      items:  [
                                                                  escalationFieldNewTag
                                                              ]
                                                  },
                                                  {
                                                      id:     'tabPanelEscalationActions',
                                                      title:  lang("Escalation Actions"),
                                                      layout: 'form',
                                                      items:  [
                                                                  escalationFieldNewPriority,
                                                                  escalationFieldReassign,
                                                                  escalationFieldOnlyApplyOnce
                                                              ]
                                                  },
                                                  {
                                                      id:     'tabPanelNotificationActions',
                                                      title:  lang("Notification Actions"),
                                                      layout: 'form',
                                                      items:  [
                                                                  escalationFieldTranscriptionDestinataries
                                                              ]
                                                  }
                                              ]
                          }
                      ]
    });
    
    //simpleForm.render(document.body);
    
// Window
    escalationWin = new Ext.Window({
        id:           "escalationWindow",
        y:            25,
        layout:       'fit',
        width:        480,
        autoHeight:   true,
        modal:        true,
        closeAction:  'hide',
        title:        lang("Add Escalation Rule"),
        plain:        true,
        shadow:       false,
        items:        [simpleForm],
        buttons:      [
                          {
                              text:     'Close',
                              handler:  function(){
                                            escalationWin.hide();
                                        }
                          },
                          {
                              id:       'btnDeleteEscalation',
                              text:     lang("Delete"),
                              hidden:   true,
                              onClick:  function(record){
                                            Ext.Msg.show({
                                                title:    "Delete?" ,
                                                msg:      "Are you sure you want to delete this escalation rule?",
                                                buttons:  Ext.Msg.YESNOCANCEL,
                                                fn:       function(btn, text){
                                                              if(btn == 'yes'){
                                                                  deleteEscalation();
                                                              }
                                                          },
                                                icon:     Ext.MessageBox.QUESTION
                                            })
                                        }
                          },
                          {
                              id:       'btnAddEscalation',
                              text:     lang("Save"),
                              disabled: false,
                              hidden:   false,
                              handler:  function(){
                                            sendEscalation();
                                        }
                          }
                      ]
    });
    
    getCurrentEscalationRule = function(action, id){
        var currentEscalationRule = new Ext.data.JsonStore({
            id:             "currentEscalationRule",
            root:           'escalationrule',
            totalProperty:  'totalcount',
            idProperty:     'id',
            remoteSort:     true,
            baseParams:     {
                                id: id
                            },
            fields:         [
                                'escalationId',
                                'name',
                                'assignedDepartments',
                                'timeElapsed',
                                'ticketStatus',
                                'ticketPriority',
                                'newTag',
                                'newPriority',
                                'reassign',
                                'onlyApplyOnce',
                                'transcriptionDestinataries'
                            ],
            proxy:          new Ext.data.HttpProxy({
                                url: 'index.php?fuse=support&action=GetEscalationRule'
                            })
        });
        
        currentEscalationRule.on('load',function(){
            record = currentEscalationRule.getAt(0);
            
            switch(action){
                case 'add':
                    escalationWin.setTitle(lang("Add Escalation Rule"));
                    Ext.getCmp('btnDeleteEscalation').hide();
                    break;
                case 'edit':
                    escalationWin.setTitle(lang("Edit Escalation Rule"));
                    Ext.getCmp('btnDeleteEscalation').show();
                    break;
            }
            
            escalationFieldEscalationId.reset();
            escalationFieldEscalationId.setValue(record.get('escalationId'));
            
            escalationFieldName.reset();
            escalationFieldName.setValue(record.get('name'));
            
            escalationFieldTimeElapsed.reset();
            escalationFieldTimeElapsed.setValue(record.get('timeElapsed'));
            
            escalationFieldTicketStatus.reset();
            escalationFieldTicketStatus.setValue(record.get('ticketStatus'));
            
            escalationFieldNewTag.reset();
            escalationFieldNewTag.setValue(record.get('newTag'));
            
            escalationFieldNewPriority.reset();
            escalationFieldNewPriority.setValue(record.get('newPriority'));
            
            escalationFieldReassign.reset();
            escalationFieldReassign.setValue(record.get('reassign'));
            
            escalationFieldOnlyApplyOnce.reset();
            escalationFieldOnlyApplyOnce.setValue(record.get('onlyApplyOnce'));
            
            escalationFieldTranscriptionDestinataries.reset();
            escalationFieldTranscriptionDestinataries.setValue(record.get('transcriptionDestinataries'));
            
            Ext.getCmp('escalationTabPanels').activate('tabPanelConditions');
            
            escalationWin.show();
            
            // NEED TO RESET THESE ONES AFTER SHOWING THE WINDOW, OR THE WINDOW FAILS
            escalationFieldAssignedDepartments.reset();
            escalationFieldAssignedDepartments.setValue(record.get('assignedDepartments'));
            
            escalationFieldTicketPriority.reset();
            escalationFieldTicketPriority.setValue(record.get('ticketPriority'));
            
            
            escalationFieldName.focus('',300);
        });
        
        currentEscalationRule.load();
    }
});

function addEscalationRule(){
    getCurrentEscalationRule('add', 0);
}

function editEscalationRule(id){
    getCurrentEscalationRule('edit', id);
}

function sendEscalation(){
    if(escalationFieldName.validate()
      && escalationFieldAssignedDepartments.validate()
      && escalationFieldTimeElapsed.validate()
      && escalationFieldTicketStatus.validate()
      && escalationFieldTicketPriority.validate()
      && escalationFieldNewTag.validate()
      && escalationFieldNewPriority.validate()
      && escalationFieldReassign.validate()
      && escalationFieldOnlyApplyOnce.validate()
      && escalationFieldTranscriptionDestinataries.validate()){

        Ext.Ajax.request({
           url: 'index.php?fuse=support&action=SaveEscalationRule',
           success: function(t) {
                onCompleteAction(t);
           },
           params: {escalationId:escalationFieldEscalationId.getValue(),
                   name:escalationFieldName.getValue(),
                   assignedDepartments:escalationFieldAssignedDepartments.getValue(),
                   timeElapsed:escalationFieldTimeElapsed.getValue(),
                   ticketStatus:escalationFieldTicketStatus.getValue(),
                   ticketPriority:escalationFieldTicketPriority.getValue(),
                   newTag:escalationFieldNewTag.getValue(),
                   newPriority:escalationFieldNewPriority.getValue(),
                   reassign:escalationFieldReassign.getValue(),
                   onlyApplyOnce:escalationFieldOnlyApplyOnce.getValue(),
                   transcriptionDestinataries:escalationFieldTranscriptionDestinataries.getValue()
                  }
        });

    }else{
        message = '';
        newline = "<br>";
        
        if(!escalationFieldName.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Escalation Name");
        }
        
        if(!escalationFieldAssignedDepartments.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Assigned to departments");
        }
        
        if(!escalationFieldTimeElapsed.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Time elapsed since last reply") + ' (' + lang("Hours") + ')';
        }
        
        if(!escalationFieldTicketStatus.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Ticket status");
        }
        
        if(!escalationFieldTicketPriority.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Tickets of priority");
        }
        
        if(!escalationFieldNewTag.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Change Ticket Tag");
        }
        
        if(!escalationFieldNewPriority.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Change Priority");
        }
        
        if(!escalationFieldReassign.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Reassign to");
        }
        
        if(!escalationFieldOnlyApplyOnce.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang('Only apply once');
        }
        
        if(!escalationFieldTranscriptionDestinataries.validate()){
            if(message != ''){
                message += newline;
            }
            
            message += lang("Send Transcription To");
        }
        
        if(message != ''){
            Ext.MessageBox.alert(lang("Errors"), lang("The following form field(s) were incomplete or incorrect") + ":<br><br>" + message + "<br><br>" + lang("Please complete or correct the form and submit again."));
            return;
        }
    }
}

function deleteEscalation(){

    Ext.Ajax.request({
       url: 'index.php?fuse=support&action=DeleteEscalationRule',
       success: function(t) {
            onCompleteAction(t);
       },
       params: {escalationId:escalationFieldEscalationId.getValue()}
    });

}

function onCompleteAction(responseObj){
    var data = Ext.util.JSON.decode(responseObj.responseText);
    if(data.error){
        if(data.message){
            Ext.MessageBox.alert(lang("Errors"), data.message);
        }else{
            Ext.MessageBox.alert(lang("Errors"), "There was an error performing this action");
        }
        return;
    }else if(data.message){
        msg(data.message);
    }else{
        msg(lang("Action have been performed"));
    }
    
    escalationWin.hide();

    //get the grid if there is one
    //if we are in the escalation rules view
    //if not then skip
    grid = Ext.getCmp("escalation-grid");
    if(grid!=null){
        grid.getStore().load({params:{start:0}});
        //toggleButtons(0);
    }
    //we might want to check to see if we are showing a dropdown
    //in the event we are creating an invoice
    //do that code here and update the dropdown
}