Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 12491 | Rev 16817 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php
$acl = $this->viewModel()->getRoot()->getVariable('acl');
$currentUser = $this->currentUserHelper();

$roleName = $currentUser->getUserTypeId();

$routeAdd = $this->url('organizational-climate/form/add');
$routeDatatable = $this->url('organizational-climate/form');
$routeDashboard = $this->url('dashboard');

$allowAdd = $acl->isAllowed($roleName, 'organizational-climate/form/add') ? 1 : 0;
$allowEdit = $acl->isAllowed($roleName, 'organizational-climate/form/edit') ? 1 : 0;
$allowDelete = $acl->isAllowed($roleName, 'organizational-climate/form/delete') ? 1 : 0;


$this->inlineScript()->appendFile($this->basePath('plugins/ckeditor/ckeditor.js'));


$this->headLink()->appendStylesheet($this->basePath('plugins/nprogress/nprogress.css'));
$this->inlineScript()->appendFile($this->basePath('plugins/nprogress/nprogress.js'));


$this->inlineScript()->appendFile($this->basePath('plugins/jquery-validation/jquery.validate.js'));
$this->inlineScript()->appendFile($this->basePath('plugins/jquery-validation/additional-methods.js'));
$this->inlineScript()->appendFile($this->basePath('plugins/jquery-validation/localization/messages_es.js'));

$this->headLink()->appendStylesheet($this->basePath('plugins/datatables-bs4/css/dataTables.bootstrap4.min.css'));
$this->headLink()->appendStylesheet($this->basePath('plugins/datatables-responsive/css/responsive.bootstrap4.min.css'));

$this->inlineScript()->appendFile($this->basePath('plugins/datatables/jquery.dataTables.min.js'));
$this->inlineScript()->appendFile($this->basePath('plugins/datatables-bs4/js/dataTables.bootstrap4.min.js'));
$this->inlineScript()->appendFile($this->basePath('plugins/datatables-responsive/js/dataTables.responsive.min.js'));
$this->inlineScript()->appendFile($this->basePath('plugins/datatables-responsive/js/responsive.bootstrap4.min.js'));


$this->headLink()->appendStylesheet($this->basePath('plugins/select2/css/select2.min.css'));
$this->headLink()->appendStylesheet($this->basePath('plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css'));

$this->inlineScript()->appendFile($this->basePath('plugins/select2/js/select2.full.min.js'));

$this->inlineScript()->appendFile($this->basePath('plugins/moment/moment-with-locales.min.js'));
$this->headLink()->appendStylesheet($this->basePath('plugins/bootstrap-datetimepicker/css/bootstrap-datetimepicker.css'));
$this->inlineScript()->appendFile($this->basePath('plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js'));


$this->headLink()->appendStylesheet($this->basePath('plugins/bootstrap4-toggle/css/bootstrap4-toggle.min.css'));
$this->inlineScript()->appendFile($this->basePath('plugins/bootstrap4-toggle/js/bootstrap4-toggle.min.js'));

$this->inlineScript()->appendFile($this->basePath('plugins/bootstrap-confirmation/dist/bootstrap-confirmation.js'));
$this->headLink()->appendStylesheet($this->basePath('plugins/bootstrap-checkbox/awesome-bootstrap-checkbox.css'));
$this->inlineScript()->appendFile($this->basePath('plugins/jquery-input-number/input-number-format.jquery.js'));

// bootbox Alert //
$this->inlineScript()->appendFile($this->basePath('plugins/bootbox/bootbox.min.js'));

// JsRender //
$this->inlineScript()->appendFile($this->basePath('plugins/jsrender/jsrender.min.js'));

// Page Styles
$this->headLink()->appendStylesheet($this->basePath('css/pages/self-evaluation.css'));

$status_active = \LeadersLinked\Model\SurveyForm::STATUS_ACTIVE;
$status_inactive = \LeadersLinked\Model\SurveyForm::STATUS_INACTIVE;

$this->inlineScript()->captureStart();
echo <<<JS
    const classFormGenerator = function() {
    this.id = 0,
        this.table = '',
        this.name = '',
        this.text = '',
        this.status = 'a',
        this.sections = [],
        this.clear = function() {
            this.sections = [];
            this.render();
        },
        /**
         * Render array sections
         */
        this.renderSection = function(slug_section) {
            var s = '';
            for (i = 0; i < this.sections.length; i++) {
                if (slug_section != this.sections[i].slug_section) {
                    continue;
                }
                for (j = 0; j < this.sections[i].questions.length; j++) {
                    this.sections[i].questions[j].position = j;
                    if (this.sections[i].questions[j].type == 'simple' || this.sections[i].questions[j].type == 'multiple' || this.sections[i].questions[j].type == 'rating-open') {
                        this.sections[i].questions[j].options.sort(function(a, b) {
                            if (a.position > b.position) {
                                return 1;
                            }
                            if (a.position < b.position) {
                                return -1;
                            }
                            return 0;
                        });
                        for (k = 0; k < this.sections[i].questions[j].options.length; k++) {
                            this.sections[i].questions[j].options[k].position = j;
                        }
                    }
                }
            }
            $('[data-toggle="tooltip"]').tooltip();
        },
        this.render = function() {
            this.sections.sort(function(a, b) {
                if (a.position > b.position) {
                    return 1;
                }
                if (a.position < b.position) {
                    return -1;
                }
                return 0;
            });
            var s = '';
            for (i = 0; i < this.sections.length; i++) {
                this.sections[i].position = i;
                this.sections[i].questions.sort(function(a, b) {
                    if (a.position > b.position) {
                        return 1;
                    }
                    if (a.position < b.position) {
                        return -1;
                    }
                    return 0;
                });
                for (j = 0; j < this.sections[i].questions.length; j++) {
                    this.sections[i].questions[j].position = j;
                    if (this.sections[i].questions[j].type == 'simple' || this.sections[i].questions[j].type == 'multiple' || this.sections[i].questions[j].type == 'rating-open') {
                        this.sections[i].questions[j].options.sort(function(a, b) {
                            if (a.position > b.position) {
                                return 1;
                            }
                            if (a.position < b.position) {
                                return -1;
                            }
                            return 0;
                        });
                        for (k = 0; k < this.sections[i].questions[j].options.length; k++) {
                            this.sections[i].questions[j].options[k].position = j;
                        }
                    }
                }
            }
            $('[data-toggle="tooltip"]').tooltip();
        },
        /**
         * Add element to section array
         */
        this.addSection = function(name, text) {
            var d = new Date();
            var slug = 'section' + d.getTime();
            var position = 0;
            $.each(this.sections, function(index, section) {
                if (position < section.position) {
                    position = section.position;
                }
            });
            position++;
            var section = {
                'slug_section': slug,
                'name': name,
                'text': text,
                'position': position,
                'questions': [],
                'status': 0
            }
            this.sections.push(section);
        },
         /**
         * Edit element to section array
         */
        this.editSection = function(slug, name, text) {
            var renderTable = false;
            for (i = 0; i < this.sections.length; i++) {
                if (slug == this.sections[i].slug_section) {
                    this.sections[i].name = name;
                    this.sections[i].text = text;
                    renderTable = true;
                    break;
                }
            }
            if (renderTable) {
                this.renderSection(slug);
            }
        },
         /**
         * Remove element to section array
         */
        this.deleteSection = function(slug) {
            var renderTable = false;
            for (i = 0; i < this.sections.length; i++) {
                if (slug == this.sections[i].slug_section) {
                    this.sections.splice(i, 1);
                    renderTable = true;
                    break;
                }
            }
            if (renderTable) {
                $('#panel' + slug).remove();
            }
        },
         /**
         * Add element to question array
         */
        this.addQuestion = function(slug_section, text, type, maxlength, multiline, range) {
            var d = new Date();
            var slug_question = 'question' + d.getTime();
            var position = 0;
            var renderTable = false;
            for (i = 0; i < this.sections.length; i++) {
                if (slug_section == this.sections[i].slug_section) {
                    $.each(this.sections[i].questions, function(index, question) {
                        if (position < question.position) {
                            position = question.position;
                        }
                    });
                    position++;
                    var question = {
                        'slug_section': slug_section,
                        'slug_question': slug_question,
                        'text': text,
                        'type': type,
                        'position': position,
                        'maxlength': maxlength,
                        'multiline': multiline,
                        'range': range,
                        'options': [],
                        'answer': type=='multiple' ? [] : ''
                    }
                    this.sections[i].questions.push(question);
                    renderTable = true;
                    break;
                }
            }
            if (renderTable) {
                this.renderSection(slug_section);
            }
        },
         /**
         * Add element to question array
         */
        this.editQuestion = function(slug_section, slug_question, text, type, maxlength, multiline, range) {
            var renderTable = false;
            for (i = 0; i < this.sections.length; i++) {
                if (slug_section == this.sections[i].slug_section) {
                    for (j = 0; j < this.sections[i].questions.length; j++) {
                        if (slug_question == this.sections[i].questions[j].slug_question) {
                            this.sections[i].questions[j].text = text,
                                this.sections[i].questions[j].type = type;
                            if (type == 'open') {
                                this.sections[i].questions[j].maxlength = maxlength;
                                this.sections[i].questions[j].multiline = multiline;
                                this.sections[i].questions[j].options = [];
                            } else {
                                this.sections[i].questions[j].maxlength = 0;
                                this.sections[i].questions[j].multiline = 0;
                            }
                            if (type == 'rating-range') {
                                this.sections[i].questions[j].range = range;
                            } else {
                                this.sections[i].questions[j].range = 0;
                            }

                            if(type=='multiple'){
                                this.sections[i].questions[j].answer = [];  
                            }else{
                                this.sections[i].questions[j].answer = '';  
                            }

                            renderTable = true;
                            break;
                        }
                    }
                }
                if (renderTable) {
                    break;
                }
            }
            if (renderTable) {
                this.renderSection(slug_section);
            }
        },
        /**
         * Remove element to question array
         */
        this.deleteQuestion = function(slug_section, slug_question) {
            var renderTable = false;
            for (i = 0; i < this.sections.length; i++) {
                if (slug_section == this.sections[i].slug_section) {
                    for (j = 0; j < this.sections[i].questions.length; j++) {
                        if (slug_question == this.sections[i].questions[j].slug_question) {
                            this.sections[i].questions.splice(j, 1);
                            renderTable = true;
                            break;
                        }
                    }
                }
                if (renderTable) {
                    break;
                }
            }
            if (renderTable) {
                this.renderSection(slug_section);
            }
        },
        /**
         * Add element to option array
         */
        this.addOption = function(slug_section, slug_question, text) {
            var d = new Date();
            var slug_option = 'option' + d.getTime();
            var position = 0;
            var renderTable = false;
            for (i = 0; i < this.sections.length; i++) {
                if (slug_section == this.sections[i].slug_section) {
                    for (j = 0; j < this.sections[i].questions.length; j++) {
                        if (slug_question == this.sections[i].questions[j].slug_question) {
                            $.each(this.sections[i].questions[j].options, function(index, option) {
                                if (position < option.position) {
                                    position = option.position;
                                }
                            });
                            position++;
                            var option = {
                                'slug_section': slug_section,
                                'slug_question': slug_question,
                                'slug_option': slug_option,
                                'text': text,
                                'checked': false
                            }
                            this.sections[i].questions[j].options.push(option);
                            renderTable = true;
                            break;
                        }
                        if (renderTable) {
                            break;
                        }
                    }
                }
            }
            if (renderTable) {
                this.renderSection(slug_section);
            }
        },
        /**
         * Edit element to option array
         */
        this.editOption = function(slug_section, slug_question, option_slug, text) {
            var renderTable = false;
            for (i = 0; i < this.sections.length; i++) {
                if (slug_section == this.sections[i].slug_section) {
                    for (j = 0; j < this.sections[i].questions.length; j++) {
                        if (slug_question == this.sections[i].questions[j].slug_question) {
                            for (k = 0; k < this.sections[i].questions[j].options.length; k++) {
                                if (option_slug == this.sections[i].questions[j].options[k].slug_option) {
                                    this.sections[i].questions[j].options[k].text = text;
                                    renderTable = true;
                                    break;
                                }
                            }
                        }
                        if (renderTable) {
                            break;
                        }
                    }
                }
                if (renderTable) {
                    break;
                }
            }
            if (renderTable) {
                this.renderSection(slug_section);
            }
        },
        /**
         * Remove element to option array
         */
        this.deleteOption = function(slug_section, slug_question, option_slug) {
            var renderTable = false;
            for (i = 0; i < this.sections.length; i++) {
                if (slug_section == this.sections[i].slug_section) {
                    for (j = 0; j < this.sections[i].questions.length; j++) {
                        if (slug_question == this.sections[i].questions[j].slug_question) {
                            for (k = 0; k < this.sections[i].questions[j].options.length; k++) {
                                if (option_slug == this.sections[i].questions[j].options[k].slug_option) {
                                    this.sections[i].questions[j].options.splice(k, 1);
                                    renderTable = true;
                                    break;
                                }
                            }
                        }
                        if (renderTable) {
                            break;
                        }
                    }
                }
                if (renderTable) {
                    break;
                }
            }
            if (renderTable) {
                this.renderSection(slug_section);
            }
        }
}

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
jQuery(document).ready(function($) {
    var objFormGenerator = new classFormGenerator();
    objFormGenerator.render();
    var allowEdit = $allowEdit;
    var allowDelete = $allowDelete;
    /**
     * Get rows and set data table
     */
    var tableForm = $('#gridTable').dataTable({
        'processing': true,
        'serverSide': true,
        'searching': true,
        'order': [
            [0, 'asc']
        ],
        'ordering': true,
        'ordenable': true,
        'responsive': true,
        'select': false,
        'paging': true,
        'pagingType': 'simple_numbers',
        'ajax': {
            'url': '$routeDatatable',
            'type': 'get',
            'beforeSend': function(request) {
                NProgress.start();
            },
            'dataFilter': function(response) {
                var response = jQuery.parseJSON(response);
                var json = {};
                json.recordsTotal = 0;
                json.recordsFiltered = 0;
                json.data = [];
                if (response.success) {
                    json.recordsTotal = response.data.total;
                    json.recordsFiltered = response.data.total;
                    json.data = response.data.items;
                } else {
                    $.fn.showError(response.data)
                }
                return JSON.stringify(json);
            }
        },
        'language': {
            'sProcessing': 'LABEL_DATATABLE_SPROCESSING',
            'sLengthMenu': 'LABEL_DATATABLE_SLENGTHMENU',
            'sZeroRecords': 'LABEL_DATATABLE_SZERORECORDS',
            'sEmptyTable': 'LABEL_DATATABLE_SEMPTYTABLE',
            'sInfo': 'LABEL_DATATABLE_SINFO',
            'sInfoEmpty': 'LABEL_DATATABLE_SINFOEMPTY',
            'sInfoFiltered': 'LABEL_DATATABLE_SINFOFILTERED',
            'sInfoPostFix': '',
            'sSearch': 'LABEL_DATATABLE_SSEARCH',
            'sUrl': '',
            'sInfoThousands': ',',
            'sLoadingRecords': 'LABEL_DATATABLE_SLOADINGRECORDS',
            'oPaginate': {
                'sFirst': 'LABEL_DATATABLE_SFIRST',
                'sLast': 'LABEL_DATATABLE_SLAST',
                'sNext': 'LABEL_DATATABLE_SNEXT',
                'sPrevious': 'LABEL_DATATABLE_SPREVIOUS'
            },
            'oAria': {
                'sSortAscending': ': LABEL_DATATABLE_SSORTASCENDING',
                'sSortDescending': ':LABEL_DATATABLE_SSORTDESCENDING'
            },
        },
        'drawCallback': function(settings) {
            NProgress.done();
            $('button.btn-delete').confirmation({
                rootSelector: 'button.btn-delete',
                title: 'LABEL_ARE_YOU_SURE',
                singleton: true,
                btnOkLabel: 'LABEL_YES',
                btnCancelLabel: 'LABEL_NO',
                onConfirm: function(value) {
                    action = $(this).data('href');
                    NProgress.start();
                    $.ajax({
                        'dataType': 'json',
                        'accept': 'application/json',
                        'method': 'post',
                        'url': action,
                    }).done(function(response) {
                        if (response['success']) {
                            $.fn.showSuccess(response['data']);
                            tableForm.fnDraw();
                        } else {
                            $.fn.showError(response['data']);
                        }
                    }).fail(function(jqXHR, textStatus, errorThrown) {
                        $.fn.showError(textStatus);
                    }).always(function() {
                        NProgress.done();
                    });
                },
            });
        },
        'aoColumns': [{
                'mDataProp': 'name'
            },
            {
                'mDataProp': 'description'
            },
            {
                'mDataProp': 'status'
            },
            {
                'mDataProp': 'actions'
            },
        ],
        'columnDefs': [{
                'targets': 0,
                'className': 'text-vertical-middle',
            },
            {
                'targets': 1,
                'className': 'text-vertical-middle',
            },
            {
                'targets': -2,
                'orderable': false,
                'className': 'text-center',
                'render': function(data, type, row) {
                    checked = data == 'A' ? ' checked="checked" ' : '';
                    return '<div class="checkbox checkbox-success">' +
                        '<input class="styled" type="checkbox" ' + checked + ' disabled="disabled">' +
                        '<label ></label></div>';
                }
            },
            {
                'targets': -1,
                'orderable': false,
                'render': function(data, type, row) {
                    s = '';
                    if (allowEdit) {
                        s = s + '<button class="btn btn-primary btn-edit-form" data-href="' + data['link_edit'] + '" data-toggle="tooltip" title="LABEL_EDIT"><i class="fa fa-pencil"></i> LABEL_EDIT </button>&nbsp;';
                    }
                    if (allowDelete) {
                        s = s + '<button class="btn btn-danger btn-delete" data-href="' + data['link_delete'] + '" data-toggle="tooltip" title="LABEL_DELETE"><i class="fa fa-trash"></i> LABEL_DELETE </button>&nbsp;';
                    }
                    return s;
                }
            }
        ],
    });
    /**
     * Clicked on edit form
     */
    $('body').on('click', 'button.btn-edit-form', function(e) {
        e.preventDefault();
        form_id = $(this).data('id')
        var action = $(this).data('href');
        $.ajax({
            'dataType': 'json',
            'accept': 'application/json',
            'method': 'get',
            'url': action,
        }).done(function(response) {
            if (response['success']) {
                validatorForm.resetForm();
                $('#form-main').attr('action', action);
                $('#form-main #form-id').val(response['data']['id']),
                $('#form-main #form-continue').val('0');
                $('#form-main #name').val(response['data']['name']),

                /*----------Set Ckeditor ------------*/
                CKEDITOR.instances.description.setData(response['data']['description']);
                CKEDITOR.instances.text.setData(response['data']['text']);

                $('#form-main #status').val(response['data']['status']);

                /*-------------Render Sections -------*/
               
                objFormGenerator.clear();
                objFormGenerator.sections = response['data']['content'] || [];
                objFormGenerator.render();
                renderSectionData(objFormGenerator.sections);
               
                $('#row-forms').hide();
                $('#row-edit').show();
                $('#form-main #name').focus();

            } else {
                $.fn.showError(response['message'] || 'ERROR_UNKNOWN');
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            $.fn.showError(textStatus);
        });
    });
    $(document).on('click', '[data-type="select_all"]', function() {
        if ($('input[name="select_all"]:checked').val() == 'all') {
            $('[data-type="select"]').prop('checked', true);
            $('[data-action="delete"]').removeClass('hide');
        } else {
            $('[data-type="select"]').prop('checked', false);
            $('[data-action="delete"]').addClass('hide');
        }
    });

    function getLength() {
        return $('[data-type="select"]').length;
    }

    function currentSelected() {
        var selected = [];
        $.each($("input[name='select[]']:checked"), function() {
            selected.push($(this).val());
        });
        return selected;
    }
    $(document).on('change', "input[name='select[]']", function() {
        var c = currentSelected();
        var cc = getLength();
        if (c.length == cc) {
            if ($('[data-action="delete"]').hasClass('hide')) {
                $('[data-action="delete"]').removeClass('hide');
            }
            return true;
        } else {
            $('input[name="select_all"]').prop('checked', false);
        }
        if (c.length > 0) {
            if ($('[data-action="delete"]').hasClass('hide')) {
                $('[data-action="delete"]').removeClass('hide');
            }
        } else {
            if (!$('[data-action="delete"]').hasClass('hide')) {
                $('[data-action="delete"]').addClass('hide');
            }
        }
    });
    var form3 = $('#form_sample_3');
    var error3 = $('.alert-danger', form3);
    var success3 = $('.alert-success', form3);
    //IMPORTANT: update CKEDITOR textarea with actual content before submit
    $("#form-main").on('submit', function() {
        for (var instanceName in CKEDITOR.instances) {
            CKEDITOR.instances[instanceName].updateElement();
        }
    })
    /**
     * Validate rules form
     */
    var validatorForm = $("#form-main").validate({
        ignore: [],
        errorClass: 'help-block',
        errorElement: 'span',
        rules: {
            'form-name': {
                required: true,
                minlength: 2,
                maxlength: 50
            },
            'description':{
                updateCkeditor:function() {
                    CKEDITOR.instances.description.updateElement();
                },
            },
            'text':{
                updateCkeditor:function() {
                    CKEDITOR.instances.text.updateElement();
                },
            },
            'forrm-status': {
                required: true,
            },
        },
        highlight: function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorPlacement: function(error, element) {
            if (element.attr("data-error-container")) {
                error.appendTo(element.attr("data-error-container"));
            } else {
                error.insertAfter(element);
            }
        },
        invalidHandler: function(form, validator) {
            if (!validator.numberOfInvalids())
                return;
            $('html, body').animate({
                scrollTop: $(validator.errorList[0].element).offset().top - 100
            }, 1000);
        },
        submitHandler: function(form) {
            var error = false;
            if (objFormGenerator.sections.length == 0) {
                $.fn.showError('ERROR_SECCTIONS');
                return false;
            } else {
                for (i = 0; i < objFormGenerator.sections.length; i++) {
                    if (objFormGenerator.sections[i].questions.length == 0) {
                        $.fn.showError('ERROR_QUESTIONS'.replace('%s', objFormGenerator.sections[i].name));
                        return false;
                    }
                    for (j = 0; j < objFormGenerator.sections[i].questions.length; j++) {
                        if (objFormGenerator.sections[i].questions[j].type == 'simple' ||
                            objFormGenerator.sections[i].questions[j].type == 'multiple' ||
                            objFormGenerator.sections[i].questions[j].type == 'rating-open') {
                            var questionNumber = j + 1;
                            var numberCorrect = 0;
                            if (objFormGenerator.sections[i].questions[j].options.length == 0) {
                                $.fn.showError('ERROR_OPTIONS'.replace('%s', objFormGenerator.sections[i].name).replace('%n', questionNumber));
                                return false;
                            }
                            var totalOption = 0;
                            var maxOption = 0;
                        }
                    }
                }
                var formContinue = parseInt($('#form-main #form-continue').val());
                var data = {
                    'name': $('#form-main #name').val(),
                    'description': $('#form-main #description').val(),
                    'text': $('#form-main #text').val(),
                    'status': $('#form-main #status').val(),
                    'content': JSON.stringify(objFormGenerator.sections)
                }
                $.ajax({
                    'dataType': 'json',
                    'method': 'post',
                    'url': $('#form-main').attr('action'),
                    'data': data,
                }).done(function(response) {
                    if (response['success']) {
                        $.fn.showSuccess(response['data']);
                        if (formContinue == 1) {
                            $('#form-main').attr('action',response['action_edit']);
                            $('#form-main #form-id').val(response['id']);
                            $('#form-main #form-continue').val(0);
                        } else {
                            $('#row-edit').hide();
                            $('#row-forms').show();
                        /*---------- Reset Form -------- */
                        $('#form-main')[0].reset();
                        /*--------Reset Ckeditor ----------*/
                        CKEDITOR.instances.text.setData('');
                        CKEDITOR.instances.description.setData('');
                        /*--------Reset Sections ----------*/
                        clearSectionData();
                        /* ------- Refresh Table -----------*/

                        }
                        tableForm.fnDraw();
                    } else {
                        $.fn.showError(response['message'] || 'ERROR_UNKNOWN');
                    }
                }).fail(function(jqXHR, textStatus, errorThrown) {
                    $.fn.showError(textStatus);
                });
                return false;
            }
        }
    });
    //IMPORTANT: update CKEDITOR textarea with actual content before submit
    $("#form-section").on('submit', function() {
        for (var instanceName in CKEDITOR.instances) {
            CKEDITOR.instances[instanceName].updateElement();
        }
    })
    /**
     * Validate rules form section
     */
    var validatorFormSection = $("#form-section").validate({
        ignore: [],
        errorClass: 'help-block',
        errorElement: 'span',
        rules: {
            'section-name': {
                required: true,
                minlength: 2,
                maxlength: 50
            },
            'section-text': {
                required: false,
            },
        },
        highlight: function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorPlacement: function(error, element) {
            if (element.attr("data-error-container")) {
                error.appendTo(element.attr("data-error-container"));
            } else {
                error.insertAfter(element);
            }
        },
        invalidHandler: function(form, validator) {
            if (!validator.numberOfInvalids())
                return;
            $('html, body').animate({
                scrollTop: $(validator.errorList[0].element).offset().top - 100
            }, 1000);
        },
        submitHandler: function(form) {
            // do other things for a valid form
            //form.submit();
            var slug = $('#form-section #section-slug').val();
            if (slug) {
                objFormGenerator.editSection(
                    $('#form-section #section-slug').val(),
                    $('#form-section #section-name').val(),
                    $('#form-section #section-text').val(),
                );
            } else {
                objFormGenerator.addSection(
                    $('#form-section #section-name').val(),
                    $('#form-section #section-text').val()
                );
            }
            renderSectionData(objFormGenerator.sections);
            $('#modal-section').modal('hide');
            return false;
        }
    });
    //IMPORTANT: update CKEDITOR textarea with actual content before submit
    $("#form-question").on('submit', function() {
        for (var instanceName in CKEDITOR.instances) {
            CKEDITOR.instances[instanceName].updateElement();
        }
    })
    /**
     * Validate rules form Questions
     */
    var validatorFormQuestion = $("#form-question").validate({
        ignore: [],
        errorClass: 'help-block',
        errorElement: 'span',
        rules: {
            'question-text': {
                required: true,
            },
            'question-type': {
                required: true,
            },
            'question-max-length': {
                required: true,
                digits: true,
                min: 0
            },
            'question-range': {
                required: true,
                number: true,
                min: 1
            },
        },
        highlight: function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorPlacement: function(error, element) {
            if (element.attr("data-error-container")) {
                error.appendTo(element.attr("data-error-container"));
            } else {
                error.insertAfter(element);
            }
        },
        invalidHandler: function(form, validator) {
            if (!validator.numberOfInvalids())
                return;
            $('html, body').animate({
                scrollTop: $(validator.errorList[0].element).offset().top - 100
            }, 1000);
        },
        submitHandler: function(form) {
            if ($('#form-question #question-slug').val()) {
                objFormGenerator.editQuestion(
                    $('#form-question #question-section').val(),
                    $('#form-question #question-slug').val(),
                    $('#form-question #question-text').val(),
                    $('#form-question #question-type').val(),
                    $('#form-question #question-max-length').val(),
                    $('#form-question #question-multiline').val(),
                    $('#form-question #question-range').val()
                );
            } else {
                objFormGenerator.addQuestion(
                    $('#form-question #question-section').val(),
                    $('#form-question #question-text').val(),
                    $('#form-question #question-type').val(),
                    $('#form-question #question-max-length').val(),
                    $('#form-question #question-multiline').val(),
                    $('#form-question #question-range').val()
                );
            }
            renderSectionData(objFormGenerator.sections);
            $('#modal-question').modal('hide');
            return false;
        }
    });
    //IMPORTANT: update CKEDITOR textarea with actual content before submit
    $("#form-option").on('submit', function() {
        for (var instanceName in CKEDITOR.instances) {
            CKEDITOR.instances[instanceName].updateElement();
        }
    })
    /**
     * Validate rules form options
     */
    var validatorFormOption = $("#form-option").validate({
        ignore: [],
        errorClass: 'help-block',
        errorElement: 'span',
        rules: {
            'option-text': {
                required: true,
            }
           
        },
        highlight: function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorPlacement: function(error, element) {
            if (element.attr("data-error-container")) {
                error.appendTo(element.attr("data-error-container"));
            } else {
                error.insertAfter(element);
            }
        },
        invalidHandler: function(form, validator) {
            if (!validator.numberOfInvalids())
                return;
            $('html, body').animate({
                scrollTop: $(validator.errorList[0].element).offset().top - 100
            }, 1000);
        },
        submitHandler: function(form) {
            if ($('#form-option #option-slug').val()) {
                objFormGenerator.editOption(
                    $('#form-option #option-section').val(),
                    $('#form-option #option-question').val(),
                    $('#form-option #option-slug').val(),
                    $('#form-option #option-text').val()                  
                );
            } else {
                objFormGenerator.addOption(
                    $('#form-option #option-section').val(),
                    $('#form-option #option-question').val(),
                    $('#form-option #option-text').val()
                );
            }
            renderSectionData(objFormGenerator.sections);
            $('#modal-option').modal('hide');
            return false;
        }
    });
    /**
     * Clicked on add new section
     */
    $('body').on('click', 'button[id="btn-add-section"]', function(e) {
        e.preventDefault();
        validatorFormSection.resetForm();
        $('#form-section #section-slug').val('');
        $('#form-section #section-name').val('');
        CKEDITOR.instances['section-text'].setData('');
        $('#modal-section h4[class="modal-title"]').html('LABEL_ADD LABEL_SECTION');
        $('#modal-section').modal('show');
    });
    /**
     * Clicked on edit section
     */
    $('body').on('click', 'button.btn-edit-section', function(e) {
        e.preventDefault();
        var slug = $(this).data('section');
        var section;
        var showForm = false;
        for (i = 0; i < objFormGenerator.sections.length; i++) {
            section = objFormGenerator.sections[i];
            if (slug == section.slug_section) {
                validatorFormSection.resetForm();
                $('#form-section #section-slug').val(section.slug_section);
                $('#form-section #section-name').val(section.name);
                CKEDITOR.instances['section-text'].setData(section.text);
                showForm = true;
                break;
            }
        }
        if (showForm) {
            $('#modal-section h4[class="modal-title"]').html('LABEL_EDIT LABEL_SECTION');
            $('#modal-section').modal('show');
        }
    });
    /**
     * Clicked on remove section
     */
    $('body').on('click', 'button.btn-delete-section', function(e) {
        e.preventDefault();
        var slug = $(this).data('section');
        bootbox.confirm({
            title: "LABEL_DELETE LABEL_SECTION",
            message: "LABEL_QUESTION_DELETE",
            buttons: {
                cancel: {
                    label: '<i class="fa fa-times"></i> LABEL_CANCEL'
                },
                confirm: {
                    label: '<i class="fa fa-check"></i> LABEL_ACCEPT'
                }
            },
            callback: function(result) {
                if (result) {
                    objFormGenerator.deleteSection(slug);
                    renderSectionData(objFormGenerator.sections);
                }
            }
        });
    });
    /**
     * Clicked add new question
     */
    $('body').on('click', 'button.btn-add-question', function(e) {
        e.preventDefault();
        validatorFormQuestion.resetForm();
        var slug = $(this).data('section');
        $('#form-question #question-section').val(slug);
        $('#form-question #question-slug').val('');
        CKEDITOR.instances['question-text'].setData('');
        $('#form-question #question-type').val($('#form-question #question-type option:first').val());
        $('#form-question #question-max-length').val('0');
        $('#form-question #question-max-length').parent().show();
        $('#form-question #question-multiline').val('0');
        $('#form-question #question-multiline').parent().show();
        $('#form-question #question-range').val('10');
        $('#form-question #question-range').parent().hide();
        $('#modal-question h4[class="modal-title"]').html('LABEL_ADD LABEL_QUESTION');
        $('#modal-question').modal('show');
    });
    /**
     * Clicked edit question
     */
    $('body').on('click', 'button.btn-edit-question', function(e) {
        e.preventDefault();
        var slug_section = $(this).data('section');
        var slug = $(this).data('question');
        var showForm = false;
        for (i = 0; i < objFormGenerator.sections.length; i++) {
            if (slug_section == objFormGenerator.sections[i].slug_section) {
                for (j = 0; j < objFormGenerator.sections[i].questions.length; j++) {
                    if (slug == objFormGenerator.sections[i].questions[j].slug_question) {
                        validatorFormQuestion.resetForm();
                        $('#form-question #question-section').val(objFormGenerator.sections[i].slug_section);
                        $('#form-question #question-slug').val(objFormGenerator.sections[i].questions[j].slug_question);
                        CKEDITOR.instances['question-text'].setData(objFormGenerator.sections[i].questions[j].text);
                        $('#form-question #question-type').val(objFormGenerator.sections[i].questions[j].type);
                        if (objFormGenerator.sections[i].questions[j].type == 'open') {
                            $('#form-question #question-max-length').val(objFormGenerator.sections[i].questions[j].maxlength);
                            $('#form-question #question-max-length').parent().show();
                            $('#form-question #question-multiline').val(objFormGenerator.sections[i].questions[j].multiline);
                            $('#form-question #question-multiline').parent().show();
                        } else {
                            $('#form-question #question-max-length').val('0');
                            $('#form-question #question-max-length').parent().hide();
                            $('#form-question #question-multiline').val('0');
                            $('#form-question #question-multiline').parent().hide();
                        }
                        if (objFormGenerator.sections[i].questions[j].type == 'rating-range') {
                            $('#form-question #question-range').val(objFormGenerator.sections[i].questions[j].range);
                            $('#form-question #question-range').parent().show();
                        } else {
                            $('#form-question #question-range').val('10');
                            $('#form-question #question-range').parent().hide();
                        }
                        showForm = true;
                        break;
                    }
                }
                break;
            }
        }
        if (showForm) {
            $('#modal-question h4[class="modal-title"]').html('LABEL_EDIT LABEL_QUESTION');
            $('#modal-question').modal('show');
        }
    });
    /**
     * Clicked remove question
     */
    $('body').on('click', 'button.btn-delete-question', function(e) {
        e.preventDefault();
        var slug_section = $(this).data('section');
        var slug = $(this).data('question');
        bootbox.confirm({
            title: "LABEL_DELETE LABEL_QUESTION",
            message: "LABEL_QUESTION_DELETE",
            buttons: {
                cancel: {
                    label: '<i class="fa fa-times"></i> LABEL_CANCEL'
                },
                confirm: {
                    label: '<i class="fa fa-check"></i> LABEL_ACCEPT'
                }
            },
            callback: function(result) {
                if (result) {
                    objFormGenerator.deleteQuestion(slug_section, slug);
                    renderSectionData(objFormGenerator.sections);
                }
            }
        });
    });
    /**
     * Clicked add new Option
     */
    $('body').on('click', 'button.btn-add-option', function(e) {
        e.preventDefault();
        var slug_section = $(this).data('section');
        var slug_question = $(this).data('question');
        var showForm = false;
        for (i = 0; i < objFormGenerator.sections.length; i++) {
            if (slug_section == objFormGenerator.sections[i].slug_section) {
                for (j = 0; j < objFormGenerator.sections[i].questions.length; j++) {
                    if (slug_question == objFormGenerator.sections[i].questions[j].slug_question) {
                        validatorFormOption.resetForm();
                        $('#form-option #option-section').val(slug_section);
                        $('#form-option #option-question').val(slug_question);
                        $('#form-option #option-slug').val('');
                        CKEDITOR.instances['option-text'].setData('', function() {
                            editor.focus();
                        });
                       
                        renderSectionData(objFormGenerator.sections);
                        $('#modal-option h4[class="modal-title"]').html('LABEL_ADD LABEL_OPTION');
                        $('#modal-option').modal('show');
                        return true;
                    }
                }
            }
        }
    });
    /**
     * Clicked edit option
     */
    $('body').on('click', 'button.btn-edit-option', function(e) {
        e.preventDefault();
        var slug_section = $(this).data('section');
        var slug_question = $(this).data('question');
        var slug = $(this).data('slug');
        var showForm = false;
        for (i = 0; i < objFormGenerator.sections.length; i++) {
            if (slug_section == objFormGenerator.sections[i].slug_section) {
                for (j = 0; j < objFormGenerator.sections[i].questions.length; j++) {
                    if (slug_question == objFormGenerator.sections[i].questions[j].slug_question) {
                        for (k = 0; k < objFormGenerator.sections[i].questions[j].options.length; k++) {
                            if (slug == objFormGenerator.sections[i].questions[j].options[k].slug_option) {
                                validatorFormOption.resetForm();
                                $('#form-option #option-section').val(objFormGenerator.sections[i].slug_section);
                                $('#form-option #option-question').val(objFormGenerator.sections[i].questions[j].slug_question);
                                $('#form-option #option-slug').val(objFormGenerator.sections[i].questions[j].options[k].slug_option);
                                CKEDITOR.instances['option-text'].setData(objFormGenerator.sections[i].questions[j].options[k].text,
                                    function() {
                                        editor.focus();
                                    });
                                showForm = true;
                                break;
                            }
                        }
                    }
                    if (showForm) {
                        break;
                    }
                }
            }
            if (showForm) {
                break;
            }
        }
        if (showForm) {
            $('#modal-option h4[class="modal-title"]').html('LABEL_EDIT LABEL_OPTION');
            $('#modal-option').modal('show');
        }
    });
    /**
     * Clicked remove option
     */
    $('body').on('click', 'button.btn-delete-option', function(e) {
        e.preventDefault();
        var slug_section = $(this).data('section');
        var slug_question = $(this).data('question');
        var slug = $(this).data('slug');
        bootbox.confirm({
            title: "LABEL_DELETE LABEL_OPTION",
            message: "LABEL_QUESTION_DELETE",
            buttons: {
                cancel: {
                    label: '<i class="fa fa-times"></i> LABEL_CANCEL'
                },
                confirm: {
                    label: '<i class="fa fa-check"></i> LABEL_ACCEPT'
                }
            },
            callback: function(result) {
                if (result) {
                    objFormGenerator.deleteOption(slug_section, slug_question, slug);
                    renderSectionData(objFormGenerator.sections);
                }
            }
        });
    })
  
    /**
     * Format input number (Form Question)
     */
    $('#form-question #question-max-length').inputNumberFormat({
        'decimal': 0
    });
    /**
     * Detect when updating question status and hide/Show options
     */
    $('#form-question #question-type').change(function(e) {
        e.preventDefault();
        if ($('#form-question #question-type').val() == 'open') {
            $('#form-question #question-max-length').parent().show();
            $('#form-question #question-multiline').parent().show();
        } else {
            $('#form-question #question-max-length').val('0');
            $('#form-question #question-max-length').parent().hide();
            $('#form-question #question-multiline').val('0');
            $('#form-question #question-multiline').parent().hide();
        }
        $('#form-question #question-range').val('10');
        if ($('#form-question #question-type').val() == 'rating-range') {
            $('#form-question #question-range').parent().show();
        } else {
            $('#form-question #question-range').parent().hide();
        }
    });
    /**
     * Clicked new Form
     */
    $('button.btn-add-form').click(function(e) {
        e.preventDefault();
        objFormGenerator.clear();
        objFormGenerator.render();
        validatorForm.resetForm();
        clearSectionData();
        $('#form-main').attr('action', '$routeAdd');
        $('#form-main #form-continue').val('0');
        $('#form-main #name').val('');
        $('#form-main #status').val('$status_inactive');
        CKEDITOR.instances.text.setData('');
        CKEDITOR.instances.description.setData('');
        $('#row-forms').hide();
        $('#row-edit').show();
        $('#form-main #name').focus();
    });
    /**
     * Clicked cancel new/edit Form
     */
    $('button.btn-edit-cancel').click(function(e) {
        e.preventDefault();
        $('#row-edit').hide();
        $('#row-forms').show();
    });
    /**
     * Clicked save and continue new Form
     */
    $('button.btn-form-save-continue').click(function(e) {
        e.preventDefault();
        $('#form-main #form-continue').val('1')
        $('#form-main').submit();
    });
    /**
     * Clicked save and close new/edit Form
     */
    $('button.btn-form-save-close').click(function(e) {
        e.preventDefault();
        $('#form-main #form-continue').val('0')
        $('#form-main').submit();
    });
    /**
     * Modal Settings
     */
    $('#modal-section, #modal-question, #modal-option').modal({
        backdrop: 'static',
        keyboard: false,
        show: false
    });
    /**
     * Get Question type
     */
    const getQuestionTypeBySlug = (slug_section, slug_question) => {
        for (i = 0; i < objFormGenerator.sections.length; i++) {
            if (slug_section == objFormGenerator.sections[i].slug_section) {
                for (j = 0; j < objFormGenerator.sections[i].questions.length; j++) {
                    if (slug_question == objFormGenerator.sections[i].questions[j].slug_question) {
                        return objFormGenerator.sections[i].questions[j].type;
                    }
                }
            }
        }
    }
    /**
     * Remove Html Tags
     */
    const removeTags = (str) => str.toString().replace( /(<([^>]+)>)/ig, '')
    /**
     * Render Sections data
     */
    const renderSectionData = (data) => $("#rows").html($("#sectionTemplate").render(data, {
        getType: getQuestionTypeBySlug,
        removeTags: removeTags
    }));


    /**
     * Clear Div Section data
     */
    const clearSectionData = () => $("#rows").html('');
    /**
     * Clicked refresh button
     */
    $('button.btn-refresh').click(function(e) {
        tableForm.fnDraw();
    });

    CKEDITOR.replace('description', {
                                toolbar: [
                                        { name: 'editing', items: ['Scayt'] },
                                        { name: 'links', items: ['Link', 'Unlink'] },
                                        { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'] },
                                        { name: 'basicstyles', items: ['Bold', 'Italic', 'Strike', 'RemoveFormat'] },
                                        '/',
                                        { name: 'insert', items: ['Image', 'Table', 'HorizontalRule', 'SpecialChar'] },
                                        { name: 'styles', items: ['Styles', 'Format'] },
                                        { name: 'tools', items: ['Maximize'] }
                                ],
                                removePlugins: 'elementspath,Anchor',
                                heigth: 100
                        });
    CKEDITOR.replace('text', {
                                toolbar: [
                                        { name: 'editing', items: ['Scayt'] },
                                        { name: 'links', items: ['Link', 'Unlink'] },
                                        { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'] },
                                        { name: 'basicstyles', items: ['Bold', 'Italic', 'Strike', 'RemoveFormat'] },
                                        '/',
                                        { name: 'insert', items: ['Image', 'Table', 'HorizontalRule', 'SpecialChar'] },
                                        { name: 'styles', items: ['Styles', 'Format'] },
                                        { name: 'tools', items: ['Maximize'] }
                                ],
                                removePlugins: 'elementspath,Anchor',
                                heigth: 100
                        });
     
});
JS;
$this->inlineScript()->captureEnd();

$js = <<<JS
        const backendVariables= {
                dashboard_link: "$routeDashboard",
        add_link: "$routeAdd",
        table_link: "$routeDatatable",
        permisions: {
            allowAdd: $allowAdd,
            allowEdit: $allowEdit,
            allowDelete: $allowDelete
        }
        }       
JS;

$this->inlineScript()->appendScript($js);
$this->headLink()->appendStylesheet($this->basePath('/react-bundles/organizational-climate/form/main.css'));
$this->inlineScript()->appendFile('/react-bundles/organizational-climate/form/organizationalFormBundle.js');
?>

<div id="organizational_climate-form">
</div>