var getCurrentRoutingRule;
var routingFieldTargetGroupsValidate;
var routingFieldTargetTypeValidate;
var defaultassignee;
var pipeCommand;

var routingWin;
var routingFieldRoutingId;
var routingFieldName;
var routingFieldRoutingType;
var routingFieldUserType;
var routingFieldTargetGroups;
var routingFieldTargetGroupsContainer;
var routingFieldAutoresponderTemplateId;
var routingFieldOpenTicket;
var routingFieldTargetPriority;
var routingFieldTargetPriorityContainer;
var routingFieldTargetPriorityFixed;
var routingFieldTargetPriorityFixedContainer;
var routingFieldTargetType;
var routingFieldTargetTypeContainer;
var routingFieldTargetTypeFixed;
var routingFieldTargetTypeFixedContainer;
var routingFieldAssignee;
var routingFieldAssigneeContainer;
var routingFieldAssigneeNotice;
var routingFieldCopyDestinataries;
var routingFieldPipingEmails;
var routingFieldRTNoticeEmailPipeForwarding;
var routingFieldRTEmailPipeForwardingContainer;
var routingFieldRTNoticeEmailPOP3Fetching;
var routingFieldPop3Hostname;
var routingFieldPop3Port;
var routingFieldPop3Emails;
var routingFieldPop3Username;
var routingFieldPop3Password;
var routingFieldPop3DeleteEmails;
var routingFieldRTEmailPOP3FetchingContainer;
var routingFieldRTNoticePublicSection;

var routingfilter = {};
var routingrule = {};

function addRoutingRule(){
    getCurrentRoutingRule('add', 0);
}

function editRoutingRule(id){
    getCurrentRoutingRule('edit', id);
}

function sendRouting(){
    if(routingFieldName.validate()
      && routingFieldRoutingType.validate()
      && routingFieldUserType.validate()
      && routingFieldTargetGroupsValidate() //&& routingFieldTargetGroups.validate()
      && routingFieldAutoresponderTemplateId.validate()
      && routingFieldOpenTicket.validate()
      && routingFieldTargetPriority.validate()
      && routingFieldTargetTypeValidate() //&& routingFieldTargetType.validate()
      && routingFieldAssignee.validate()
      && routingFieldCopyDestinataries.validate()
      && routingFieldPipingEmails.validate()
      && routingFieldPop3Hostname.validate()
      && routingFieldPop3Port.validate()
      && routingFieldPop3Emails.validate()
      && routingFieldPop3Username.validate()
      && routingFieldPop3Password.validate()
      && routingFieldPop3DeleteEmails.validate()){
          Ext.Ajax.request({
              url : 'index.php?fuse=support&action=SaveRoutingRule',
              success: function(t) {
                  onCompleteAction(t);
              },
              params: {
                  routingId:               routingFieldRoutingId.getValue(),
                  name:                    routingFieldName.getValue(),
                  routingType:             routingFieldRoutingType.getValue(),
                  userType:                routingFieldUserType.getValue(),
                  targetGroups:            routingFieldTargetGroups.getValue(),
                  autoresponderTemplateId: routingFieldAutoresponderTemplateId.getValue(),
                  openTicket:              routingFieldOpenTicket.getValue(),
                  targetPriority:          routingFieldTargetPriority.getValue(),
                  targetType:              routingFieldTargetType.getValue(),
                  assignee:                routingFieldAssignee.getValue(),
                  copyDestinataries:       routingFieldCopyDestinataries.getValue(),
                  piping_emails:           routingFieldPipingEmails.getValue(),
                  pop3Hostname:            routingFieldPop3Hostname.getValue(),
                  pop3Port:                routingFieldPop3Port.getValue(),
                  pop3_emails:             routingFieldPop3Emails.getValue(),
                  pop3Username:            routingFieldPop3Username.getValue(),
                  pop3Password:            routingFieldPop3Password.getValue(),
                  pop3DeleteEmails:        routingFieldPop3DeleteEmails.getValue()
              }
          });
    }else{
        message = '';
        newline = "<br>";

        if(!routingFieldName.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("Rule name");
        }

        if(!routingFieldRoutingType.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("Request source");
        }

        if(!routingFieldUserType.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("User type");
        }

        if(!routingFieldTargetGroupsValidate()){ //if(!routingFieldTargetGroups.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("Select groups");
        }

        if(!routingFieldAutoresponderTemplateId.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("Autoresponder template");
        }

        if(!routingFieldOpenTicket.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang('Open Ticket?');
        }

        if(!routingFieldTargetPriority.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("Set to priority");
        }

        if(!routingFieldTargetTypeValidate()){ //if(!routingFieldTargetType.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("Set to type");
        }

        if(!routingFieldAssignee.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("Assign to");
        }

        if(!routingFieldCopyDestinataries.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("Send copy to");
        }

        if(!routingFieldPipingEmails.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("E-mails");
        }

        if(!routingFieldPop3Hostname.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("E-mail server hostname");
        }

        if(!routingFieldPop3Port.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("E-mail server port");
        }

        if(!routingFieldPop3Emails.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("E-mails");
        }

        if(!routingFieldPop3Username.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("E-mail account username");
        }

        if(!routingFieldPop3Password.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("E-mail account password");
        }

        if(!routingFieldPop3DeleteEmails.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang('Delete E-mails on server') + ' ' + lang('after retrieval') + '?';
        }

        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 deleteRouting(){
    Ext.Ajax.request({
        url : 'index.php?fuse=support&action=DeleteRoutingRule',
        success: function(t) {
            onCompleteAction(t);
        },
        params: {
            routingId: routingFieldRoutingId.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"));
    }

    routingWin.hide();

    //get the grid if there is one
    //if we are in the routing rules view
    //if not then skip
    grid = Ext.getCmp("supportrouting-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
}

Ext.onReady(function(){
    
    
    routingfilter.updateRoutingFilter = function(btn, text) {
       //alert(text);
       if (btn!="ok") return;
       Ext.Ajax.request({
            url: "index.php?fuse=admin&action=saveRoutingFilters",
            params: {
                filters : text
            },
            success: function(respObj){
                json = ce.parseAjaxResponse(respObj);
                if (!json.error) {
                    ce.msg(lang('Filters Updated'));
                }
            }
        });
    }

    //function to show routing filter window
    routingfilter.addRoutingFilter = function() {
        
        //obtain code to add into msgbox.. if error return error and do not show snippet 
        Ext.Ajax.request({
            url: "index.php?fuse=admin&action=getRoutingFilters",
            params: {
                arg1 : 'test'
            },
            success: function(respObj){
                json = ce.parseAjaxResponse(respObj);
                helpFilterOut = lang('Rules are based on e-mail header values.<br />Format is "headername: content".<br />E-mails having the header "headername" that contain the string "content", will be discarded. Rules are applied in an OR fashion.');
                if (!json.error) {
                    var snippet = json.filters;
                    routingfilter.msgbox = Ext.MessageBox;
                    Ext.MessageBox.buttonText.ok = lang('Update');
                    routingfilter.msgbox.show({
                       title: 'Routing Filters',
                       msg: "<span style='border-bottom: 1px dotted; top: 0px;' class='tip-target' qtip='" + helpFilterOut.replace(/'/g, "&#39;") + "'>" + lang("Enter a list of rules to discard an E-mail") + "</span>",
                       width:500,
                       defaultTextHeight: 160,
                       buttons: Ext.MessageBox.OKCANCEL,
                       multiline: 260,
                       fn: routingfilter.updateRoutingFilter,
                       value: snippet,
                       animEl: 'addroutingfilterbutton'
                   });

                }
            }
        });
    }
    
    
    var defaultWidth  = 180;
    var defaultWidth2 = 200;
    var defaultWidth3 = 230;
    
//  routingId
    routingFieldRoutingId = new Ext.form.Hidden({
        id:               'routingFieldRoutingId',
        name:             'routingFieldRoutingId',
        value:            0,
        validationEvent:  false
    });
    
//  name
    routingFieldName = new Ext.form.TextField({
        id:               'routingFieldName',
        name:             'routingFieldName',
        fieldLabel:       lang("Rule name"),
        validationEvent:  false,
        anchor:           '100%',
        border:           false,
        value:            '',
        allowBlank:       false
    });
    
//  1 routingType
    routingFieldRoutingType = new Ext.form.ComboBox({
        id:               'routingFieldRoutingType',
        name:             'routingFieldRoutingType',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Request source"),
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'routingtypename'
            ],
            data:     [
                [
                    1,
                    lang("E-mail pipe forwarding")
                ],
                [
                    2,
                    lang("E-mail POP3 fetching")
                ],
                [
                    3,
                    lang("Public section")
                ]
            ]
        }),
        valueField:       'id',
        displayField:     'routingtypename',
        value:            1,
        hiddenId:         'routingFieldRoutingTypeValue',
        hiddenName:       'routingFieldRoutingTypeValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    routingFieldRoutingType.on('afterrender', showRoutingTypeFields);
    routingFieldRoutingType.on('select', showRoutingTypeFields);
    
    function showRoutingTypeFields(){
        hideShowTargetPriorityFields();
        hideShowTargetTypeFields();
        
        switch(parseInt(routingFieldRoutingType.getValue())){
            case 1:
                if(routingFieldRTEmailPipeForwardingContainer != undefined){
                    routingFieldRTEmailPipeForwardingContainer.show();
                }
                
                if(routingFieldRTEmailPOP3FetchingContainer != undefined){
                    routingFieldRTEmailPOP3FetchingContainer.hide();
                }
                
                if(routingFieldRTNoticePublicSection != undefined){
                    routingFieldRTNoticePublicSection.hide();
                }
                
                break;
            case 2:
                if(routingFieldRTEmailPipeForwardingContainer != undefined){
                    routingFieldRTEmailPipeForwardingContainer.hide();
                }
                
                if(routingFieldRTEmailPOP3FetchingContainer != undefined){
                    routingFieldRTEmailPOP3FetchingContainer.show();
                }
                
                if(routingFieldRTNoticePublicSection != undefined){
                    routingFieldRTNoticePublicSection.hide();
                }
                
                break;
            case 3:
                if(routingFieldRTEmailPipeForwardingContainer != undefined){
                    routingFieldRTEmailPipeForwardingContainer.hide();
                }
                
                if(routingFieldRTEmailPOP3FetchingContainer != undefined){
                    routingFieldRTEmailPOP3FetchingContainer.hide();
                }
                
                if(routingFieldRTNoticePublicSection != undefined){
                    routingFieldRTNoticePublicSection.show();
                }
                
                break;
        }
        
        Ext.getCmp('tabPanelRequestSource').doLayout();
        Ext.getCmp('tabPanelActions').doLayout();
    }
    
//  2 userType
    routingFieldUserType = new Ext.form.ComboBox({
        id:               'routingFieldUserType',
        name:             'routingFieldUserType',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth3,
        fieldLabel:       lang("User type"),
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'usertypename'
            ],
            data:     [
                [
                    'both',
                    lang("Any (Guests and Registered)")
                ],
                [
                    'anonymous',
                    lang("Guests")
                ],
                [
                    'registered',
                    lang("Registered")
                ],
                [
                    'groups',
                    lang("Registered, from selected groups")
                ]
            ]
        }),
        valueField:       'id',
        displayField:     'usertypename',
        value:            'registered',
        hiddenId:         'routingFieldUserTypeValue',
        hiddenName:       'routingFieldUserTypeValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    routingFieldUserType.on('afterrender', hideShowTargetGroups);
    routingFieldUserType.on('select', hideShowTargetGroups);
    
//  [2] targetGroups[]
    var groupstore = new Ext.data.JsonStore({
        id:             "groupstore",
        root:           'groups', //'departments',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            filter: "",
            customerid: "0"
        },
        fields:         [
            'groupId',
            'groupName'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=support&action=GetGroupList'
        })
    });
    
    groupstore.setDefaultSort('id', 'asc');
    
    groupstore.load();
    
    routingFieldTargetGroups = new Ext.ux.form.LovCombo({
        id:               'routingFieldTargetGroups',
        name:             'routingFieldTargetGroups',
        fieldLabel:       lang("Select groups"),
        validationEvent:  false,
        width:            defaultWidth3,
        hideOnSelect:     true,
        //hidden :          true,
        maxHeight:        200,
        allowBlank:       false,
        store:            groupstore,
        valueField:       'groupId',
        displayField:     'groupName',
        value:            '',
        triggerAction:    'all',
        mode:             'local',
        beforeBlur:       Ext.emptyFn
    });
    
    routingFieldTargetGroupsValidate = function(){
        if(routingFieldUserType != undefined
          && routingFieldUserType.getValue() == 'groups'){
            if(routingFieldTargetGroups != undefined){
                if(routingFieldTargetGroups.getValue() != ''){
                    routingFieldTargetGroups.clearInvalid();
                    return true;
                }else{
                    routingFieldTargetGroups.markInvalid('This field is required');
                    return false;
                }
            }else{
                return false;
            }
        }else{
            if(routingFieldTargetGroups != undefined){
                routingFieldTargetGroups.clearInvalid();
            }
            
            return true;
        }
    }
    
    routingFieldTargetGroupsContainer = new Ext.Container({
        id:       'routingFieldTargetGroupsContainer',
        layout:   'form',
        items :   [
            routingFieldTargetGroups
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
    function hideShowTargetGroups(){
        if(routingFieldTargetGroupsContainer != undefined){
            if(routingFieldUserType.getValue() == 'groups'){
                routingFieldTargetGroupsContainer.show();
            }else{
                routingFieldTargetGroupsContainer.hide();
            }
        }
    }
    
//  autoresponderTemplateId
    var templatestore = new Ext.data.JsonStore({
        id:             "templatestore",
        root:           'templates',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            filter: "",
            customerid: "0",
            shownone:"1"
        },
        fields:         [
            'templateId',
            'templateName'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=admin&action=Admin_GetEmailTemplates'
        })
    });
    
    templatestore.setDefaultSort('id', 'asc');
    
    templatestore.load();
    
    routingFieldAutoresponderTemplateId = new Ext.form.ComboBox({
        id:               'routingFieldAutoresponderTemplateId',
        name:             'routingFieldAutoresponderTemplateId',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth,
        fieldLabel:       lang("Autoresponder template"),
        store:            templatestore,
        valueField:       'templateId',
        displayField:     'templateName',
        value:            0,
        hiddenId:         'routingFieldAutoresponderTemplateIdValue',
        hiddenName:       'routingFieldAutoresponderTemplateIdValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
//  3 openTicket
    routingFieldOpenTicket = new Ext.form.Checkbox({
        id:               'routingFieldOpenTicket',
        name:             'routingFieldOpenTicket',
        //fieldLabel:       lang("Open Ticket?"),
        value:            false,
        validationEvent:  false,
        boxLabel :        lang('Open Ticket?')
    });
    
    routingFieldOpenTicket.on('afterrender', hideShowTicketFields);
    routingFieldOpenTicket.on('check', hideShowTicketFields);
    
    function hideShowTicketFields(){
        hideShowTargetPriorityFields();
        hideShowTargetTypeFields();
        hideShowAssignee();
        hideShowAssigneeNotice();
    }
    
    function hideShowTargetPriorityFields(){
        hideShowTargetPriority();
        hideShowTargetPriorityFixed();
    }
    
    function hideShowTargetTypeFields(){
        hideShowTargetType();
        hideShowTargetTypeFixed();
    }
    
//  [3][1] targetPriority
    routingFieldTargetPriority = new Ext.form.ComboBox({
        id:               'routingFieldTargetPriority',
        name:             'routingFieldTargetPriority',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth2,
        fieldLabel:       lang("Set to priority"),
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'priorityname'
            ],
            data:     [
                [
                    3,
                    lang("Low")
                ],
                [
                    2,
                    lang("Medium")
                ],
                [
                    1,
                    lang("High")
                ]
            ]
        }),
        valueField:       'id',
        displayField:     'priorityname',
        value:            3,
        hiddenId:         'routingFieldTargetPriorityValue',
        hiddenName:       'routingFieldTargetPriorityValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    
    routingFieldTargetPriorityContainer = new Ext.Container({
        id:       'routingFieldTargetPriorityContainer',
        layout:   'form',
        items :   [
            routingFieldTargetPriority
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
    function hideShowTargetPriority(){
        if(routingFieldTargetPriorityContainer != undefined){
            if(routingFieldOpenTicket != undefined
              && routingFieldOpenTicket.getValue() == true
              && routingFieldRoutingType != undefined
              && routingFieldRoutingType.getValue() != 3){
                routingFieldTargetPriorityContainer.show();
            }else{
                routingFieldTargetPriorityContainer.hide();
            }
        }
    }
    
    routingFieldTargetPriorityFixed = new Ext.form.ComboBox({
        id:               'routingFieldTargetPriorityFixed',
        name:             'routingFieldTargetPriorityFixed',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth2,
        fieldLabel:       lang("Set to priority"),
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'priorityname'
            ],
            data:     [
                [
                    0,
                    lang('Selected by customer')
                ]
            ]
        }),
        valueField:       'id',
        displayField:     'priorityname',
        value:            0,
        hiddenId:         'routingFieldTargetPriorityFixedValue',
        hiddenName:       'routingFieldTargetPriorityFixedValue',
        editable:         false,
        disabled:         true
    });
    
    routingFieldTargetPriorityFixedContainer = new Ext.Container({
        id:       'routingFieldTargetPriorityFixedContainer',
        layout:   'form',
        items :   [
            routingFieldTargetPriorityFixed
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
    function hideShowTargetPriorityFixed(){
        if(routingFieldTargetPriorityFixedContainer != undefined){
            if(routingFieldOpenTicket != undefined
              && routingFieldOpenTicket.getValue() == true
              && routingFieldRoutingType != undefined
              && routingFieldRoutingType.getValue() == 3){
                routingFieldTargetPriorityFixedContainer.show();
            }else{
                routingFieldTargetPriorityFixedContainer.hide();
            }
        }
    }
    
//  [3][1] targetType
    var tickettypestore = new Ext.data.JsonStore({
        id:             "tickettypestore",
        root:           'tickettypes',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        baseParams:     {
            filter: "",
            customerid: "0"
        },
        fields:         [
            'ticketTypeId',
            'ticketTypeName'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=support&action=GetTicketTypeList&simple=1'
        })
    });
    
    tickettypestore.setDefaultSort('id', 'asc');
    
    tickettypestore.load();
    
    routingFieldTargetType = new Ext.form.ComboBox({
        id:               'routingFieldTargetType',
        name:             'routingFieldTargetType',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth2,
        fieldLabel:       lang("Set to type"),
        store:            tickettypestore,
        valueField:       'ticketTypeId',
        displayField:     'ticketTypeName',
        value:            0,
        hiddenId:         'routingFieldTargetTypeValue',
        hiddenName:       'routingFieldTargetTypeValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false,
        listeners:        {
            select: function(combo,record,index){
                if(record.get('ticketTypeId') == 0){
                    routingFieldAssignee.setValue('dep_0_staff_0');
                }else{
                    routingFieldAssignee.setValue(defaultassignee);
                }
            }
        }
    });
    
    routingFieldTargetTypeValidate = function (){
        if(routingFieldOpenTicket != undefined
          && routingFieldOpenTicket.getValue() == true
          && routingFieldRoutingType != undefined
          && routingFieldRoutingType.getValue() != 3){
            if(routingFieldTargetType != undefined){
                if(routingFieldTargetType.getValue() != 0){
                    routingFieldTargetType.clearInvalid();
                    return true;
                }else{
                    routingFieldTargetType.markInvalid('This field is required');
                    return false;
                }
            }else{
                return false;
            }
        }else{
            if(routingFieldTargetType != undefined){
                routingFieldTargetType.clearInvalid();
            }
            
            return true;
        }
    }
    
    routingFieldTargetTypeContainer = new Ext.Container({
        id:       'routingFieldTargetTypeContainer',
        layout:   'form',
        items :   [
            routingFieldTargetType
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
    function hideShowTargetType(){
        if(routingFieldTargetTypeContainer != undefined){
            if(routingFieldOpenTicket != undefined
              && routingFieldOpenTicket.getValue() == true
              && routingFieldRoutingType != undefined
              && routingFieldRoutingType.getValue() != 3){
                routingFieldTargetTypeContainer.show();
            }else{
                routingFieldTargetTypeContainer.hide();
            }
        }
    }
    
    routingFieldTargetTypeFixed = new Ext.form.ComboBox({
        id:               'routingFieldTargetTypeFixed',
        name:             'routingFieldTargetTypeFixed',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth2,
        fieldLabel:       lang("Set to type"),
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'ticketTypeId',
                'ticketTypeName'
            ],
            data:     [
                [
                    0,
                    lang('Selected by customer')
                ]
            ]
        }),
        valueField:       'ticketTypeId',
        displayField:     'ticketTypeName',
        value:            0,
        hiddenId:         'routingFieldTargetTypeFixedValue',
        hiddenName:       'routingFieldTargetTypeFixedValue',
        editable:         false,
        disabled:         true
    });
    
    routingFieldTargetTypeFixedContainer = new Ext.Container({
        id:       'routingFieldTargetTypeFixedContainer',
        layout:   'form',
        items :   [
            routingFieldTargetTypeFixed
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
    function hideShowTargetTypeFixed(){
        if(routingFieldTargetTypeFixedContainer != undefined){
            if(routingFieldOpenTicket != undefined
              && routingFieldOpenTicket.getValue() == true
              && routingFieldRoutingType != undefined
              && routingFieldRoutingType.getValue() == 3
              ){
                routingFieldTargetTypeFixedContainer.show();
            }else{
                routingFieldTargetTypeFixedContainer.hide();
            }
        }
    }
    
//  [3][1] assignee
    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=' + '3,1'
        })
    });
    
    staffstore.setDefaultSort('id', 'asc');
    
    staffstore.on('load', function(){
        record = staffstore.getAt(0); //defaultassignee
        defaultassignee = record.get('assigneeId');
        routingFieldAssignee.setValue(defaultassignee);
    });
    
    staffstore.load();
    
    // Custom rendering Template
    var routingFieldAssigneeTpl = new Ext.XTemplate(
        '<tpl for="."><div class="combo-value {indentClass}"><span>{assigneeLabel}</span></div></tpl>'
    );
    
    routingFieldAssignee = new Ext.form.ComboBox({
        id:               'routingFieldAssignee',
        name:             'routingFieldAssignee',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        validationEvent:  false,
        width:            defaultWidth2,
        fieldLabel:       lang("Assign to"),
        store:            staffstore,
        valueField:       'assigneeId',
        displayField:     'assigneeLabel',
        value:            defaultassignee,
        hiddenId:         'routingFieldAssigneeValue',
        hiddenName:       'routingFieldAssigneeValue',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false,
        tpl:              routingFieldAssigneeTpl,
        itemSelector:     'div.combo-value'
    });
    
    routingFieldAssigneeContainer = new Ext.Container({
        id:       'routingFieldAssigneeContainer',
        layout:   'form',
        items :   [
            routingFieldAssignee
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
    function hideShowAssignee(){
        if(routingFieldAssigneeContainer != undefined){
            if(routingFieldOpenTicket != undefined
              && routingFieldOpenTicket.getValue() == true){
                routingFieldAssigneeContainer.show();
            }else{
                routingFieldAssigneeContainer.hide();
            }
        }
    }
    
    routingFieldAssigneeNotice = new Ext.form.FieldSet({
        id:           'routingFieldAssigneeNotice',
        name:         'routingFieldAssigneeNotice',
        title:        lang('NOTICE'),
        hidden:       true,
        autoHeight:   true,
        defaults:     {width: 240},
        labelAlign:   'top',
        items :       [
            {
                xtype:          "label",
                id:             'NoticeAssignee',
                name:           'NoticeAssignee',
                fieldLabel:     lang('If you assign tickets under routing rules to something different than the Ticket Type Default Assignee, then it will over rule the settings under Ticket Type where you may already have a different Assignee selected.<br><br>If you assign tickets to an admin under routing rules (instead of Department), then it will over rule the settings under Departments where you may already have a different admin selected to assign the tickets to.'),
                labelSeparator: ''
                //text:           lang('Be aware that this rule will only apply to E-mails sent to this account, to the E-mail(s) address(es) specified below. You can use a same account in many routing rules, as long as you set the E-mails below consistently.'),

            }
        ]
    });
    
    function hideShowAssigneeNotice(){
        if(routingFieldAssigneeNotice != undefined){
            if(routingFieldOpenTicket != undefined
              && routingFieldOpenTicket.getValue() == true){
                routingFieldAssigneeNotice.show();
            }else{
                routingFieldAssigneeNotice.hide();
            }
        }
    }
    
//  copyDestinataries
    var helpCopyDestinataries = lang('Enter one E-mail per line.');
    
    routingFieldCopyDestinataries = new Ext.form.TextArea({
        id:               'routingFieldCopyDestinataries',
        name:             'routingFieldCopyDestinataries',
        //fieldLabel:       lang("Send copy to") + " <img class='tip-target' src='../templates/admin/images/information-button.png' qtip='" + helpCopyDestinataries.replace(/'/g, "&#39;") + "'/>",
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpCopyDestinataries.replace(/'/g, "&#39;") + "'>" + lang("Send copy to") + "</span>",
        border:           false,
        validationEvent:  false,
        width:            defaultWidth2,
        height:           100,
        value:            ''
    });
    
//  REQUEST SOURCE SETTINGS
    var helpEmails = lang('Enter one E-mail per line.') + '<br />' + lang('You can use * to apply to all incoming E-mails.');
    //var helpFilterOut = lang('Enter a list of rules to discard an E-mail, based on header values.<br />Format is "headername: content".<br />E-mails having the header "headername" that contain the string "content", will be discarded. Rules are applied in an OR fashion.');
    
//  Pipe Forwarding Settings
//  [1] piping_emails
    routingFieldPipingEmails = new Ext.form.TextArea({
        id:               'routingFieldPipingEmails',
        name:             'routingFieldPipingEmails',
        //fieldLabel:       lang("E-mails") + " <img class='tip-target' src='../templates/admin/images/information-button.png' qtip='" + helpEmails.replace(/'/g, "&#39;") + "'/>",
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpEmails.replace(/'/g, "&#39;") + "'>" + lang("E-mails") + "</span>",
        border:           false,
        validationEvent:  false,
        width:            422,
        height:           100,
        value:            ''
    });
    
//  Routing Type Notice Email Pipe Forwarding
    var currentPipeCommand = new Ext.data.JsonStore({
        id:             "currentPipeCommand",
        root:           'pipeCommand',
        totalProperty:  'totalcount',
        idProperty:     'id',
        remoteSort:     true,
        fields:         [
            'pipeCommandText'
        ],
        proxy:          new Ext.data.HttpProxy({
            url: 'index.php?fuse=support&action=GetPipeCommand'
        })
    });
    
    currentPipeCommand.on('load', function(){
        record = currentPipeCommand.getAt(0);
        pipeCommand = record.get('pipeCommandText');
        Ext.getCmp('NoticeEmailPipeForwarding').setText('| ' + pipeCommand);
    });
    
    currentPipeCommand.load();
    
    routingFieldRTNoticeEmailPipeForwarding = new Ext.form.FieldSet({
        id:           'routingFieldRTNoticeEmailPipeForwarding',
        name:         'routingFieldRTNoticeEmailPipeForwarding',
        title:        lang('NOTICE'),
        autoHeight:   true,
        defaults:     {width: 240},
        labelAlign:   'top',
        items :       [
            {
                xtype:      "label",
                id:         'NoticeEmailPipeForwarding',
                name:       'NoticeEmailPipeForwarding',
                fieldLabel: lang('Have each of the above E-mail addresses forward to'),
                labelStyle: "font-weight: bold;",
                text:       '| ' + pipeCommand,
                style:      "font-weight: bold; color: green;"
            }
        ]
    });
    
//  Routing Type Email Pipe Forwarding Container
    routingFieldRTEmailPipeForwardingContainer = new Ext.Container({
        id:       'routingFieldRTEmailPipeForwardingContainer',
        layout:   'form',
        items :   [
            {
                layout: 'column',
                border: false,
                items:  [
                    {
                        columnWidth:  1,
                        layout:       'form',
                        border:       false,
                        items:        [
                            routingFieldPipingEmails
                        ]
                    },
                    {
                        columnWidth:  1,
                        layout:       'form',
                        border:       false,
                        items:        [
                            routingFieldRTNoticeEmailPipeForwarding
                        ]
                    }
                ]
            }
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
//  POP3 Fetching Settings
//  Routing Type Notice Email POP3 Fetching
    routingFieldRTNoticeEmailPOP3Fetching = new Ext.form.FieldSet({
        id:           'routingFieldRTNoticeEmailPOP3Fetching',
        name:         'routingFieldRTNoticeEmailPOP3Fetching',
        title:        lang('NOTICE'),
        autoHeight:   true,
        defaults:     {width: 240},
        labelAlign:   'top',
        items :       [
            {
                xtype:          "label",
                id:             'NoticeEmailPOP3Fetching',
                name:           'NoticeEmailPOP3Fetching',
                fieldLabel:     lang('This works in tandem with the Tickets Generator automation service, so you need to have it enabled for this routing rule to work.'),
                labelSeparator: ''
                //text:           lang('Be aware that this rule will only apply to E-mails sent to this account, to the E-mail(s) address(es) specified below. You can use a same account in many routing rules, as long as you set the E-mails below consistently.'),
            }
        ]
    });
    
//  [1] pop3Hostname
    routingFieldPop3Hostname = new Ext.form.TextField({
        id:               'routingFieldPop3Hostname',
        name:             'routingFieldPop3Hostname',
        fieldLabel:       lang("E-mail server hostname"),
        validationEvent:  false,
        width:            defaultWidth2,
        border:           false,
        value:            '',
        allowBlank:       true
    });
    
//  [1] pop3Port
    routingFieldPop3Port = new Ext.form.TextField({
        id:               'routingFieldPop3Port',
        name:             'routingFieldPop3Port',
        fieldLabel:       lang("E-mail server port"),
        validationEvent:  false,
        width:            defaultWidth2,
        border:           false,
        value:            '',
        allowBlank:       true
    });
    
//  [1] pop3_emails
    routingFieldPop3Emails = new Ext.form.TextArea({
        id:               'routingFieldPop3Emails',
        name:             'routingFieldPop3Emails',
        //fieldLabel:       lang("E-mails") + " <img class='tip-target' src='../templates/admin/images/information-button.png' qtip='" + helpEmails.replace(/'/g, "&#39;") + "'/>",
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpEmails.replace(/'/g, "&#39;") + "'>" + lang("E-mails") + "</span>",
        border:           false,
        validationEvent:  false,
        width:            420,
        height:           100,
        value:            ''
    });
    
//  [1] pop3Username
    routingFieldPop3Username = new Ext.form.TextField({
        id:               'routingFieldPop3Username',
        name:             'routingFieldPop3Username',
        fieldLabel:       lang("E-mail account username"),
        validationEvent:  false,
        width:            defaultWidth2,
        border:           false,
        value:            '',
        allowBlank:       true
    });
    
//  [1] pop3Password
    routingFieldPop3Password = new Ext.form.TextField({
        id:               'routingFieldPop3Password',
        name:             'routingFieldPop3Password',
        autoCreate:       {tag: "input", type: "password", size: "20", autocomplete: "off"},
        cls:              'x-form-text',
        fieldLabel:       lang("E-mail account password"),
        validationEvent:  false,
        width:            defaultWidth2,
        border:           false,
        value:            '',
        allowBlank:       true
    });
    
//  [1] pop3DeleteEmails
    routingFieldPop3DeleteEmails = new Ext.form.Checkbox({
        id:               'routingFieldPop3DeleteEmails',
        name:             'routingFieldPop3DeleteEmails',
        //fieldLabel:       lang('Delete E-mails on server') + ' ' + lang('after retrieval') + '?',
        value:            false,
        validationEvent:  false,
        boxLabel :        lang('Delete E-mails on server') + ' ' + lang('after retrieval') + '?'
    });
    
//  Routing Type Email POP3 Fetching Container
    routingFieldRTEmailPOP3FetchingContainer = new Ext.Container({
        id:       'routingFieldRTEmailPOP3FetchingContainer',
        layout:   'form',
        items :   [
            {
                layout: 'column',
                border: false,
                items:  [
                    {
                        columnWidth:  1,
                        layout:       'form',
                        border:       false,
                        items:        [
                            routingFieldRTNoticeEmailPOP3Fetching
                        ]
                    },
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            routingFieldPop3Hostname,
                            routingFieldPop3Port
                        ]
                    },
                    
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            routingFieldPop3Username,
                            routingFieldPop3Password
                        ]
                    },
                    {
                        columnWidth:  1,
                        layout:       'form',
                        border:       false,
                        items:        [
                            routingFieldPop3Emails
                        ]
                    },
                    {
                        columnWidth:  1,
                        layout:       'form',
                        border:       false,
                        items:        [
                            routingFieldPop3DeleteEmails
                        ]
                    }
                ]
            }
        ],
        hideMode: 'offsets',
        hidden:   true
    });
    
//  Routing Type Notice Public Section
    routingFieldRTNoticePublicSection = new Ext.form.FieldSet({
        id:           'routingFieldRTNoticePublicSection',
        name:         'routingFieldRTNoticePublicSection',
        title:        lang('NOTICE'),
        autoHeight:   true,
        defaults:     {width: 240},
        labelAlign:   'top',
        items :       [
            {
                xtype:          "label",
                id:             'NoticePublicSection',
                name:           'NoticePublicSection',
                fieldLabel:     lang('By creating this rule, you will be giving access to the public support section under the directory /public of your installation.'),
                labelSeparator: '',
                text:           lang("If the type of customer (Guest or Registered) that enters a request in the public section doesn't have an associated routing rule, then his request will be silently ignored. Therefore we recomend to have rules for all customer types, setting autoresponders with the appropriate messages for those you don't wish to process."),
            }
        ],
        hideMode:     'offsets',
        hidden:       true
    });
    
//  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:        [
            routingFieldRoutingId,
            routingFieldName,
            {
                id:             'routingTabPanels',
                xtype:          'tabpanel',
                plain:          true,
                activeTab:      'tabPanelRequestSource',
                //deferredRender: false,
                height:          490,
                defaults:       {bodyStyle:'padding:10px; background-color:WhiteSmoke'},
                items:          [
                    {
                        id:       'tabPanelRequestSource',
                        title:    lang("Request Source"),
                        layout:   'form',
                        listeners:  {
                            'activate': {
                                fn: function(){
                                    this.doLayout();
                                }
                            }
                        },
                        items:    [
                            routingFieldRoutingType,
                            routingFieldRTEmailPipeForwardingContainer,
                            routingFieldRTEmailPOP3FetchingContainer,
                            routingFieldRTNoticePublicSection
                        ]
                    },
                    {
                        id:     'tabPanelUserType',
                        title:  lang("User Type"),
                        layout: 'form',
                        items:  [
                            {
                                layout: 'column',
                                border: false,
                                items:  [
                                    {
                                        columnWidth:  1,
                                        layout:       'form',
                                        border:       false,
                                        items:        [
                                            routingFieldUserType,
                                            routingFieldTargetGroupsContainer
                                        ]
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        id:     'tabPanelActions',
                        title:  lang("Actions"),
                        layout: 'form',
                        listeners:  {
                            'activate': {
                                fn: function(){
                                    this.doLayout();
                                }
                            }
                        },
                        items:  [
                            {
                                layout: 'column',
                                border: false,
                                items:  [
                                    {
                                        columnWidth:  .5,
                                        layout:       'form',
                                        border:       false,
                                        items:        [
                                            routingFieldAutoresponderTemplateId,
                                            routingFieldCopyDestinataries
                                        ]
                                    },
                                    {
                                        columnWidth:  .5,
                                        layout:       'form',
                                        border:       false,
                                        items:        [
                                            routingFieldOpenTicket,
                                            routingFieldTargetPriorityContainer,
                                            routingFieldTargetPriorityFixedContainer,
                                            routingFieldTargetTypeContainer,
                                            routingFieldTargetTypeFixedContainer,
                                            routingFieldAssigneeContainer
                                        ]
                                    },
                                    {
                                        columnWidth:  1,
                                        layout:       'form',
                                        border:       false,
                                        items:        [
                                            routingFieldAssigneeNotice
                                        ]
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    });
    
    //simpleForm.render(document.body);
    
//  Window
    routingWin = new Ext.Window({
        id:           "routingWindow",
        y:            25,// 200,
        layout:       'fit',
        width:        480,
        autoHeight:   true,
        modal:        true,
        closeAction:  'hide',
        title:        lang("Add Routing Rule"),
        plain:        true,
        shadow:       false,
        items:        [simpleForm],
        buttons:      [
            {
                text:     'Close',
                handler:  function(){
                    routingWin.hide();
                }
            },
            {
                id:       'btnDeleteRouting',
                text:     lang("Delete"),
                hidden:   true,
                onClick:  function(record){
                    Ext.Msg.show({
                        title:    "Delete?" ,
                        msg:      "Are you sure you want to delete this routing rule?",
                        buttons:  Ext.Msg.YESNOCANCEL,
                        fn:       function(btn, text){
                            if(btn == 'yes'){
                                deleteRouting();
                            }
                        },
                        icon:     Ext.MessageBox.QUESTION
                    })
                }
            },
            {
                id:       'btnAddRouting',
                text:     lang("Save"),
                disabled: false,
                hidden:   false,
                handler:  function(){
                    sendRouting();
                }
            }
        ]
    });
    
    getCurrentRoutingRule = function(action, id){
        var currentRoutingRule = new Ext.data.JsonStore({
            id:             "currentRoutingRule",
            root:           'routingrule',
            totalProperty:  'totalcount',
            idProperty:     'id',
            remoteSort:     true,
            baseParams:     {
                id: id
            },
            fields:         [
                'routingId',
                'name',
                'routingType',
                'userType',
                'targetGroups',
                'autoresponderTemplateId',
                'openTicket',
                'targetPriority',
                'targetType',
                'assignee',
                'copyDestinataries',
                'piping_emails',
                'pop3Hostname',
                'pop3Port',
                'pop3_emails',
                'pop3Username',
                'pop3Password',
                'pop3DeleteEmails'
            ],
            proxy:          new Ext.data.HttpProxy({
                url: 'index.php?fuse=support&action=GetRoutingRule'
            })
        });
        
        currentRoutingRule.on('load', function(){
            record = currentRoutingRule.getAt(0);
            
            switch(action){
                case 'add':
                    routingWin.setTitle(lang("Add Routing Rule"));
                    Ext.getCmp('btnDeleteRouting').hide();
                    break;
                case 'edit':
                    routingWin.setTitle(lang("Edit Routing Rule"));
                    Ext.getCmp('btnDeleteRouting').show();
                    break;
            }
            
            routingFieldRoutingId.reset();
            routingFieldRoutingId.setValue(record.get('routingId'));
            
            routingFieldName.reset();
            routingFieldName.setValue(record.get('name'));
            
            routingFieldRoutingType.reset();
            routingFieldRoutingType.setValue(record.get('routingType'));
            
            routingFieldUserType.reset();
            routingFieldUserType.setValue(record.get('userType'));
            
            routingFieldAutoresponderTemplateId.reset();
            routingFieldAutoresponderTemplateId.setValue(record.get('autoresponderTemplateId'));
            
            routingFieldOpenTicket.reset();
            routingFieldOpenTicket.setValue(record.get('openTicket'));
            
            routingFieldTargetPriority.reset();
            routingFieldTargetPriority.setValue(record.get('targetPriority'));
            
            routingFieldTargetType.reset();
            routingFieldTargetType.setValue(record.get('targetType'));
            
            routingFieldAssignee.reset();
            routingFieldAssignee.setValue(record.get('assignee'));
            
            routingFieldCopyDestinataries.reset();
            routingFieldCopyDestinataries.setValue(record.get('copyDestinataries'));
            
            routingFieldPipingEmails.reset();
            routingFieldPipingEmails.setValue(record.get('piping_emails'));
            
            routingFieldPop3Hostname.reset();
            routingFieldPop3Hostname.setValue(record.get('pop3Hostname'));
            
            routingFieldPop3Port.reset();
            routingFieldPop3Port.setValue(record.get('pop3Port'));
            
            routingFieldPop3Emails.reset();
            routingFieldPop3Emails.setValue(record.get('pop3_emails'));
            
            routingFieldPop3Username.reset();
            routingFieldPop3Username.setValue(record.get('pop3Username'));
            
            routingFieldPop3Password.reset();
            routingFieldPop3Password.setValue(record.get('pop3Password'));
            
            routingFieldPop3DeleteEmails.reset();
            routingFieldPop3DeleteEmails.setValue(record.get('pop3DeleteEmails'));
            
            // NEED TO RUN THESE OPERATION BEFORE SHOWING THE WINDOW, OR THE "ROUTINGFIELDTARGETGROUPS" FIELD FAILS
            Ext.getCmp('routingTabPanels').activate('tabPanelUserType');
            
            showRoutingTypeFields();
            hideShowTicketFields();
            
            routingWin.show();
            
            // NEED TO RUN THESE OPERATIONS AFTER SHOWING THE WINDOW, OR THE "ROUTINGFIELDTARGETGROUPS" FIELD FAILS
            routingFieldTargetGroupsContainer.show();
            hideShowTargetGroups();
            
            // SETTING THE INITIAL ACTIVE TAB
            Ext.getCmp('routingTabPanels').activate('tabPanelRequestSource');
            
            // NEED TO CLEAR THE INVALID MESSAGE OF THE "ROUTINGFIELDNAME" FIELD BECAUSE IT CAN START WITH AN EMPTY VALUE
            routingFieldName.clearInvalid();
            
            // NEED TO RESET THESE ONES AFTER SHOWING THE WINDOW, OR THE WINDOW FAILS
            routingFieldTargetGroups.reset();
            routingFieldTargetGroups.setValue(record.get('targetGroups'));
            
            
            routingFieldName.focus('',300);
        });
        
        currentRoutingRule.load();
    }
});