/**
 * 2007-2022 ETS-Soft
 *
 * NOTICE OF LICENSE
 *
 * This file is not open source! Each license that you purchased is only available for 1 wesite only.
 * If you want to use this file on more websites (or projects), you need to purchase additional licenses.
 * You are not allowed to redistribute, resell, lease, license, sub-license or offer our resources to any third party.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please contact us for extra customization service at an affordable price
 *
 *  @author ETS-Soft <etssoft.jsc@gmail.com>
 *  @copyright  2007-2022 ETS-Soft
 *  @license    Valid for 1 website (or project) for each purchase of license
 *  International Registered Trademark & Property of ETS-Soft
 */

var ETS_HD_FIELD_TYPES = [
    'mediumtext',
    'longtext',
    'date',
    'datetime',
    'int',
    'tinyint',
    'decimal',
];
var ETS_HD_CURRENT_INDEX = ETS_HD_CURRENT_INDEX || '',
    ETS_HD_DELETE_TITLE = ETS_HD_DELETE_TITLE || 'Delete',
    ets_hd_maximum_character = ets_hd_maximum_character || 'Maximum character %d'
;

var ets_hd_admin_fn = {
    init: function () {
        ets_hd_admin_fn.sort($('.ets_hd_columns .table > tbody'));
        ets_hd_admin_fn.sortOptions($('.ets_hd_options > tbody'));
        ets_hd_admin_fn.reCaptchaConfigs();
        ets_hd_admin_fn.newTicketMails();
        if (ets_hd_fn) {
            ets_hd_fn.init();
        }
        //if($('.alert.alert-success').length)
//        {
//            setTimeout(function(){$('.alert.alert-success').hide();},3000);
//        }
    },
    newTicketMails: function () {
        var custom_email = $('.form-group.mail_new_ticket.custom_emails');
        if ($('.mail_new_ticket #custom_emails:checked').length > 0) {
            custom_email.show();
        } else
            custom_email.hide();

        return this;
    },
    reCaptchaConfigs: function (type, allow) {
        var captchaType = type || $('#ETS_HD_CAPTCHA_TYPE').val()
            , enabledCaptcha = allow || $('input[name=ETS_HD_ALLOW_CAPTCHA]:checked').val()
        ;

        if (parseInt(enabledCaptcha) < 1) {
            $('.form-group.captcha').hide();
        } else {
            $('.form-group.captcha').show();
            $('.form-group.captcha.google').hide();
            $('.form-group.captcha.google.' + captchaType).show();
        }

        return this;
    },
    readURL: function (input, binding) {
        if (input.files && input.files[0]) {
            var binding_of_input = binding || '';
            var reader = new FileReader();
            reader.onload = function (e) {
                $('.ets_hd_reader_image' + (binding_of_input ? '.' + binding_of_input : '') + ' > img')
                    .attr({'src': e.target.result, 'title': input.files[0].name})
                    .css('max-width', '110px')
                    .addClass('image-loading')
                ;
            };

            reader.readAsDataURL(input.files[0]); // convert to base64 string
        }

        return this;
    },
    showOptions: function (type, changedType) {

        var _columnType = type || $('#ets_hd_column_form #type'),
            _changedType = changedType || false,
            _fieldType = $('#ets_hd_column_form #field_type'),
            _groupPlaceHolder = $('#ets_hd_column_form .form-group.placeholder'),
            _groupDefault = $('#ets_hd_column_form .form-group.default.text'),
            _groupDefaultTextarea = $('#ets_hd_column_form .form-group.default.textarea'),
            _groupDefaultDate = $('#ets_hd_column_form .form-group.default.date'),
            _groupDefaultDateTime = $('#ets_hd_column_form .form-group.default.datetime'),
            _groupFieldType = $('#ets_hd_column_form .form-group.field_type'),
            _groupFieldLength = $('#ets_hd_column_form .form-group.field_length'),
            _wrapOption = $('#ets_hd_column_form .ets_hd_option_wrap'),
            _typeInput = $('.ets_hd_options .ets_hd_radio_checkbox input')
        ;
        _groupPlaceHolder.show();
        _groupDefault.show();
        _groupDefault.find('input').prop('disabled',false);
        _groupDefaultTextarea.hide();
        _groupDefaultTextarea.find('textarea').prop('disabled',true);
        _groupDefaultDate.hide();
        _groupDefaultDate.find('input').prop('disabled',true);
        _groupDefaultDateTime.hide();
        _groupDefaultDateTime.find('input').prop('disabled',true);
        _groupFieldType.show();
        _groupFieldLength.show();
        _wrapOption.removeClass('active');

        _fieldType.find('option').prop('disabled', false);
        if (_changedType) {
            _fieldType.find('option:not([disabled])').first().val();
        } else
            _fieldType.val(_fieldType.find('option:not([disabled])[selected="selected"]').val());
        if(_groupDefault.find('text').val()==_groupDefaultDate.find('input').val() && _groupDefaultDate.find('input').val()==_groupDefaultDateTime.find('input').val())
        {
            if(_columnType.val()=='textarea')
            {
                _groupDefaultDateTime.find('input').val('');
                _groupDefaultDate.find('input').val('');
                _groupDefault.find('input').val('');
            }
            else if(_columnType.val()=='date')
            {
                _groupDefaultDateTime.find('input').val('');
                _groupDefaultTextarea.find('textarea').val('');
                _groupDefault.find('input').val('');
            }
            else if(_columnType.val()=='datetime')
            {
                _groupDefaultDate.find('input').val('');
                _groupDefaultTextarea.find('textarea').val('');
                _groupDefault.find('input').val('');
            }
            else
            {
                _groupDefaultDate.find('input').val('');
                _groupDefaultTextarea.find('textarea').val('');
                _groupDefaultDateTime.find('input').val('');
            }
            
        }
        switch (_columnType.val()) {
            case 'text':
                _fieldType.find('option').prop('disabled', true);
                _fieldType.find('[value=char],[value=varchar]').prop('disabled', false);
                if (_changedType) {
                    _fieldType.val(_fieldType.find('option[value=varchar]').val());
                } else
                    _fieldType.val(_fieldType.find('option:not([disabled])[selected="selected"]').val() || _fieldType.find('option[value=varchar]').val());
                break;
            case 'numeric':
                _fieldType.find('option').prop('disabled', true);
                _fieldType.find('[value=int],[value=tinyint],[value=decimal]').prop('disabled', false);
                _fieldType.val(_fieldType.find('option:not([disabled])[selected="selected"]').val() || _fieldType.find('option[value=int]').val());
                _groupFieldLength.hide();
                _groupFieldLength.find('input').val('');
                break;
            case 'textarea':
                _fieldType.find('option').prop('disabled', true);
                _fieldType.find('[value=text],[value=mediumtext],[value=longtext]').prop('disabled', false);
                _fieldType.val(_fieldType.find('option:not([disabled])').first().val() || _fieldType.find('option[value=text]').val());
                _groupDefault.hide();
                _groupDefault.find('input').prop('disabled',true);
                _groupDefaultTextarea.show();
                _groupDefaultTextarea.find('textarea').prop('disabled',false);
                break;
            case 'select':
                _groupPlaceHolder.hide();
                _groupFieldType.hide();
                _wrapOption.addClass('active').addClass('type_select').removeClass('type_radio').removeClass('type_checkbox');
                if (_changedType)
                    _typeInput.attr('type', 'radio').prop('checked', false);
                _groupDefault.hide();
                _groupFieldLength.hide();
                _groupFieldLength.find('input').val('');
                break;
            case 'radio':
                _groupPlaceHolder.hide();
                _groupFieldType.hide();
                _groupFieldLength.hide();
                _groupFieldLength.find('input').val('');
                _wrapOption.addClass('active').addClass('type_radio').removeClass('type_checkbox').removeClass('type_select');
                if (_changedType)
                    _typeInput.attr('type', 'radio').prop('checked', false);
                _groupDefault.hide();
                break;
            case 'email':
                _fieldType.find('option').prop('disabled', true);
                _fieldType.find('[value=char],[value=varchar]').prop('disabled', false);
                if (_changedType) {
                    _fieldType.val(_fieldType.find('option[value=varchar]').val());
                } else
                    _fieldType.val(_fieldType.find('option:not([disabled])[selected="selected"]').val() || _fieldType.find('option[value=varchar]').val());
                _groupFieldLength.hide();
                _groupFieldLength.find('input').val('');
                _groupFieldType.hide();
                break;
            case 'file':
                _groupFieldType.hide();
                 _groupFieldLength.hide();
                _groupFieldLength.find('input').val('');
                _groupPlaceHolder.hide();
                _groupDefault.hide();
                break;
            case 'checkbox':
                _groupPlaceHolder.hide();
                _groupFieldType.hide();
                 _groupFieldLength.hide();
                _groupFieldLength.find('input').val('');
                _wrapOption.addClass('active').addClass('type_checkbox').removeClass('type_radio').removeClass('type_select');
                if (_changedType)
                    _typeInput.attr('type', 'checkbox').prop('checked', false);
                _groupDefault.hide();
                break;
            case 'date':
                _groupFieldType.hide();
                 _groupFieldLength.hide();
                _groupFieldLength.find('input').val('');
                _groupDefault.hide();
                _groupDefault.find('input').prop('disabled',true);
                _groupDefaultDate.show();
                _groupDefaultDate.find('input').prop('disabled',false);
                break;
            case 'datetime':
                _groupFieldType.hide();
                _groupFieldLength.hide();
                _groupFieldLength.find('input').val('');
                _groupDefault.hide();
                _groupDefault.find('input').prop('disabled',true);
                _groupDefaultDateTime.show();
                _groupDefaultDateTime.find('input').prop('disabled',false);
                break;
        }

        return this;
    },
    showFieldTypes: function (field_type) {
        var fieldType = field_type || $('#field_type');
        if (fieldType.val() !== '' && ETS_HD_FIELD_TYPES.indexOf(fieldType.val()) !== -1) {
            $('.form-group.field_length').hide();
            $('.form-group.field_length #field_length').val('');
        } else {
            $('.form-group.field_length').show();
        }

        return this;
    },
    sort: function (selector) {
        if ($.fn.sortable) {
            $(selector).sortable({
                cancel: '.empty',
                axis: 'y',
                handle: '.ets_hd_sortable',
                helper: function (e, ui) {
                    ui.children().each(function () {
                        $(this).width($(this).width());
                    });
                    return ui;
                },
                update: function (e, ui) {
                    if (this === ui.item.parent()[0]) {
                        var itemId = ui.item.attr('data-id');
                        var previousId = ui.item.prev('.ets_hd_column').length > 0 ? ui.item.prev('.ets_hd_column').attr('data-id') : 0;
                        $.ajax({
                            url: ETS_HD_CURRENT_INDEX,
                            type: 'post',
                            dataType: 'json',
                            data: {
                                itemId: itemId,
                                previousId: previousId,
                                action: 'position',
                                ajax: 1,
                            },
                            success: function (json) {
                                if (!json.ok) {
                                    $(selector).sortable('cancel');
                                    if (json.msg) {
                                        showErrorMessage(json.msg);
                                    }
                                } else {
                                    if (json.msg) {
                                        showSuccessMessage(json.msg);
                                    }
                                }
                            },
                            error: function () {
                                $(selector).sortable('cancel');
                            }
                        });
                    }
                }
            }).disableSelection();
        }

        return this;
    },
    sortOptions: function (selector) {
        if ($.fn.sortable) {
            $(selector).sortable({
                cancel: '.empty',
                handle: '.ets_hd_arrow_move',
                axis: 'y',
                helper: function (e, ui) {
                    ui.children().each(function () {
                        $(this).width($(this).width());
                    });
                    return ui;
                },
            }).disableSelection();
        }

        return this;
    },
    navTabs: function (tab) {
        $('.ets-hd-nav-tab, .form-wrapper-group-tab').removeClass('active');
        tab.addClass('active');
        let tab_name = tab.data('tab');
        $('#current_tab').val(tab_name);
        $('.form-wrapper-group-tab.' + tab_name).addClass('active');

        return this;
    },
    copy2friendlyURL: function (title, alias, alias_link) {
        if (typeof str2url !== "undefined" &&
            alias.length > 0 &&
            title.trim() !== ''
        ) {
            let url_alias = str2url(title, 'UTF-8');
            alias.val(url_alias);
            this.replaceLink(url_alias, alias_link);
        }
        return '';
    },
    replaceLink: function (alias, alias_link) {
        if (alias.trim() !== '' &&
            alias_link.length > 0
        ) {
            let href = alias_link.attr('href').replace(/\/[\_a-zA-Z0-9\-]+(\/add)?(\.html)?$/, '/' + alias + '$1$2');
            alias_link.attr('href', href).html(href);
        }
    },
    genCode: function (size) {
        var chars = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";
        var random = '';
        for (var i = 1; i <= size; ++i) {
            random += chars.charAt(Math.floor(Math.random() * chars.length));
        }

        return random;
    },
    toColumnName: function (str) {
        str = str.toUpperCase();
        str = str.toLowerCase();
        /* Lowercase */
        str = str.replace(/[\u00E0\u00E1\u00E2\u00E3\u00E5\u0101\u0103\u0105\u0430\u1EA7\u1EA3\u1EA1\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EA5\u1EA9\u1EAB\u1EAD]/g, 'a');
        str = str.replace(/[\u0431]/g, 'b');
        str = str.replace(/[\u00E7\u0107\u0109\u010D\u0446]/g, 'c');
        str = str.replace(/[\u010F\u0111\u0434]/g, 'd');
        str = str.replace(/[\u00E8\u00E9\u00EA\u00EB\u0113\u0115\u0117\u0119\u011B\u0435\u044D\u1EC7\u1EBB\u1EBD\u1EB9\u1EBF\u1EC1\u1EC3\u1EC5]/g, 'e');
        str = str.replace(/[\u0444]/g, 'f');
        str = str.replace(/[\u011F\u0121\u0123\u0433\u0491]/g, 'g');
        str = str.replace(/[\u0125\u0127]/g, 'h');
        str = str.replace(/[\u00EC\u00ED\u00EE\u00EF\u0129\u012B\u012D\u012F\u0131\u0438\u0456\u1EC9\u1ECB]/g, 'i');
        str = str.replace(/[\u0135\u0439]/g, 'j');
        str = str.replace(/[\u0137\u0138\u043A]/g, 'k');
        str = str.replace(/[\u013A\u013C\u013E\u0140\u0142\u043B]/g, 'l');
        str = str.replace(/[\u043C]/g, 'm');
        str = str.replace(/[\u00F1\u0144\u0146\u0148\u0149\u014B\u043D]/g, 'n');
        str = str.replace(/[\u00F2\u00F3\u00F4\u00F5\u00F8\u014D\u014F\u0151\u043E\u01A1]/g, 'o');
        str = str.replace(/[\u043F]/g, 'p');
        str = str.replace(/[\u0155\u0157\u0159\u0440]/g, 'r');
        str = str.replace(/[\u015B\u015D\u015F\u0161\u0441]/g, 's');
        str = str.replace(/[\u00DF]/g, 'ss');
        str = str.replace(/[\u0163\u0165\u0167\u0442]/g, 't');
        str = str.replace(/[\u00F9\u00FA\u00FB\u0169\u016B\u016D\u016F\u0171\u0173\u0443\u1EED]/g, 'u');
        str = str.replace(/[\u0432]/g, 'v');
        str = str.replace(/[\u0175]/g, 'w');
        str = str.replace(/[\u00FF\u0177\u00FD\u044B]/g, 'y');
        str = str.replace(/[\u017A\u017C\u017E\u0437]/g, 'z');
        str = str.replace(/[\u00E4\u00E6]/g, 'ae');
        str = str.replace(/[\u0447]/g, 'ch');
        str = str.replace(/[\u0445]/g, 'kh');
        str = str.replace(/[\u0153\u00F6]/g, 'oe');
        str = str.replace(/[\u00FC]/g, 'ue');
        str = str.replace(/[\u0448]/g, 'sh');
        str = str.replace(/[\u0449]/g, 'ssh');
        str = str.replace(/[\u044F]/g, 'ya');
        str = str.replace(/[\u0454]/g, 'ye');
        str = str.replace(/[\u0457]/g, 'yi');
        str = str.replace(/[\u0451]/g, 'yo');
        str = str.replace(/[\u044E]/g, 'yu');
        str = str.replace(/[\u0436]/g, 'zh');

        /* Uppercase */
        str = str.replace(/[\u0100\u0102\u0104\u00C0\u00C1\u00C2\u00C3\u00C4\u00C5\u0410\u1EA2\u1EA0\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC]/g, 'A');
        str = str.replace(/[\u0411]/g, 'B');
        str = str.replace(/[\u00C7\u0106\u0108\u010A\u010C\u0426]/g, 'C');
        str = str.replace(/[\u010E\u0110\u0414]/g, 'D');
        str = str.replace(/[\u00C8\u00C9\u00CA\u00CB\u0112\u0114\u0116\u0118\u011A\u0415\u042D\u1EBA\u1EBC\u1EB8\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6]/g, 'E');
        str = str.replace(/[\u0424]/g, 'F');
        str = str.replace(/[\u011C\u011E\u0120\u0122\u0413\u0490]/g, 'G');
        str = str.replace(/[\u0124\u0126]/g, 'H');
        str = str.replace(/[\u0128\u012A\u012C\u012E\u0130\u0418\u0406\u00CD\u00CC\u1EC8\u1ECA]/g, 'I');
        str = str.replace(/[\u0134\u0419]/g, 'J');
        str = str.replace(/[\u0136\u041A]/g, 'K');
        str = str.replace(/[\u0139\u013B\u013D\u0141\u041B]/g, 'L');
        str = str.replace(/[\u041C]/g, 'M');
        str = str.replace(/[\u00D1\u0143\u0145\u0147\u014A\u041D]/g, 'N');
        str = str.replace(/[\u00D3\u014C\u014E\u0150\u041E]/g, 'O');
        str = str.replace(/[\u041F]/g, 'P');
        str = str.replace(/[\u0154\u0156\u0158\u0420]/g, 'R');
        str = str.replace(/[\u015A\u015C\u015E\u0160\u0421]/g, 'S');
        str = str.replace(/[\u0162\u0164\u0166\u0422]/g, 'T');
        str = str.replace(/[\u00D9\u00DA\u00DB\u0168\u016A\u016C\u016E\u0170\u0172\u0423]/g, 'U');
        str = str.replace(/[\u0412]/g, 'V');
        str = str.replace(/[\u0174]/g, 'W');
        str = str.replace(/[\u0176\u042B]/g, 'Y');
        str = str.replace(/[\u0179\u017B\u017D\u0417]/g, 'Z');
        str = str.replace(/[\u00C4\u00C6]/g, 'AE');
        str = str.replace(/[\u0427]/g, 'CH');
        str = str.replace(/[\u0425]/g, 'KH');
        str = str.replace(/[\u0152\u00D6]/g, 'OE');
        str = str.replace(/[\u00DC]/g, 'UE');
        str = str.replace(/[\u0428]/g, 'SH');
        str = str.replace(/[\u0429]/g, 'SHH');
        str = str.replace(/[\u042F]/g, 'YA');
        str = str.replace(/[\u0404]/g, 'YE');
        str = str.replace(/[\u0407]/g, 'YI');
        str = str.replace(/[\u0401]/g, 'YO');
        str = str.replace(/[\u042E]/g, 'YU');
        str = str.replace(/[\u0416]/g, 'ZH');

        str = str.toLowerCase();

        str = str.replace(/^[^a-zA-Z]+/g, '');
        str = str.replace(/[^a-z0-9\s\'\:\/\[\]-_]/g, '');
        str = str.replace(/[\u0028\u0029\u0021\u003F\u002E\u0026\u005E\u007E\u002B\u002A\u002F\u003A\u003B\u003C\u003D\u003E]/g, '');
        str = str.replace(/[\s\'\:\/\[\]-]+/g, '_');

        // Add special char not used for url rewrite
        str = str.replace(/[\/\\"'|,;%]*/g, '');

        return str;
    }
}

$(document).ready(function () {
    ets_hd_admin_fn.init();
    $(document).on('click','.btn-send-mail',function(e){
        e.preventDefault();
        if(!$(this).hasClass('loading'))
        {
            $(this).addClass('loading');
            var $this = $(this);
            $.ajax({
    			type: 'POST',
    			headers: { "cache-control": "no-cache" },
    			url: $this.attr('href'),
                data:'ajax=1',
    			async: true,
    			cache: false,
    			dataType : "json",
    			success: function(json)
    			{
                    if(json.success)
                    {
                        showSuccessMessage(json.success);
                        $this.parents('tr').remove();
                    }
                    if(json.errors)
                    {
                        showErrorMessage(json.errors)
                    }
                    $this.removeClass('loading');
                }
    		});
        }
    });
    $(document).on('click','.close_popup',function(){
        $('.ets_hd_mail_popup').removeClass('show');
    });
    $(document).on('click','#list-mail_log .link_view',function(){
        if(!$(this).hasClass('loading'))
        {
           $(this).addClass('loading') ;
           var $button = $(this);
           url_ajax = $(this).attr('href');
           $.ajax({
            url: url_ajax,
            data: '',
            type: 'post',
            dataType: 'json',
            success: function(json){
                $button.removeClass('loading');
                if(json.mail_content)
                {
                    if($('.ets_hd_mail_popup').length>0)
                        $('.ets_hd_mail_popup').remove();
                    if($('.ets_hd_mail_popup').length==0)
                    {
                        var html ='<div class="ets_hd_mail_popup show">';
                            html +='<div class="popup_content table">';
                                html +='<div class="popup_content_tablecell">';
                                    html +='<div class="popup_content_wrap" style="position: relative">';
                                        html +=' <span class="close_popup">+</span>';
                                        html +='<div id="block-form-popup-dublicate">';
                                            html +='<div id="quick-view-mail" class="quick-view-mail">';
                                                html +='<div class="header_poup">';
                                                html += json.title;
                                                html +='</div>';
                                                html +='<div class="content_poup">';
                                                    html +='<div class="row form-group subject-mail">';
                                                    html += json.subject;
                                                    html +='<div>';
                                                html +='</div>';
                                            html +='</div>';
                                        html +='</div>';
                                    html +='</div>';
                                html +='</div>';
                            html +='</div>';
                        html +='</div>';
                        $('body').append(html);
                    }
                    else
                        $('.ets_hd_mail_popup').addClass('show');
                    createIframe = $('<iframe id="preview_template_html_mail"></iframe>');
                    $('body .ets_hd_mail_popup .popup_content_wrap .content_poup').append(createIframe);
                    var contentIFrame = createIframe[0].contentDocument || createIframe[0].contentWindow.document;
                    contentIFrame.write(json.mail_content);
                    contentIFrame.close();
                }
            },
            error: function(xhr, status, error)
            {
                $button.removeClass('loading');
                var err = eval("(" + xhr.responseText + ")");
                alert(err.Message);                    
            }
        });
        }
        return false; 
    });
    if ($(".ets_hd_datepicker input").length > 0) {
		$(".ets_hd_datepicker input").datepicker({
			dateFormat: 'yy-mm-dd',
		});
	}
    $(document).on('input change', '#ets_hd_column_form  #name', function () {
        var ele = $(this);
        if (ele.val().length > 0) {
            ele.val(ets_hd_admin_fn.toColumnName(ele.val()));
        }
    });

    $(document).on('keyup', '.ets_hd_title_character', function () {
        var ele = $(this),
            number_of_character = ele.next('.help-block').find('.ets_hd_number_of_character[data-lang=' + id_language + ']'),
            size = number_of_character.data('size')
        ;
        if (ele.val().length > size) {
            ele.val(ele.val().substr(0, size));
            number_of_character.html(size);
            showErrorMessage(ets_hd_maximum_character.replace(/%d/g, size));
        } else
            number_of_character.html(ele.val().length);
    });

    $(document).on('click', '.ets_hd_radio_checkbox input[type=radio]', function () {
        $('.ets_hd_radio_checkbox input[type=radio]:checked').prop('checked', false);
        $(this).prop('checked', true);
    });

    $(document).on('click', 'button[name=ets_hd_general_token]', function () {
        var code = ets_hd_admin_fn.genCode(10);
        $('#ETS_HD_CRONJOB_SECURE_TOKEN').val(code);
        $('.ets-hd-cronjob-secure-value').text(code);
    });

    $(document).on('click', 'a.js-ets-hd-run-cronjob', function (e) {
        e.preventDefault();
        var ele = $(this),
            href = ele.attr('href')
        ;
        if (!ele.hasClass('active')) {
            ele.addClass('active');
            $.ajax({
                type: 'post',
                url: href,
                data: {
                    ajax: 1,
                    action: 'runCronjob',
                },
                dataType: 'json',
                success: function (json) {
                    ele.removeClass('active');
                    if (json) {
                        if (json.msg) {
                            showNoticeMessage(json.msg);
                        }
                        if (json.log) {
                            $('#ETS_HD_CRONJOB_LOG').val(json.log);
                        }
                    }
                },
                error: function () {
                    ele.removeClass('active');
                }
            });
        }
    });

    $(document).on('click', 'button[name=ets_hd_clear_log]', function () {
        var ele = $(this);
        if (!ele.hasClass('active')) {
            ele.addClass('active');
            $.ajax({
                type: 'post',
                data: {
                    ajax: 1,
                    action: 'clearLog',
                },
                dataType: 'json',
                success: function (json) {
                    ele.removeClass('active');
                    if (json) {
                        if (json.msg) {
                            showSuccessMessage(json.msg);
                        }
                        $('#ETS_HD_CRONJOB_LOG').val('');
                    }
                },
                error: function () {
                    ele.removeClass('active');
                }
            });
        }
    });

    $(document).on('click', '#form-ets_hd_staff a.list-action-enable', function (e) {
        e.preventDefault();
        var ele = $(this),
            href = ele.attr('href'),
            status = ele.hasClass('action-enabled') ? 0 : 1
        ;

        if (!ele.hasClass('active')) {
            ele.addClass('active');
            $.ajax({
                type: 'post',
                url: href,
                data: {
                    ajax: 1,
                    action: 'updateStatus',
                    active: status
                },
                dataType: 'json',
                success: function (json) {
                    ele.removeClass('active');
                    if (json) {
                        if (json.errors) {
                            showErrorMessage(json.errors);
                        } else {
                            if (json.msg) {
                                showSuccessMessage(json.msg);
                            }
                            if (status) {
                                ele.addClass('action-enabled').removeClass('action-disabled');
                                ele.find('i.icon-check').removeClass('hidden');
                                ele.find('i.icon-remove').addClass('hidden');
                            } else {
                                ele.removeClass('action-enabled').addClass('action-disabled');
                                ele.find('i.icon-check').addClass('hidden');
                                ele.find('i.icon-remove').removeClass('hidden');
                            }
                            if (json.link) {
                                ele.attr('href', json.link);
                            }
                        }
                    }
                },
                error: function () {
                    ele.removeClass('active');
                }
            });
        }
    });

    $(document).on('click', '.ets_hd_staff_item', function () {
        $('.ets_hd_staff_item.active, .ets_hd_staff_wrap.active').removeClass('active');
        $(this).addClass('active');
        let staff = $(this).data('id');
        $('.ets_hd_staff_wrap.' + staff).addClass('active');
        $('#current_staff').val(staff);
    });

    

    $(document).on('click', '.mail_new_ticket #custom_emails', function () {
        ets_hd_admin_fn.newTicketMails();
    });

    $(document).on('change', 'input[name=ETS_HD_ALLOW_CAPTCHA]', function () {
        ets_hd_admin_fn.reCaptchaConfigs(false, $(this).val());
    });

    $(document).on('change', '#ETS_HD_CAPTCHA_TYPE', function () {
        ets_hd_admin_fn.reCaptchaConfigs($(this).val());
    });

    $(document).on('click', 'a.addColumn, a.ets_hd_edit', function (e) {
        e.preventDefault();
        var btn = $(this),
            href = btn.attr('href')
        ;
        if (!btn.hasClass('active') && href !== '') {
            btn.addClass('active');
            $.ajax({
                url: href,
                type: 'post',
                data: 'ajax=1',
                dataType: 'json',
                success: function (json) {
                    btn.removeClass('active');
                    if (json) {
                        if (json.errors) {
                            showErrorMessage(json.errors);
                        } else {
                            if (json.form) {
                                $('.ets_hd_form').html(json.form);
                                $('.ets_hd_overload').addClass('active');
                                ets_hd_admin_fn
                                    .showOptions()
                                    .sortOptions($('.ets_hd_options > tbody'));
                            }
                        }
                    }
                },
                error: function () {
                    btn.removeClass('active');
                }
            });
        }
    });

    $(document).on('click', 'button[name=submitAddets_hd_column]', function (e) {
        e.preventDefault();
        var btn = $(this);
        if (!btn.hasClass('active')) {
            btn.addClass('active');
            var form = btn.parents('form').eq(0),
                tmpInput = form.find('.ets_hd_option[data-ref="tmp"] input')
            ;
            if (form.attr('action') !== '') {

                // Build form data to Submit:
                tmpInput.prop('disabled', true);
                var formData = new FormData(form.get(0));
                formData.append('action', 'save');
                formData.append('ajax', 1);
                tmpInput.prop('disabled', false);

                // Remove all msg error:
                form.find('.op_error').remove();
                form.find('.msg_error').removeClass('msg_error');

                $.ajax({
                    url: form.attr('action'),
                    type: 'post',
                    data: formData,
                    contentType: false,
                    processData: false,
                    dataType: 'json',
                    success: function (json) {
                        btn.removeClass('active');
                        if (json) {
                            // Add options:
                            if (json.op_errors) {
                                for (const ik in json.op_errors) {
                                    for (const ik2 in json.op_errors[ik]) {
                                        $('input[name="option[' + ik + '][' + ik2 + ']"]')
                                            .after('<span class="op_error">' + json.op_errors[ik][ik2] + '</span>')
                                            .parents('.ets_hd_option')
                                            .addClass('msg_error')
                                        ;
                                    }
                                }
                            }
                            if (json.errors) {
                                showErrorMessage(json.errors);
                            } else {
                                if (json.msg) {
                                    showSuccessMessage(json.msg);
                                }
                                if (json.column) {
                                    $('.ets_hd_overload').removeClass('active');
                                    var column = $('.ets_hd_column[data-id=' + json.id + ']');
                                    if (column.length > 0) {
                                        column.replaceWith(json.column);
                                    } else {
                                        var body = $('.ets_hd_columns .table > tbody');
                                        if (body.find('.ets_hd_column.empty').length > 0) {
                                            body.find('.ets_hd_column.empty').remove();
                                        }
                                        body.append(json.column);
                                    }
                                }
                                if (json.cache_options) {
                                    for (const ik3 in json.cache_options) {
                                        var option = json.cache_options[ik3],
                                            optionRef = $('.ets_hd_option[data-ref=' + ik3.replace(/op_/, '') + ']')
                                        ;
                                        if (optionRef.length > 0) {
                                            if (parseInt(option.id) > 0) {
                                                optionRef
                                                    .attr('data-id', parseInt(option.id))
                                                    .find('input[name="option[' + ik3 + '][id_ets_hd_option]"]').val(parseInt(option.id));
                                            }
                                        }
                                    }
                                }
                                $('.ets_hd_option.deleted').remove();
                            }
                        }
                    },
                    error: function () {
                        btn.removeClass('active');
                    }
                });
            }
        }
    });

    $(document).on('click', 'a.ets_hd_delete', function (e) {
        e.preventDefault();
        var btn = $(this),
            href = btn.attr('href')
        ;
        if (confirm(btn.data('confirm')) && !btn.hasClass('active') && href !== '') {
            btn.addClass('active');
            $.ajax({
                url: href,
                type: 'post',
                data: 'ajax=1',
                dataType: 'json',
                success: function (json) {
                    btn.removeClass('active');
                    if (json) {
                        if (json.errors) {
                            showErrorMessage(json.errors);
                        } else {
                            if (json.msg)
                                showSuccessMessage(json.msg);
                            btn.parents('.ets_hd_column').eq(0).remove();
                        }
                    }
                },
                error: function () {
                    btn.removeClass('active');
                }
            });
        }
    });

    $(document).on('change', '#type', function () {
        ets_hd_admin_fn.showOptions($(this), true);
    });

    $(document).on('change', '#field_type', function () {
        ets_hd_admin_fn.showFieldTypes($(this));
    });

    $(document).on('click', '.ets_hd_add_option', function () {
        var btn = $(this);
        if (!btn.hasClass('active')) {
            btn.addClass('active');
            var copy_tmp = $('.ets_hd_option[data-ref=tmp]'),
                options = $('.ets_hd_options')
            ;
            if (copy_tmp.length > 0 && options.length > 0) {
                var randomSize = Math.random().toString(36).slice(-8),
                    optionItem = $('<div>').append(copy_tmp.clone().attr('data-ref', randomSize));
                ;
                copy_tmp.before(optionItem.html().replace(/@ID@/g, 'op_' + randomSize));
                ets_hd_admin_fn
                    .showOptions()
                    .sortOptions(options.find('tbody'));
            }

            btn.removeClass('active');
        }
    });

    $(document).on('click', '.ets_hd_delete_option', function () {
        var optionItem = $(this).parents('.ets_hd_option').eq(0),
            id = optionItem.data('id');
        if (parseInt(id) === 0) {
            optionItem.remove();
        } else {
            optionItem
                .addClass('deleted')
                .find('input[name="option[' + id + '][deleted]"]').val(1)
            ;
        }
    });

    $(document).on('click', '.ets_hd_cancel, span.ets_hd_close_form', function (e) {
        e.preventDefault();
        $('.ets_hd_overload.active').removeClass('active');
    });

    $(document).on('click', '.ets_hd_column_status, .ets_hd_required, .ets_hd_display_field, .ets_hd_display_field_admin', function () {
        var btn = $(this),
            columnItem = btn.parents('.ets_hd_column'),
            field = 'active'
        ;
        if (btn.hasClass('ets_hd_required')) {
            field = 'required';
        } else if (btn.hasClass('ets_hd_display_field')) {
            field = 'display_field';
        } else if (btn.hasClass('ets_hd_display_field_admin')) {
            field = 'display_field_admin';
        }
        if (!btn.hasClass('active') && columnItem.data('id') !== '') {
            $.ajax({
                data: 'ajax=1&action=status&field=' + field + '&id_ets_hd_column=' + columnItem.data('id'),
                type: 'post',
                dataType: 'json',
                success: function (json) {
                    btn.removeClass('active');
                    if (json) {
                        if (json.errors) {
                            showErrorMessage(json.errors);
                        }
                        if (json.msg) {
                            showSuccessMessage(json.msg);
                        }
                        if (json.ok) {
                            btn.toggleClass('enabled');
                        }
                    }
                },
                error: function () {
                    btn.removeClass('active');
                }
            });
        }
    });

    $(document).on('click', '.ets-hd-nav-tab', function () {
        ets_hd_admin_fn.navTabs($(this));
    });

    $(document).on('change', 'input[name=avatar], input[name=ETS_HD_EMPLOYEE_AVATAR_DEFAULT], input[name=ETS_HD_CUSTOMER_AVATAR_DEFAULT]', function () {
        var input_name = $(this).attr('name'),
            reader_wrap = $(this).parents('.form-group').find('.ets_hd_reader_image.' + input_name.toLowerCase())
        ;
        $('#' + input_name + '-name').val(this.files[0].name);
        if (reader_wrap.find('img').length <= 0) {
            reader_wrap.append('<img/>');
        }
        if (!reader_wrap.find('.ets_hd_delete_avatar').length) {
            reader_wrap.append('<span class="ets_hd_delete_avatar" data-ref="' + input_name + '" title="' + ETS_HD_DELETE_TITLE + '"><svg class="w_14 h_14" width="14" height="14" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M704 736v576q0 14-9 23t-23 9h-64q-14 0-23-9t-9-23v-576q0-14 9-23t23-9h64q14 0 23 9t9 23zm256 0v576q0 14-9 23t-23 9h-64q-14 0-23-9t-9-23v-576q0-14 9-23t23-9h64q14 0 23 9t9 23zm256 0v576q0 14-9 23t-23 9h-64q-14 0-23-9t-9-23v-576q0-14 9-23t23-9h64q14 0 23 9t9 23zm128 724v-948h-896v948q0 22 7 40.5t14.5 27 10.5 8.5h832q3 0 10.5-8.5t14.5-27 7-40.5zm-672-1076h448l-48-117q-7-9-17-11h-317q-10 2-17 11zm928 32v64q0 14-9 23t-23 9h-96v948q0 83-47 143.5t-113 60.5h-832q-66 0-113-58.5t-47-141.5v-952h-96q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h309l70-167q15-37 54-63t79-26h320q40 0 79 26t54 63l70 167h309q14 0 23 9t9 23z"/></svg></span>');
        }
        ets_hd_admin_fn.readURL(this, input_name.toLowerCase());
    });

    $(document).on('click', '.ets_hd_delete_avatar', function () {
        var binding_input = $(this).data('ref');
        if (binding_input !== '') {
            $('input[name=' + binding_input + '], input[name=' + binding_input + '-name]').val('');
            $('input[name=' + binding_input + '_DELETED]').val(1);
            $(this).parents('.ets_hd_reader_image.' + binding_input.toLowerCase()).html('');
        }
    });
    $(document).on('click', 'button[name=submitOptionsets_hd_staff]', function (e) {
        e.preventDefault();

        var btn = $(this),
            form = btn.parents('form')
        ;
        if (!btn.hasClass('active')) {
            btn.addClass('active');
            var formData = new FormData(form.get(0));
            formData.append('ajax', 1);
            formData.append('action', 'postConfig');
            $.ajax({
                url: btn.attr('href'),
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function (json) {
                    btn.removeClass('active');
                    if (json) {
                        if (json.errors) {
                            showErrorMessage(json.errors);
                        }
                        if (json.msg) {
                            showSuccessMessage(json.msg);
                        }
                    }
                },
                error: function () {
                    btn.removeClass('active');
                }
            });
        }

        return false;
    });

    $(document).on('click', '.ets_hd_customer_staff_item .remove-ctm', function () {
        if (ets_hd_fn) {
            var customer_ids = $('#id_customer'),
                customers = customer_ids.val().split(','),
                customer_staff_item = $(this).parents('.ets_hd_customer_staff_item'),
                id_customer = customer_staff_item.data('id') + '',
                search_customer = $('input[name=search_customer]')
            ;
            customer_ids.val(ets_hd_fn.removeIds(customers, id_customer));
            ets_hd_fn
                .closeSearch(search_customer, true)
                .searchCustomer(search_customer)
            ;
            customer_staff_item.remove();
        }
    });

    $(document).on('change', 'input[id^=ETS_HD_TICKET_TITLE]', function () {
        ets_hd_admin_fn.copy2friendlyURL($(this).val(), $('#ETS_HD_TICKET_URL_ALIAS_' + id_language), $('#ETS_HD_TICKET_URL_ALIAS_LINK_' + id_language));
    });

    $(document).on('change', 'input[id^=ETS_HD_TICKET_URL_ALIAS]', function () {
        ets_hd_admin_fn.replaceLink($(this).val(), $('#ETS_HD_TICKET_URL_ALIAS_LINK_' + id_language));
    });

    $(document).on('change', 'input[id^=ETS_HD_STAFF_TITLE]', function () {
        ets_hd_admin_fn.copy2friendlyURL($(this).val(), $('#ETS_HD_STAFF_URL_ALIAS_' + id_language), $('#ETS_HD_STAFF_URL_ALIAS_LINK_' + id_language));
    });

    $(document).on('change', 'input[id^=ETS_HD_STAFF_URL_ALIAS]', function () {
        ets_hd_admin_fn.replaceLink($(this).val(), $('#ETS_HD_STAFF_URL_ALIAS_LINK_' + id_language));
    });
    $(document).ready(function(){
        var block_left_height =  $('.ets_hd_menus').height();
        $('.menu_height').css('height',block_left_height);
        $(window).resize(function(e){
            var block_left_height =  $('.ets_hd_menus').height();
            $('.menu_height').css('height',block_left_height);
        });
    });
    $(document).on('click', 'button[name=ets_hd_clear_file_upload]', function (e) {
        e.preventDefault();

        var ele = $(this);
        if (!ele.hasClass('active')) {
            ele.addClass('active');
            $.ajax({
                type: 'post',
                data: {
                    ajax: 1,
                    ETS_HD_CLEAR_FILE_UPLOAD: $('#ETS_HD_CLEAR_FILE_UPLOAD').val(),
                    action: 'clearFiles',
                },
                dataType: 'json',
                success: function (json) {
                    ele.removeClass('active');
                    if (json) {
                        if (json.errors) {
                            showErrorMessage(json.errors);
                        } else {
                            if (json.msg) {
                                showSuccessMessage(json.msg);
                            }
                            if (json.options) {
                                $.each(json.options, function (key, option) {
                                    $('#ETS_HD_CLEAR_FILE_UPLOAD option[value=' + key + ']').text(option.name);
                                });
                            }
                        }
                    }
                },
                error: function () {
                    ele.removeClass('active');
                }
            });
        }
    });
});
