Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 117 | Rev 119 | 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('self-evaluation/forms/add');
$routeDatatable = $this->url('self-evaluation/forms');
$routeDashboard = $this->url('dashboard');

$allowAdd               = $acl->isAllowed($roleName, 'self-evaluation/forms/add') ? 1 : 0;
$allowEdit              = $acl->isAllowed($roleName, 'self-evaluation/forms/edit') ? 1 : 0;
$allowDelete            = $acl->isAllowed($roleName, 'self-evaluation/forms/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'));

$status_active = \LeadersLinked\Model\CompanySelfEvaluationForm::STATUS_ACTIVE;

$language_es = \LeadersLinked\Model\CompanySelfEvaluationForm::LANGUAGE_SPANISH;





$this->inlineScript()->captureStart();
echo <<<JS
    jQuery( document ).ready(function( $ ) {

        $.validator.setDefaults({
            debug: true,
            highlight: function(element) {
                $(element).addClass('is-invalid');
            },
            unhighlight: function(element) {
                $(element).removeClass('is-invalid');
            },
            errorElement: 'span',
            errorClass: 'error invalid-feedback',
            errorPlacement: function(error, element) {
                if(element.parent('.form-group').length) {
                    error.insertAfter(element);
                } else if(element.parent('.toggle').length) {
                    error.insertAfter(element.parent().parent());
                } else {
                    error.insertAfter(element.parent());
                }
            }
        });
    
    
        $.fn.showFormErrorValidator = function(fieldname, errors) {
            var field = $(fieldname);
            if(field) {
                $(field).addClass('is-invalid');
    

                var error = $('<span id="' + fieldname +'-error" class="error invalid-feedback">' + errors + '</div>');
                if(field.parent('.form-group').length) {
                    error.insertAfter(field);
                } else  if(field.parent('.toggle').length) {
                    error.insertAfter(field.parent().parent());
                } else {
                    error.insertAfter(field.parent());
                }
            }
        };




        var allowEdit   = $allowEdit;
        var allowDelete = $allowDelete;
        
        var gridTable = $('#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']);
                                gridTable.api().ajax.reload(null, false);
                            } else {
                                $.fn.showError(response['data']);
                            }
                        }).fail(function( jqXHR, textStatus, errorThrown) {
                            $.fn.showError(textStatus);
                        }).always(function() {
                            NProgress.done();
                        });
                    },
                });
            },
            'aoColumns': [
                { 'mDataProp': 'name' },
                { 'mDataProp': 'language'},
                { '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" data-href="' + data['link_edit']+ '" data-toggle="tooltip" title="LABEL_EDIT"><i class="fa fa-pencil"></i> LABEL_EDIT </button>&nbsp;';
                            s = s + '<button class="btn btn-primary btn-add-sections" data-toggle="tooltip" title="LABEL_ADD LABEL_SECTION"><i class="fa fa-pencil"></i> LABEL_ADD LABEL_SECTION </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;
                    }
                }
              ],
        });


        var validator = $('#form').validate({
            debug: true,
            onclick: false,
            onkeyup: false,
            ignore: [],
            rules: {
                'name': {
                    required: true,
                    maxlength: 128,
                },
                'description': {
                    updateCkeditor:function() {
                        CKEDITOR.instances.description.updateElement();
                    },
                    required: true,
                },
                'text': {
                    updateCkeditor:function() {
                        CKEDITOR.instances.text.updateElement();
                    },
                    required: false,
                },
                'language': {
                    required: true,
                },
                'status': {
                    required: false,
                },
            },
            submitHandler: function(form)
            {
                $.ajax({
                    'dataType'  : 'json',
                    'accept'    : 'application/json',
                    'method'    : 'post',
                    'url'       :  $('#form').attr('action'),
                    'data'      :  $('#form').serialize()
                }).done(function(response) {
                    NProgress.start();
                    if(response['success']) {
                        $.fn.showSuccess(response['data']);
                        
                        $('#modal').modal( 'hide');
                        
                         gridTable.api().ajax.reload(null, false);
                    } else {
                        validator.resetForm();
                        if(jQuery.type(response['data']) == 'string') {
                            $.fn.showError(response['data']);
                        } else  {
                            $.each(response['data'], function( fieldname, errors ) {
                                $.fn.showFormErrorValidator('#form #' + fieldname, errors);
                            });
                        }
                    }
                }).fail(function( jqXHR, textStatus, errorThrown) {
                   $.fn.showError(textStatus);
                }).always(function() {
                    NProgress.done();
                });
                return false;
            },
            invalidHandler: function(form, validator) {
            
            }
        });
        
        $('body').on('click', 'button.btn-add', function(e) {
            e.preventDefault();

            $('span[id="form-title"]').html('LABEL_ADD');
            $('#form').attr('action', '$routeAdd');
            $('#form #name').val('');
            $('#form #language').val('$language_es');
            CKEDITOR.instances.description.setData('');
            CKEDITOR.instances.text.setData('');

            $('#form #status').bootstrapToggle('on');


            validator.resetForm();
            $('#modal').modal('show');
        });
        
        $('body').on('click', 'button.btn-edit', function(e) {
            e.preventDefault();
            NProgress.start();
            var action = $(this).data('href');

            $.ajax({
                'dataType'  : 'json',
                'accept'    : 'application/json',
                'method'    : 'get',
                'url'       :  action,
            }).done(function(response) {
                if(response['success']) {

                    $('span[id="form-title"]').html('LABEL_EDIT');
                    $('#form').attr('action', action);
                    $('#form #name').val(response['data']['name']);
                    $('#form #language').val(response['data']['language']);
                    CKEDITOR.instances.description.setData(response['data']['description']);
                    CKEDITOR.instances.text.setData(response['data']['text']);
                    $('#form #status').bootstrapToggle(response['data']['status'] == '$status_active' ? 'on' : 'off')
                    validator.resetForm();
                    
                    $('#modal').modal('show');
                } else {
                    $.fn.showError(response['data']);
                }
            }).fail(function( jqXHR, textStatus, errorThrown) {
                $.fn.showError(textStatus);
            }).always(function() {
                NProgress.done();
            });
        });

        $('body').on('click', 'button.btn-refresh', function(e) {
            e.preventDefault();
            gridTable.api().ajax.reload(null, false);
        });
        

        $('body').on('click', 'button.btn-cancel', function(e) {
            e.preventDefault();
            $('#modal').modal('hide');
        });

        $('#form #status').bootstrapToggle({'on' : 'LABEL_ACTIVE',  'off' : 'LABEL_INACTIVE', 'width' : '160px', 'height' : '40px'});

        CKEDITOR.replace('description');
        CKEDITOR.replace('text');
    });
JS;
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();
                        },
                        this.renderSection = function(section_slug)
                        {
                        
                                var s = '';
                                for(i = 0; i < this.sections.length; i++)
                                {
                                        if(section_slug !=  this.sections[i].slug) {
                                                continue;
                                        }

                                        $('span.section-name' + section_slug).html(this.sections[i].name);

                                        let table = 'table-section-question-option' + this.sections[i].slug; 
                                        $('#' + table  + ' tbody').empty();
                                        
                                        s = '<tr class="tr-section" data-slug="' + this.sections[i].slug + '">';
                                        s = s  + '<td class="text-left">Seccion</td>';
                                        s = s  + '<td class="text-left">' + this.sections[i].name +  '</td>';
                                        s = s  + '<td class="text-right">' + this.sections[i].value + '</td>';
                                        s = s  + '<td>&nbsp</td>';
                                        s = s  + '<td>';
                                        s = s  + '<button class="btn btn-default btn-edit-section" data-slug="' + this.sections[i].slug + '" data-toggle="tooltip" title="LABEL_EDIT LABEL_SECTION"><i class="fa fa-edit" aria-hidden="true"></i> LABEL_EDIT LABEL_SECTION </button>&nbsp';
                                        s = s  + '<button class="btn btn-default btn-delete-section" data-slug="' + this.sections[i].slug + '" data-toggle="tooltip" title="LABEL_DELETE LABEL_SECTION"><i class="fa fa-ban" aria-hidden="true"></i> LABEL_DELETE LABEL_SECTION </button>&nbsp';
                                        s = s  + '<button class="btn btn-default btn-add-question" data-slug="' + this.sections[i].slug + '" data-toggle="tooltip" title="LABEL_ADD LABEL_QUESTION"><i class="fa fa-plus" aria-hidden="true"></i> LABEL_ADD LABEL_QUESTION </button>&nbsp';
                                        s = s  + '</td>';
                                        s = s  + '</tr>';
                                        $('#' + table + ' tbody').append(s);
                                        
                                        

                                        for(j = 0; j < this.sections[i].questions.length; j++)
                                        {
                                                this.sections[i].questions[j].position = j;

                                                this.drawQuestion( this.sections[i].slug, this.sections[i].questions[j].slug, this.sections[i].questions[j].text, this.sections[i].questions[j].value , this.sections[i].questions[j].type);
                                                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;
                                                                this.drawOption(
                                                                        this.sections[i].slug, 
                                                                        this.sections[i].questions[j].slug,  
                                                                        this.sections[i].questions[j].type, 
                                                                        this.sections[i].questions[j].options[k].slug, 
                                                                        this.sections[i].questions[j].options[k].text, 
                                                                        this.sections[i].questions[j].options[k].type, 
                                                                        this.sections[i].questions[j].options[k].correct, 
                                                                        this.sections[i].questions[j].options[k].value
                                                                );
                                                        }
                                                }
                                        }
                                }
                                
                                $('[data-toggle="tooltip"]').tooltip();
                        },
                        this.drawSection = function(section_slug, section_name, section_value)
                        {
                                let table = 'table-section-question-option' + section_slug; 
                                let collapse = 'collapse-' + section_slug;

                                s = '<div class="panel panel-default" id="panel' + section_slug + '">';
                                s = s + '       <div class="panel-heading">';
                                s = s + '               <h4 class="panel-title">';
                                s = s + '                       <a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#' + collapse + '"><span class="section-name' + section_slug + '">' + section_name + '</span></a>';
                                s = s + '               </h4>';
                                s = s + '       </div>';
                                s = s + '       <div id="' + collapse + '" class="panel-collapse collapse">';
                                s = s + '               <div class="panel-body">';
                                s = s + '                       <div class="table-responsive">';
                                s = s + '                               <table class="table table-bordered" id="' + table + '">';
                                s = s + '                                       <thead>';
                                s = s + '                                               <tr>';
                                s = s + '                                                       <th>LABEL_ELEMENT</th>';
                                s = s + '                                                       <th>LABEL_TEXT</th>';
                                s = s + '                                                       <th>LABEL_VALUE</th>';
                                s = s + '                                                       <th>LABEL_TYPE</th>';
                                s = s + '                                                       <th>LABEL_ACTIONS</th>';
                                s = s + '                                               </tr>';
                                s = s + '                                       </thead>';
                                s = s + '                                       <tbody>';
                                s = s + '                                       </tbody>';                                      
                                s = s + '                               </table>';
                                s = s + '                       </div>';
                                s = s + '               </div>';
                                s = s + '       </div>';
                                s = s + '</div>';

                                $('#accordion').append(s);


                                s = '<tr class="tr-section" data-slug="' + section_slug + '">';
                                s = s  + '<td class="text-left">LABEL_SECTION</td>';
                                s = s  + '<td class="text-left">' + section_name +  '</td>';
                                s = s  + '<td class="text-right">' + section_value + '</td>';
                                s = s  + '<td>&nbsp</td>';
                                s = s  + '<td>';
                                s = s  + '<button class="btn btn-default btn-edit-section" data-slug="' + section_slug + '" data-toggle="tooltip" title="LABEL_EDIT LABEL_SECTION"><i class="fa fa-edit" aria-hidden="true"></i> LABEL_EDIT LABEL_SECTION </button>&nbsp';
                                s = s  + '<button class="btn btn-default btn-delete-section" data-slug="' + section_slug + '" data-toggle="tooltip" title="LABEL_DELETE LABEL_SECTION"><i class="fa fa-ban" aria-hidden="true"></i> LABEL_DELETE LABEL_SECTION </button>&nbsp';
                                s = s  + '<button class="btn btn-default btn-add-question" data-slug="' + section_slug + '" data-toggle="tooltip" title="LABEL_ADD LABEL_SECTION"><i class="fa fa-plus" aria-hidden="true"></i> LABEL_ADD LABEL_SECTION </button>&nbsp';
                                s = s  + '</td>';
                                s = s  + '</tr>';
                                $('#' + table + ' tbody').append(s);
                        },

                        this.drawQuestion = function(section_slug, question_slug, question_text, question_value, question_type)
                        {
                                
                                
                                s = '<tr class="tr-question" data-slug="' + question_slug + '">';
                                s = s  + '<td class="text-left">--LABEL_QUESTION</td>';
                                s = s  + '<td class="text-left">' + question_text +  '</td>';
                                s = s  + '<td class="text-right"><font color="red">' + question_value + '</font></td>';
                                s = s  + '<td>' + question_type.substr(0,1).toUpperCase() + question_type.substr(1) +  '</td>';
                                s = s  + '<td>';
                                s = s  + '<button class="btn btn-default btn-edit-question" data-section="' + section_slug + '" data-slug="' + question_slug + '" data-toggle="tooltip" title="LABEL_EDIT LABEL_QUESTION"><i class="fa fa-edit" aria-hidden="true"></i> LABEL_EDIT LABEL_QUESTION</button>&nbsp';
                                s = s  + '<button class="btn btn-default btn-delete-question" data-section="' + section_slug + '" data-slug="' + question_slug + '" data-toggle="tooltip" title="LABEL_DELETE LABEL_QUESTION"><i class="fa fa-ban" aria-hidden="true"></i> LABEL_DELETE LABEL_QUESTION</button>&nbsp';
                                if(question_type == 'simple' || question_type == 'multiple' || question_type == 'rating-open') {
                                        s = s  + '<button class="btn btn-default btn-add-option" data-section="' + section_slug + '" data-slug="' + question_slug + '" data-toggle="tooltip" title="LABEL_ADD LABEL_OPTION"><i class="fa fa-plus" aria-hidden="true"></i> LABEL_ADD LABEL_OPTION</button>&nbsp';
                                }
                                
                                s = s  + '</td>';

                                let table = 'table-section-question-option' + section_slug; 
                                $('#' + table + ' tbody').append(s);
                        },

                        this.drawOption = function(section_slug, question_slug,  question_type, option_slug, option_text, option_type, option_correct, option_value)
                        {
                                
                                
                                s = '<tr class="tr-option" data-slug="' + option_slug + '">';
                                s = s  + '<td class="text-left">---LABEL_OPTION</td>';
                                s = s  + '<td class="text-left">' + option_text +  '</td>';
                                if(question_type == 'multiple' || question_type == 'rating-open') {

                                        if(question_type == 'multiple') {
                                                if(option_correct == 1) {
                                                        s = s  + '<td class="text-right">' + option_value + '</td>';
                                                } else {
                                                        s = s  + '<td>&nbsp</td>';
                                                }
                                        } else {
                                                s = s  + '<td class="text-right">' + option_value + '</td>';
                                        }       
                                } else {
                                        s = s  + '<td>&nbsp</td>';
                                }

                                if(question_type == 'simple' || question_type == 'multiple') {
                                        if(option_correct == 1) {
                                                s = s  + '<td class="text-left"><font color="green">LABEL_CORRECT</font></td>';
                                        } else {
                                                s = s  + '<td class="text-left"><font color="red">LABEL_FAIL</font></td>';
                                                
                                        }
                                } else {
                                        s = s  + '<td>&nbsp</td>';
                                }
                                
                                
                                s = s  + '<td>';
                                s = s  + '<button class="btn btn-default btn-edit-option" data-section="' + section_slug + '" data-question="' + question_slug + '" data-slug="' + option_slug + '" data-toggle="tooltip" title="LABEL_EDIT LABEL_OPTION"><i class="fa fa-edit" aria-hidden="true"></i></button>&nbsp';
                                s = s  + '<button class="btn btn-default btn-delete-option" data-section="' + section_slug + '" data-question="' + question_slug + '" data-slug="' + option_slug + '" data-toggle="tooltip" title="LABEL_DELETE LABEL_OPTION"><i class="fa fa-ban" aria-hidden="true"></i></button>&nbsp';
                                s = s  + '</td>';

                                let table = 'table-section-question-option' + section_slug; 
                                $('#' + table + ' tbody').append(s);

                        },
                        
                        this.render = function() 
                        {
                                $('#accordion').empty();

                                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.drawSection(this.sections[i].slug, this.sections[i].name, this.sections[i].value);
                                        
                                        
                                        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;

                                                this.drawQuestion( this.sections[i].slug, this.sections[i].questions[j].slug, this.sections[i].questions[j].text, this.sections[i].questions[j].value , this.sections[i].questions[j].type);
                                                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;
                                                                this.drawOption(
                                                                        this.sections[i].slug, 
                                                                        this.sections[i].questions[j].slug,  
                                                                        this.sections[i].questions[j].type, 
                                                                        this.sections[i].questions[j].options[k].slug, 
                                                                        this.sections[i].questions[j].options[k].text, 
                                                                        this.sections[i].questions[j].options[k].type, 
                                                                        this.sections[i].questions[j].options[k].correct, 
                                                                        this.sections[i].questions[j].options[k].value
                                                                );
                                                        }
                                                }

                                        }
                                        
                                        
                                }

                                
                                $('[data-toggle="tooltip"]').tooltip();

                        },

                        this.addSection = function (name, text, value)
                        {
                                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'          : slug,
                                        'name'          : name,
                                        'text'          : text,
                                        'value'         : value,
                                        'position'      : position,
                                        'questions' : [],
                                }

                                this.sections.push(section);
                                this.drawSection(slug, name, text);
                        },
                        this.editSection = function (slug, name, text, value)
                        {
                                var renderTable = false;
                                for(i = 0; i < this.sections.length; i++) 
                                {
                                                if(slug == this.sections[i].slug) {
                                                        this.sections[i].name = name;
                                                        this.sections[i].text = text;
                                                        this.sections[i].value = value;
                                                        renderTable = true;
                                                        
                                                        break;
                                                }
                                }
                                if(renderTable) {
                                        this.renderSection(slug);
                                }

                                
                        },
                        this.deleteSection = function(slug)
                        {
                                var renderTable = false;
                                for(i = 0; i < this.sections.length; i++) 
                                {
                                                if(slug == this.sections[i].slug) {
                                                        this.sections.splice(i, 1);
                                                        
                                                        renderTable = true;
                                                        break;
                                        }

                                
                                }
                                if(renderTable) {
                                        $('#panel' + slug).remove();
                                }
                        },
                        this.addQuestion = function (section_slug, text, value, type, maxlength, multiline, range) 
                        {
                                var d = new Date();
                                var slug = 'question' + d.getTime();
                                        
                                var position = 0;
                                var renderTable = false;
                                for(i = 0; i < this.sections.length; i++)
                                {
                                        if(section_slug == this.sections[i].slug) {
                                                $.each(this.sections[i].questions, function(index, question) {
                                                        if(position < question.position) {
                                                                position = question.position;
                                                        }
                                                });
                                                position++;
                                                        
                                                var question = {
                                                        'slug' : slug,
                                                                'text' : text,
                                                                'value' : value,
                                                                'type' : type,
                                                                'position' : position,
                                                                'maxlength' :maxlength,
                                                                'multiline' : multiline,
                                                                'range' : range,
                                                                'options' : [],
                                                        }

                                                this.sections[i].questions.push(question);
                                                renderTable = true;
                                                break;
                                        }
                                }
                                        
                                if(renderTable) {
                                        this.renderSection(section_slug);
                                }
                        },
                        this.editQuestion = function(section_slug, question_slug, text, value, type, maxlength, multiline, range) 
                        {
                                var renderTable = false;
                                for(i = 0; i < this.sections.length; i++)
                                {
                                        if(section_slug == this.sections[i].slug) {
                                                for(j = 0; j < this.sections[i].questions.length; j++) {
                                                        if(question_slug == this.sections[i].questions[j].slug) {
                                                                this.sections[i].questions[j].text      = text,
                                                                this.sections[i].questions[j].value     = value,
                                                                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;
                                                                        }
                                                                renderTable = true;
                                                                break;
                                                        }
                                                }
                                        }
                                        if(renderTable) {
                                                break;
                                        }
                                }
                                if(renderTable) {
                                        this.renderSection(section_slug);
                                }
                        },
                        this.deleteQuestion = function(section_slug, question_slug)
                        {
                                var renderTable = false;
                                for(i = 0; i < this.sections.length; i++) 
                                {
                                                if(section_slug == this.sections[i].slug) {
                                                        for(j = 0; j < this.sections[i].questions.length; j++) {
                                                        if(question_slug == this.sections[i].questions[j].slug) {
                                                                        this.sections[i].questions.splice(j, 1);
                                                                                renderTable = true;
                                                                                break;
                                                        }
                                                }
                                        }
                                                
                                        if(renderTable) {
                                                break;
                                        }
                                }
                                if(renderTable) {
                                        this.renderSection(section_slug);
                                }
                        },
                        this.addOption = function (section_slug, question_slug, text, correct, value) 
                        {
                                var d = new Date();
                                var slug = 'option' + d.getTime();
                                
                                var position = 0;
                                var renderTable = false;
                                for(i = 0; i < this.sections.length; i++)
                                {
                                        if(section_slug == this.sections[i].slug) {
                                                for(j = 0; j < this.sections[i].questions.length; j++) {
                                                        if(question_slug == this.sections[i].questions[j].slug) {
                                                                $.each(this.sections[i].questions[j].options, function(index, option) {
                                                                                if(position < option.position) {
                                                                                        position = option.position;
                                                                                }
                                                                        });
                                                                        position++;
                                                                                
                                                                        var option = {
                                                                                'slug' : slug,
                                                                                        'text' : text,
                                                                                        'correct' : correct,
                                                                                        'value' : value
                                                                                }

                                                                                this.sections[i].questions[j].options.push(option);
                                                                        renderTable = true;
                                                                        break;
                                                        }
                                                                
                                                                        if(renderTable) {
                                                                break;
                                                        }
                                                }
                                        }
                                }
                                if(renderTable) {
                                        this.renderSection(section_slug);
                                }
                        },
                        this.editOption = function(section_slug, question_slug, option_slug, text, correct, value) 
                        {
                                var renderTable = false;
                                for(i = 0; i < this.sections.length; i++)
                                {
                                        if(section_slug == this.sections[i].slug) {
                                                for(j = 0; j < this.sections[i].questions.length; j++) {
                                                        if(question_slug == this.sections[i].questions[j].slug) {
                                                                for(k = 0; k < this.sections[i].questions[j].options.length; k++) {
                                                                        if(option_slug == this.sections[i].questions[j].options[k].slug) {
                                                                                this.sections[i].questions[j].options[k].text = text;
                                                                                this.sections[i].questions[j].options[k].correct = correct;
                                                                                this.sections[i].questions[j].options[k].value = value;
                                                                                renderTable = true;
                                                                                                break;
                                                                        }
                                                                }
                                                        }
                                                                        if(renderTable) {
                                                                break;
                                                        }
                                                }
                                        }
                                                if(renderTable) {
                                                        break;
                                                }
                                }
                                        
                                if(renderTable) {
                                        this.renderSection(section_slug);
                                }
                        },
                        this.deleteOption = function(section_slug, question_slug, option_slug)
                        {
                                var renderTable = false;
                                for(i = 0; i < this.sections.length; i++) 
                                {
                                                if(section_slug == this.sections[i].slug) {
                                                        for(j = 0; j < this.sections[i].questions.length; j++) {
                                                        if(question_slug == this.sections[i].questions[j].slug) {
                                                                for(k = 0; k < this.sections[i].questions[j].options.length; k++) {
                                                                        if(option_slug == this.sections[i].questions[j].options[k].slug) {
                                                                                this.sections[i].questions[j].options.splice(k, 1);
                                                                                renderTable = true;
                                                                                                break;
                                                                        }
                                                                }
                                                        }
                                                                        if(renderTable) {
                                                                break;
                                                        }
                                                }
                                        }
                                                
                                        if(renderTable) {
                                                break;
                                        }
                                }
                                if(renderTable) {
                                        this.renderSection(section_slug);
                                }
                        }
                }

                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 tableForm = $('#table-form').dataTable({
                select :true,
        bProcessing: true,
        bServerSide: true,
        sAjaxSource: "ajax.<?php echo $this->module; ?>.php?action=gridview",
        fnServerData: function (sSource, aoData, fnCallback) {
                $.ajax({
                dataType: 'json',
                type: "POST",
                url: sSource,
                data: aoData,
                success: fnCallback
                });
        },
        aaSorting : [],
        aoColumns: [
                                        {sName: "checkbox", sTitle : '<input type="checkbox" value="all" data-type="select_all" name="select_all" id="select_all">',bSortable:false,bSearchable:false},
                                        {sName: "name", sTitle: 'LABEL_FIRST_NAME'},
                                        {sName: "language", sTitle: 'LABEL_LANGUAGE'},
                                        {sName: "added_on", sTitle : 'LABEL_ADDED_ON'},
                                        {sName: "status", sTitle: 'LABEL_STATUS', bSortable:false, bSearchable:false},
                                        {sName: "operation", sTitle: 'LABEL_OPERATION', bSortable: false, bSearchable: false},
         ],
        //  fnServerParams: function(aoData){
        //      setTitle(aoData, this)
        //  },
         fnDrawCallback: function(oSettings) {
                        $('.make-switch-form').bootstrapSwitch();
            $('.make-switch-form').bootstrapSwitch('setOnClass', 'success');
            $('.make-switch-form').bootstrapSwitch('setOffClass', 'danger');
         }
        });

        $('body').on('click', 'a.btn-delete-form',function(e) {
                e.preventDefault();
                form_id =  $(this).data('id')
                
                bootbox.confirm({
                    title: "LABEL_DELETE LABEL_FORM",
                    message: "LABEL_ARE_YOU_SURE",
                    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) {
                        $.ajax({
                        'dataType': 'json',
                        'method': 'post',
                        'url' :  'ajax.<?php echo $this->module; ?>.php?action=delete',
                        'data' :{
                            'form-id' : form_id
                        },
                    }).done(function(response) {
    
                        if(response['success']) {
                                $.fn.showSuccess(response['message']);
                                tableForm.fnDraw();
                        } else {
                                $.fn.showError(response['message']);
                        }
                    }).fail(function( jqXHR, textStatus, errorThrown) {
                                        $.fn.showError(textStatus);
                    });
                            }
                    }
                });
                

    });

    $(document).on('click','[data-action="delete"]',function(){

        bootbox.confirm({
                    title: "LABEL_DELETE LABEL_FORMS_2",
                    message: "LABEL_ARE_YOU_SURE",
                    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) {
                                var d = currentSelected();      
                        $.ajax({
                        'dataType': 'json',
                        'method': 'post',
                        'url' :  'ajax.<?php echo $this->module; ?>.php?action=delete-selected',
                        'data' :{
                                 selected : d
                        },
                    }).done(function(response) {
    
                        if(response['success']) {
                                $.fn.showSuccess(response['message']);
                                tableForm.fnDraw();
                        } else {
                                $.fn.showError(response['message']);
                        }
                    }).fail(function( jqXHR, textStatus, errorThrown) {
                                        $.fn.showError(textStatus);
                    });
                            }
                    }
                });
        
    });


    $('body').on('switch-change', 'input[type="checkbox"].make-switch-form', function(e) {
                e.preventDefault();
                e.stopPropagation();

                form_id =  $(this).data('id')
                form_status = $(this).prop('checked') ? 'A' : 'D';
                
        
                $.ajax({
                'dataType': 'json',
            'method': 'post',
            'url' :  'ajax.<?php echo $this->module; ?>.php?action=status',
            'data' :{
                'form-id' : form_id,
                'form-status' : form_status
            },
        }).done(function(response) {
                if(response['success']) {
                        $.fn.showSuccess(response['message']);
               } else {
                $.fn.showError(response['message']);
            }
         }).fail(function( jqXHR, textStatus, errorThrown) {
                        $.fn.showError(textStatus);
        })
    }); 

        $('body').on('click', 'a.btn-edit-form',function(e) {
                e.preventDefault();
                form_id =  $(this).data('id')
        
                $.ajax({
                        'dataType': 'json',
                        'method': 'post',
                        'url' :  '/test/method-one',
                        'data' :{
                                'form-id' : form_id
                        },
                }).done(function(response) {
                        if(response['success']) {
                                        validatorForm.resetForm();

                                        $('#form-main #form-id' ).val(response['id']),
                                        $('#form-main #form-continue').val('0');
                                        $('#form-main #form-name' ).val(response['name']),


                                        instanceName = 'form-description'; 
                                        let editor = CKEDITOR.instances[instanceName ];
                                        editor.setData(response['description'], function() {
                                                        editor.focus();
                                        });
                                        
                                        
                                        instanceName = 'form-text'; 
                                        CKEDITOR.instances[instanceName ].setData(response['text']);

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

                                        objFormGenerator.clear();
                                        objFormGenerator.sections = response['sections'];
                                        objFormGenerator.render();
                                        $('#row-forms').hide();
                                        $('#row-edit').show();

                                        $('#form-main #form-name').focus();
                                        
                                } else {
                                        $.fn.showError(response['message']);
                                }
                        }).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();
                }
        })
            
        var validatorForm = $( "#form-main" ).validate( {
        ignore: [],
        errorClass: 'help-block',
        errorElement: 'span',
                rules: {
                        'form-name':  {
                                required: true,
                                minlength: 2,
                                maxlength: 50
                        },
                        'form-description' : {
                                required: true,
                        },
                        'form-text' : {
                                required: true,
                        },
                        'form-language' : {
                                required: true,
                        },
                        '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) {
                    // do other things for a valid form
                    //form.submit();

                    
                    var error = false;
                    if(objFormGenerator.sections.length == 0) {
                        $.fn.showError('There are no sections');
                        error = true;
                    } else {
                        
                        for(i = 0; i < objFormGenerator.sections.length; i++) 
                        {
                                
                                if(objFormGenerator.sections[i].questions.length == 0) {
                                        $.fn.showError('El "' + objFormGenerator.sections[i].name + '" no tiene preguntas');
                                        break;
                                }
                                
                                var valueSection = parseInt(objFormGenerator.sections[i].value);
                                var totalValueQuestion = 0;
                                
                                
                                for(j = 0; j < objFormGenerator.sections[i].questions.length; j++)
                                {
                                        valueQuestion = parseInt(objFormGenerator.sections[i].questions[j].value);
                                        totalValueQuestion = totalValueQuestion + valueQuestion;
                                        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('El "' + objFormGenerator.sections[i].name + '" seccion, La pregunta #' + questionNumber + ' no tiene opciones');
                                                                        error = true;
                                                                        break;
                                                }

                                                
                                                var totalOption = 0;
                                                var maxOption = 0;
                                                for(k = 0;  k < objFormGenerator.sections[i].questions[j].options.length; k++)
                                                {
                                                        if(objFormGenerator.sections[i].questions[j].type == 'simple' || objFormGenerator.sections[i].questions[j].type == 'multiple' ) {
                                                        if(objFormGenerator.sections[i].questions[j].options[k].correct == 1) {
                                                                numberCorrect++;
                                                        }
                                                        }

                                                        if(objFormGenerator.sections[i].questions[j].type == 'multiple' && objFormGenerator.sections[i].questions[j].options[k].correct == 1) {
                                                                totalOption = totalOption + parseInt(objFormGenerator.sections[i].questions[j].options[k].value);
                                                        }

                                                        if(objFormGenerator.sections[i].questions[j].type == 'rating-open') {
                                                                if(parseInt(objFormGenerator.sections[i].questions[j].options[k].value) > maxOption) {
                                                                                        maxOption = parseInt(objFormGenerator.sections[i].questions[j].options[k].value);
                                                                }
                                                        }
                                                        
                                                }

                                                if(objFormGenerator.sections[i].questions[j].type == 'simple' || objFormGenerator.sections[i].questions[j].type == 'multiple' ) {
                                                
                                                if(numberCorrect == 0) {
                                                        $.fn.showError('El "' + objFormGenerator.sections[i].name + '" seccion, La pregunta #' + questionNumber + ' no tiene una opcion correcta');
                                                        error = true;
                                                        break;
                                                }
                                                if(objFormGenerator.sections[i].questions[j].type == 'simple' && numberCorrect > 1) {
                                                        $.fn.showError('El "' + objFormGenerator.sections[i].name + '" seccion, La pregunta #' + questionNumber + ' tiene más de una opción correcta');
                                                        error = true;
                                                        break;
                                                }
                                                if(objFormGenerator.sections[i].questions[j].type == 'multiple' && numberCorrect == 1) {
                                                        $.fn.showError('El "' + objFormGenerator.sections[i].name + '" seccion, La pregunta #' + questionNumber + ' solo tiene una opción correcta');
                                                        error = true;
                                                        break;
                                                }
                                                }

                                                //console.log('totalOption = ' + totalOption + ' valueQuestion = ' + valueQuestion );
                                                
                                                        if(objFormGenerator.sections[i].questions[j].type == 'multiple' && totalOption > valueQuestion ) {
                                                        $.fn.showError('El "' + objFormGenerator.sections[i].name + '" seccion, La pregunta #' + questionNumber + ' la suma de los valores de las opciones es mayor que el valor de la pregunta');
                                                        error = true;
                                                        break;
                                                }

                                                        //console.log('maxOption = ' + maxOption + ' valueQuestion = ' + valueQuestion );
                                                
                                                if(objFormGenerator.sections[i].questions[j].type == 'rating-open' && maxOption > valueQuestion ) {
                                                        $.fn.showError('El "' + objFormGenerator.sections[i].name + '" seccion, La pregunta #' + questionNumber + ' ');
                                                        error = true;
                                                        break;
                                                }
                                                }

        
                                }

                                if(valueSection != totalValueQuestion) {
                                        $.fn.showError('El "' + objFormGenerator.sections[i].name + '" sección y las preguntas no son las mismas');
                                        error = true;
                                        break;
                                        }
                                }

                                

                        if(error) {
                                return false;
                        } else {


                                var formId              = parseInt($( '#form-main #form-id' ).val());
                                var formContinue = parseInt($( '#form-main #form-continue' ).val());
                                
                                var data = {
                                'form-id'       : formId,
                                        'form-name' : $( '#form-main #form-name' ).val(),
                                        'form-description' : $( '#form-main #form-description' ).val(),
                                        'form-text' : $( '#form-main #form-text' ).val(),
                                        'form-language' : $( '#form-main #form-language' ).val(),
                                        'form-status' : $( '#form-main #form-status' ).val(),
                                        'sections' : objFormGenerator.sections
                                }
                                

                                $.ajax({
                        'dataType': 'json',
                        'method': 'post',
                        'url' :  '/test/method-one',
                        'data' : data,
                    }).done(function(response) {

                        if(response['success']) {
                                $.fn.showSuccess(response['message']);
                                                        if(formContinue == 1) {
                                                                $('#form-main #form-id').val(response['form-id']);
                                                                $('#form-main #form-continue').val(0);
                                                        } else {
                                                                $('#row-edit').hide();
                                        $('#row-forms').show();
                                                        }


                                                        tableForm.fnDraw();
                                
                        } else {
                                $.fn.showError(response['message']);
                        }
                    }).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();
                }
        })
        
        var validatorFormSection = $( "#form-section" ).validate( {
        ignore: [],
        errorClass: 'help-block',
        errorElement: 'span',
                rules: {
                        'section-name':  {
                                required: true,
                                minlength: 2,
                                maxlength: 50
                        },
                        'section-text' : {
                                required: false,
                        },
                        'section-value' : {
                                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) {
                    // 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(),
                                $('#form-section #section-value').val()
                                );      
                    } else {
                        objFormGenerator.addSection(
                                $('#form-section #section-name').val(), 
                                $('#form-section #section-text').val(),
                                $('#form-section #section-value').val()
                        );      
                    }
                    
                    
                    
                        $('#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();
                }
        })
        
        
        var validatorFormQuestion = $( "#form-question" ).validate( {
        ignore: [],
        errorClass: 'help-block',
        errorElement: 'span',
                rules: {
                        'question-text' : {
                                required: true,
                        },
                        'question-value' : {
                                required: true,
                                number: true,
                                min: 1
                        },
                        '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) {

                        //console.log(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();
                    
                    /*console.log('submitHandler');
                    console.log('question-section = ' + $('#form-question #question-section').val()); 
                    console.log('question-text = ' + $('#form-question #question-text').val());
                    console.log('question-value = ' + $('#form-question #question-value').val());
                    console.log('question-type = ' + $('#form-question #question-type').val());
                    console.log('question-max-length = ' + $('#form-question #question-max-length').val());
                    console.log('question-multiline = ' + $('#form-question #question-multiline').val());
                    console.log('question-range = ' + $('#form-question #question-range').val());*/

                    

                    if($('#form-question #question-slug').val()) {
                        console.log('editQuestion');
                            
                        objFormGenerator.editQuestion(
                                $('#form-question #question-section').val(), 
                                $('#form-question #question-slug').val(),
                                $('#form-question #question-text').val(), 
                                $('#form-question #question-value').val(),
                                $('#form-question #question-type').val(),
                                $('#form-question #question-max-length').val(),
                                $('#form-question #question-multiline').val(),
                                $('#form-question #question-range').val()
                                );      
                    } else {
                        console.log('addQuestion');
                            
                        objFormGenerator.addQuestion(
                                $('#form-question #question-section').val(), 
                                $('#form-question #question-text').val(), 
                                $('#form-question #question-value').val(),
                                    $('#form-question #question-type').val(),
                                    $('#form-question #question-max-length').val(),
                                $('#form-question #question-multiline').val(),
                                $('#form-question #question-range').val()
                        );      
                    }
                    
                        $('#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();
                }
        })
        
        var validatorFormOption = $( "#form-option" ).validate( {
        ignore: [],
        errorClass: 'help-block',
        errorElement: 'span',
                rules: {
                        'option-text' : {
                                required: true,
                        },
                'option-value' : {
                                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) {
                    // do other things for a valid form
                    //form.submit();
                    

                    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(), 
                                $('#form-option #option-correct').val(),
                                $('#form-option #option-value').val()
                                );      
                    } else {
                        objFormGenerator.addOption(
                                $('#form-option #option-section').val(), 
                                $('#form-option #option-question').val(), 
                                $('#form-option #option-text').val(), 
                                $('#form-option #option-correct').val(),
                                $('#form-option #option-value').val()
                        );      
                    }


                    
                    
                        $('#modal-option').modal('hide');
                        return false;
                  }
        } );
        
        $('body').on('click', 'button[id="btn-add-section"]', function(e){
                e.preventDefault();
                
                validatorFormSection.resetForm();
                $('#form-section #section-slug').val('');
                $('#form-section #section-name').val('');

                instanceName = 'section-text'; 
                let editor = CKEDITOR.instances[instanceName ];
                editor.setData( '', function() {
                    editor.focus();
                });

        
                $('#form-section #section-value').val('0');
                $('#modal-section h4[class="modal-title"]').html('New Section');
                $('#modal-section').modal('show');
        });
        
        $('body').on('click', 'button.btn-edit-section', function(e){
            e.preventDefault();
            
            var slug = $(this).data('slug');
            var section;
            var showForm = false;
            
            for(i = 0; i < objFormGenerator.sections.length; i++) {
                section = objFormGenerator.sections[i];
                
                if(slug == section.slug) {

                        //console.log('btn-edit-section');
                        //console.log(section);

                                validatorFormSection.resetForm();
                        $('#form-section #section-slug').val(section.slug);
                        $('#form-section #section-name').val(section.name);
        
                        instanceName = 'section-text'; 
                        let editor = CKEDITOR.instances[instanceName ];
                        editor.setData( section.text, function() {
                            editor.focus();
                        });
                                
                                $('#form-section #section-value').val(section.value);
                                
                                showForm = true;
                                break;
                }
            }
            
            if(showForm) {
                $('#modal-section h4[class="modal-title"]').html('Edit Section');
                        $('#modal-section').modal('show');
            }
            
        });
        
        $('body').on('click', 'button.btn-delete-section', function(e){
                e.preventDefault();
                var slug = $(this).data('slug');

                bootbox.confirm({
                    title: "LABEL_DELETE LABEL_SECTION?",
                    message: "LABEL_ARE_YOU_SURE",
                    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);
                                }
                    }
                });
                

        
        });
        
        
        $('body').on('click', 'button.btn-add-question', function(e){
                e.preventDefault();
                
                validatorFormQuestion.resetForm();
                var slug = $(this).data('slug');
                
                $('#form-question #question-section').val(slug);
                $('#form-question #question-slug').val('');

                instanceName = 'question-text'; 
                let editor = CKEDITOR.instances[instanceName ];
                editor.setData( '', function() {
                    editor.focus();
                });


                $('#form-question #question-value').val('0');
                $('#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('New Question');
                $('#modal-question').modal('show');
                
        });
        

        
        $('body').on('click', 'button.btn-edit-question', function(e){
            e.preventDefault();
            
            var slug_section    = $(this).data('section');
            var slug                    = $(this).data('slug');
            var showForm                = false;
            
            for(i = 0; i < objFormGenerator.sections.length; i++) {
                
                if(slug_section == objFormGenerator.sections[i].slug) {
                        
                        for(j = 0; j < objFormGenerator.sections[i].questions.length; j++) {
                                
                                if(slug == objFormGenerator.sections[i].questions[j].slug) {
                                        validatorFormQuestion.resetForm();
                                        
                                        $('#form-question #question-section').val(objFormGenerator.sections[i].slug);
                                        $('#form-question #question-slug').val(objFormGenerator.sections[i].questions[j].slug);

                                instanceName = 'question-text'; 
                                let editor = CKEDITOR.instances[instanceName ];
                                editor.setData( objFormGenerator.sections[i].questions[j].text, function() {
                                    editor.focus();
                                });


                                        $('#form-question #question-value').val(objFormGenerator.sections[i].questions[j].value);
                                        $('#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');
            }
            
        });
        
        
        
        
        $('body').on('click', 'button.btn-delete-question', function(e){
                e.preventDefault();
                
                var slug_section        = $(this).data('section');
                var slug                        = $(this).data('slug');

                bootbox.confirm({
                        title: "LABEL_DELETE LABEL_QUESTION?",
                        message: "LABEL_ARE_YOU_SURE",
                        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);
                                }
                        }
                });                 
        });
        
        
        $('body').on('click', 'button.btn-add-option', function(e){
                e.preventDefault();
            var slug_section    = $(this).data('section');
                var slug_question       = $(this).data('slug');
                var showForm            = false;

            for(i = 0; i < objFormGenerator.sections.length; i++) {
                if(slug_section == objFormGenerator.sections[i].slug) {
                        for(j = 0; j < objFormGenerator.sections[i].questions.length; j++) {
                                if(slug_question == objFormGenerator.sections[i].questions[j].slug) {

                                validatorFormOption.resetForm();
                                $('#form-option #option-section').val(slug_section);
                                $('#form-option #option-question').val(slug_question);
                                $('#form-option #option-slug').val('');
                                                
                                instanceName = 'option-text'; 
                                let editor = CKEDITOR.instances[instanceName ];
                                editor.setData( '', function() {
                                    editor.focus();
                                });


                                $('#form-option #option-correct').val('0');
                                if(objFormGenerator.sections[i].questions[j].type == 'rating-open') {
                                $('#form-option #option-correct').parent().hide();
                        } else {
                                $('#form-option #option-correct').parent().show();
                        }
                                
                                if(objFormGenerator.sections[i].questions[j].type == 'multiple' || objFormGenerator.sections[i].questions[j].type == 'rating-open') {
                                        $('#form-option #option-value').val('0');
                                        $('#form-option #option-value').parent().show();
                                } else {
                                        $('#form-option #option-value').val('1');
                                        $('#form-option #option-value').parent().hide();
                                        
                        }
                                showForm = true;
                                }
                        }
                }
            }

                if(showForm) {
                $('#modal-option h4[class="modal-title"]').html('New Option');
                $('#modal-option').modal('show');
                }
                
        });
        

        
        $('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) {
                        for(j = 0; j < objFormGenerator.sections[i].questions.length; j++) {
                                if(slug_question == objFormGenerator.sections[i].questions[j].slug) {
                                        for(k = 0; k < objFormGenerator.sections[i].questions[j].options.length; k++) {
                                                if(slug == objFormGenerator.sections[i].questions[j].options[k].slug) {
                                                        validatorFormOption.resetForm();
                                                        $('#form-option #option-section').val(objFormGenerator.sections[i].slug);
                                                        $('#form-option #option-question').val(objFormGenerator.sections[i].questions[j].slug);
                                                $('#form-option #option-slug').val(objFormGenerator.sections[i].questions[j].options[k].slug);

                                                instanceName = 'option-text'; 
                                        let editor = CKEDITOR.instances[instanceName ];
                                        editor.setData( objFormGenerator.sections[i].questions[j].options[k].text, function() {
                                            editor.focus();
                                        });
                                                
                                                
                                                $('#form-option #option-correct').val(objFormGenerator.sections[i].questions[j].options[k].correct);
                                                if(objFormGenerator.sections[i].questions[j].type == 'multiple' || objFormGenerator.sections[i].questions[j].type == 'simple') {
                                                        $('#form-option #option-correct').parent().show();
                                                } else {
                                                        $('#form-option #option-correct').parent().hide();
                                        }

                                                $('#form-option #option-value').val(objFormGenerator.sections[i].questions[j].options[k].value);

                                                                if(objFormGenerator.sections[i].questions[j].type == 'multiple' || objFormGenerator.sections[i].questions[j].type == 'rating-open') {
                                                        $('#form-option #option-value').parent().show();
                                                                } else {
                                                                        $('#form-option #option-value').parent().hide();
                                                                }


                                                                
                                                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');
            }
        });
        
        $('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_ARE_YOU_SURE",
                        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);
                                }
                        }
                });                         
        })

        $('#form-section #section-value').inputNumberFormat({'decimal' : 2});

        $('#form-question #question-value').inputNumberFormat({'decimal' : 2});
        $('#form-question #question-max-length').inputNumberFormat({'decimal' : 0});

        $('#form-option #option-value').inputNumberFormat({'decimal' : 2});
        
        $('#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();
                }


                
        });

        $('button.btn-add-form').click(function(e) {
                e.preventDefault();

                objFormGenerator.clear();
                objFormGenerator.render();
                validatorForm.resetForm();

                $('#form-main #form-id').val('0');
                $('#form-main #form-continue').val('0');
                $('#form-main #form-name').val('');

                instanceName = 'form-text'; 
                let editor = CKEDITOR.instances[instanceName ];
                editor.setData('', function() {
                    editor.focus();
                });


                instanceName = 'form-description'; 
                CKEDITOR.instances[instanceName ].setData('');
                
                $( '#form-main #form-language' ).val('EN'),
                $( '#form-main #form-status' ).val('D');
                
                $('#row-forms').hide();
                $('#row-edit').show();
                $('#form-main #form-name').focus();

        /*$('html, body').animate({
            scrollTop: $('#form-main #form-name').offset().top - 100
        }, 1000);*/
        });

        $('button.btn-edit-cancel').click(function(e) {
                e.preventDefault();
                $('#row-edit').hide();
                $('#row-forms').show();
                
        });


        $('button.btn-form-save-continue').click(function(e) {
                e.preventDefault();
                $('#form-main #form-continue').val('1')
                $('#form-main').submit();
        });
        
        $('button.btn-form-save-close').click(function(e) {
                e.preventDefault();
                $('#form-main #form-continue').val('0')
                $('#form-main').submit();
                
        });

        $('#modal-section, #modal-question, #modal-option').modal({
                        backdrop: 'static',
                        keyboard: false,
                        show: false
                });
        });
JS;
$this->inlineScript()->captureEnd();
?>


  
<!-- Content Header (Page header) -->
<section class="content-header">
        <div class="container-fluid">
        <div class="row mb-2">
                <div class="col-sm-12">
                <h1>LABEL_SELF_EVALUATION_FORMS</h1>
                        </div>
                </div>
        </div><!-- /.container-fluid -->
</section>

<section class="content">
        <div class="container-fluid">
        <div class="row">
                <div class="col-12">
                                <div class="card">                    
                                        <div class="card-body">
                                <table id="gridTable" class="table   table-hover">
                                <thead>
                                                        <tr>
                                        <th>LABEL_NAME</th>
                                        <th>LABEL_LANGUAGE</th>
                                        <th>LABEL_ACTIVE</th>
                                        <th>LABEL_ACTIONS</th>
                                </tr>
                                </thead>
                                <tbody>
                                </tbody>
                        </table>
                        </div>
                        <div class="card-footer clearfix">
                                <div style="float:right;">
                                                        <button type="button" class="btn btn-info btn-refresh"><i class="fa fa-refresh"></i> LABEL_REFRESH </button>
                                                        <?php if($allowAdd) : ?>
                                                        <button type="button" class="btn btn-primary btn-add"><i class="fa fa-plus"></i> LABEL_ADD </button>
                                                        <?php endif; ?>
                                                </div>
                        </div>
                        </div>
                </div>     
        </div>          
        </div>
</section>      

<!-- The Modal -->
<div class="modal" id="modal">
        <div class="modal-dialog  modal-xl">
        <div class="modal-content">

            <!-- Modal Header -->
                <div class="modal-header">
                        <h4 class="modal-title">LABEL_SELF_EVALUATION_FORM - <span id="form-title"></span></h4>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                </div>

            <!-- Modal body -->
                <div class="modal-body">
                         <?php 
                    $form = $this->form;
                        $form->setAttributes([
                        'method'    => 'post',
                        'name'      => 'form',
                        'id'        => 'form'
                    ]);
    
                    $form->prepare();
                    echo $this->form()->openTag($form);
                    ?>                                  
                                        <div class="form-group">
                                                <?php 
                            $element = $form->get('name');
                            $element->setOptions(['label' => 'LABEL_NAME']);
                            $element->setAttributes(['class' => 'form-control']); 
                                            
                            echo $this->formLabel($element);
                            echo $this->formText($element);
                            ?>
                                                </div>
                                                <div class="form-group">
                        <?php 
                            $element = $form->get('language');
                            $element->setOptions(['label' => 'LABEL_LANGUAGE']);
                            $element->setAttributes(['class' => 'form-control']); 

                            echo $this->formLabel($element);
                            echo $this->formSelect($element);
                        ?>
                                                </div>
                                                <div class="form-group">
                        <?php 
                            $element = $form->get('description');
                            $element->setOptions(['label' => 'LABEL_DESCRIPTION']);
                            $element->setAttributes(['class' => 'form-control']); 
                                        
                            echo $this->formLabel($element);
                            echo $this->formTextArea($element);
                        ?>
                                                </div>
                                                <div class="form-group">
                        <?php 
                            $element = $form->get('text');
                            $element->setOptions(['label' => 'LABEL_TEXT']);
                            $element->setAttributes(['class' => 'form-control']); 
                                        
                            echo $this->formLabel($element);
                            echo $this->formTextArea($element);
                        ?>
                                                </div>
                                                <div class="form-group">
                        <?php 
                            $element = $form->get('status');
                            echo $this->formCheckbox($element);
                        ?>
                                                </div>
                                                                
                                        <div class="form-group">
                                <button type="submit" class="btn btn-primary">LABEL_SAVE</button>
                                <button type="button" class="btn btn-light btn-cancel">LABEL_CANCEL</button>
                                </div>
                        <?php echo $this->form()->closeTag($form); ?>
                </div>

            <!-- Modal footer -->
                <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
                </div>

        </div>
        </div>
</div>