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

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 routingFieldCopyDestinataries;
var routingFieldPipingEmails;
var routingFieldPipingFilterOut;
var routingFieldRTNoticeEmailPipeForwarding;
var routingFieldRTEmailPipeForwardingContainer;
var routingFieldRTNoticeEmailPOP3Fetching;
var routingFieldPop3Hostname;
var routingFieldPop3Port;
var routingFieldPop3Emails;
var routingFieldPop3Username;
var routingFieldPop3Password;
var routingFieldPop3DeleteEmails;
var routingFieldPop3FilterOut;
var routingFieldRTEmailPOP3FetchingContainer;
var routingFieldRTNoticePublicSection;

Ext.onReady(function(){

    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();
    }

    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
    });

    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=' + encodeURIComponent('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();
            }
        }
    }

//  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:            defaultWidth2,
        height:           100,
        value:            ''
    });

//  [1] piping_filterout
    routingFieldPipingFilterOut = new Ext.form.TextArea({
        id:               'routingFieldPipingFilterOut',
        name:             'routingFieldPipingFilterOut',
        //fieldLabel:       lang("Filter out") + " <img class='tip-target' src='../templates/admin/images/information-button.png' qtip='" + helpFilterOut.replace(/'/g, "&#39;") + "'/>",
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpFilterOut.replace(/'/g, "&#39;") + "'>" + lang("Filter out") + "</span>",
        border:           false,
        validationEvent:  false,
        width:            defaultWidth2,
        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:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            routingFieldPipingEmails
                        ]
                    },
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            routingFieldPipingFilterOut
                        ]
                    },
                    {
                        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.'),
                labelStyle:     "font-weight: bold;",
                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.'),
                style:          "font-weight: bold;"
            }
        ]
    });

//  [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:            defaultWidth2,
        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') + '?'
    });

//  [1] pop3_filterout
    routingFieldPop3FilterOut = new Ext.form.TextArea({
        id:               'routingFieldPop3FilterOut',
        name:             'routingFieldPop3FilterOut',
        //fieldLabel:       lang("Filter out") + " <img class='tip-target' src='../templates/adminw/images/information-button.png' qtip='" + helpFilterOut.replace(/'/g, "&#39;") + "'/>",
        fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpFilterOut.replace(/'/g, "&#39;") + "'>" + lang("Filter out") + "</span>",
        border:           false,
        validationEvent:  false,
        width:            defaultWidth2,
        height:           100,
        value:            ''
    });

//  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,
                            routingFieldPop3Emails
                        ]
                    },
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            routingFieldPop3Username,
                            routingFieldPop3Password,
                            routingFieldPop3FilterOut
                        ]
                    },
                    {
                        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.'),
                labelStyle:     "font-weight: bold;",
                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."),
                style:          "font-weight: bold;"
            }
        ],
        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:         445,// 260,
                              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
                                                                                                    ]
                                                                                  }
                                                                              ]
                                                                  }
                                                              ]
                                                  }
                                              ]
                          }
                      ]
    });

    //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',
                                'piping_filterout',
                                'pop3Hostname',
                                'pop3Port',
                                'pop3_emails',
                                'pop3Username',
                                'pop3Password',
                                'pop3DeleteEmails',
                                'pop3_filterout'
                            ],
            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'));

            routingFieldPipingFilterOut.reset();
            routingFieldPipingFilterOut.setValue(record.get('piping_filterout'));

            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'));

            routingFieldPop3FilterOut.reset();
            routingFieldPop3FilterOut.setValue(record.get('pop3_filterout'));

            // 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(); // for some reason the focus get lost
        });

        currentRoutingRule.load();
    }
});

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()
      && routingFieldPipingFilterOut.validate()
      && routingFieldPop3Hostname.validate()
      && routingFieldPop3Port.validate()
      && routingFieldPop3Emails.validate()
      && routingFieldPop3Username.validate()
      && routingFieldPop3Password.validate()
      && routingFieldPop3DeleteEmails.validate()
      && routingFieldPop3FilterOut.validate()){
        new Ajax.Request('index.php?fuse=support&action=SaveRoutingRule',
                         {parameters: 'routingId='               + encodeURIComponent(routingFieldRoutingId.getValue())
                                   + '&name='                    + encodeURIComponent(routingFieldName.getValue())
                                   + '&routingType='             + encodeURIComponent(routingFieldRoutingType.getValue())
                                   + '&userType='                + encodeURIComponent(routingFieldUserType.getValue())
                                   + '&targetGroups='            + encodeURIComponent(routingFieldTargetGroups.getValue())
                                   + '&autoresponderTemplateId=' + encodeURIComponent(routingFieldAutoresponderTemplateId.getValue())
                                   + '&openTicket='              + encodeURIComponent(routingFieldOpenTicket.getValue())
                                   + '&targetPriority='          + encodeURIComponent(routingFieldTargetPriority.getValue())
                                   + '&targetType='              + encodeURIComponent(routingFieldTargetType.getValue())
                                   + '&assignee='                + encodeURIComponent(routingFieldAssignee.getValue())
                                   + '&copyDestinataries='       + encodeURIComponent(routingFieldCopyDestinataries.getValue())
                                   + '&piping_emails='           + encodeURIComponent(routingFieldPipingEmails.getValue())
                                   + '&piping_filterout='        + encodeURIComponent(routingFieldPipingFilterOut.getValue())
                                   + '&pop3Hostname='            + encodeURIComponent(routingFieldPop3Hostname.getValue())
                                   + '&pop3Port='                + encodeURIComponent(routingFieldPop3Port.getValue())
                                   + '&pop3_emails='             + encodeURIComponent(routingFieldPop3Emails.getValue())
                                   + '&pop3Username='            + encodeURIComponent(routingFieldPop3Username.getValue())
                                   + '&pop3Password='            + encodeURIComponent(routingFieldPop3Password.getValue())
                                   + '&pop3DeleteEmails='        + encodeURIComponent(routingFieldPop3DeleteEmails.getValue())
                                   + '&pop3_filterout='          + encodeURIComponent(routingFieldPop3FilterOut.getValue()),
                          onComplete: onCompleteAction
                         }
                        );
    }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(!routingFieldPipingFilterOut.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("Filter out");
        }

        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(!routingFieldPop3FilterOut.validate()){
            if(message != ''){
                message += newline;
            }

            message += lang("Filter out");
        }

        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(){
    new Ajax.Request('index.php?fuse=support&action=DeleteRoutingRule',
                     {parameters: 'routingId=' + encodeURIComponent(routingFieldRoutingId.getValue()),
                      onComplete: onCompleteAction
                     }
                    );
}

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
}