HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/buyercall_new/buyercall/buyercall/assets/components/inbound/inbound.js
// jshint esversion: 6

var __ = require('localize');
var Backbone = require('backbone');
var $ = require('jquery');
var utils = require('../utils');
const swal = require('sweetalert2');
let {showConfirm, createFlashMsg} = utils;
const { WhisperMessageView } = require('../backbone/whisper_message.js');

// Views
var WizardView = require('../wizard/wizard.js');
const { Agents, AgentsView, AgentsLimitedView, Agent, AgentCreationModalView } = require('../agents/agents.js');

// Models
var { PhoneNumberRouting, Routing } = require('./models');

// Templates
var callRoutingTemplate = require('./templates/call_routing.tpl');
var notificationsTemplate = require('./templates/notifications.tpl');

const API_ROOT = '/api/inbound';
const MAX_FILE_SIZE = 4 * 1024 * 1024;

var phonenumberType = '';

var InboundRouteWizardView = WizardView.extend({
    events: function () {
        return _.extend({
            'change #friendly-name': 'handleRoutingNameChange',
            'click #inbound-instructions': 'handleInboundInstructionsClick',
            'click #next': 'handleNextClick',
            'click #save': 'handleSaveClick',
        }, WizardView.prototype.events);
    },

    initialize: function () {
        phonenumberType = this.model.get('type');

        if (this.model.get('type') === 'mobile') {
            Agents.allAgents = new Agents({ excludeGroups: true });
        } else {
            Agents.allAgents = new Agents();
        }
        Agents.allAgents.fetch();
        this.model.on('change:type', () => {
            Agents.allAgents.excludeGroups = (this.model.get('type') === 'tracking') || (this.model.get('type') === 'mobile');
            Agents.allAgents.fetch();

            this.enableStep(1);
            this.setupNavigation();
        });
        this.model.on('change:phoneNumber', () => {
            this.enableStep(2);
            this.setupNavigation();
        });
        this.on('change:page', (pageNo) => {
            this.setButtonVisibility(pageNo);
        });

        this.render();
        this.setupNavigation();
    },

    render: function () {
        WizardView.prototype.render.call(this);

        this.$('#friendly-name').val(this.model.get('friendlyName'));

        var steps = this.$el.find('.wizard-step');
        new SelectNumberTypePageView({
           el: steps[0],
           model: this.model
        });
        new SecureNumberPageView({
           el: steps[1],
           model: this.model
        });
        new CallRoutingPageView({
            el: steps[2],
            parentModel: this.model,
            model: this.model.get('routingConfig')
        });
    },

    setButtonVisibility: function (pageNo) {
        console.log('Showing page ' + pageNo);

        switch (pageNo) {
            case 0:
                this.$('#next').show();
                this.$('#save').hide();
                this.$('#inbound-instructions').hide();
                if (this.model.get('type')) {
                    this.$('#next').removeAttr('disabled');
                }
                break;
            case 1:
                this.$('#next').show();
                this.$('#save').hide();
                this.$('#inbound-instructions').hide();
                break;
            case 2:
                this.$('#next').hide();
                this.$('#save').show();
                this.$('#inbound-instructions').show();
                this.$('#save').removeAttr('disabled');
                break;
        }
    },

    setupNavigation: function () {
        var phoneNumber = this.model.get('phoneNumber'),
            type = this.model.get('type');

        if (!type) {
            this.disableStep(1);
            this.disableStep(2);
            this.disableStep(3);
        } else {
            this.enableStep(1);
            this.enableStep(2);
        }

        if (!phoneNumber) {
            this.disableStep(2);
            this.disableStep(3);
        } else {
            this.enableStep(1);
            this.enableStep(2);
            this.enableStep(3);
            this.$('.secure_number_text').text(__('2. NUMBER DETAILS'));
        }

        if (this.model.id) {
            this.showStep(2);
            this.disableStep(0);
            this.$('#save').removeAttr('disabled');
            this.$('#inbound-instructions').removeAttr('disabled');
        } else {
            this.setButtonVisibility(0);
        }
    },

    openInboundInstructions: function () {
        window.location.href = `/inbound/install-instructions/${this.model.id}`;
    },

    handleNextClick: function () {
        this.showNextStep();
    },

    handleRoutingNameChange: function () {
        this.model.set({ friendlyName: this.$('#friendly-name').val() });
    },

    handleInboundInstructionsClick: function () {
        if (!this.model.changedAttributes()) {
            window.location.href = `/inbound/install-instructions/${this.model.id}`;
            return;
        }

        var saveModel = confirm('Would you like to save the routing?');
        if (saveModel) {
            this.model.save().done(() => {
                this.openInboundInstructions();
            });
        }
    },

    handleSaveClick: function (evt) {
        var title = 'Activate ' + utils.formatNumber(this.model.get('phoneNumber')) + '?',
            text = 'You will not be able to change the phone number afterwards. You will, however, be able to change the phone number configuration after activation.',
            type = 'warning',
            buttonText = 'Activate',
            newNumber = !this.model.id;

        evt.target.setAttribute('disabled', 'disabled');

        if (!newNumber) {
            title = 'Save this phone number?';
            text = 'Your changes will be applied.';
            type = 'info';
            buttonText = 'Save';
        }

        swal({
            title: title,
            text: text,
            type: type,
            showCancelButton: true,
            confirmButtonColor: '#03a9f4',
            cancelButtonColor: '#f44336',
            confirmButtonText: buttonText
        }).then((x) => {
            return this.model.save();
        }).then((x) => {
            this.model.set({ id: this.model.id }, { silent: true });

            this.$('#inbound-instructions').removeAttr('disabled');
            this.openInboundInstructions();
            evt.target.removeAttribute('disabled');
        }).catch((reason) => {
            if (reason !== 'cancel') {
                utils.flash(__('The routing could not be saved.','danger'));
            }
            evt.target.removeAttribute('disabled');
        });
    }
});

// First wizard page: Select Type
var SelectNumberTypePageView = Backbone.View.extend({
    events: {
        'change:value': 'handleTypeChange'
    },

    handleTypeChange: function () {
        this.model.set('type', this.$('input:checked').val());
    },
});

// Second wizard page: Secure Number
var SecureNumberPageView = Backbone.View.extend({
    events: {
        'click #search-pn': 'handleSearchClick',
        'change #channel-pn': 'handleChannelChange',
        'change #source-pn': 'handleSourceChange',
        'change input[type=radio]': 'handleSelectNumberChange',
        'change select[name=type-pn]': 'handleNumberTypeChange'
    },

    initialize: function () {
        var phoneNumber = this.model.get('phoneNumber');
        if (phoneNumber) {
            this.$('#pn-edit-pn-type, #local-code, #toll-free-code, #pn-edit-mode-text, #pn-edit-mode-button' ).hide();
        }
        this.listenTo(this.model, 'change:type', () => {
            this.clearResults();
            if (this.model.get('type') === 'mobile') {
                this.$('#pn-edit-pn-type').hide();
                this.$('#local-code').addClass('col-md-6').removeClass('col-md-3');
                this.$('.type-pn').val('local');
                this.$('#toll-free-code').hide();
                this.$('#local-code').show();
            } else {
                this.$('#pn-edit-pn-type').show();
                this.$('#local-code').addClass('col-md-3').removeClass('col-md-6');
            };
        });
    },

    handleSearchClick: function (options) {
        var $code, tollfree;
        this.parentModel = options.parentModel;

        if ($('.type-pn').val() ==='local') {
            $code = this.$('#area-code').val();
        } else {
            $code = this.$('#free-code').val();
        }

        tollfree = (this.$('select[name=type-pn]').val() === 'tollfree');
        this.$('#search-pn').prop('disabled', true);

        $.ajax({
            url: `${API_ROOT}/search`,
            data: {
                tollfree: tollfree,
                type: this.model.get('type'),
                prefix: $code,
                phrase: this.$('#phrase').val()
            },
            success: (results) => {
                var $results = this.$('#pn-results');
                this.$('#search-pn').prop('disabled', false);

                $results.empty();
                if (results.data.length > 15) {
                    results.data.length = 15;
                }
                for (var i = 0; i < results.data.length; i++) {
                    var item = $('<div>').addClass('radio col-md-4');
                    var label = $('<label>').addClass('pn-results-label');
                    var circle = $('<span>').addClass('circle');
                    var check = $('<span>').addClass('check');
                    var input = $('<input>').attr('type', 'radio').attr('name', 'pn-new');
                    label.text(utils.formatNumber(results.data[i]));
                    input.attr('value', results.data[i]).
                    text(utils.formatNumber(results.data[i]));
                    label.append(input,circle,check);
                    item.append(label);
                    item.appendTo($results);
                }
                if (results.data.length === 0) {
                    utils.flash(__('There is no phone number based on your search terms.'),'warning');
                } else {
                    this.model.set({ phoneNumber: $results.val() });
                }
            },
            error: (xhr, status, errorThrown) => {
                this.$('#search-pn').prop('disabled', false);
                utils.flash(xhr.responseText, 'danger');
            }
        });
     },

    clearResults: function () {
        this.$('#pn-results').empty();
        this.model.set({ phoneNumber: null });
    },

    handleSelectNumberChange: function (evt) {
        this.model.set({
            phoneNumber: $("input[type=radio][name=pn-new]:checked").val()
        });
    },

    handleNumberTypeChange: function (evt) {
        var numberType = this.$('select[name=type-pn]').val();
        this.model.set('typePn', numberType);
    },

    handleChannelChange: function (evt) {
        this.model.set('channel', this.$('#channel-pn').val());
    },

    handleSourceChange: function (evt) {
        this.model.set('source', this.$('#source-pn').val());
    }
});

// Third wizard page: Configure Settings
// Model class: RoutingConfig
var CallRoutingPageView = Backbone.View.extend({
    events: {
        'change #routing-type-default': 'handleRoutingTypeDefaultSelection',
        'change #routing-type-digit': 'handleRoutingTypeDigitSelection',
        'click #add-routing': 'handleAddRoutingClick',
        'change input[type=checkbox]': 'handleCheckboxChange',
        'change select': 'handleInputChange',
        'change textarea': 'handleInputChange',
        'change input': 'handleInputChange',
        'change input[name=notify-leads]': 'handleNotifyChange',
        'change #caller-name-pn': 'handleCallerIdChange',
        'change #SMSAutoReply': 'handleSMSAutoReply',
        'change #MissedCallAutoReply': 'handleSMSMissedCallReply',
        'change #SMSAutoReplyImage': 'handleSMSImageUpload',
        'click #remove-mms-attachment': 'handleRemoveMMSUpload',
        'change #SMSRuleOne': 'handleSMSRule01',
        'change #SMSRuleOneRecipientType': 'handleSMSRule01TypeSelect',
        'change #SMSRuleOneAction': 'handleSMSRule01ActionChange',
        'change #voicemail': 'handleVoicemailChange',
        'change #clientVoicemail': 'handleClientVoicemailChange',
        'change #caller-id-pn': 'handleCallerIdPnChange',
    },

    initialize: function (options) {
        this.parentModel = options.parentModel;
        this.allAgents = new Agents({ excludeGroups: true });
        this.render();
        this.listenTo(this.parentModel, 'change:friendlyName', function (model, val) {
            this.$('#friendly-name').text(val);
        });
        this.listenTo(this.parentModel, 'change:phoneNumber', function () {
            var selectedPhoneNumber = utils.formatNumber(this.parentModel.get('phoneNumber'));
            this.$('#phone-number').text(selectedPhoneNumber);
            if (this.parentModel.get('subscriptionPlan') == 'partnershipsingle') {
                this.$('#forwarding-routing-title').text('We will forward all calls for your new phone number(' + selectedPhoneNumber + ') to:')
            } else if (this.parentModel.get('type') == 'tracking') {
                this.$('#forwarding-routing-title').text('Select who needs to receive the calls to ' + selectedPhoneNumber + ' & with what device')
            } else if (this.parentModel.get('type') == 'mobile') {
                this.$('#forwarding-routing-title').text('The mobile app number is: ' + selectedPhoneNumber + '. Now select the agent that needs to be associated with the mobile number')
            }
            else {
                this.$('#forwarding-routing-title').text('Setup the call routing agents and features for ' + selectedPhoneNumber)
            }
        });
        this.listenTo(this.parentModel, 'change:type', function() {
            if (!this.model.get('configSMSSetup') && this.parentModel.get('type') == 'mobile') {
                if (this.parentModel.get('type') == 'mobile') {
                    this.model.set('configSMSSetup', true);
                }
            }
            else {
                this.model.set('configSMSSetup', false);
            }
        });
        this.listenTo(this.parentModel, 'change:type', this.showAdvancedOptions);
        this.listenTo(this.model, 'change:greetingMessage', this.showGreetingSection);
        this.listenTo(this.model, 'change:routingType', this.showRoutingSection);
        this.listenTo(this.model, 'change:playHoldMusic', this.showHoldMusicSection);
        this.listenTo(this.model, 'change:customHoldMusic', this.showUploadSection);
        this.listenTo(this.model, 'change:clientVoicemail', this.showClientVoicemailSection);
        this.listenTo(this.model, 'change:voicemail', this.showVoicemailSection);
        this.listenTo(this.model, 'change:callBack', this.showCallbackSection());
        this.listenTo(this.model, 'change:callBackMessage', this.showCallbackMessageSection);
        this.listenTo(this.model, 'change:configSMSSetup', this.showSMSSection);
    },
    handleCallerIdChange: function (evt) {
        this.parentModel.set({
            callerId: $('#caller-name-pn').prop('checked')
        });
    },
    handleCallerIdPnChange: function (evt) {
        this.parentModel.set({
            callerIdPn: $('#caller-id-pn').prop('checked')
        });
    },
    handleVoicemailChange: function (evt) {
        if (this.model.get('voicemail')) {
            this.$('#voicemail-message-container').show();
            this.$('#clientVoicemail').prop('checked', false);
            this.model.set('voicemail', true);
            this.model.set('clientVoicemail', false);
            if (this.model.get('voicemailMessageType') == '') {
                this.$('[name=voicemail-message-type][value=text]').click();
            }
        } else {
            this.$('#voicemail-message-container').hide();
        }
    },
    handleClientVoicemailChange: function (evt) {
        if (this.model.get('clientVoicemail')) {
            this.$('#voicemail').prop('checked', false);
            this.$('#voicemail-message-container').hide();
            this.model.set('clientVoicemail', true);
            this.model.set('voicemail', false);
        }
    },
    render: function () {
        var that = this;
        this.$('#single-agent').hide();
        var selectedPhoneNumber = utils.formatNumber(this.parentModel.get('phoneNumber'));
        this.$('#phone-number').text(selectedPhoneNumber);
        this.$('#friendly-name').text(this.parentModel.get('friendlyName'));

        if (this.parentModel.get("callerId")) {
            this.$('#caller-name-pn').prop('checked', true)
        } else {
            this.$('#caller-name-pn').prop('checked', false)
        };
        if (this.parentModel.get("callerIdPn")) {
            this.$('#caller-id-pn').prop('checked', true)
        } else {
            this.$('#caller-id-pn').prop('checked', false)
        };
        if (this.model.get('greetingMessage')) {
            this.$('#greetingMessage').prop('checked', true)
            this.$('#whisper-message-container').show();
        } else {
            this.$('#whisper-message-container').hide();
            this.$('#greetingMessage').prop('checked', false)
        }
        if (this.model.get('callBackMessage')) {
            this.$('#callBackMessage').prop('checked', true)
            this.$('#call-back-text-container').show();
        } else {
            this.$('#call-back-text-container').hide();
            this.$('#callBackMessage').prop('checked', false)
        }

        if (this.parentModel.get('subscriptionPlan') == 'partnershipsingle') {
                this.$('#forwarding-routing-title').text('We will forward all calls for your new phone number(' + selectedPhoneNumber + ') to:')
                this.$('#caller-id-pn-title').text('Use ' + selectedPhoneNumber + ' as the caller id shown to the routing agent(s):')
        } else if (this.parentModel.get('type') == 'tracking') {
            this.$('#forwarding-routing-title').text('Select who needs to receive the calls to ' + selectedPhoneNumber + ' & with what device')
            this.$('#caller-id-pn-title').text('Use ' + selectedPhoneNumber + ' as the caller id shown to the routing agent(s):')
        } else if (this.parentModel.get('type') == 'mobile') {
                this.$('#forwarding-routing-title').text('The mobile app number is: ' + selectedPhoneNumber + '. Now select the agent that needs to be associated with the mobile number')
        } else {
            this.$('#forwarding-routing-title').text('Setup the call routing agents and features for ' + selectedPhoneNumber)
            this.$('#caller-id-pn-title').text('Use ' + selectedPhoneNumber + ' as the caller id shown to the routing agent(s):')
        }


        this.listenTo(this.parentModel, 'change:phoneNumber', function () {
            var selectedPhoneNumber = utils.formatNumber(this.parentModel.get('phoneNumber'));
            if (this.parentModel.get('subscriptionPlan') == 'partnershipsingle') {
                if (this.parentModel.get('phoneNumber')) {
                    this.$('#forwarding-routing-title').text('We will forward all calls for your new phone number('+utils.formatNumber(this.parentModel.get('phoneNumber'))+') to:')
                    this.$('#caller-id-pn-title').text('Use ' + selectedPhoneNumber + ' as the caller id shown to the routing agent(s):')
                } else {
                    this.$('#forwarding-routing-title').text('We will forward all calls for your new phone number(' + selectedPhoneNumber + ') to:')
                    this.$('#caller-id-pn-title').text('Use ' + selectedPhoneNumber + ' as the caller id shown to the routing agent(s):')
                }
            } else if (this.parentModel.get('type') == 'tracking') {
                this.$('#forwarding-routing-title').text('Select who needs to receive the calls & with what device')
                this.$('#caller-id-pn-title').text('Use ' + selectedPhoneNumber + ' as the caller id shown to the routing agent(s):')
            } else {
                this.$('#forwarding-routing-title').text('Setup the call routing agents and features')
                this.$('#caller-id-pn-title').text('Use ' + selectedPhoneNumber + ' as the caller id shown to the routing agent(s):')
            }
        });

        var agent = this.model.get('defaultRouting').get('agents').at(0);
        this.showRoutingSection();
        this.showGreetingSection();
        this.setupUploadSection();
        this.showHoldMusicSection();
        this.setupSMSUploadSection();
        this.showSMSSection();
        this.showSMSAttachments();
        this.showUploadSection();
        this.disableNotifyAdfRecipients();

        this.showAdvancedOptions();

        new NotificationsView({
            el: this.$('#tab3Notifications'),
            model: this.parentModel.get('notificationConfig'),
            routingModel: this.model,
        }).render();

        if (this.parentModel.get('subscriptionPlan') == 'partnershipsingle') {
            this.$('#adf-notification-section').hide()
            this.$('#all-routing-agents').hide()
            this.$('#missed-routing-agents').hide()
        } else {
            this.$('#adf-notification-section').show()
            this.$('#all-routing-agents').show()
            this.$('#missed-routing-agents').show()
        }
        this.$('#digit-routing-list').empty();
        this.$('#default-routing').empty();

        var digitRoutings = this.model.get('digitRoutings');
        digitRoutings.forEach((model) => {
            new DigitRoutingView({
                parentModel: this.parentModel,
                model: model
            }).$el.appendTo(this.$('#digit-routing-list'));
        });

        new DefaultRoutingView({
            parentModel: this.parentModel,
            model: this.model.get('defaultRouting'),
        }).$el.appendTo(this.$('#default-routing'));

        for (let attr in this.model.attributes) {
            let value = this.model.get(attr),
                control = this.$('#' + utils.propertyNameToId(attr, ''));

            switch (typeof value) {
                case 'boolean':
                    control.prop('checked', value);
                    break;
                case 'string':
                    control.val(value);
                    break;
            }
        }

        // Select the whisper type radio buttons
        for (let modelField of [
            'whisperMessageType', 'digitWhisperMessageType',
            'noDigitWhisperMessageType', 'voicemailMessageType', 'callBackMessageType'
        ]) {
            if (!this.model.get('modelField')) {
                continue;
            }

            this.$(utils.format(
                'input[name={0}][value={1}]',
                utils.propertyNameToId(modelField, ''),
                this.model.get(modelField)
            )).prop('checked', true);
        }

        for (let el of [
            '#whisper-message-container', '#digit-whisper-message-container',
            '#no-digit-whisper-message-container', '#voicemail-message-container',
            '#call-back-text-container'
        ]) {
            new WhisperMessageView({
                el: el,
                model: this.model,
            });
        }
        this.showVoicemailSection();
        this.showClientVoicemailSection();
        this.showCallbackSection();
        return this;
    },

    showGreetingSection: function () {
        if (this.model.get('greetingMessage')) {
            this.$('#whisper-message-container').fadeIn();
            this.$('.language-feature-field').fadeIn();
            if (this.model.get('whisperMessageType') == '') {
                this.$('[name=whisper-message-type][value=text]').click()
            }
        } else {
            this.$('#whisper-message-container').hide();
            this.$('.language-feature-field').hide();
        }
    },

    showRoutingSection: function () {
        var routingType = this.model.get('routingType'),
            routingDefault = (routingType === 'default');

        if (routingDefault && this.parentModel.get("subscriptionPlan") != 'partnershipsingle' ) {
            this.$('#default-routing').show();
            this.$('#digit-routings').hide();
        } else {
            this.$('#default-routing').hide();
            this.$('#digit-routings').show();
        }

        if (this.parentModel.get("subscriptionPlan") == 'partnershipsingle') {
            this.$('#default-routing').hide()
            this.$('#single-agent').show()
        } else {
            this.$('#default-routing').show()
            this.$('#single-agent').hide()
        }

        this.$('#routing-type-default').prop('checked', routingDefault);
        this.$('#routing-type-digit').prop('checked', !routingDefault);
    },

    setupUploadSection: function () {
        var that = this;

        this.$('#hold-music-container .upload-music').dropzone({
            url: '/inbound/hold-music',

            headers: {
                'X-CSRFToken': $('meta[name="csrf-token"]').attr('content')
            },

            init: function () {
                this.on('addedfile', function (file) {
                    utils.flash('');

                    if (file.size > MAX_FILE_SIZE) {
                        utils.flash(__('File size must be < 4 MB.'), 'danger');
                        this.removeAllFiles();
                        return;
                    }
                });
            },

            success: function (file, response, xhr) {
                utils.flash(__('File uploaded successfully.'), 'success');
                that.model.set('holdMusicId', response.guid);
                that.model.set('holdMusicFilename', response.filename);
            },

            error: function (file, response, xhr) {
                utils.flash(__('File upload failed. Please make sure you use a mp3 or wav file format.'), 'danger');
            },

            complete: function () { }
        });
    },

    showHoldMusicSection: function (animate) {
        if (this.model.get('playHoldMusic')) {
            this.$('#hold-music-container').fadeIn();
        } else {
            this.$('#hold-music-container').hide();
        }
    },

    showUploadSection: function () {
        if (this.model.get('customHoldMusic')) {
            this.$('#hold-music-container .upload-music').fadeIn();
        } else {
            this.$('#hold-music-container .upload-music').hide();
        }
    },

    showCallbackSection: function () {
        if (this.model.get('callBack')) {
            this.$("#call-back-interval-container").fadeIn()
            this.$('#first-call-back,#second-call-back,#third-call-back,#call-back-text').prop('disabled',false);
            this.$('#first-call-back,#second-call-back,#third-call-back,#call-back-text').removeClass('grey-disabled');
        } else {
            this.$("#call-back-interval-container").hide()
            this.$('#first-call-back,#second-call-back,#third-call-back,#call-back-text').prop('disabled',true);
            this.$('#first-call-back,#second-call-back,#third-call-back,#call-back-text').addClass('grey-disabled');
        }
    },

    showCallbackMessageSection: function () {
        if (this.model.get('callBackMessage')) {
            this.$('#call-back-text-container').fadeIn();
            if (this.model.get('callBackTextType') == '') {
                this.$('[name=call-back-text-type][value=text]').click()
            }
        } else {
            this.$('#call-back-text-container').hide();
        }
    },
    showVoicemailSection: function () {
        if (this.model.get('voicemail')) {
            this.$('#voicemail-message-container').show();
            if (this.model.get('voicemailMessageType') == '') {
                this.$('[name=voicemail-message-type][value=text]').click();
            }
        } else {
            this.$('#voicemail-message-container').hide();
        }
    },
    showClientVoicemailSection: function () {
        if (this.parentModel.get('type') === 'tracking') {
            this.$('#personal-voicemail').show();
        } else {
            this.$('#personal-voicemail').hide();
        }
        if (this.model.get('clientVoicemail')) {
            this.$('#clientVoicemail').prop('checked', true);
        }
    },
    setupSMSUploadSection: function () {
        var that = this;

        this.$('#sms-setup-container .upload-music').dropzone({
            url: '/inbound/sms-attachment',

            headers: {
                'X-CSRFToken': $('meta[name="csrf-token"]').attr('content')
            },

            init: function () {
                this.on('addedfile', function (file) {
                    utils.flash('');

                    if (file.size > MAX_FILE_SIZE) {
                        utils.flash(__('File size must be less than 4 MB.'), 'danger');
                        this.removeAllFiles();
                        return;
                    }
                });
            },

            success: function (file, response, xhr) {
                utils.flash(__('File uploaded successfully.'), 'success');
                that.model.set('SMSAutoReplyImageUrl', response.image_url);
                that.$('#attachment-files').show()
                that.$('#remove-mms-attachment').show()
                that.$('#attachment-files').html('<div class="card-avatar"><a href="#" class="img"><img class="img" id="mms_image_thumb" src=""></a>')
                var url = that.model.get('SMSAutoReplyImageUrl')
                that.$("#mms_image_thumb").attr("src", url);
                that.$('#add-image-section').hide()
                that.$('.sms-attachements').show()

            },

            error: function (file, response, xhr) {
                utils.flash(__('File upload failed. Please try again.'), 'danger');
            },

            complete: function () { }
        });
    },

    showSMSSection: function (animate) {
        var that = this;
        showSection();
        function showSection() {
            if (that.model.get('configSMSSetup')) {
                //if (that.parentModel.get('type') === 'tracking') {
                //    that.$('#priority-feature').hide();
                //}
                that.$('#configSMSSetup').prop('checked', true);
                that.$('#sms-setup-container').show();
                if (that.model.get('SMSAutoReply')) {
                    that.$('#SMSAutoReply').prop('checked', true);
                    that.$('#sms-auto-reply-section').show();
                    that.$('#SMSAutoReplyText').val(that.model.get('SMSAutoReplyText'));
                }
                else {
                    that.$('#sms-auto-reply-section').hide();
                    that.$('#SMSAutoReply').prop('checked', false);
                }
                if (that.model.get('MissedCallAutoReply')) {
                    that.$('#MissedCallAutoReply').prop('checked', true);
                    that.$('#sms-missed-call-section').show();
                    that.$('#MissedCallAutoReplyText').val(that.model.get('MissedCallAutoReplyText'));
                }
                else {
                    that.$('#sms-missed-call-section').hide();
                    that.$('#MissedCallAutoReply').prop('checked', false);
                }
                if (that.model.get('SMSRuleOne')) {
                    that.$('#SMSRuleOne').prop('checked', true);
                    that.$('#sms-rule-one-call-section').show();
                    that.$('#SMSRuleOneKeyword').val(that.model.get('SMSRuleOneKeyword'));
                    that.$('#SMSRuleOneAction').val(that.model.get('SMSRuleOneAction'));
                    that.$('#SMSRuleOneRecipientType').val(that.model.get('SMSRuleOneRecipientType'));
                    if (that.model.get('SMSRuleOneRecipientType') == 'custom') {
                        that.$('#rule-one-call-agent').hide();
                        if (that.model.get('SMSRuleOneAction') == 'email') {
                            that.$('#rule-one-email').show()
                            that.$('#rule-one-type-custom').hide()
                            that.$('#SMSEmailBody').show()
                            if (that.model.get('SMSRuleOneEmailBody') != '') {
                                that.$('#SMSRuleOneEmailBody').val(that.model.get('SMSRuleOneEmailBody'));
                            }
                            if (that.model.get('SMSRuleOneEmails') != '') {
                                that.$('#SMSRuleOneEmails').val(that.model.get('SMSRuleOneEmails'));
                            }
                        }
                        else {
                            that.$('#rule-one-type-custom').show()
                            that.$('#rule-one-email').hide()
                            that.$('#SMSEmailBody').hide()

                        }
                        that.$('#rule-one-type-agent').hide()
                        that.$('#rule-one-email-agent').hide();
                        that.$('#rule-one-call-agent').hide();
                        that.$('#SMSRuleOneRecipientCustom').val(that.model.get('SMSRuleOneRecipientCustom'));
                    }
                    else if (that.model.get('SMSRuleOneRecipientType') == 'agent') {
                        that.$('#rule-one-call-agent').hide();
                        that.$('#rule-one-type-custom').hide()
                        that.$('#rule-one-email').hide()
                        if (that.model.get('SMSRuleOneAction') == 'email') {
                            that.$('#rule-one-email-agent').show();
                            that.$('#rule-one-call-agent').hide();
                            that.$('#rule-one-type-agent').hide();
                            if (that.model.get('SMSRuleOneEmailAgent') != '') {
                                that.allAgents.each((agent) => {
                                    that.$('.email-agent-select').append(
                                    `<option value=${agent.id}>${agent.getFullName()}</option>`
                                );
                                    that.$('.email-agent-select').val(that.model.get('SMSRuleOneEmailAgent'));
                                });
                            }
                            else {
                                that.allAgents.each((agent) => {
                                    that.$('.email-agent-select').append(
                                    `<option value=${agent.id}>${agent.getFullName()}</option>`
                                    );
                                });
                                that.$('.email-agent-select').prepend("<option value=''>[select agent]</option>").val('');
                            }
                            that.$('#SMSEmailBody').show()
                            if (that.model.get('SMSRuleOneEmailBody') != '') {
                                that.$('#SMSRuleOneEmailBody').val(that.model.get('SMSRuleOneEmailBody'));
                            }
                        }
                        else if (that.model.get('SMSRuleOneAction') == 'sms') {
                            that.$('#SMSEmailBody').hide();
                            that.$('#rule-one-email-agent').hide();
                            that.$('#rule-one-call-agent').hide();
                            if (that.model.get('SMSRuleOneRecipientAgent') != '') {
                                that.allAgents.each((agent) => {
                                    that.$('.sms-agent-select').append(
                                    `<option value=${agent.id}>${agent.getFullName()}</option>`
                                );
                                    that.$('.sms-agent-select').val(that.model.get('SMSRuleOneRecipientAgent'));
                                });
                            }
                            else {
                                 that.allAgents.each((agent) => {
                                    that.$('.sms-agent-select').append(
                                    `<option value=${agent.id}>${agent.getFullName()}</option>`
                                    );
                                });
                                that.$('.sms-agent-select').prepend("<option value=''>[select agent]</option>").val('');
                            }
                        }
                        else {
                            that.$('#rule-one-type-agent').show();
                            that.$('#rule-one-email-agent').hide();
                            this.$('#rule-one-call-agent').hide();
                            that.$('#SMSEmailBody').hide()
                        }
                    }
                    else if (that.model.get('SMSRuleOneRecipientType') == 'lead') {
                        if (that.model.get('SMSRuleOneAction') == 'unsubscribe') {
                            that.$("#SMSRuleOneRecipientType option[value='agent'], #SMSRuleOneRecipientType option[value='custom'], #SMSRuleOneRecipientType option[value='']").remove()
                        }
                        if (that.model.get('SMSRuleOneAction') == 'call') {
                            that.$('#rule-one-call-agent').show();
                            that.$('#SMSEmailBody').hide();
                            if (that.model.get('SMSRuleOneCallAgent') != '') {
                                that.allAgents.each((agent) => {
                                    that.$('.call-agent-select').append(
                                    `<option value=${agent.id}>${agent.getFullName()}</option>`
                                );
                                    that.$('.call-agent-select').val(that.model.get('SMSRuleOneCallAgent'));
                                });
                            }
                            else {
                                 that.allAgents.each((agent) => {
                                    that.$('.call-agent-select').append(
                                    `<option value=${agent.id}>${agent.getFullName()}</option>`
                                    );
                                });
                                that.$('.call-agent-select').prepend("<option value=''>[select agent]</option>").val('');
                            }
                        }
                        else if (that.model.get('SMSRuleOneAction') == 'sms' || that.model.get('SMSRuleOneAction') == 'unsubscribe') {
                            that.$('#rule-one-call-agent').hide();
                            that.$('#SMSEmailBody').hide();
                        }
                        else if (that.model.get('SMSRuleOneAction') == 'email') {
                            that.$('#rule-one-call-agent').hide();
                            that.$('#SMSEmailBody').show();
                            if (that.model.get('SMSRuleOneEmailBody') != '') {
                                that.$('#SMSRuleOneEmailBody').val(that.model.get('SMSRuleOneEmailBody'));
                            }
                        }
                        that.$('#rule-one-type-custom').hide();
                        that.$('#rule-one-type-agent').hide();
                        that.$('#rule-one-email').hide();
                        that.$('#rule-one-email-agent').hide();
                    }
                    else {
                        that.$('#rule-one-type-custom').hide();
                        that.$('#rule-one-type-agent').hide();
                        that.$('#rule-one-email').hide();
                        that.$('#rule-one-email-agent').hide();
                        that.$('#rule-one-call-agent').hide();
                        that.$('#SMSEmailBody').hide()
                    }
                    if (that.model.get('SMSRuleOneAction') == '' ) {
                        that.$('#SMSRuleOneRecipientType').hide();
                        that.$('.no-contact-method').hide();
                        that.$('#SMSTextBody').hide();
                        that.$('#rule-one-email').hide();
                        that.$('#SMSEmailBody').hide();
                        that.$('#rule-one-call-agent').hide();
                    }
                    else {
                        if ((that.model.get('SMSRuleOneAction') == 'sms') && (that.model.get('SMSRuleOneRecipientType') != '')) {
                            if (that.model.get('SMSRuleOneSMSBody') != '') {
                                that.$('#SMSRuleOneSMSBody').val(that.model.get('SMSRuleOneSMSBody'));
                            }
                        }
                        else {
                            that.$('#SMSTextBody').hide()
                        }
                    }
                }
                else {
                    that.$('#sms-rule-one-call-section').hide();
                    that.$('#SMSRuleOne').prop('checked', false);
                }
            } else {
                that.$('#sms-setup-container').hide();
                that.$('#configSMSSetup').prop('checked', false);
            }
        }
        if (this.model.get('configSMSSetup')) {
            if (!this.allAgents.isEmpty()) {
                console.log("The agent list is for the sms rule is not empty")
                this.allAgents.fetch({
                    success: () => {
                        showSection();
                    }
                });
            } else {
                console.log("The agent list for the sms rule is empty")
                this.allAgents.fetch({
                    success: () => {
                        showSection();
                    }
                });
            }
        }
    },

    handleSMSAutoReply: function (evt) {
        if (this.model.get('SMSAutoReply')) {
            this.$('#SMSAutoReply').prop('checked', true);
            this.$('#sms-auto-reply-section').show();
            this.$('#SMSAutoReplyText').val(this.model.get('SMSAutoReplyText'));
        }
        else {
            this.$('#sms-auto-reply-section').hide();
            this.$('#SMSAutoReply').prop('checked', false);
            }
    },

    handleSMSMissedCallReply: function (evt) {
        if (this.model.get('MissedCallAutoReply')) {
            this.$('#MissedCallAutoReply').prop('checked', true);
            this.$('#sms-missed-call-section').show();
            this.$('#MissedCallAutoReplyText').val(this.model.get('MissedCallAutoReplyText'));
        }
        else {
            this.$('#sms-missed-call-section').hide();
            this.$('#MissedCallAutoReply').prop('checked', false);
            }
    },

    showSMSAttachments: function() {
        if (this.model.get('SMSAutoReplyImageUrl')) {
            this.$('.sms-attachements').show()
            this.$('#add-image-section').hide();
            this.$('#attachment-files').html('<div class="card-avatar"><a href="#" class="img"><img class="img" id="mms_image_thumb" src=""></a>')
            var url = this.model.get('SMSAutoReplyImageUrl')
            this.$("#mms_image_thumb").attr("src", url);
        }
        else {
            this.$('#add-image-section').show();
            this.$('.sms-attachements').hide()
        }
        if (this.model.get('SMSAutoReplyImage')) {
            this.$('#SMSAutoReplyImage').prop('checked', true);
            this.$('#attachment-upload-section').show();
        }
        else {
            this.$('#attachment-upload-section').hide();
            this.$('#SMSAutoReplyImage').prop('checked', false);
            }
    },

    handleSMSImageUpload: function (evt) {
        if (this.model.get('SMSAutoReplyImage')) {
            this.$('#SMSAutoReplyImage').prop('checked', true);
            this.$('#attachment-upload-section').show();
            //'this.$('#MissedCallAutoReplyText').val(this.model.get('MissedCallAutoReplyText'));
        }
        else {
            this.$('#attachment-upload-section').hide();
            this.$('#SMSAutoReplyImage').prop('checked', false);
            }
    },

    handleRemoveMMSUpload: function (evt) {
        this.$('#attachment-files').hide()
        this.$('#remove-mms-attachment').hide()
        this.model.set('SMSAutoReplyImageUrl', '')
        this.$('#add-image-section').show();
        this.$('#SMSAutoReplyImage').prop('checked', true);
        this.$('#attachment-upload-section').show();
        this.$('.sms-attachements').hide()
    },

    handleSMSRule01: function (evt) {
        if (this.model.get('SMSRuleOne')) {
            this.$('#SMSRuleOne').prop('checked', true);
            this.$('#sms-rule-one-call-section').show();
            this.$('#rule-one-call-agent').hide();
            if (this.model.get('SMSRuleOneKeyword') != '') {
                this.$('#SMSRuleOneKeyword').val(this.model.get('SMSRuleOneKeyword'))
            }
            if (this.model.get('SMSRuleOneAction') != '') {
                this.$('#SMSRuleOneAction').val(this.model.get('SMSRuleOneAction'))
            }
            else if (this.model.get('SMSRuleOneAction') != 'call') {
                this.$("#SMSRuleOneRecipientType option[value='agent']").remove();
            }
            else {
                this.$('#SMSRuleOneRecipientType').hide()
                this.$('.no-contact-method').hide()
                this.$('#SMSTextBody').hide();
                this.$('#SMSEmailBody').hide();
                this.$('#rule-one-type-custom').hide();
                this.$('#rule-one-type-agent').hide();
                this.$('#rule-one-email').hide()
                this.$('#rule-one-email-agent').hide();
                this.$('#rule-one-call-agent').hide();
            }
            if (this.model.get('SMSRuleOneRecipientType') != '') {
                this.$('#SMSRuleOneRecipientType').val(this.model.get('SMSRuleOneRecipientType'))
                if (this.$('#SMSRuleOneRecipientType').val() == 'custom') {
                    if (this.$('#SMSRuleOneAction') == 'email') {
                        this.$('#rule-one-email').show()
                        this.$('#rule-one-type-custom').hide()
                        this.$('#SMSEmailBody').show();
                        if (this.model.get('SMSRuleOneEmailBody') != '') {
                            this.$('#SMSRuleOneEmailBody').val(this.model.get('SMSRuleOneEmailBody'));
                        }
                    }
                    else {
                        this.$('#rule-one-type-custom').show()
                        this.$('#rule-one-email').hide()
                        this.$('#SMSEmailBody').hide();
                    }
                    this.$('#rule-one-type-agent').hide()
                    this.$('#SMSRuleOneRecipientCustom').val(this.model.get('SMSRuleOneRecipientCustom'))
                }
                else if (this.$('#SMSRuleOneRecipientType').val() == 'agent') {
                    if (this.$('#SMSRuleOneAction').val() == 'email') {
                        this.$('#rule-one-email-agent').show()
                        this.$('#rule-one-call-agent').hide();
                        this.$('#rule-one-type-agent').hide()
                        if (this.model.get('SMSRuleOneEmailAgent') != '') {
                            this.$('#SMSRuleOneEmailAgent').val(this.model.get('SMSRuleOneEmailAgent'));
                        }
                        this.$('#SMSEmailBody').show();
                        if (this.model.get('SMSRuleOneEmailBody') != '') {
                            this.$('#SMSRuleOneEmailBody').val(this.model.get('SMSRuleOneEmailBody'));
                        }
                    }
                    else {
                        this.$('#rule-one-email-agent').hide()
                        this.$('#rule-one-type-agent').show()
                        this.$('#rule-one-call-agent').hide();
                        this.$('#SMSEmailBody').hide();
                        if (this.model.get('SMSRuleOneRecipientAgent') != '') {
                            this.$('#SMSRuleOneRecipientAgent').val(this.model.get('SMSRuleOneRecipientAgent'));
                        }
                    }
                    this.$('#rule-one-type-custom').hide()
                    this.$('#rule-one-email').hide()
                    this.$('#rule-one-call-agent').hide();
                }
                else if (this.$('#SMSRuleOneRecipientType').val() == 'lead') {
                    if (this.$('#SMSRuleOneAction').val() == 'call') {
                        this.$('#rule-one-call-agent').show();
                    }
                }
                else {
                    this.$('#rule-one-type-custom').hide()
                    this.$('#rule-one-type-agent').hide()
                    this.$('#rule-one-email').hide()
                    this.$('#rule-one-call-agent').hide();
                }
            }
            else {
                this.$('.no-contact-method').hide()
                this.$('#SMSTextBody').hide();
                this.$('#SMSEmailBody').hide();
                this.$('#rule-one-type-custom').hide();
                this.$('#rule-one-type-agent').hide();
                this.$('#rule-one-email-agent').hide();
                this.$('#rule-one-email').hide();
                this.$('#SMSRuleOneRecipientType').hide();
            }
        }
        else {
            this.$('#sms-rule-one-call-section').hide();
            this.$('#SMSRuleOne').prop('checked', false);
            }
    },

    handleSMSRule01TypeSelect: function (evt) {
        if (this.$('#SMSRuleOneRecipientType').val() == 'custom') {
            this.$('.sms-agent-select option').remove();
            this.$('.email-agent-select option').remove();
            if (this.$('#SMSRuleOneAction').val() == 'email') {
                this.$('#rule-one-email').show();
                this.$('#rule-one-type-custom').hide();
                this.$('#SMSEmailBody').show();
                if (this.model.get('SMSRuleOneEmailBody') != '') {
                    this.$('#SMSRuleOneEmailBody').val(this.model.get('SMSRuleOneEmailBody'));
                }
            }
            else {
                this.$('#rule-one-email').hide();
                this.$('#rule-one-type-custom').show();
                this.$('#SMSEmailBody').hide();

            }
            this.$('#rule-one-type-agent').hide();
            this.$('#rule-one-email-agent').hide();
            this.$('#SMSRuleOneRecipientCustom').val(this.model.get('SMSRuleOneRecipientCustom'));
            if (this.$('#SMSRuleOneAction').val() == 'sms') {
                this.$('#SMSTextBody').show();
                this.$('#SMSEmailBody').hide();
                if (this.model.get('SMSRuleOneSMSBody') != '') {
                            this.$('#SMSRuleOneSMSBody').val(this.model.get('SMSRuleOneSMSBody'));
                        }
            }
        }
        else if (this.$('#SMSRuleOneRecipientType').val() == 'agent') {
            this.$('#rule-one-type-custom').hide();
            this.$('#rule-one-email').hide()
            if (this.$('#SMSRuleOneAction').val() == 'email') {
                this.$('#rule-one-email-agent').show();
                this.$('#rule-one-type-agent').hide();
                this.$('#rule-one-call-agent').hide();
                this.$('#SMSEmailBody').show();
                if (this.model.get('SMSRuleOneEmailBody') != '') {
                    this.$('#SMSRuleOneEmailBody').val(this.model.get('SMSRuleOneEmailBody'));
                }
                this.allAgents.each((agent) => {
                    this.$('.email-agent-select').append(
                    `<option value=${agent.id}>${agent.getFullName()}</option>`
                );
                });
                this.$('.email-agent-select').prepend("<option value=''>[select agent]</option>").val('');
            }
            else if (this.$('#SMSRuleOneAction').val() == 'sms') {
                this.$('#rule-one-type-agent').show();
                this.$('#rule-one-call-agent').hide();
                this.$('#SMSTextBody').show();
                if (this.model.get('SMSRuleOneSMSBody') != '') {
                    this.$('#SMSRuleOneSMSBody').val(this.model.get('SMSRuleOneSMSBody'));
                }
                this.allAgents.each((agent) => {
                    this.$('.sms-agent-select').append(
                    `<option value=${agent.id}>${agent.getFullName()}</option>`
                );
                });
                this.$('.sms-agent-select').prepend("<option value=''>[select agent]</option>").val('');
            }
            else {
                this.$('#rule-one-type-agent').hide();
                this.$('#SMSEmailBody').hide();
                this.$('#rule-one-email-agent').hide();
                this.$('#rule-one-call-agent').hide();
            }
        }
        else if (this.$('#SMSRuleOneRecipientType').val() == 'lead') {
            this.$('#rule-one-type-custom').hide();
            this.$('#rule-one-type-agent').hide();
            this.$('#rule-one-email-agent').hide();
            this.$('.sms-agent-select option').remove();
            this.$('.email-agent-select option').remove();
            this.$('#rule-one-email').hide()
            if (this.$('#SMSRuleOneAction').val() == 'sms') {
                this.$('#SMSTextBody').show();
                this.$('#rule-one-call-agent').hide();
                if (this.model.get('SMSRuleOneSMSBody') != '') {
                            this.$('#SMSRuleOneSMSBody').val(this.model.get('SMSRuleOneSMSBody'));
                        }
            }
            if (this.$('#SMSRuleOneAction').val() == 'email'){
                this.$('#SMSEmailBody').show();
                this.$('#rule-one-call-agent').hide();
                if (this.model.get('SMSRuleOneEmailBody') != '') {
                    this.$('#SMSRuleOneEmailBody').val(this.model.get('SMSRuleOneEmailBody'));
                }
            }
            if (this.$('#SMSRuleOneAction').val() == 'call') {
                this.$('#rule-one-call-agent').show();
                if (this.model.get('SMSRuleOneCallAgent') != '') {
                    this.allAgents.each((agent) => {
                        this.$('.call-agent-select').append(
                        `<option value=${agent.id}>${agent.getFullName()}</option>`
                    );
                        this.$('.call-agent-select').val(this.model.get('SMSRuleOneCallAgent'));
                    });
                }
                else {
                    this.allAgents.each((agent) => {
                        this.$('.call-agent-select').append(
                        `<option value=${agent.id}>${agent.getFullName()}</option>`
                        );
                    });
                    this.$('.call-agent-select').prepend("<option value=''>[select agent]</option>").val('');
                }
            }
        }
        else {
            this.$('#rule-one-type-custom').hide();
            this.$('#rule-one-type-agent').hide();
            this.$('#rule-one-email-agent').hide();
            this.$('#rule-one-call-agent').hide();
            this.$('#rule-one-email').hide();
            this.$('#SMSTextBody').hide();
            this.$('#SMSEmailBody').hide();
            this.$('.sms-agent-select option').remove();
            this.$('.email-agent-select option').remove();
            this.$('.call-agent-select option').remove();
        }
    },

    handleSMSRule01ActionChange: function (evt) {
        if (this.model.get('SMSRuleOneAction')) {
            this.$('#SMSRuleOneRecipientType').show()
            this.$('.no-contact-method').show()
            this.$('.sms-agent-select option').remove();
            this.$('.call-agent-select option').remove();
            this.$('.email-agent-select option').remove();
            this.$("#SMSRuleOneRecipientType option").remove();
            if (this.$('#SMSRuleOneAction').val() == 'call') {
                this.$('#SMSRuleOneRecipientType').append(
                    `<option value=''>[contact]</option>`
                );
                this.$('#SMSRuleOneRecipientType').append(
                    `<option value='lead'>lead</option>`
                );
                if (this.$('#SMSRuleOneRecipientType').val() == 'lead') {
                    this.$('#rule-one-call-agent').show();
                    this.$('#rule-one-type-custom').hide();
                    this.$('#rule-one-type-agent').hide();
                    this.$('#rule-one-email-agent').hide();
                    if (this.model.get('SMSRuleOneCallAgent') != '') {
                        this.allAgents.each((agent) => {
                            this.$('.call-agent-select').append(
                            `<option value=${agent.id}>${agent.getFullName()}</option>`
                        );
                            this.$('.call-agent-select').val(this.model.get('SMSRuleOneCallAgent'));
                        });
                    }
                    else {
                        this.allAgents.each((agent) => {
                            this.$('.call-agent-select').append(
                            `<option value=${agent.id}>${agent.getFullName()}</option>`
                            );
                        });
                        this.$('.call-agent-select').prepend("<option value=''>[select agent]</option>").val('');
                    }
                    this.$('#rule-one-email').hide();
                    this.$('#SMSTextBody').hide();
                    this.$('#SMSEmailBody').hide();
                }
                else {
                    this.$('#rule-one-type-custom').hide()
                    this.$('#rule-one-type-agent').hide()
                    this.$('#rule-one-email-agent').hide();
                    this.$('#rule-one-call-agent').hide();
                    this.$('#SMSTextBody').hide();
                    this.$('#rule-one-email').hide();
                    this.$('#SMSEmailBody').hide();
                }
            }
            else if (this.$('#SMSRuleOneAction').val() == 'sms') {
                this.$('#SMSRuleOneRecipientType').append(
                    `<option value=''>[contact]</option>`
                );
                this.$('#SMSRuleOneRecipientType').append(
                    `<option value='lead'>lead</option>`
                );
                this.$('#SMSRuleOneRecipientType').append(
                    `<option value='agent'>agent</option>`
                );
                this.$('#SMSRuleOneRecipientType').append(
                    `<option value='custom'>custom</option>`
                );
                if (this.$('#SMSRuleOneRecipientType').val() == 'custom') {
                    this.$('#SMSRuleOneRecipientCustom').attr("placeholder", "[Enter phone number]").val("").focus().blur();
                    this.$('#rule-one-type-custom').show()
                    this.$('#rule-one-email').hide();
                    this.$('#rule-one-type-agent').hide();
                    this.$('#rule-one-email-agent').hide();
                    this.$('#rule-one-call-agent').hide();
                    this.$('#SMSRuleOneRecipientCustom').val(this.model.get('SMSRuleOneRecipientCustom'));
                    this.$('#SMSTextBody').show();
                    this.$('#SMSEmailBody').hide();
                    if (this.model.get('SMSRuleOneSMSBody') != '') {
                        this.$('#SMSRuleOneSMSBody').val(this.model.get('SMSRuleOneSMSBody'));
                    }
                }
                else if (this.$('#SMSRuleOneRecipientType').val() == 'agent') {
                    this.$('#rule-one-type-custom').hide()
                    this.$('#rule-one-call-agent').hide();
                    this.$('#rule-one-email').hide();
                    this.$('#rule-one-type-agent').show();
                    this.$('#rule-one-email-agent').hide();
                    this.$('#SMSEmailBody').hide();
                    if (this.model.get('SMSRuleOneRecipientAgent') != '') {
                        this.$('#SMSRuleOneRecipientAgent').val(this.model.get('SMSRuleOneRecipientAgent'));
                    }
                    this.$('#SMSTextBody').show();
                    if (this.model.get('SMSRuleOneSMSBody') != '') {
                        this.$('#SMSRuleOneSMSBody').val(this.model.get('SMSRuleOneSMSBody'));
                    }
                }
                else if (this.$('#SMSRuleOneRecipientType').val() == 'lead') {
                    this.$('#SMSTextBody').show();
                    this.$('#rule-one-call-agent').hide();
                    if (this.model.get('SMSRuleOneSMSBody') != '') {
                        this.$('#SMSRuleOneSMSBody').val(this.model.get('SMSRuleOneSMSBody'));
                    }
                    this.$('#rule-one-type-custom').hide()
                    this.$('#rule-one-type-agent').hide()
                    this.$('#rule-one-email-agent').hide()
                    this.$('#rule-one-call-agent').hide();
                    this.$('#rule-one-email').hide();
                    this.$('#SMSEmailBody').hide()
                }
                else {
                    this.$('#rule-one-type-custom').hide()
                    this.$('#rule-one-type-agent').hide()
                    this.$('#rule-one-email-agent').hide()
                    this.$('#rule-one-call-agent').hide();
                    this.$('#SMSTextBody').hide();
                    this.$('#rule-one-email').hide();
                    this.$('#SMSEmailBody').hide()
                }
            }
            else if (this.$('#SMSRuleOneAction').val() == 'email') {
                this.$('#SMSRuleOneRecipientType').append(
                    `<option value=''>[contact]</option>`
                );
                this.$('#SMSRuleOneRecipientType').append(
                    `<option value='lead'>lead</option>`
                );
                this.$('#SMSRuleOneRecipientType').append(
                    `<option value='agent'>agent</option>`
                );
                this.$('#SMSRuleOneRecipientType').append(
                    `<option value='custom'>custom</option>`
                );
                if (this.$('#SMSRuleOneRecipientType').val() == 'custom') {
                    this.$('#rule-one-email').show();
                    this.$('#SMSTextBody').hide();
                    this.$('#rule-one-type-custom').hide();
                    this.$('#rule-one-type-agent').hide();
                    this.$('#rule-one-email-agent').hide()
                    this.$('#rule-one-call-agent').hide();
                    this.$('#SMSEmailBody').show();
                    if (this.model.get('SMSRuleOneEmailBody') != '') {
                        this.$('#SMSRuleOneEmailBody').val(this.model.get('SMSRuleOneEmailBody'));
                    }

                }
                else if (this.$('#SMSRuleOneRecipientType').val() == 'agent') {
                    this.$('#rule-one-email').hide();
                    this.$('#SMSTextBody').hide();
                    this.$('#rule-one-type-custom').hide();
                    if (this.$('#SMSRuleOneAction').val() == 'email') {
                        this.$('#rule-one-email-agent').show();
                        this.$('#rule-one-call-agent').hide();
                        this.$('#rule-one-type-agent').hide();
                        this.$('#SMSEmailBody').show();
                        if (this.model.get('SMSRuleOneEmailBody') != '') {
                            this.$('#SMSRuleOneEmailBody').val(this.model.get('SMSRuleOneEmailBody'));
                        }
                    }
                    else {
                        this.$('#rule-one-type-agent').show();
                        this.$('#rule-one-email-agent').hide();
                        this.$('#rule-one-call-agent').hide();
                    }
                }
                else if (this.$('#SMSRuleOneRecipientType').val() == 'lead') {
                    this.$('#rule-one-email').hide();
                    this.$('#SMSTextBody').hide();
                    this.$('#rule-one-type-custom').hide();
                    this.$('#rule-one-type-agent').hide();
                    this.$('#rule-one-email-agent').hide();
                    this.$('#rule-one-call-agent').hide();
                    this.$('#SMSEmailBody').show();
                    if (this.model.get('SMSRuleOneEmailBody') != '') {
                        this.$('#SMSRuleOneEmailBody').val(this.model.get('SMSRuleOneEmailBody'));
                    }
                }
                else {
                    this.$('#rule-one-email').hide();
                    this.$('#SMSTextBody').hide();
                    this.$('#rule-one-type-custom').hide();
                    this.$('#rule-one-type-agent').hide();
                    this.$('#rule-one-email-agent').hide();
                    this.$('#rule-one-call-agent').hide();
                    this.$('#SMSEmailBody').hide();
                }
                this.$('#rule-one-call-agent').hide();
            }
            else if (this.$('#SMSRuleOneAction').val() == 'unsubscribe') {
                this.$('#SMSRuleOneRecipientType').append(
                        `<option value='lead'>lead</option>`
                    );
                if (this.$('#SMSRuleOneRecipientType').val() == 'lead') {
                    this.model.set('SMSRuleOneRecipientType','lead');
                }
                this.$('#SMSTextBody').hide();
                this.$('#SMSEmailBody').hide();
                this.$('#rule-one-type-custom').hide();
                this.$('#rule-one-type-agent').hide();
                this.$('#rule-one-email-agent').hide();
                this.$('#rule-one-call-agent').hide();
                this.$('#rule-one-email').hide();
            }
            else {
                this.$('#SMSTextBody').hide();
                this.$('#SMSEmailBody').hide();
                this.$('#rule-one-type-custom').hide();
                this.$('#rule-one-type-agent').hide();
                this.$('#rule-one-email-agent').hide();
                this.$('#rule-one-call-agent').hide();
                this.$('#rule-one-email').hide();
                this.$('#SMSRuleOneRecipientType').hide();
            }
        }
        else {
            this.$('#SMSRuleOneRecipientType').hide()
            this.$('.no-contact-method').hide()
            this.$('#SMSTextBody').hide();
        }
    },

    showAdvancedOptions: function () {
        if (this.parentModel.get('type') === 'tracking') {
            this.$('#li-auto-attendance').show();
            this.$('.accept-decline-call').hide();
            this.$('#li-call-backs').hide();
            this.$('#callerNameWp').hide();
            this.$('.call-routing-text').text(__('Call Forwarding'));
            this.$('#tracking-pn-caller-id').show();
            this.$('#default-routing-heading').css('display');
            this.$('#tracking-pn-option').show();
            this.$('#tracking-pn-option-sms').show();
            this.$('#priority-pn-option').hide();
            this.$('#priority-pn-option-callback').hide();
            this.$('#li-sms-settings').show();
            this.$('#li-email-notifications').show();
            this.$('#li-hold-music').show();
        // The following else hides all the sections for mobile during
        // the mobile phone number provisioning
        } else if (this.parentModel.get('type') === 'mobile') {
            this.$('.accept-decline-call').hide();
            this.$('#li-auto-attendance').hide();
            this.$('#li-call-backs').hide();
            this.$('#callerNameWp').hide();
            this.$('#li-sms-settings').hide();
            this.$('#li-email-notifications').hide();
            this.$('#li-hold-music').hide();
            this.$('.call-routing-text').text(__('Mobile App Agent'));
            this.$('#tracking-pn-caller-id').hide();
            this.$('#default-routing-heading').css('display', 'none');
            this.$('#tracking-pn-option').show();
            this.$('#tracking-pn-option-sms').hide();
            this.$('#priority-pn-option').hide();
            this.$('#priority-pn-option-callback').hide()
        // The following else if checks what the current users subscription plan is
        // If the plan is partnershipsingle hide the call forward toggle
        } else if (this.parentModel.get("subscriptionPlan") == 'partnershipsingle') {
            this.$('#default-routing-heading').css('display', 'none');
            this.$('#li-call-backs').show();
            this.$('#li-auto-attendance').hide();
            this.$('.call-routing-text').text(__('Call Forwarding'));
            this.$('#tracking-pn-caller-id').show();
            this.$('#callerNameWp').show();
            this.$('#tracking-pn-option').show();
            this.$('#tracking-pn-option-sms').show();
            this.$('#priority-pn-option').hide();
            this.$('#priority-pn-option-callback').show()
            this.$('#li-sms-settings').show();
            this.$('#li-email-notifications').show();
            this.$('#li-hold-music').show();
        } else {
            this.$('#li-auto-attendance').show();
            this.$('#li-call-backs').show();
            this.$('#callerNameWp').show();
            this.$('.call-routing-text').text(__('Call Routing'));
            this.$('#default-routing-heading').css('display', '');
            this.$('#tracking-pn-option').hide();
            this.$('#tracking-pn-caller-id').show();
            this.$('#tracking-pn-option-sms').hide();
            this.$('#priority-pn-option').show();
            this.$('#priority-pn-option-callback').show();
            this.$('#li-sms-settings').show();
            this.$('#li-email-notifications').show();
            this.$('#li-hold-music').show();
        }
    },

    disableNotifyAdfRecipients: function () {
        if (this.model.get('notifyAdf')) {
            //enable text area
            $('#notify-adf-custom').prop('disabled', false);

        } else {
            //disable text area
            $('#notify-adf-custom').prop('disabled', true);
        }
    },

    addRouting: function () {
        var newRouting = new Routing({
            name: 'When digit 1 is pressed:',
            dialDigit: '1',
        });
        this.model.get('digitRoutings').add(newRouting);

        new DigitRoutingView({
            parentModel: this.parentModel,
            model: newRouting
        }).$el.appendTo(this.$('#digit-routing-list'));
    },

    handleRoutingTypeDefaultSelection: function (evt) {
        this.setRoutingType(evt.target.checked ? 'default' : 'digits');
    },

    handleRoutingTypeDigitSelection: function (evt) {
        this.setRoutingType(evt.target.checked ? 'digits' : 'default');
    },

    setRoutingType: function (routingType) {
        this.model.set('routingType', routingType);

        if (routingType === 'digits' && !this.model.get('digitRoutings').length) {
            this.addRouting();
        }
    },

    handleAddRoutingClick: function () {
        this.addRouting();
    },

    handleInputChange: function (evt) {
        var value = evt.target.value,
            propName = utils.idToPropertyName(evt.target.id, ''),
            type = evt.target.getAttribute('type');

        if (propName in this.model.attributes) {
            switch (type) {
                case 'checkbox':
                    this.model.set(propName, evt.target.checked);
                    break;
                case 'radio':
                    if (evt.target.checked) {
                        this.model.set(propName, value);
                    }
                    break;
                default:
                    this.model.set(propName, value);
                    break;
            }
        }
    },

    handleCheckboxChange: function (evt) {
        var checked = evt.target.checked,
            propName = utils.idToPropertyName(evt.target.id, '');

        if (propName in this.model.attributes) {
            this.model.set(propName, checked);
        }

        this.showCallbackSection();
        this.disableNotifyAdfRecipients();
    },

    handleNotifyChange: function (evt) {
        var notify = this.$('input[name=notify-leads]:checked').val();

        if (notify === 'all') {
            $('#notify-all-me,#notify-all-agents,#notify-all-custom').prop('disabled', false);
            $('#notify-missed-me,#notify-missed-agents,#notify-missed-custom').prop('disabled', true);
        } else {
            $('#notify-all-me,#notify-all-agents,#notify-all-custom').prop('disabled', true);
            $('#notify-missed-me,#notify-missed-agents,#notify-missed-custom').prop('disabled', false);
        }
    },
    /** Hide the prompt to enter text or upload custom messsage */
    showNoDigitMessageControls: function () {
        var val = this.$('input[name=no-digit-whisper-message-type]:checked').val(),
            $container = this.$('#no-digit-whisper-message-container');

        $container.find('div[data-message-type]').hide();
        $container.find('div[data-message-type=' + val + ']').show();
    },
});

// Notifications section
var NotificationsView = Backbone.View.extend({
    template: notificationsTemplate,

    events: {
        'change input': 'handleInputChange',
        'change textarea': 'handleInputChange',
    },

    initialize: function (options) {
        this.routingModel = options.routingModel;
    },

    render: function() {
        var args = this.model.toJSON();
        args.currentUserEmail = Globals.currentUserEmail;
        args.notifyAdf = this.routingModel.get('notifyAdf');
        args.notifyAdfCustom = this.routingModel.get('notifyAdfCustom');

        this.$el.html(this.template(args));

        return this;
    },

    handleInputChange: function (e) {
        var el = e.target;

        switch (el.id) {
            case 'notify-adf-custom':
                this.routingModel.set('notifyAdfCustom', el.value);
                break;
            case 'notify-adf':
                this.routingModel.set('notifyAdf', el.checked);
                break;
            case 'notify-all-custom':
            case 'notify-missed-custom':
                this.model.set(utils.idToPropertyName(el.id), el.value);
                break;
            case 'notify-all-leads':
                this.model.set({
                    'notifyLeads': 'all'
                });
                break;
            case 'notify-missed-leads':
                this.model.set({
                    'notifyLeads': 'missed'
                });
                break;
            case 'notify-all-me':
            case 'notify-all-agents':
            case 'notify-missed-me':
            case 'notify-missed-agents':
                this.model.set(utils.idToPropertyName(el.id), el.checked);
                break;
        }
    },
});

// Individual call routing
var RoutingView = Backbone.View.extend({
    gloCallOrder: '',

    events: {
        'change .call-order': 'handleCallOrderChange',
        'change .retry-routing': 'handleRetryRoutingChange',
        'click #add-agent-btn': 'handleAddAgentClick',
    },

    template: callRoutingTemplate,

    initialize: function (options) {
        this.parentModel = options.parentModel;
        this.render();
        this.listenTo(this.parentModel, 'change:type', this.showHideRoutingSettings);

        this.gloCallOrder = this.$('.call-order').val();

        if (phonenumberType == 'tracking') {
            this.$('.call-order').addClass('tracking');
        }
    },

    render: function () {
        this.$el.html(this.template(this.model.toJSON()));

        this.$('.call-order').val(this.model.get('callOrder'));
        this.$('.retry-routing').val(this.model.get('retryRouting'));

        if (this.parentModel.get('type') === 'mobile') {
            this.createAgentView(AgentsLimitedView);
        } else {
            this.createAgentView(AgentsView);
        }

        this.showHideRoutingSettings();

        return this;
    },

    createAgentView: function (Constructor) {
        if (this.agentView) {
            this.agentView.remove();
        }
        this.agentView = new Constructor({ collection: this.model.get('agents') });
        this.agentView.$el.appendTo(this.$('.agents'));
    },

    showHideRoutingSettings: function () {
        if (this.parentModel.get('type') === 'mobile') {
            this.$('.routing-settings').hide();
            this.createAgentView(AgentsLimitedView);
        } else {
            this.$('.routing-settings').show();
            this.$('#agent-button-inbound').show();
            this.createAgentView(AgentsView);
        }
    },

    handleCallOrderChange: function () {
        var callOrder = this.$('.call-order').val();
        var agentListLength = $('#default-routing .call-settings-agent-table tr').length - 2;

        if (phonenumberType == 'tracking' && callOrder == 'simultaneous' && agentListLength > 7) {
            swal({
                title: 'Forwarding Agent Limit Reached',
                text: 'You cannot have more than 7 forwarding agents when routing is set to "Simultaneous".',
                type: 'warning',
                showCancelButton: false,
                confirmButtonColor: '#03a9f4',
                cancelButtonColor: '#f44336',
                confirmButtonText: 'ok'
            });

            this.$('.call-order').val(this.gloCallOrder);
        } else {
            this.model.set({
                'callOrder': callOrder
            });
            this.gloCallOrder = callOrder;
        }
    },

    handleRetryRoutingChange: function () {
        this.model.set({
            'retryRouting': parseInt(this.$('.retry-routing').val(), 10)
        });
    },

    handleAddAgentClick: function () {
        $('#new-agent-modal').modal();
        new AgentCreationModalView({
            el: '#new-agent-modal',
            collection: this.model.get('agents'),
        });
    }
});

var DefaultRoutingView = RoutingView.extend({
    render: function () {
        RoutingView.prototype.render.call(this);
        this.$('.dial-digit-container').empty();
        this.$('.dial-digit-container').hide();
        this.$('.delete-button-container').empty();
        return this;
    }
});

var DigitRoutingView = RoutingView.extend({
    events: function () {
        return _.extend({
            'change .dial-digit': 'handleDialDigitChange',
            'click .remove-routing': 'handleRemoveRouting'
        }, RoutingView.prototype.events);
    },

    render: function () {
        RoutingView.prototype.render.call(this);
            this.$('.dial-digit').empty();
        for (var i = 1; i <= 10; i++) {
            this.$('.dial-digit').append(`<option>${i % 10}</option>`);
        }
        this.$('.dial-digit').val(this.model.get('dialDigit'));

        return this;
    },

    handleDialDigitChange: function () {
        var digit = this.$('.dial-digit').val(),
            name = `When digit ${digit} is pressed`;

        this.model.set({
            dialDigit: this.$('.dial-digit').val(),
            name: name
        });
        this.$('h3').text(name);
    },

    handleRemoveRouting: function () {
        if (this.model.collection.length < 2) {
            alert('You must have at least one routing defined!');
        } else {
            this.model.destroy();
            this.undelegateEvents();
            this.$el.remove();
        }
    }
});

(function () {
    var text = $('#model-data').text(),
        model = (text) ? new PhoneNumberRouting(JSON.parse(text), { parse: true })
                       : new PhoneNumberRouting();
   model.set('subscriptionPlan', $('#user-subscription-plan').text())

   if (model.get('subscriptionPlan') == 'partnershipsingle') {
        model.get('routingConfig').get('defaultRouting').get('agents').add(
        new Agent({
            'fullName': $('#agent-single-fullname').text(),
            'id': $('#agent-single-id').text(),
            'phoneNumber': $('#agent-single-phone').text(),
        })
        )
   }

    new InboundRouteWizardView({ el: '.wizard', model: model });

    var csrfToken = $('meta[name=csrf-token]').attr('content');
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrfToken);
            }
        }
    });
}());
//Show phone number code field based on the selection of local or toll-free selection
$('.type-pn').on('change',function(){
    if( $(this).val()==="local"){
        $("#local-code").show();
        $("#toll-free-code").hide();
    } else {
        $("#toll-free-code").show();
        $("#local-code").hide();
    }
});