<?php Fun::lang() ?>
<script>
    /* window.history.replaceState(window.location.pathname, document.title, window.location.pathname);*/
    let menu_name = null;
    let tbLeng = [20, 50, 100, 500, 1000, 2000]
    $(document).ready(function () {
        autoOff(); //autocomplete off
        $('.select2').select2();
        $('.app_body').show()
        // active button in report
        let p_name = window.location.href;
        $('table a').filter(function () {
            return this.href === p_name;
        }).removeClass('button_primary').addClass('button_success');


        $(document).on('click', '.save_to_excel', function () {
            $(".btn-save-excel").click();
        });


        //set Active menu
        let active = $('a[href="' + p_name + '"]:first');
        menu_name = active.text();
        $('.set_menu_name').html(active.html());

        active.closest('li.set_active').addClass('active');
        active.closest('li').addClass('active');

        $('li.set_active').each(function (i, v) {
            let menu = $(this).find('ul.dropdown-menu li a[href!="#"]').length
            if (menu === 0 && $(this).find('ul').html()) {
                $(this).hide()
            }
        })

        //========================


        $(document).on('click', '.btn_purchase_invoice_public', function () {
            getHtmlFormShow($(this).data('href'), '1000px');
        });
        $(document).on('click', '.btn_supplier_info_public,.btn_show_customer_info_public,.btn_show_transfer_stock_public', function () {
            getHtmlFormShow($(this).data('href'), '1200px');
        });
        $('table,.getImg').on('click', 'img', function (e) {
            let img = $(this).attr('src');
            jalert('Image', '<img src="' + img + '" width="100%">', '40%');
        });
        $(document).on('click', '.jconfirm a.page-link', function (e) {
            e.preventDefault();
            let this_ = $(this);
            let url = this_.attr('href');
            let barcode = $(document).find('.jconfirm input[name=barcode_hide]').val();
            let supplier_id = $(document).find('.jconfirm input[name=supplier_id_hide]').val();
            let customer_id = $(document).find('.jconfirm input[name=customer_id]').val();
            let type_hidden = $(document).find('.jconfirm input[name=type_hidden]').val();
            let warehouse_hide = $(document).find('.jconfirm input[name=warehouse_hide]').val();
            $.ajax({
                url: url,
                data: {
                    prcode: barcode,
                    supplier_id,
                    customer_id,
                    type_hidden,
                    warehouse_hide,
                },
                dataType: 'html',
                success(data) {
                    this_.closest('.jconfirm-content').html(data);
                }
            });
        });

        $(".search_customer").select2({
            tags: true,
            tokenSeparators: [','],
            minimumInputLength: 0,
            minimumResultsForSearch: 0,
            ajax: {
                url: '{{route('select2-search-customer')}}',
                dataType: "json",
                type: "GET",
                data: function (term) {
                    return {
                        term: term,
                    };
                },
                processResults: function (data) {
                    return {
                        results: data
                    };
                }
            }
        });

        $(document).on('click', '.show_reference_file', function () {
            let image = $(this).data('image');
            image = '<img src="' + image + '">';
            jalert('{{__('administrator.reference_file')}}', image, '40%');
        });
        set_date_picker();
        $('input[type=text],input[type=number]').prop('autocomplete', 'off');
        //disable right click
        $("html").on("contextmenu", function () {
            return false;
        });
        $('.focus').focus();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        jconfirm.defaults = {
            typeAnimated: true,
            draggable: true,
            dragWindowGap: 15,
            dragWindowBorder: true,
            animateFromElement: true,
            smoothContent: true,
            defaultButtons: {
                close: {
                    btnClass: 'button_waring',
                    action: function () {
                    }
                },
            },
            theme: 'modern',
            animation: 'scale',
            closeAnimation: 'scale',
            animationSpeed: 400,
            animationBounce: 1,
            closeIconClass: true,
        };
        $('.check-default-currency').on('click', function () {
            let $check = $(this).prop('checked');
            let $value = $(this).val();
            $.ajax({
                type: "GET",
                dataType: "json",
                url: '{{route("currency-checkbox")}}',
                data: {
                    check: $check ? 1 : 0,
                    value: $value,
                },
                success: function (data) {
                    if (data === 'success') {
                        let url = window.location.href;
                        window.location.replace(url)

                    }

                }
            });
        });
        $(document).on('click', '.getHtmlForm', function (e) {
            let t = $(this);
            if (t.data('href')) {
                let width = t.data('width');
                let form_name = t.data('name');
                let full_name = t.data('full_name');
                let btn_name = t.data('btn_name');
                form_name = form_name ? (form_name + ' ') : '';
                form_name = full_name ? full_name : (form_name + menu_name);
                width = width ? width : '600px';
                getHtmlForm(t.data('href'), form_name, width, btn_name);
            } else {
                jalert('No Href');
            }

        });
        $(document).on('click', '.getHtmlFormShow', function (e) {
            let t = $(this);
            let href = t.data('href');
            if (href) {
                let width = t.data('width');
                width = width ? width : '600px';
                getHtmlFormShow(href, width);
            } else {
                jalert('No Href');
            }

        });
        $('.jform').ajaxForm({
            beforeSend: function () {
                $(document).find('button').prop('disabled', true);
            },
            uploadProgress: function (event, position, total, percentComplete) {
                // console.log(percentComplete);
            },
            success: function (data1) {
                console.log('js-function')

                new jBox('Notice', {
                    content: '<span style="font-size: 20px">👍‍‍</span> បានជោគជ័យ',
                    color: 'green'
                });
                if (data1.input_name) {
                    $(document).find(`select[name="${data.input_name}"]`).append(`<option value="${data.value}">${data.text}</option>`).val(data.value).change();
                    $(document).find('.click_close_form').trigger('click');
                    return
                }

                if (data1.sale_id || data1.purchase_id) { // if in sale or purchase it will show invoice
                    $.ajax({
                        url: data1.sale_id,
                        dataType: 'html',
                        method: 'get',
                        success: function (data) {
                            $.confirm({
                                title: '',
                                theme: 'modern',
                                useBootstrap: false,
                                boxWidth: '900px',
                                closeAnimation: 'zoom',
                                content: data,
                                buttons: {
                                    hidden: {
                                        btnClass: 'button_warning click_close_form',
                                        text: '{{__('administrator.close')}}',
                                        keys: ['esc'],
                                        action: function () {
                                            location.reload();
                                        }
                                    },
                                    enter: {
                                        btnClass: 'button_info',
                                        text: '{{__('administrator.print')}}',
                                        keys: ['enter'],
                                        action: function () {
                                            let this_ = this.$content.find('.print_this_form');
                                            this_.printThis();

                                            return false;
                                        }
                                    },
                                },
                            });
                        },
                        error(xhr) {
                            alertErrorFormController(xhr);
                        }
                    });
                }
                else {
                    if (data1.status === "success" || data1.status === "ok") {
                        if (data1.route) {
                            window.location.replace(data1.route);
                        } else {
                            window.location.reload();
                        }
                    }
                    if (data1.checked_item) { // in production request
                        let text = '<div class="text-left">';
                        $.each(data1.alert, function (ii, vv) {
                            text += '<h5><span class="fa fa-arrow-right text-danger"></span> ' + vv + '</h5>';
                        });
                        text += '</div><br><br>';
                        $.confirm({
                            title: '{{__('administrator.warning')}}',
                            theme: 'modern',
                            useBootstrap: false,
                            boxWidth: '400px',
                            closeAnimation: 'zoom',
                            content: text,
                            buttons: {
                                hidden: {
                                    btnClass: 'button_warning',
                                    text: '{{__('administrator.close')}}',
                                    keys: ['esc'],
                                },
                                enter: {
                                    btnClass: 'button_primary',
                                    text: '{{__('administrator.submit')}}',
                                    keys: ['enter'],
                                    action: function () {
                                        $(document).find('button').prop('disabled', true);
                                        $('.jform').find('input[name=checked_item]').val(1);
                                        $('.jform').submit();
                                        return false;
                                    }
                                },

                            },
                        });
                    }
                }

                if (data1.status === 'success') {
                    let datep = $('.date_picker').val();
                    $('.paid_kh').val(0);
                    $('.paid_usd').val(0);
                    $('.paid_baht').val(0);
                    $('.total-discount').val(0);
                    $('.form-control').val('').change();
                    $('.get_discount').val('').change();
                    $('#append_product').html('');
                    $('.date_picker').val(datep);
                }

                setTimeout(function () {
                    $(document).find('button').prop('disabled', false);
                }, data1.sale_id ? 3000 : 8000);
            },
            error: function (xhr, textStatus, errorThrown) {
                alertErrorFormController(xhr);
                setTimeout(function () {
                    $(document).find('button').prop('disabled', false);
                }, 3000);
            },
        });
    });
    $(document).ready(function () {
        {{----------------------------insert breadcrumb li ------------------------}}
        let pathname = location.pathname;
        loc = pathname.split('/');

        let bread = $('ol.breadcrumb');
        let last_url = '{{$name}}';
        last_url = last_url.split('.');
        last_url = last_url[last_url.length - 1] ? last_url[last_url.length - 1] : '';
        let sum_text = '';
        $.each(loc, function (i, v) {
            let link = '#';
            if (v.length > 30) {
                v = '';
            }
            if (!isNaN(v)) {
                v = '';
            }
            if (i === 1) {
                link = '\\' + v;
            }
            if (v) {
                let str = v.toLowerCase().replace(/\b[a-z]/g, function (letter) {
                    return letter.toUpperCase();
                });
                str = str.replace(/\-/g, ' ');
                str = str.replace(/\_/g, ' ');
                bread.append('<li><a href="#">' + str + '</a></li>');

                sum_text += ' → ' + str;
            }
        });
        if (!menu_name) {
            menu_name = sum_text.replace(' → ', '');
        }
        if (last_url === 'show') {
            bread.append('<li><a href="">' + last_url + '</a></li>');
        }

        $('head title').text(menu_name + ' | {{$br->name}}');// set title
    });
    /*Number Only*/
    $(document).on('keypress', '.number-only', function (e) {
        if (isNaN(this.value + "" + String.fromCharCode(e.charCode))) return false;
    });
    /*Datatable*/
    $.fn.dataTable.ext.errMode = function (settings, helpPage, message) {
        $.confirm({
            title: false,
            content: '<p>' + message + '</p>',
            theme: 'modern',
            useBootstrap: false,
            boxWidth: '30%',
            buttons: {
                close: {
                    keys: ['esc'],
                    text: '{{__('administrator.close')}}',
                    btnClass: 'button_warning',
                    action: function () {

                    }
                },
                reload: {
                    keys: ['enter'],
                    text: '{{__('administrator.reload')}}',
                    btnClass: 'button_info',
                    action: function () {
                        window.location.reload();
                    }
                },
            }
        });
    };
    /*Timepicker*/
    $('.timepicker').timepicker({
        showInputs: false
    });
    /*month_year*/
    $('.month_year').datepicker({
        format: "mm-yyyy",
        viewMode: "months",
        minViewMode: "months",
        autoclose: true,
    });

    /*Date Picker*/
    function set_date_picker() {
        $(".date_picker").datepicker({
            format: 'dd-mm-yyyy',
            todayHighlight: true,
            autoclose: true,
        });
    }

    $('.lds-ring').hide();
    $(document).on({
        ajaxStart: function () {
            $('.lds-ring').show();
        },
        ajaxStop: function () {
            $('.lds-ring').hide();
            // $('*').tooltip();
        }
    });
    $(document).on('click', '.print_button', function () {
        let text = $(this).data('text');
        if ($('#print_table').html()) {
            $('#print_table').printThis({
                loadCSS: "{{asset('assets/css/post-print-styles.css')}}",
                beforePrint: function () {
                    $(document).find('.hide_when_print').hide();
                },
                afterPrint: function () {
                    $(document).find('.hide_when_print').show();
                    $('#print_table').find('a,button').closest('td').show();
                },
                header: `<table class="tb-header">
                                   <tr>
                                        <td><img src="{{headerlogo()}}" ></td>
                                   </tr>
                                   <tr >
                                        <td>&nbsp;</td>
                                   </tr>
                                   <tr class="m-top-30">
                                        <td class="report-stock m-top-30">
                                                <b>` + text + `</b>
                                         </td>
                                   </tr>
                                   <tr>
                                        <td>
                                            <p>{{getBranch()->name}}</p>
                                         </td>
                                   </tr>
                                   <tr>
                                       <td>
                                           <span >
                                               <i style="font-size: 14px">{{__('administrator.date')}}: {{date('d-M-Y')}}</i>
                                           </span>
                                       </td>
                                   </tr>
                               </table>`,
                footer: ``
            });
        }
        if ($('#print_table_report').html()) {
            $('#print_table_report').printThis({
                loadCSS: "{{asset('assets/css/post-print-styles.css')}}",
                beforePrint: function () {
                    $(document).find('.hide_when_print').hide();
                    // $('#print_table').find('a,button').closest('td').hide();
                },
                afterPrint: function () {
                    $(document).find('.hide_when_print').show();
                    $('#print_table').find('a,button').closest('td').show();
                },
                header: `<table class="tb-header" style="margin-bottom:50px">
                                   <tr>
                                        <td width="30%"><img src="{{LogoImage()}}" width="100%"></td>
                                        <td width="40%" class="report-stock m-top-30" style="padding-left:30px;text-align:center">
                                                <h3><b >{{getBranch()->name}}</b></h3>
                                                 <p class="m-top-30">` + text + `</p>
                                                 <span >
                                                       <i style="font-size: 14px">{{__('administrator.date')}}: {{date('d-M-Y')}}</i>
                                                  </span>
                                         </td>
                                         <td>
                                         </td>
                                   </tr>
                               </table>`,
                footer: `
                 <table class="text-center" width="100%" style="margin-top: 50px">
                    <tr>
                        <td>រៀបចំដោយ</td>
                        <td>ត្រួតពិនិត្យ</td>
                        <td>អនុម័តដោយ</td>
                    </tr>
                    <tr>
                        <td style="padding-top: 40px">----------------------</td>
                        <td style="padding-top: 40px">----------------------</td>
                        <td style="padding-top: 40px">----------------------</td>
                    </tr>
                    <tr>
                        <td>ប្រធានឃ្លាំង</td>
                        <td>ប្រធានគណនិយ</td>
                        <td>អគ្គរាយក</td>
                    </tr>
                </table>`
            });
        }

    });
    $(document).on('click', '.close_jquery_confirm', function () {
        $(document).find('.jconfirm-buttons .hidden').trigger('click');
    });
    $(document).on('click', '.print_jquery_confirm', function () {
        $(document).find('.jconfirm  .print_form').printThis({
            loadCSS: "{{asset('assets/css/production.css')}}",
            beforePrint: function () {
                $(document).find('button').hide();
            },
            afterPrint: function () {
                $(document).find('button').show();
            },
        });
    });

    function getHtmlForm(route, form_name = '', width = '20%', confirm = '') {
        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            width = '100%'
        }
        $.ajax({
            url: route,
            dataType: 'html',
            method: 'get',
            success: function (data) {
                $.confirm({
                    title: form_name,
                    theme: 'modern',
                    useBootstrap: false,
                    boxWidth: width,
                    closeAnimation: 'zoom',
                    content: data,
                    buttons: {
                        hidden: {
                            text: '{{__('administrator.close')}}',
                            btnClass: 'button_warning click_close_form',
                            keys: ['esc'],
                            action: function () {
                                // window.location.reload();
                            }
                        },
                        enter: {
                            text: '{{__('administrator.submit')}}',
                            btnClass: 'button_primary',
                            keys: ['enter'],
                            action: function () {
                                let this_ = this;
                                if (confirm) {
                                    $.confirm({
                                        title: '{{__('administrator.are_you_sure')}}',
                                        theme: 'modern',
                                        closeAnimation: 'zoom',
                                        buttons: {
                                            hidden: {
                                                btnClass: 'button_warning click_close_form',
                                                text: '{{__('administrator.close')}}',
                                                keys: ['esc'],
                                            },
                                            submit: {
                                                btnClass: 'button_danger',
                                                text: '{{__('administrator.confirm')}}',
                                                keys: ['enter'],
                                                action: function () {
                                                    this_.$content.find('button[type=submit]').trigger('click');
                                                    this_.$content.find('input[type=submit]').trigger('click');
                                                    this.buttons.submit.disable();
                                                    return false;
                                                }
                                            },
                                        },
                                    });

                                } else {
                                    this_.buttons.enter.disable();
                                    setTimeout(function () {
                                        this_.buttons.enter.enable();
                                    }, 3000);
                                    this_.$content.find('button[type=submit]').trigger('click');
                                    this_.$content.find('input[type=submit]').trigger('click');
                                }
                                return false;
                            }
                        },
                    },
                });
            },
            error(xhr) {
                alertErrorFormController(xhr);
            }
        });
    }

    function getHtmlFormShow(route = '', width = '20%', some_btn_route = '', form_name = '', form_width = '700px') {
        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            width = '100%'
        }
        $.ajax({
            url: route,
            dataType: 'html',
            method: 'get',
            success: function (data) {
                $.confirm({
                    title: '',
                    theme: 'modern',
                    useBootstrap: false,
                    boxWidth: width,
                    closeAnimation: 'zoom',
                    content: data,
                    buttons: {
                        hidden: {
                            btnClass: 'button_warning click_close_form',
                            text: '{{__('administrator.close')}}',
                            keys: ['esc'],
                            action: function () {
                            }
                        },
                        enter: {
                            btnClass: 'button_info',
                            text: '{{__('administrator.print')}}',
                            keys: ['enter'],
                            action: function () {
                                let this_ = this.$content.find('.print_this_form');
                                this_.printThis({
                                    //loadCSS: "{{asset('assets/css/pos-invoice.css')}}",
                                    header: `
                                    <style>
                                    @font-face {
                                        font-family: nso-font;
                                        src: url('{{asset('assets/font/KhmerOSbattambang.ttf')}}');
                                    }

                                    *, h1, h2, h3, h4, h5, h6 {
                                        font-family: nso-font, serif;
                                        line-height: 20px;
                                        line-height: 1.1;
                                    }
                                    </style>
                                    `,
                                    beforePrint: function () {
                                        $('.print_this_form').find('.hide_when_print').hide();
                                        $('.print_this_form').find('button').hide();
                                    },
                                    afterPrint: function () {
                                        $('.print_this_form').find('button').show();
                                        $('.print_this_form').find('.hide_when_print').show();
                                        // window.location.reload();
                                    },
                                });
                                return false;
                            }
                        },
                        some_btn_route: {
                            btnClass: 'button_primary',
                            text: '{{__('administrator.add')}}',
                            keys: ['enter'],
                            isHidden: !some_btn_route,
                            action: function () {
                                getHtmlForm(some_btn_route, form_name, form_width);
                                return false;
                            }
                        },
                    },
                });
            },
            error(xhr) {
                alertErrorFormController(xhr);
            }
        });
    }

    function showPurchaseOrderInvoice(url, id, status) {
        let width = '50%';
        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            width = '100%'
        }
        $.ajax({
            url: url,
            async: false,
            success: function (data) {
                let content_ = (data);
                $.confirm({
                    title: '',
                    content: content_,
                    boxWidth: width,
                    useBootstrap: false,
                    buttons: {
                        close: {
                            text: '{{__('administrator.close')}}',
                            btnClass: 'button_warning',
                            keys: ['esc'],
                            action: function () {

                            }
                        },
                        print: {
                            text: '{{__('administrator.print')}}',
                            btnClass: 'button_info',
                            keys: ['enter'],
                            action: function () {
                                $('.print_invoice_wholesale').printThis({
                                    loadCSS: "{{asset('assets/css/pos-invoice.css')}}",
                                    afterPrint: function () {
                                        window.location.reload();
                                    }
                                });
                                return false;
                            }
                        },
                        @if(Auth::user()->user_type == 1)
                        approve: {
                            text: '{{__('administrator.approve')}}',
                            btnClass: 'button_success ifstatus',
                            action: function () {
                                $.confirm({
                                    title: '{{__('administrator.please_complete_information_below')}}',
                                    boxWidth: '25%',
                                    theme: 'modern',
                                    useBootstrap: false,
                                    content: `
                                                <form class="jform" action="{!! url("update-status-purchase-order/1") !!}" method="get">
                                                <table width="100%" class="delivery-form">
                                                <tr><td colspan="2" ><h4 class="text-center" style="margin-bottom:15px">{{__('administrator.delivery_info')}}</h4></td></tr>
                                                    <tr>
                                                        <td width="25%">{{__('administrator.phone')}}<span class="text-danger">*</span></td>
                                                        <td><input type="text" class="form-control" name="phone" value="" required  maxlength="30" autocomplete="off"></td>
                                                        <td><input type="hidden" name="id" value="` + id + `" required></td>
                                                    </tr>
                                                    <tr>
                                                        <td>{{__('administrator.delivery_fee')}} ($)<span class="text-danger">*</span></td>
                                                        <td><input type="text" class="form-control number-only" name="delivery_fee" value="" required maxlength="4" autocomplete="off"></td>
                                                    </tr>
                                                    <tr>
                                                        <td><span class="required">{{__('administrator.note')}}</td>
                                                        <td><textarea name="note" id="" class="no-resize form-control" maxlength="200"></textarea></td>
                                                    </tr>
                                                </table>
                                                <button type="submit" class="submit_delivery display-none"></button>
                                                </form>
                                    `,
                                    buttons: {
                                        submit: {
                                            text: '{{__('administrator.approve')}}',
                                            btnClass: 'button_primary',
                                            action: function () {
                                                $('.submit_delivery').trigger('click');
                                                return false;
                                            }
                                        },
                                        close: {
                                            text: '{{__('administrator.close')}}',
                                            btnClass: 'button_warning',
                                            action: function () {

                                            }
                                        },
                                    }
                                });
                                if (data.status === 'fail') {
                                    if (data.count > 0) {
                                        $.alert({
                                            theme: 'modern',
                                            title: '{{__('administrator.warning')}}',
                                            content: data.message,
                                        });
                                    }
                                } else {
                                }
                                return false;
                            }
                        },
                        reject: {
                            text: '{{__('administrator.reject')}}',
                            btnClass: 'button_danger ifstatus',
                            action: function () {
                                $.confirm({
                                    title: '{{__('administrator.are_you_sure')}}',
                                    content: '',
                                    buttons: {
                                        submit: {
                                            text: '{{__('administrator.reject')}}',
                                            btnClass: 'button_danger',
                                            action: function () {
                                                $.ajax({
                                                    url: '{!! url("update-status-purchase-order/2?id='+id+'") !!}',
                                                    async: false,
                                                    success: function (data) {
                                                        window.location.reload();
                                                    }
                                                });
                                            }
                                        },
                                        close: {
                                            text: '{{__('administrator.close')}}',
                                            btnClass: 'button_warning click_close_form',
                                            action: function () {

                                            }
                                        },
                                    }
                                });
                                return false;
                            }
                        },
                        @endif
                    }
                });
            }
        });
        setTimeout(function () {
            if (status !== 0) {
                $(document).find('.ifstatus').remove();
            }
        }, 1);
    }

    function confirmForm(route, title = '{{__('administrator.are_you_sure')}}', content = '', btn_color = 'info') {
        let width = '500px'
        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            width = '100%'
        }
        $.confirm({
            title: title,
            theme: 'modern',
            useBootstrap: false,
            boxWidth: width,
            closeAnimation: 'zoom',
            content: content,
            buttons: {
                '{{__('administrator.close')}}': {
                    btnClass: 'button_warning',
                    keys: ['esc'],
                    action: function () {
                        // window.location.reload();
                    }
                },
                'confirm': {
                    btnClass: 'button_' + btn_color,
                    keys: ['enter'],
                    text: '{{__('administrator.confirm')}}',
                    action: function () {
                        if (route) {
                            $.ajax({
                                method: 'get',
                                url: route,
                                success: function (data) {
                                    if (data.status) {
                                        if (data.route) {
                                            console.log('route')
                                            window.location.replace(data.route);
                                        } else {
                                            console.log('route')
                                            window.location.reload();
                                        }
                                    }

                                },
                                error: function (xhr) {
                                    alertErrorFormController(xhr);
                                }
                            });
                        }
                    }
                },
            }
        });
    }

    function pad(str, max) {  //string prefix
        str = str.toString();
        return str.length < max ? pad("0" + str, max) : str;
    }

    function alertErrorFormController(xhr, this_ = '') {
        let error1 = xhr.responseJSON.errors;
        let error2 = xhr.responseJSON.message;

        let select2 = $(document).find('.select2-container,.select2-selection--single');
        $(document).find('input').removeClass('is-invalid');
        $(document).find('select').removeClass('is-invalid');
        $(document).find('.my-error-sibling').remove();
        select2.removeClass('is-invalid');
        select2.removeClass('form-control');
        if (error1) {
            $.each(error1, function (i, val) {
                let message = val[0].replace('The ', '')
                let fletter = message.substr(0, 1);
                let ii_arr = `${i}`;
                ii_arr = ii_arr.split(".");

                let name = '';
                if (ii_arr.length === 1) {
                    name = `${ii_arr[0]}`;
                    message = message.replace(i, ii_arr[0]);
                }
                if (ii_arr.length === 2) {
                    name = `${ii_arr[0]}[${ii_arr[1]}]`;
                    message = message.replace(i, `${ii_arr[0]}`);
                }

                let input = $(document).find(`.jform input[name="${name}"],.jform select[name="${name}"]`)
                message = message.replace(fletter, fletter.toUpperCase())
                input.addClass('is-invalid');


                if (input.length) {
                    let text = `<small class="text-danger my-error-sibling" style="font-size: 12px;width: 100%">${message}</small>`
                    let parent_tag = input.parent().prop("tagName") === 'TD' ? 'td' : 'div'
                    if (input.closest(parent_tag).find('.select2-container').length) {
                        $((parent_tag === 'td' ? '<br>' : '') + text).insertAfter(input.closest(parent_tag).find('.select2-container'))
                    } else {
                        $(text).insertAfter(input)
                    }
                }

                // input.closest('.form-floating').find('.invalid-feedback').text(message);


                input.closest('td').find('.select2-selection--single').addClass('form-control is-invalid');

                if (!input.length) {
                    new jBox('Notice', {
                        content: '<span style="font-size: 20px">👍‍ </span> ' + message,
                        color: 'red',
                        autoClose: 5000
                    });
                }
            });
        }
        setTimeout(function () {
            $('button').prop('disabled', false)
        }, 4000)
    }

    function khmer_number() {
        $('body :not(script)').contents().filter(function () {
            return this.nodeType === 3;
        }).replaceWith(function () {
            return this.nodeValue.replace(/1/g, '{{__('administrator.1')}}').replace(/2/g, '{{__('administrator.2')}}').replace(/3/g, '{{__('administrator.3')}}').replace(/4/g, '{{__('administrator.4')}}').replace(/5/g, '{{__('administrator.5')}}').replace(/6/g, '{{__('administrator.6')}}').replace(/7/g, '{{__('administrator.7')}}').replace(/8/g, '{{__('administrator.8')}}').replace(/9/g, '{{__('administrator.9')}}').replace(/0/g, '{{__('administrator.0')}}');
        });
    }

    function jalert(title, content, width = '20%') {
        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            width = '100%'
        }
        $.alert({
            title: title,
            content: content,
            useBootstrap: false,
            boxWidth: width,
            typeAnimated: true,
            draggable: true,
            dragWindowGap: 15,
            dragWindowBorder: true,
            animateFromElement: true,
            smoothContent: true,
            buttons: {
                close: {
                    text: '{{__('administrator.close')}}',
                    btnClass: 'button_warning click_close_form',
                    action: function () {

                    }
                },
            },
            theme: 'modern',
            animation: 'scale',
            closeAnimation: 'scale',
            animationSpeed: 400,
            animationBounce: 1,
            closeIconClass: true,
        });
    }

    function autoOff() {
        $('input').attr('autocomplete', 'off');
    }


    function search_account_chart() {
        $(".search_account_chart").select2({
            tags: true,
            tokenSeparators: [','],
            delay: 500,
            minimumInputLength: 0,
            minimumResultsForSearch: 0,
            ajax: {
                url: '{{route('select2-search-account-chart')}}',
                dataType: "json",
                type: "GET",
                data: function (term) {
                    return {
                        term: term,
                    };
                },
                processResults: function (data) {
                    return {
                        results: data
                    };
                }
            }
        });
    }

    function toFloat($something) {
        if (typeof $something === "undefined") $something = 0;

        $something = ($something + '').replaceAll(',', '')
        return $something ? parseFloat($something) : 0
    }
    function addComma(yourNumber) {
        //Seperates the components of the number
        var n = yourNumber.toString().split(".");
        //Comma-fies the first part
        n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        //Combines the two sections
        return n.join(".");
    }

</script>
