
<script>
    $(".btn-loadicon").click(function(){
    $(this).addClass('disabled');
    $(this).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>');
    setTimeout(() => {
        $(this).removeClass('disabled');
    }, 3000);
});
$(".btn-addprocedure").click(function(){
$(this).addClass('disabled');
$(this).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> &ensp; Loading...');
});
$(".btn-load").click(function(){
$(this).addClass('disabled');
$(this).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> &ensp; Loading...');
setTimeout(() => {
    $(this).removeClass('disabled');
}, 3000);
});
</script>
<script>
    $(document).on('select2:open', function(e) {
        window.setTimeout(function() {
            document.querySelector('input.select2-search__field').focus();
        }, 0);
    });
</script>
<script>
    $("#btn-capture2").on('click', function() {
        socket.emit('chat message', "source2_capture");
        socket.emit('chat message',
            '{"case":"true","cid":"{{ $cid }}","hn":"{{ $hn }}","procedure":"{{ @$json->procedurename . '' }}","operationdate":"{{ @$appointment . '' }}", "caseuniq":"{{ @$caseuniq . '' }}"}'
        );
    });

    $(document).ready(function() {
        $('#SwitchCheck2').change(function() {
            if ($(this).is(':checked')) {
                $(".source1_toggle").hide()
                $(".source2_toggle").show()
                $("#reload_btn2").show()

            } else {
                $(".source1_toggle").show()
                $(".source2_toggle").hide()
                $("#reload_btn2").hide()

            }
        });
    });


    $(document).ready(function() {


        $('.source1').select2({
            placeholder: "Select Camera",
            // allowClear: true,
            dropdownParent: $('#modal_select_camera')

        });

        $('.source1').on('select2:open', function(e) {
            $('.select2-dropdown').hide();
            setTimeout(function() {
                jQuery('.select2-dropdown').slideDown(300);
            });


        });


        // -------------------------------------------





        $('#doctorname').select2({
            placeholder: "Select Camera",
            allowClear: true,

        });

        $('#doctorname').on('select2:open', function(e) {
            $('.select2-dropdown').hide();
            setTimeout(function() {
                jQuery('.select2-dropdown').slideDown(300);
            });
        });
    });
</script>


<script>
    $('.source1').on('change', function() {
        console.log(this.value);
    });

    $("#change_camera").click(function() {
        $("#modal_select_camera").modal("show");
    })



    // let markerVH = Number({{ $camera->marker_height ?? 8 }});

    document.onkeydown = function(e) {
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.className.includes(
                'select2-search__field')) {
            return;
        }
        return false;
    }

    window.addEventListener('keydown', function(e) {
        console.log(e.target.tagName, 'a');

        // user can input only on input or textarea
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
            return;
        }

        if (e.key == "F2") {
            $("#btn_time_start").trigger("click")
        }
        if (e.key == "F3") {
            $("#btn_time_3").trigger("click")
        }
        if (e.key == "F4") {
            $("#btn_time_4").trigger("click")
        }
        if (e.key == "+") {
            markerVH = markerVH + 0.1;
            $(".point-top1").css("height", markerVH + "vh");
            $(".point-bottom1").css("height", markerVH + "vh");
            $(".point-top11").css("height", markerVH + "vh");
            $(".point-top21").css("height", markerVH + "vh");
            $(".point-bottom11").css("height", markerVH + "vh");
            $(".point-bottom2").css("height", markerVH + "vh");

            set_marker_height(markerVH.toFixed(2));
        }
        if (e.key == "-") {
            markerVH = markerVH - 0.1;
            $(".point-top1").css("height", markerVH + "vh");
            $(".point-bottom1").css("height", markerVH + "vh");
            $(".point-top11").css("height", markerVH + "vh");
            $(".point-top21").css("height", markerVH + "vh");
            $(".point-bottom11").css("height", markerVH + "vh");
            $(".point-bottom2").css("height", markerVH + "vh");
            set_marker_height(markerVH.toFixed(2));
        }
    }, false);


    // const set_marker_height = (height) => {
    //     $.post("{{ url('api/camera') }}", {
    //         event: "set_marker_height",
    //         height: height,
    //     }, function(data, status) {})
    // }

    $("#change_icon").click(function() {
        $(this).find($(".ri-arrow-down-s-line")).toggleClass("ri-arrow-up-s-line");
    })

    $(".physician-select").select2({
        placeholder: "Select Physician",
        allowClear: true
    });

    $(".select_camera_nurse").select2({
        placeholder: "Select Nurse",
        allowClear: true,
        dropdownParent: $('#attendant_offcanvas')

    });

    $('.select_camera_nurse').on('select2:open', function(e) {
        $('.select2-dropdown').hide();
        setTimeout(function() {
            jQuery('.select2-dropdown').slideDown(300);
        });
    });
</script>



<script src="{{ domainnameport(':3000/socket.io/socket.io.js') }}"></script>

{{-- รอใส่ superadmin --}}
@if (@$feature->liveconsult)
    <script src='http://medicaendo.com:3000/socket.io/socket.io.js'></script>
    <script>
        var socketserver = io.connect('http://medicaendo.com:3000');
    </script>
@endif


<script>
    $(".hide-camera-detail").click(function() {
        let img_height = $("#box_showcapture").attr('hide')
        if (img_height == 'true') {
            $("i", this).toggleClass("ri-arrow-up-s-line");
            $("#box_showcapture").css('height', '79vh')
            $("#box_showcapture").attr('hide', 'false')

        } else {
            // $(".ri", this).toggleClass("");
            $("#box_showcapture").css('height', '37vh')
            $("#box_showcapture").attr('hide', 'true')

        }

        $(".toggle-detail").slideToggle();
    })
</script>

<script src="{{ domainnameport(':3000/socket.io/socket.io.js') }}"></script>

<script>
    // ปิดปุ่ม back บน browser ใหม่ล่าสุด
    window.history.pushState(null, null, window.location.href);
    window.onpopstate = function() {
        window.history.go(1);
    };
</script>


<script>
    // ปิดปุ่ม back บน browser
    // window.onload = function() {
    // if (typeof history.pushState === "function") {
    //     history.pushState(null, null, location.href);
    //     window.onpopstate = function () {
    //     history.pushState(null, null, location.href);
    //     };
    // } else {
    //     window.location.hash = "no-back";
    //     window.location.hash = "";
    // }
    // };



    function validateHhMm(inputField) {
        var isValid = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/.test(inputField.value);

        if (isValid) {
            // alert(1);
            // inputField.style.backgroundColor = '#bfa';
        } else {
            alert('กรุณากรอกข้อมูลเวลาให้ครบถ้วน')
            inputField.style.backgroundColor = '#fba';
        }

        return isValid;
    }
</script>
<script>
    var cleave = new Cleave('.time_camera_format1', {
        time: true,
        timePattern: ['h', 'm', 's']
    });
    var cleave = new Cleave('.time_camera_format2', {
        time: true,
        timePattern: ['h', 'm', 's']
    });
    if ($('.time_camera_format3').length > 0) {
        var cleave = new Cleave('.time_camera_format3', {
            time: true,
            timePattern: ['h', 'm', 's']
        });
    }
    if ($('.time_camera_format4').length > 0) {
        var cleave = new Cleave('.time_camera_format4', {
            time: true,
            timePattern: ['h', 'm', 's']
        });
    }



    document.addEventListener("wheel", function(event) {
        if (document.activeElement.type === "number" &&
            document.activeElement.classList.contains("noscroll")) {
            document.activeElement.blur();
        }
    });
</script>

<script>
    function validate_timestr(time) {
        let new_time = time.trim().replace(/:/g, '');
        if (new_time.length <= 2) {
            new_time += '00';
        } else if (new_time.length === 3) {
            new_time = new_time.substring(0, 2) + '0' + new_time.substring(2);
        } else if (new_time.length > 4) {
            new_time = new_time.substring(0, 4);
        }
        let hours = new_time.substring(0, 2);
        let minutes = new_time.substring(2, 4);
        return `${hours}:${minutes}:00`;
    }

    function edit_time(text, id) {
        let time_value = text.trim()
        // filter empty str out
        let parts = time_value.split(':').filter(part => part !== '')
        parts = parts.map((part, index) => {
            // for hours and sec, pad 0 at the start
            if (index === 0 || index === 2) {
                return part.padStart(2, '0')
            }
            // for min, if single digit, assume tens
            if (index == 1 && part.length == 1) {
                return part + '0'
            }
            return part
        })

        // if only hour, add '00' for both min and sec
        if (parts.length == 1) {
            parts.push('00', '00')
        }

        // if only hour and min, add '00' for sec
        if (parts.length == 2) {
            parts.push('00')
        }

        new_value = parts.slice(0, 3).join(':')
        if (parts[0]) {
            if (parts[0].length >= 3) {
                // in case, cleave.js format wrong (e.g., '111'=>'111:00:00' in withdrawal time)
                new_value = validate_timestr(new_value)
            }
        }

        $(`#${id}`).val(new_value)

        $.post('{{ url('api/procedure') }}', {
            event: 'savejson',
            name: id,
            value: new_value,
            table: 'tb_case',
            field: 'case_json',
            id: '{{ $cid }}',
            comcreate: '{{ @$case->comcreate }}',
            procedure: '{{ @$case->procedurecode }}',
        }, function(data, status) {});
    }
</script>




<script>
    var audio_casetest = new Audio("{{ domainname('config/sound/capture/alert.mp3') }}");
    var audio_incorrect = new Audio("{{ domainname('config/sound/capture/incorrect.mp3') }}");
    @if ($type == 'test')
        setTimeout(function() {
            audio_casetest.play();
            setInterval(function() {
                audio_casetest.play();
            }, 13000);
            $('#modal_casetest').modal('show');
        }, 60000);
    @endif
</script>


<script>
    $('input[type=text]').each(function() {
        if ($(this).val() != '' && $(this).val() != null) {
            // $(this).css('color', '#ffffff', );
            $(this).css('border', '1px solid #bbbbbb80');

        }
    });

    $('input[type=number]').each(function() {
        if ($(this).val() != '' && $(this).val() != null) {
            $(this).css('color', '#CFD4D9', );
            $(this).css('border', '1px solid #bbbbbb80');
        }
    })
    $('.form-control').focusout(function() {
        var text_val = $(this).val();
        if (text_val != null && text_val != '') {
            $(this).css('color', '#CFD4D9', );
            $(this).css('border', '1px solid #bbbbbb80');
        } else {
            $(this).css('background', 'none');
        }
    });

    $("#cick-hide").click(function() {
        $('.box-data').hide()
        $('#full_screen1').css()
    });

    $("#cick-show").click(function() {
        $('#hide-screen').show()
        $('#fullscreen_card').hide()
        $('#bottom-bar').hide()
    });

    var start_time
    var elasped_time = 0
    var interval_id
    var size_interval_id
    var curr_timer_id
    var is_video1 = false
    var is_video2 = false

    // let size1temp = "";
    // let counttempsize = 0;

    function update_timer(source_num) {

        //ตรวจสอบว่า VDO ยังบันทึกอยู่หรือป่าว

        // let size1now = $(".size1")[0].html();
        // console.log("size1 : "+size1now);

        let size1now = $(".size1").html();
        console.log("size1 : " + size1now);

        if (size1now == size1temp) {
            counttempsize++;
            if (counttempsize == 5 && size1now != '0') {
                $("#pleasereload1").show();
                audio_incorrect.play();
                counttempsize = 0;
            }
        } else {
            setTimeout(() => {
                size1temp = size1now;
            }, 3000);
            counttempsize = 0;
        }
        //ตรวจสอบว่า VDO ยังบันทึกอยู่หรือป่าว

        curr_timer_id = (source_num != undefined) ? source_num : curr_timer_id
        const now = Date.now()
        const time_diff = now - start_time + elasped_time
        const hours = Math.floor(time_diff / 3600000)
        const minutes = Math.floor((time_diff % 3600000) / 60000)
        const seconds = Math.floor(((time_diff % 3600000) / 1000) % 60)
        $(`.timer${curr_timer_id}`).html(
            `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
        )
    }

    function start_timer(source_num) {
        start_time = Date.now()
        update_timer(source_num)
        interval_id = setInterval(update_timer, 1000)
    }

    function stop_timer(source_num) {
        clearInterval(interval_id)
        $(`#video_size${source_num}`).html(0)
        setTimeout(() => {
            $(`.timer${curr_timer_id}`).html('00:00:00')
            $(`.size${curr_timer_id}`).html('0')
        }, 2 * 1000);
    }

    $("#btn_liveconsult").click(function() {
        $("#modal_sms").modal("show");
    });

    $("#btn_livestream").click(function() {
        alert("Live Stream");
        $.post('{{ url('api/sendto') }}', {
            event: 'camera_sendto',
            cid: '{{ $cid }}',
        }, function(data, status) {
            socketserver.emit('chat message', '{{ $cid }}');
        });
    });

    $('#btn_confirm_sms').on('click', function() {
        // alert("Confirm");
        var phone = $("#phonenumbersms").val();
        $.post('{{ url('sms') }}', {
            event: 'liveconsult_sms',
            phone: phone,
            cid: "{{ $cid }}"
        }, function(data, status) {
            let json = JSON.parse(data);
            console.log(json);
            if (json.status == 'success') {
                $('#liveconsult_modal').modal('hide');
            }
        });
    });

    $('.editroom').bind('focusout', function() {
        var room_id = $(this).val();
        setTimeout(function() {
            $.post('{{ url('api/photomove') }}', {
                event: 'editroom',
                room_id: room_id,
                cid: '{{ $cid }}',
            }, function(data, status) {
                $("#room_text").html(data);
                // console.log(room_name);

            });
        }, 1000);
    });

    $('#submit_newprocedure').on('click', function() {
        if (check_null('time_end')) {
            $('#btn_time_4').click()
        }
        var this_pcd_value = $(".select-pcd").val()
        if (this_pcd_value != 0) {
            $.post('{{ url('api/jquery') }}', {
                event: 'camera_copy_pcd',
                case_procedurecode: this_pcd_value,
                case_id: "{{ $case->_id }}",
                this_url: "{{ url('') }}"
            }, function(data, status) {
                location.replace('{{ url('camera') }}/' + data);
                ck_pcd()
            });
        } else {
            alert("this zero");
        }
    });

    $('.text-time').on('input', function() {
        var this_index = $(this).attr('time')
        var this_time = $(this).val()
        var field = 'case_time'
        $.post('{{ url('api') }}/jquery', {
            event: 'update_time',
            time: this_time,
            cid: "{{ $case->_id }}",
            index: this_index
        }, function(data, status) {

        });
    })
</script>

<script>
    function scope_force_select(){
        @if(@$camera->force_select)
        let change_camera = $("#change_camera").val();
        if(change_camera==""){
            $("#modal_scope_alert").modal("show");
        }
        @endif
    }
</script>




<script>
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    var socket = io.connect("{{ domainnameport(':3000') }}");
    var old_vdosize = 0
    var new_vdosize = 0
    var time_alert = 0
    var vdo_file_interval = ''
    var all_serial = @json(@$scope_serial);
    let antieletic = 0;

    socket.emit('chat message', 'casemonitor');

    function antieletic_capture() {
        setTimeout(() => {
            if (antieletic == 1) {

                scope_force_select();

                socket.emit('chat message', 'source0_capture');
                var source_num = $('#camera_2').val()
                if (source_num == 1 || source_num == '1') {
                    $("#btn-capture").trigger("click");
                } else if (source_num == 2 || source_num == '2') {
                    $("#btn-capture").trigger("click");
                    $("#btn-capture2").trigger("click");
                }
            }
            antieletic = 0;
        }, 100);
    }

    function antieletic_vdo() {
        setTimeout(() => {
            if (antieletic == 1) {
                $("#record1").trigger('click');
            }
            antieletic = 0;
        }, 100);
    }



    var img_storage = localStorage.getItem('imgname')
    if (img_storage == null || img_storage == undefined) {
        let img_arr = []
        localStorage.setItem('imgname', JSON.stringify(img_arr))
    }
    setInterval(() => {
        check_and_reload_img()
    }, 1 * 2000);

    var operation_date = '{{ @$case->appointment }}'.split(' ')[0].replace(' ', '_')
    // !!! remove space bar from procedure name !!!
    socket.emit('chat message',
        `{"case":"true","cid":"{{ $cid }}","hn":"{{ $hn }}","procedure":"{{ @$case->procedurename . '' }}","operationdate":"${operation_date}","caseuniq":"{{ @$case->caseuniq . '' }}"}`
    );
    socket.emit('chat message', 'get_video_status');
    // camera record
    socket.emit('chat message', `to_page`)

    // ตรวจสอบ resolution หน้าจอ
    var ori_w_resolution = window.screen.width
    var init_num = get_img_num()
    $('#img_num').text(init_num)
    var url = "{{ $url }}"
    var server = url.replace('endoindex', '')

    // let timefix = '{{date("dHis")}}';
    // setTimeout(() => {
    //     socket.emit('chat message', `{"event":"check_open_other","time":"${timefix}"}`);
    // }, 1000);



    socket.on('chat message', function(msg) {
        console.log(msg, msg != '', msg != undefined);
        if (msg != '' && msg != undefined) {
            if (msg == 1) {
                antieletic++;
                antieletic_capture();
            }

            if (msg.includes('size')) {
                var vdo_size = msg.split('_')
                var size_format = (Math.round(parseFloat(vdo_size[1]) * 100) / 100).toFixed(2)
                console.log(size_format);
                $(`.${vdo_size[0]}`).html(`${size_format}`)
            }

            if (msg.includes('scope') && !msg.includes('procedure')) {
                var scope_split = msg.split('_')
                source_id = scope_split[0].replace('scope', 'source')
                var pic_name = "{{ @$olympus_disabled }}" != 'true' ? "{{ @$olympus_picname }}" :
                    "{{ @$fuji_picname }}"
                var img_url = `{{ @$ocr_img }}/{{ @$hn }}_crop_${pic_name}`
                ocr_image(img_url, source_id)
                var ocr = $(`#${source_id}`).val()
                // save camera name
                if (ocr != undefined && ocr != '') {
                    $.post("{{ url('api/jquery') }}", {
                        event: 'savejson_checkbox',
                        id: '{{ @$cid }}',
                        idhtml: 'case_scope',
                        value: ocr
                    }, function(data, status) {});
                }
            }

            if (msg.includes('signal_remove')) {
                $(`#status_video1`).html('No signal')
                if (is_video1) {
                    clearInterval(vdo_file_interval)
                    $('#link1').css('display', 'block')
                    $('#pleasereload1').css('display', 'block')
                }

                if (is_video2) {
                    clearInterval(vdo_file_interval)
                    $(`#record2`).removeClass('active')
                }
            }

            if (msg.includes('signal_detect')) {
                // ask python first if video preview is true or false -> false -> rescope
                if (msg.includes('txt')) {
                    var vdo_status = msg.replace('signal_detect_txt_', '')
                    var vdo_split = vdo_status.split('_')
                    var source = vdo_split[1] != '' && vdo_split[1] != undefined ? vdo_split[1] : 1
                    vdo_property = vdo_split[2] != '' && vdo_split[2] != undefined ? vdo_split[2].replaceAll(
                        '-', ' ') : ''
                    $(`#status_video${source}`).html(vdo_property)
                    $('#multi_signal_div').css('display', 'none')
                    $('#no_signal_div').css('display', 'none')
                    if (vdo_split[0] != 'off' && vdo_split[2] != 'No signal' && vdo_split[2] != '') {
                        $(`#status_video${source}`).html(vdo_property)
                        if (time_alert > 0) {
                            $('#no_signal_div').css('display', 'none')
                            $('#link1').css('display', 'none')
                        }
                    } else if (vdo_split[0] == 'off' && (vdo_split[2] == 'No signal' || vdo_split[2] == '')) {
                        $('#no_signal_div').css('display', 'block')
                        $(`#status_video1`).html('No signal')

                    }
                }
            }

            if (msg.includes('no_signal')) {
                clear_warning_alert()
                $('#no_signal_div').css('display', 'block')
            }

            if (msg.includes('video_error')) {
                let source_num = '';
                if (msg.includes('1')) {
                    source_num = 1
                } else if (msg.includes('2')) {
                    source_num = 2
                }
                $(`#link${source_num}`).css('display', 'block')
                $(`#link${source_num}`).data('source', source_num)
                clear_warning_alert()
                vdo_file_interval = ''
            }

            if (msg.includes('camera_ocr')) {
                let parse = JSON.parse(msg)
                if (parse['cid'] == "{{ @$cid }}") {
                    parse['code'] = parse['code'] || ''
                    let opt = `option[data-serialno="${parse['code']}"]`
                    if ($(opt).length <= 0 || parse['code'] == '') {
                        let match = check_scope_match(parse['code'])
                        $.post("{{ url('api/jquery') }}", {
                            event: "check_scope",
                            scope_serial: match
                        }, function(data, status) {
                            if (data == 'true') {
                                opt = `option[data-serialno="${match}"]`
                            }
                        })
                    }
                    $(opt).prop('selected', true)
                    let select = $(opt).closest('select');
                    select.prop('selected', true);
                    select.trigger('change');
                }
            }

            if (msg == 2) {
                antieletic++;
                antieletic_vdo();
            }

            try {
                let object = JSON.parse(msg);
                if(object.event == 'check_open_other'){
                    socket.emit('chat message', `{"event":"reponse_open_other","time":"${timefix}"}`);
                }

                if(object.event == 'reponse_open_other'){
                    if(object.time < timefix){
                        window.location.replace("{{ url("camera/$cid/edit") }}");
                    }else{
                        socket.emit('chat message', `{"case":"true","cid":"{{ $cid }}","hn":"{{ $hn }}","procedure":"{{ @$case->procedurename . '' }}","operationdate":"${operation_date}","caseuniq":"{{ @$case->caseuniq . '' }}"}`);
                        setTimeout(() => {
                            socket.emit('chat message', `{"case":"true","cid":"{{ $cid }}","hn":"{{ $hn }}","procedure":"{{ @$case->procedurename . '' }}","operationdate":"${operation_date}","caseuniq":"{{ @$case->caseuniq . '' }}"}`);
                        }, 5000);
                    }
                }
            } catch (error) {
                // console.log(error);
            }




        }
    })






    $('.video-link').on('click', function() {
        let source = $(this).data('source')
        $('#link1').css('display', 'none')
        $('#pleasereload1').css('display', 'none')
        $(`#record1`).removeClass('active')
        stop_timer(1)
        setTimeout(() => {
            socket.emit('chat message', 'to_page')
        }, 100);
        setTimeout(() => {
            socket.emit('chat message', 'camera_stop' + source)
        }, 300);
        setTimeout(() => {
            socket.emit('chat message', 'continue_scope' + source)
        }, 3 * 1000);
    })



    $(".source1").change(function() {
        var tempscopeselect_name = $(this).val();
        setTimeout(() => {
            if (tempscopeselect_name == $(".source1").val()) {
                $.post("{{ url('api/camera') }}", {
                    "event": "scopetracking",
                    "val": tempscopeselect_name,
                    "uid": "{{ @uid() }}"
                }, function(d, s) {
                    console.log("mmmmmm");
                })
            }
        }, 3000);
    });



    function send_casedata() {

    }

    function ocr_image(url, source_id) {
        Tesseract.recognize(url, 'eng').then(({
            data: {
                text
            }
        }) => {
            console.log(text);
            var choices = []
            $(`#${source_id} option`).each(function() {
                var ch = $(this).val()
                if (ch != '') {
                    choices.push(ch)
                }
            })

            if (choices.includes(text)) {
                $(`#${source_id}`).val(text.trim()).change()
            }
            // console.log(choices);
            // check in choice ก่อนว่ามีไหม ถ้าไม่มีจะไม่ทำการ change
        })
    }

    function change_doctor(doctor_id) {
        $.post("{{ url('api/camera') }}", {
            event: 'set_doctorname',
            key: 'doctorname',
            value: doctor_id,
            cid: '{{ $cid }}',
        }, function(data, status) {
            // alert(1);
            $("#text_doctorname").html(data);
        });
    }


    function change_scope(source) {
        let scope_id = $(".source1").val();
        if (scope_id != "" || scope_id != null) {
            socket.emit(`changecamera${parseInt(source)-1}`, scope_id);
            if (source == '1') {
                cameraselect = true;
            }

            $.post('{{ url('api/jquery') }}', {
                event: "update_scope",
                scope: scope_id,
                cid: "{{ @$cid }}",
                source: source
            }, function(data, status) {
                let scope = data.selected_scope;
                //    alert(scope);
                console.log(data);

                $("#change_camera").val(data)
            })
        }
    }
    // setTimeout(() => {

    //     $(".sourcescope").click(function() {
    //         let id = $(this).attr("id");
    //         alert(id);
    //     });
    // }, 4000);





    function imageSHOW(msg) {
        var img_exist = get_img_num()
        var path = msg
        var img_url = `${path}`
        var new_num = img_exist + 1

        @if (@$camera->firstimg_starttime)
            if (new_num == 1) {
                // alert(1)
                $('#btn_time_start').trigger('click')
            }
        @endif



        $(".box-capture").prepend(`
            <div class="box-capture-list" data-checknum="0" id="imgbox${new_num}">
                <img src="${img_url}" class="w-100">
                <span class="number-cap">${new_num}</span>
            </div>
        `);

        $('#img_num').text(new_num)
        append_img_localstorage(new_num, img_url)
        console.log("moss test");
    }

    function liveconsult(msg) {
        var path = msg
        var img_url = `${path}`
        var server = url.replace('endoindex', '');
        var img_path = img_url.replace(server, '');
        img_path = img_path.replace('ScreenRecord/', '');

        $.post('{{ url('api/sendto') }}', {
            event: 'camera_sendto',
            cid: '{{ $cid }}',
            imgname: img_path
        }, function(data, status) {
            socketserver.emit('chat message', `{'case_id':'{{ $cid }}', 'img_name':'${img_path}'}`);
            socket.emit('chat message', `{'case_id':'{{ $cid }}','img_name':'${img_path}'}`);
        });

    }

    function change_imgname(url) {
        let name_arr = url.split("/");
        let new_namearr = url.split("/").slice(-1)
        let datetime_arr = new_namearr[0].split('_')
        let datetime = datetime_arr[datetime_arr.length - 2]
        let new_datetime = parseInt(datetime) - 1
        datetime_arr[datetime_arr.length - 2] = new_datetime
        let new_name = datetime_arr.join('_')
        name_arr[name_arr.length - 1] = new_name
        let new_url = name_arr.join('/')
        return new_url
    }

    function get_img_num() {
        var img_num = $('.box-capture-list').length
        return img_num
    }

    function get_img_localstorage() {
        let img_storage = localStorage.getItem('imgname')
        let img_arr = JSON.parse(img_storage)
        img_arr = img_arr == null || img_arr == undefined ? [] : img_arr
        return img_arr
    }

    function append_img_localstorage(new_num, img_url) {
        let datatemp = {
            "index": new_num,
            "url": img_url,
        }
        let img_arr = get_img_localstorage()
        img_arr.push(datatemp)
        img_json = JSON.stringify(img_arr)
        localStorage.setItem('imgname', img_json)
    }

    function check_and_reload_img() {
        img_arr = get_img_localstorage()
        let index_to_remove = [];
        img_arr.forEach((data, i) => {
            let index = data.index
            let url = data.url
            let img_to_reload = $(`#imgbox${index}`).find('img').attr('src')
            $(`#imgbox${index}`).find('img').attr('src', url)
            index_to_remove.push(i)
        })

        // remove img in array
        index_to_remove.forEach((index) => {
            delete img_arr[index]
        })

        img_arr = img_arr.filter(value => value !== null);

        let img_json = JSON.stringify(img_arr)
        localStorage.setItem('imgname', img_json)
    }

    window.addEventListener('beforeunload', function() {
        localStorage.removeItem('imgname');
    });

    // ocr -> change one word to others -> use similarity between string -> Levenshtein Distance
    function levenshtein_distance(a, b) {
        let matrix = []
        for (let i = 0; i <= b.length; i++) {
            matrix[i] = [i];
        }
        for (let j = 0; j <= a.length; j++) {
            matrix[0][j] = j;
        }
        for (let i = 1; i <= b.length; i++) {
            for (let j = 1; j <= a.length; j++) {
                if (b.charAt(i - 1) == a.charAt(j - 1)) {
                    matrix[i][j] = matrix[i - 1][j - 1];
                } else {
                    matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
                        Math.min(matrix[i][j - 1] + 1, // insertion
                            matrix[i - 1][j] + 1)); // deletion
                }
            }
        }
        return matrix[b.length][a.length];
    }

    // iterate to find one with smallest distance to ocr
    function find_closest_match(ocr_text, to_matchs, max_distance = 5) {
        let closest_match = null
        let smallest_distance = Infinity
        to_matchs.forEach((match) => {
            let distance = levenshtein_distance(ocr_text, match)
            if ((distance < smallest_distance)) {
                smallest_distance = distance
                closest_match = match
            }
        })
        // return closest_match === null ? '' : closest_match;
        if (smallest_distance <= max_distance) {
            return closest_match;
        } else {
            return '';
        }
    }


    function check_scope_match(ocr_text) {
        let match = find_closest_match(ocr_text, all_serial)
        return match
    }


    function check_vdofile_size(vdofile) {
        $.post('{{ url('api/jquery') }}', {
            event: 'check_vdofile_size',
            name: vdofile,
            id: "{{ @$cid }}",
        }, function(data, status) {
            let filesize = data
            new_vdosize = parseInt(filesize)
            if (parseInt(new_vdosize) > parseInt(old_vdosize)) {
                old_vdosize = new_vdosize
                $("#pleasereload1").hide();
            } else {
                time_alert += 1
            }

            if (time_alert == 3) {
                socket.emit('chat message', 'video_error1')
            }
        })
    }


    $('.checkend_time').click(function() {
        $(this).prop("disabled", true);
        if (check_null('time_end')) {
            $('#btn_time_4').click()
        }
    })

    $('.make_report').click(function() {
        video_stop();
        $(this).prop("disabled", true);

        if (check_null('time_end')) {
            $('#btn_time_4').click()
        }

        make_report = true;
        var vdo_play = $('#vdo_play').val();
        setTimeout(() => {
            socket.emit('chat message', "case_finish");
            socket.emit('chat message', "to_page");
            socket.emit('chat message', "camera_stop1");
            $('#modal_progress_camera').modal('show');
            $('#make_report').prop("disabled", true);
            $("#finish_record").submit();
        }, 800);

    });

    var is_secondsource = localStorage.getItem("second_source")
    if (is_secondsource == 'open') {
        $('#camera_2').val('2').trigger('change')
        localStorage.setItem("second_source", 'close')
        $($('.vdo-source')[1]).addClass('active')
        $($('.vdo-shows')[1]).addClass('active')
        $('#full_screendiv2').css('display', 'block')
        $('#source2_div').css('display', 'block')
        $('#reload2_div').css('display', 'block')
    }

    function refresh_scope(source_num) {
        // alert(source_num);
        console.log('refresh');
        var ck_second = $($('.vdo-source')[1]).hasClass('active')
        $(`#status_video${source_num}`).html('Reloading...')
        if (ck_second) {
            localStorage.setItem("second_source", 'open')
        } else {
            localStorage.setItem("second_source", 'close')
        }
        setTimeout(() => {
            socket.emit('chat message', `camera_stop${source_num}`)
        }, 1000);
        setTimeout(() => {
            socket.emit('chat message', `refresh_scope${source_num}`)
        }, 3000);
        if (source_num == 1) {
            setTimeout(() => {
                window.location.reload()
            }, 5000);
        }
    }

    /// get signal status
    setTimeout(() => {
        socket.emit('chat message', `get_signal1`)
    }, 1000);


    function show_brightness_modal(source_num) {
        $(`#brighteness_modal_btn${source_num}`).click()
        $('#brightness_source').html(source_num)
        set_properties('brightness', source_num, $(`#current_brightness${source_num}`).html())
        set_properties('hue', source_num, $(`#current_hue${source_num}`).html())
        set_properties('contrast', source_num, $(`#current_contrast${source_num}`).html())
        set_properties('sharpness', source_num, $(`#current_sharpness${source_num}`).html())
        set_properties('saturation', source_num, $(`#current_saturation${source_num}`).html())
    }

    function set_properties(type, source_num, value, set_current = false) {
        $(`#${type}_range`).val(value)
        $(`#${type}_num${source_num}`).html(value)
        if (set_current) {
            // console.log('in switch', type);
            if (type.includes('brightness')) {
                set_brightness(value)
            } else if (type.includes('hue')) {
                set_hue(value)
            } else if (type.includes('contrast')) {
                set_contrast(value)
            } else if (type.includes('sharpness')) {
                set_sharpness(value)
            } else if (type.includes('saturation')) {
                set_saturation(value)
            }
        }
    }

    function set_brightness(num, change_range = false) {
        var source = $('#brightness_source').html()
        $(`#brightness_num`).html(num)
        socket.emit('chat message', `set_brightness${num}`)
        $(`#current_brightness${source}`).html(num)
        if (change_range) {
            $(`#brightness_range`).val(num)
        }
    }

    function set_contrast(num, change_range = false) {
        var source = $('#brightness_source').html()
        $(`#contrast_num`).html(num)
        socket.emit('chat message', `set_contrast${num}`)
        $(`#current_contrast${source}`).html(num)
        if (change_range) {
            $(`#contrast_range`).val(num)
        }
    }

    function set_hue(num, change_range = false) {
        var source = $('#brightness_source').html()
        $(`#hue_num`).html(num)
        socket.emit('chat message', `set_hue${num}`)
        $(`#current_hue${source}`).html(num)
        if (change_range) {
            $(`#hue_range`).val(num)
        }
    }

    function set_saturation(num, change_range = false) {
        var source = $('#brightness_source').html()
        $(`#saturation_num`).html(num)
        socket.emit('chat message', `set_saturation${num}`)
        $(`#current_saturation${source}`).html(num)
        if (change_range) {
            $(`#saturation_range`).val(num)
        }
    }

    function set_sharpness(num, change_range = false) {
        var source = $('#brightness_source').html()
        $(`#sharpness_num`).html(num)
        socket.emit('chat message', `set_sharpness${num}`)
        $(`#current_sharpness${source}`).html(num)
        if (change_range) {
            $(`#sharpness_range`).val(num)
        }
    }

    function save_video_properties(property, value) {
        var source = $('#brightness_source').html()
        $.post('{{ url('api') }}/jquery', {
            event: 'save_properties',
            source: source,
            property: property,
            value: value
        }, function(data, status) {})
    }

    function click_save_button(type) {
        var source = $('#brightness_source').html()
        setTimeout(() => {
            save_video_properties('brightness', $(`#current_brightness${source}`).html())
        }, 100);
        setTimeout(() => {
            save_video_properties('contrast', $(`#current_contrast${source}`).html())
        }, 400);
        setTimeout(() => {
            save_video_properties('hue', $(`#current_hue${source}`).html())
        }, 600);
        setTimeout(() => {
            save_video_properties('saturation', $(`#current_saturation${source}`).html())
        }, 800);
        setTimeout(() => {
            save_video_properties('sharpness', $(`#current_sharpness${source}`).html())
        }, 1000);
        if (type != 'reset') {
            setTimeout(() => {
                $('#close_property_btn').click()
            }, 1 * 1000);
        }
    }

    $('#reset_property_btn').on('click', function() {
        set_brightness(128, true)
        set_hue(128, true)
        set_contrast(128, true)
        set_saturation(128, true)
        set_sharpness(128, true)
        click_save_button('reset')
    })

    $('#save_property_btn').on('click', function() {
        click_save_button('save')
    })
</script>
<script>
    $('.anes-ck').on('change', function() {
        var ck_num = $('.anes-ck').length
        var checked = 0
        for (let x = 0; x < ck_num; x++) {
            var is_checked = $($('.anes-ck')[x]).is(':checked')
            console.log(is_checked);
            if (is_checked) {
                checked += 1
            }
        }

        save_ckval(this)

        if (checked > 0) {
            var anes_txt = $('#anesthesiaother').val()
            console.log(anes_txt);
            if (anes_txt.trim() == 'None Anesthesia') {
                $('#anesthesiaother').val('')
                $.post('{{ url('api/jquery') }}', {
                    event: "savejson_checkbox2",
                    id: "{{ @$cid }}",
                    idhtml: "anesthesiaother",
                    value: "",
                }, function(data, status) {
                    console.log(data);
                })
            }
        }
    })

    $('.inp_mi').on('input', function() {
        let medigroup_index = $(this).attr('index')
        let medigroup_val = $(this).val()
        let action = ''

        if (medigroup_val != '') {
            $(`#ck_${medigroup_index}`).prop('checked', true)
            action = 'add'
        } else {
            $(`#ck_${medigroup_index}`).prop('checked', false)
            action = 'remove'
        }

        let value = $(`#ck_${medigroup_index}`).val()

        $.post("{{ url('api/photo') }}", {
            event: "medication_update3",
            name: "select",
            value: value,
            type: action,
            cid: "{{ $cid }}"
        }, function(data, status) {});

        var ck_num = $('.inp_mi').length
        var have_val = 0
        for (let y = 0; y < ck_num; y++) {
            var have_text = $($('.inp-mi')[y]).val()
            if (have_text != '') {
                have_val += 1
            }
        }

        if (have_val > 0) {
            var medi_txt = $('#medi_other').val()
            if (medi_txt.trim() == 'None Medication') {
                $('#medi_other').val('')
                $('#medi_otherdose').val('')
                $('#medi_otherunit').val('')

                edit_medicationother()
            }
        }

    })

    function save_ckval(e) {
        var this_name = $(e).attr('name');
        var value = [];
        $('[name=' + this_name + ']:checked').each(function() {
            value.push($(this).val());
        });
        $.post('{{ url('api/jquery') }}', {
            event: 'savejson_checkbox2',
            idhtml: this_name,
            value: value,
            table: 'tb_case',
            idname: 'case_id',
            id: '{{ $cid }}',
            procedure: '{{ @$this_procedure['code'] }}',
        }, function(data, status) {});
    }
</script>

<script>
    function video_stop() {
        let stop = $(".timer1").html();
        if (stop != "00:00:00") {
            socket.emit('chat message', `vdo_stop`)
            clear_warning_alert()
            setTimeout(() => {
                let vdoname = $('#vdoname').val()
                if (vdoname != "" && vdoname != undefined) {
                    $.post("{{ url('api') }}/jquery", {
                        event: 'save_video_data',
                        cid: "{{ @$cid }}",
                        vdoname: vdoname
                    }, function(data, status) {
                        console.log(data);
                        $('#vdoname').val('')
                    })
                }
            }, 1 * 1000);
        }
    }



    function record(btn_id) {
        var source = btn_id
        source_num = source.replace('record', '')
        var first_source = source_num == 1 || source_num == "1" ? '' : source_num
        if ($(`#${btn_id}`).hasClass('active')) {
            // alert("เข้า")
            $(`#${btn_id}`).removeClass('active')

            stop_timer(source_num)
            if (btn_id == 'record1') {
                is_video1 = false
            } else {
                is_video2 = false
            }
            video_stop();
        } else {
            // alert("ไม่เข้าเงื่อนไข")
            $(`#${btn_id}`).addClass('active')
            clear_warning_alert()
            send_casedata()
            socket.emit('chat message', `vdo_start${first_source}`)
            start_timer(source_num)
            if (btn_id == 'record1') {
                is_video1 = true
            } else {
                is_video2 = true
            }
        }

        console.log(is_video1, 'is_video1');
    }

    function clear_warning_alert(clear_interval = true) {
        if (clear_interval) {
            clearInterval(vdo_file_interval)
        }
        time_alert = 0
        new_vdosize = 0
        old_vdosize = 0
    }

    $("#search_case").on("keyup", function() {
        var value = $(this).val().toLowerCase();
        $(".list-cases").filter(function() {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });

    $('#btn_back').on('click', function() {
        video_stop();
        let time_end = $("#time_end").val();
        if (time_end == "") {
            set_time('time_end');
        }


        $.post("{{ url('api/camera') }}", {
            event: "back2home",
            project : "{{ @$project }}",
            cid: "{{ $cid }}",
            hn: "{{ $hn }}",
        }, function(d, s) {});
        socket.emit('chat message', 'to_page')
        socket.emit('chat message', "camera_stop1");
        setTimeout(() => {
            redirect()
        }, 1 * 1000);
    })

    function redirect() {
        @if(@$project == "capture")
            window.location.href = "{{ url('capture/home') }}"
        @else
             window.location.href = "{{ url('') }}"
        @endif

    }

    $('#case_btn').on('click', function() {
        for (let i = 1; i <= 2; i++) {
            stop_timer(i)
            $('#record' + i).removeClass('active')
        }
        socket.emit('chat message', 'to_page')
        $('#new_case_btn').click()
    })


    $('.btn-capture').click(function() {
        scope_force_select()
        send_casedata()
        socket.emit('chat message', 'source0_capture')
    })

    $('.btn-capture2').click(function() {
        socket.emit('chat message', 'source2_capture')
    })

    function check_null(id) {
        var val = $(`#${id}`).val()
        var status = false
        if (val == '' || val == undefined) {
            status = true
        }
        return status
    }




    setTimeout(() => {
        if (check_null('time_start')) {
            $('#btn_time_start').click()
        }
    }, 1 * 1000);

    setTimeout(() => {
        if (check_null('time_patientin')) {
            $('#btn_time_patientin').click()
        }
    }, 1 * 1000);

    function set_time(key) {
        var data = $("#" + key).val()
        var today = new Date();
        var time = ('0' + today.getHours()).slice(-2) + ":" + ('0' + today.getMinutes()).slice(-2) + ":" + ('0' + today
            .getSeconds()).slice(-2);
        $("#" + key).val(time).keyup()
        update_case_time(key, time);
    }

    function update_case_time(key, value) {
        $.post('{{ url('api/procedure') }}', {
            event: "caseupdate",
            cid: cid,
            key: key,
            value: value
        }, function(d, s) {});
    }

    $('.change-user').change(function() {
        var data_id = $(this).val()
        // alert(data_type)
        if (data_id != 'none') {
            var data_type = $(this).attr('data-type')

            // console.log(data_type);
            // var data_place = $(this).attr('placeholder')
            var data_name = $('.change-user[data-type="' + data_type + '"] option[value="' + data_id + '"]')
                .text()
            var length_of_id = $(`#select_${data_type} > .row[data-id="${data_id}"]`).length
            // alert(length_of_id)
            if (length_of_id < 1) {

                var html = `
        <div class="row m-0 user_${data_type}_${data_id}">
            <div class="col-7">${data_name}</div>

            <div class="col-5 text-end">
                <i onclick='del_selectuser(".user_${data_type}_${data_id}","${data_type}", "${data_id}")' class="ri-close-fill text-danger ri-close-fill"></i>
                </div>

        </div>
    `

                var html_offcanvas = `
    <div class="row user_${data_type}_${data_id}" data-id="${data_id}">
        <div class="col-9">
            ${data_name}
        </div>

        <div class="col-3 text-end">
         <i onclick='del_selectuser(".user_${data_type}_${data_id}","${data_type}", "${data_id}")' class="ri-close-fill text-danger"></i>
        </div>
     </div>
    `
                    // $('#attendant_offcanvas').append(html_offcanvas);
                    $('.box-users-list').append(html)
                    $(`#select_${data_type}`).append(html_offcanvas)

                } else {
                    // alert('มีแล้ว')
                }
            }
            var length_of = $(`#select_${data_type} > .row`).length
            var arr = [];
            for (i = 0; i < length_of; i++) {
                arr[i] = parseInt($($(`#select_${data_type} > .row`)[i]).attr('data-id'))
            }
            update_tb_case("{{ @$cid }}", data_type, arr);
    })

    function del_selectuser(id, data_type, user_id) {
        $(id).remove()
        $('#user_' + user_id).remove()
        var length_of = $(`#select_${data_type} > .row`).length
        var arr = [];
        for (i = 0; i < length_of; i++) {
            arr[i] = parseInt($($(`#select_${data_type} > .row`)[i]).attr('data-id'))
        }
        delete_tb_case("{{ @$cid}}", data_type, user_id);
    }

    function update_tb_case(id, idhtml, value) {
        console.log(id, idhtml, value);
        $.post('{{ url('api/jquery') }}', {
            "event": "update_user_in_case",
            "id": id,
            "idhtml": 'user_in_case',
            "value": JSON.stringify(value),
        }, function(data, status) {
            console.log(data);
        });
    }

    function delete_tb_case(id, idhtml, value) {
        console.log(id, idhtml, value);
        $.post('{{ url('api/jquery') }}', {
            "event": "delete_user_in_case",
            "id": id,
            "idhtml": 'user_in_case',
            "value": value,
        }, function(data, status) {
            console.log(data);
        });
    }


    $(".call-medication, .medication-edit").on('change', function() {
        var id = $(this).attr('data-target')
        $("#attendant").attr('data-id', id).val(null)
        $("#attendant_unit").attr('data-id', id).val(null)
        $(`#attendant_text${id}`).text(null)
        $(`#attendant_unit_text${id}`).text(null)
        $('#medication_form' + id).removeClass('active');
    });

    $(".medication-edit").on('click', function() {
        console.log('open');
        var id = $(this).attr('data-target')
        var text = $(`#attendant_text${id}`).text()
        var unit = $(`#attendant_unit_text${id}`).text()
        $("#attendant").attr('data-id', id).val(parseInt(text))
        $("#attendant_unit").attr('data-id', id).val(unit)
    })

    $('.medicationsave').on('input', function() {
        var id = $(this).attr('id')
        var val = $(this).val()
        $.post('{{ url('api/jquery') }}', {
            event: 'save_medicationother',
            key: id,
            value: val,
            id: '{{ @$tb_casemedication->_id }}'
        }, function(data, status) {});
    })

    $("#attendant").keyup(function() {
        var data_id = $(this).attr('data-id')
        var values = $(this).val()
        $("#attendant_text" + data_id).text(values)
        check_span(`#attendant_text${data_id}`, `#attendant_unit_text${data_id}`, 'medication_form', data_id)
    })
    $("#attendant_unit").keyup(function() {
        var data_id = $(this).attr('data-id')
        var values = $(this).val()
        $("#attendant_unit_text" + data_id).text(values)
        check_span(`#attendant_text${data_id}`, `#attendant_unit_text${data_id}`, 'medication_form', data_id)
    })

    function open_modal(id, index) {
        console.log(id);
        $(`#medi_text`).val('')
        $(`#medi_text`).html(id)
        $(`#medi_index`).val(index)
    }

    function not_show_modal(index) {
        var is_checked = $(`#boxmedi${index}`).is(':checked')
        console.log(is_checked);
        if (is_checked) {
            $('#modal_btn' + index).click()
        } else {
            $('#mediinp' + index).val(0)
        }
    }

    function to_input(text_id, num_id, index_id) {
        var medi_text = $(`#${text_id}`).html()
        var medi_num = $(`#${num_id}`).val()
        var index = $(`#${index_id}`).val()
        $('#mediinp' + index).val(medi_num)
    }

    function check_span(txt1, txt2, text, id) {
        if ($(`${txt1}`).text() == '' && $(`${txt2}`).text() == '') {
            $('#medication_form' + id).removeClass('active');
        } else {
            if ($('#medication_form' + id).hasClass('active')) {} else {
                $('#medication_form' + id).addClass('active')
            }
        }
    }
</script>
<script>
    $("#btn_anesthesia").click(function() {
        $("input[name='anesthesia']").prop("checked", false);
        $("#anesthesiaother").val("None Anesthesia");
        $("#anesthesiaother").focus();
        $.post('{{ url('api/jquery') }}', {
            event: 'savejson_checkbox2',
            idhtml: 'anesthesia',
            value: [],
            table: 'tb_case',
            idname: 'case_id',
            id: '{{ $cid }}',
            procedure: '{{ $case->case_procedurecode }}',
        }, function(data, status) {});

        $.post('{{ url('api/jquery') }}', {
            event: 'savejson_checkbox2',
            idhtml: 'anesthesiaother',
            value: 'None Anesthesia',
            id: '{{ $cid }}',
        }, function(data, status) {})
    });


    $(".medi_other").change(function() {
        let id = $(this).attr("id");
        let val = $(this).val();
        $.post('{{ url('jquery') }}', {
            event: 'medi_other',
            name: id,
            value: val,
            cid: '{{ $cid }}'
        }, function(data, status) {});
    });

    $(".boxmedi").click(function() {
        var arr = [];
        $(".boxmedi:checked").each(function() {
            arr.push($(this).val());
        });
        $.post("{{ url('api/photo') }}", {
            event: "medication_update",
            name: "medication",
            value: arr,
            cid: "{{ $cid }}"
        }, function(data, status) {});
    });

    $(".medigroup").on('input', function() {
        var arr = [];
        var arr2 = [];
        var arr3 = [];
        $(".medigroup").each(function() {
            arr.push($(this).val());
        });
        $(".boxmedi").each(function() {
            arr2.push($(this).val());
        });
        $(".medi_unit").each(function() {
            arr3.push($(this).val());
        });
        console.log(arr);

        $.post("{{ url('api/photo') }}", {
            event: "medication_update2",
            name: "medication_unit",
            dose: arr,
            key: arr2,
            unit: arr3,
            cid: "{{ $cid }}"
        }, function(data, status) {});
    });

    $('.ck-medi').on('click', function() {
        let value = $(this).val()
        let action = $(this).is(':checked') ? 'add' : 'remove'
        let lg = $('.ck-medi').length

        let total = 0
        $('.ck-medi:checked').each(function() {
            total += 1
        })

        if (!$(this).is(':checked')) {
            for (let i = 0; i < lg; i++) {
                let inp_mi = $($('.inp_mi')[i]).attr('medigroup_id')
                if (value == inp_mi) {
                    $($('.inp_mi')[i]).val('')
                    $($('.inp_mi')[i]).trigger('change')
                }
            }

            var arr = [];
            var arr2 = [];
            var arr3 = [];
            $(".medigroup").each(function() {
                arr.push($(this).val());
            });
            $(".boxmedi").each(function() {
                arr2.push($(this).val());
            });
            $(".medi_unit").each(function() {
                arr3.push($(this).val());
            });

            $.post('{{ url('api/photo') }}', {
                event: "medication_update2",
                name: "medication_unit",
                dose: arr,
                key: arr2,
                unit: arr3,
                cid: "{{ $cid }}"
            }, function(data, status) {});
        }

        if (total > 0) {
            let medi_other = $('#medi_other').val()
            if (medi_other == 'None Medication') {
                $('#medi_other').val('')
                $('#medi_otherdose').val('')
                $('#medi_otherunit').val('')
            }
        }

        $.post("{{ url('api/photo') }}", {
            event: "medication_update3",
            name: "select",
            value: value,
            type: action,
            cid: "{{ $cid }}"
        }, function(data, status) {});
    })


    $("#btn_medication").click(function() {

        var arr = [];
        var arr2 = [];
        var arr3 = [];
        var arr4 = [];
        $(".medigroup").val("");
        $(".medigroup").each(function() {
            arr.push($(this).val());
        });
        $(".boxmedi").each(function() {
            arr2.push($(this).val());
        });
        $(".medi_unit").each(function() {
            arr3.push($(this).val());
        });

        $.post("{{ url('api/photo') }}", {
            event: "medication_update2",
            name: "medication_unit",
            dose: arr,
            key: arr2,
            unit: arr3,
            select: 'none',
            cid: "{{ $cid }}"
        }, function(data, status) {});
        $("#medi_other").val("None Medication");
        $("#medi_otherunit").val("");
        $("#medi_otherdose").val("");

        edit_medicationother()

        $(".ck-medi").each(function() {
            if ($(this).is(':checked')) {
                $(this).prop('checked', false)
            }
        })

        $("#medi_other").trigger("change");
        $("#medi_otherunit").trigger("change");
        $("#medi_otherdose").trigger("change");

    });

    function edit_medicationother() {
        var medi_arr = ['medi_other', 'medi_otherdose', 'medi_otherunit']
        medi_arr.forEach(e => {
            $.post('{{ url('api/jquery') }}', {
                event: 'save_medicationother',
                key: e,
                value: $(`#${e}`).val(),
                id: '{{ @$tb_casemedication->_id }}'
            }, function(data, status) {});
        });
    }

    function get_count_checked(class_name) {
        var value = []
        $(`.${class_name}:checked`).each(function() {
            value.push($(this).val());
        });
        return value
    }

    $('.savejson_checkbox').focusout(function() {
        var this_name = $(this).attr('name');
        var value = [];
        $('[name=' + this_name + ']:checked').each(function() {
            value.push($(this).val());
        });
        $.post('{{ url('api/jquery') }}', {
            event: 'savejson_checkbox2',
            idhtml: this_name,
            value: value,
            table: 'tb_case',
            idname: 'case_id',
            id: '{{ $cid }}',
            procedure: '{{ @$this_procedure['code'] }}',
        }, function(data, status) {});
    });

    $('.save-text').on('input', function() {
        var this_name = $(this).attr('name');
        var this_text = $(this).val();
        $.post('{{ url('api/jquery') }}', {
            event: 'savejson_checkbox2',
            idhtml: this_name,
            value: this_text,
            id: '{{ $cid }}',
        }, function(data, status) {})
    }).focusout()

    $('.call-medication').focusout(function() {
        var value = []
        $('.call-medication:checked').each(function() {
            value.push($(this).val());
        });
        $.post('{{ url('api/jquery') }}', {
            event: 'save_medication',
            idhtml: 'medi_casejson',
            value: value,
            id: '{{ @$tb_casemedication->_id }}',
        }, function(data, status) {})
    })

    $('#attendant').on('input', function() {
        var medi_text = $('#medi_text').html()
        var medi_num = $('#attendant').val()
        console.log(medi_text, medi_num);
        $.post('{{ url('api/jquery') }}', {
            event: 'save_medicationnum',
            idhtml: 'medi_casejson',
            text: medi_text,
            num: medi_num,
            id: '{{ @$tb_casemedication->_id }}',
        }, function(data, status) {})
        $(this).focusout()
    }).focusout()
</script>
<script>
    setInterval(() => {
        if ($('.modal').not('.brightness-modal').hasClass('show')) {
            $(".point-top1").hide();
            $(".point-bottom1").hide();
        } else {
            $(".point-top1").show();
            $(".point-bottom1").show();
        }
    }, 1000);
</script>
<script>
    $('.savejson').bind('focusout', function() {
        var this_id = $(this).attr('id');
        var this_name = $(this).attr('name');
        var this_type = $(this).attr('type');
        var this_table = $(this).attr('table');
        if (typeof this_table === 'undefined') {
            this_table = "tb_case";
        }
        if (this_type == "checkbox") {
            $.post('{{ url('api/photomove') }}', {
                event: 'savejson',
                name: this_name,
                value: $(this).prop('checked'),
                table: this_table,
                field: 'case_json',
                id: '{{ $cid }}',
                comcreate: '{{ $case->comcreate }}',
                procedure: '{{ $case->case_procedurecode }}',
            }, function(data, status) {});
        } else {
            $.post('{{ url('api/photomove') }}', {
                event: 'savejson',
                name: this_name,
                value: $('#' + this_id).val(),
                table: this_table,
                field: 'case_json',
                id: '{{ $cid }}',
                comcreate: '{{ $case->comcreate }}',
                procedure: '{{ $case->case_procedurecode }}',
            }, function(data, status) {});
        }
    });

    var init_room = $('.editroom').val();
    $.post('{{ url('api/photomove') }}', {
        event: 'editroom',
        room_id: init_room,
        cid: '{{ $cid }}',
    }, function(d, s) {});
</script>

{{-- <script>
    setTimeout(() => {
        $(".change-user").select2({
            templateResult: formatState,
            minimumResultsForSearch: 1,
            dropdownParent: $("#modal_attendant")
        })
    }, 10 * 1000);
</script> --}}


<script>
    socket.emit('chat message', 'source1alive?');
</script>


<script src="{{ url('assets/extra/shortcuts/shortcut.js') }}"></script>
<script>
    shortcut.add("F1", function() {
        alert("F1 pressed");
    });
</script>



{{-- WebSocket --}}

<script>
    $(window).focus(function() {
        console.log('welcome (back)');
    });

    $(window).blur(function() {
        console.log('bye bye');
    });
</script>

<script language="JavaScript" type="text/javascript">
    window.onbeforeunload = confirmExit;

    function confirmExit() {
        if (check_null('time_end')) {
            let img_num = $("#img_num").html();
            if (img_num > 0) {
                $('#btn_time_4').click()
            }
        }
    }
</script>
