<!DOCTYPE html>
<html lang="en" data-layout-mode="dark">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <link rel="shortcut icon" href="{{ url('public/images/favicon.png') }}">
    <script src="{{ url('assets/js/layout.js') }}"></script>
    <script src="{{ url('public/js/jquery-3.6.0.min.js') }}"></script>
    <script src="{{ url('assets/js/select2.min.js') }}"></script>
    <link rel="stylesheet" href="{{ url('assets/libs/filepond-plugin-image-preview/filepond-plugin-image-preview.min.css') }}">
    <link rel="stylesheet" href="{{ url('assets/libs/@simonwep/pickr/themes/classic.min.css') }}" />
    <link rel="stylesheet" href="{{ url('assets/libs/@simonwep/pickr/themes/monolith.min.css') }}" />
    <link rel="stylesheet" href="{{ url('assets/libs/@simonwep/pickr/themes/nano.min.css') }}" />
    <link rel="stylesheet" href="{{ url('public/css/input/main.css') }}"/>
    <link rel="stylesheet" href="{{ url('assets/css/bootstrap.min.css') }}"/>
    <link rel="stylesheet" href="{{ url('assets/css/icons.min.css') }}"/>
    <link rel="stylesheet" href="{{ url('assets/css/app.min.css') }}"/>
    <link rel="stylesheet" href="{{ url('assets/css/custom.min.css') }}"/>
    <link rel="stylesheet" href="{{ url('assets/css/select2.min.css') }}"/>
    <script type="text/javascript">
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    </script>

    <script>
        let cid = "{{ $cid }}";
    </script>
    <title>Camera</title>
    <style>
        :root {
            --vz-input-bg {
                color: #00000;
            }

        }

        .form-select {
            --vz-input-bg: #2B2F34;
            color: #CFD4D9;
            border: 0;
        }

        .btn-dark-primary {
            background: #245788;
            color: #fff;

        }

        .bd-white {
            border: 1px solid #707070;
        }

        .btn-record {
            background: #ffffff;
            color: #000000 !important;

        }

        .btn-record:hover {
            background: rgb(225, 224, 224);
            color: #fff;

        }

        .text-bbbb {
            color: #bbbbbb;
        }


        [data-layout-mode=dark] {
            --vz-input-bg: #2B2F34;
            --vz-body-bg: #000;
        }

        body {
            /* height: 100vh; */
            font-size: 14px;
            overflow-x: hidden;
            font-family: 'kanit';
            touch-action: none;
        }

        .p-custom {
            padding: 10px;
        }

        @font-face {
            font-family: 'kanit';
            font-style: normal;
            font-weight: Light;
            src: url("{{ url('public/fonts/Kanit-Light.ttf') }}") format("truetype");
        }

        @font-face {
            font-family: 'kanit';
            font-style: normal;
            font-weight: bold;
            src: url("{{ url('public/fonts/Kanit-Bold.ttf') }}") format("truetype");
        }

        @font-face {
            font-family: 'kanit';
            font-style: italic;
            font-weight: normal;
            src: url("{{ url('public/fonts/Kanit-Italic.ttf') }}") format("truetype");
        }

        @font-face {
            font-family: 'kanit';
            font-style: italic;
            font-weight: bold;
            src: url("{{ url('public/fonts/Kanit-ExtraBoldItalic.ttf') }}") format("truetype");
        }

        .box-detail {
            background: #222529;
            border-radius: 4px;

        }

        ::-webkit-scrollbar {
            width: 4px;
        }

        ::-webkit-scrollbar-track {
            box-shadow: inset 0 0 5px white;
            background: rgb(24, 23, 23);
        }

        ::-webkit-scrollbar-thumb {
            background: rgb(206, 206, 206);
        }

        ::-webkit-scrollbar-thumb:hover {
            transition: 0.3s;
            background: rgb(99, 98, 98);
        }

        .box-capture-image {
            position: relative;
            margin-top: 1em;
        }

        .box-capture-image:first-child {
            margin-top: 0;
        }

        .box-capture-list {
            position: relative;
            margin-top: 1em;
        }

        .box-capture-list:first-child {
            margin-top: 0;
        }

        .number-cap {
            position: absolute;
            font-size: x-large;
            color: white;
            left: 48%;
            top: 47%;
            text-shadow: 0px 0px 5px black;
        }

        .box-capture {
            height: 37vh;
            overflow-y: auto;
        }

        .point-top1 {
            transform: rotate(0deg);
            position: absolute;
            /* กล้อง 1 ตัว  */
            top: 0rem;
            /* top: 14rem; */
            left: -0.5rem;
            z-index: 9;
            /* height: 8vh; */
            height: {{ $camera->marker_height ?? 8 }}vh;
        }

        .point-bottom1 {
            transform: rotate(0deg);
            position: absolute;
            /* กรณีมีกล้องตัวเดียว */
            top: 71vh;
            /* top: 64vh; */
            right: 0rem;
            z-index: 9;
            /* height: 8vh; */
            height: {{ $camera->marker_height ?? 8 }}vh;
        }

        .text-white-camera {
            color: #CFD4D9;
        }

        .scroll {
            height: 7.5em;
            overflow: auto;
        }

        .btn-dark-primary:hover {
            background: #173857;
            color: #fff;

        }

        .btn-white-camera {
            background: white;
            color: #000;

        }

        .btn-white-camera:hover {
            background: transparent;
            color: #ffff;
            border: 1px solid #bbbbbb;
        }

        .choices__list--dropdown {
            bottom: 100% !important;
            top: auto;
        }

        .h-button {
            height: 53px;
        }

        .cs {
            cursor: pointer;
        }

        .btn-record>i {
            color: red;
            /* background: #ffffffff */
        }
        .btn-record.active{
            background: red !important;
            border: 0 !important;
        }

        .btn-record.active>i {
            animation-name: loop_record;
            animation-duration: 0.5s;
            animation-iteration-count: infinite;

        }

        .col-7 {
            -webkit-box-flex: 0;
            -ms-flex: 0 0 auto;
            flex: 0 0 auto;
            width: 57.333333%;
            padding-right: 2em;
        }

        @keyframes slideInleft {
            0% {
                transform: translateX(-100%);
            }

            100% {
                transform: translateX(0);
            }
        }

        .bar-header {
            animation: 1s ease-in-out 0s 1 slideInleft
        }

        .border-r {
            border-radius: 4px 4px 0px 0px;
            ;
        }

        @keyframes loop_record {
            from {
                color: rgb(253, 10, 10);
            }

            to {
                color: rgb(250, 159, 159);
            }
        }

        .close-hover:hover {
            cursor: pointer;
            font-weight: bold;
        }

        .choices__list--dropdown {
            height: 6.7em;
        }

        .position-warning-signal {
            position: absolute;
            top: 0%;
        }

        .select2-results__option {
            padding: 6px;
            user-select: none;
            -webkit-user-select: none;
            background: #222529;
            color: #c4cdca;
            z-index: 99999;
            border-radius: 3px;

        }

        .offcanvas-backdrop.show {
            opacity: 0 !important;
        }

        /* .select2-container--default .select2-results>.select2-results__options {
    max-height: 59px !important;
    overflow-y: auto;
} */
        .p-custom-2 {
            padding: 14px;
        }

        .select2-container--default .select2-results__option--selected {
            background-color: #245788;
        }

        .select2-container--default .select2-results__option--highlighted.select2-results__option--selectable {
            background-color: #245788 !important;
            color: #c4cdca;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            color: #c4cdca;
            background: #2b2f34;
            padding: 6px;
            line-height: 28px;
        }

        .input-group>:not(:first-child):not(.dropdown-menu):not(.valid-tooltip):not(.valid-feedback):not(.invalid-tooltip):not(.invalid-feedback) {

            margin-left: 0 !important;
        }



        .select2-container--default .select2-selection--single {
            border: 0 !important;
        }

        .offcanvas {
            width: 25vw !important;
        }

        .offcanvas-body {
            overflow-x: hidden;
        }

        .select2-container--default .select2-selection--single {
            background: #2b2f34;
        }

        .select2-container .select2-selection--single .select2-selection__clear {
            display: none;
            /* font-size: 1.5em;
            color: #ffffff;
            margin-right: 1.5em; */
        }
    </style>
</head>
{{-- New --}}
@include('endocapture.camera.mockup.liveconsult_modal')
@include('endocapture.camera.mockup.livestream_modal')
@include('endocapture.camera.mockup.medi_modal')

{{-- Old --}}
@include('endocapture.camera.modal.modal_new_case')
@include('endocapture.camera.modal.modal_sms')
@include('endocapture.camera.04controller')
@include('endocapture.camera.modal.modal_progress_camera')
@include('endocapture.camera.modal.modal_casetest')
@include('endocapture.camera.modal.modal_brightness')
@include('endocapture.camera.modal.modal_livecase')
@include('EndoCAPTURE.camera.component.modal_camera')
@include('EndoCAPTURE.camera.component.offcanvas.attendant')
@include('EndoCAPTURE.camera.component.offcanvas.camerasetting')

<body>
    <div class="navbar-menu d-none">
    </div>
    <input id="removeNotificationModal" style="display:none">
    <div class="row p-2 m-0">
        <div class="col-xl-3 box-detail">
            <div class="row">
                <div class="col-12 p-0 m-0 ">
                    <div id="multi_signal_div" class="bar-header" style="display: none">
                        <div class="bar_test bg-danger text-center h3 p-2" style="color:rgb(245, 245, 245)"> กรุณากดปุ่ม
                            Reload Source 1</div>
                    </div>
                </div>
                <div class="col-12 p-0 m-0">
                    <div class="box-procedure py-2 px-3 d-flex justify-content-between border-r "
                        style="background-color: {{ @$this_procedure['color'] }}">
                        @php
                            $this_segment   = Request::segment(2);
                            $this_color     = isset($this_procedure['color']) ? $this_procedure['color'] : 'green';
                            $this_name      = isset($case->procedurename) ? $case->procedurename : 'TEST CAMERA';
                            $this_id        = isset($this_segment) ? Request::segment(2) : 'TEST CAMERA';
                        @endphp
                        <span class=" h3 text-white">{{ @$this_name }}</span>
                        <span class="align-self-center fs-14 fw-light text-white">HN : {{ @$patient['hn'] }}</span>
                    </div>
                </div>
                <div class="col-12 m-0">
                    <div class="col-12">
                        <div class="d-flex justify-content-between mt-3">
                            <span class="text-white">Name :</span>
                            <span
                                class="text-white-camera">{{ @$patient['firstname'] . ' ' }}{{ @$patient['middlename'] . ' ' }}{{ @$patient['lastname'] }}</span>
                        </div>
                        @php
                            $gender = '-';
                            if (isset($patient['gender'])) {
                                $gen = $patient['gender'];
                                if ($gen == '1') {
                                    $gender = 'Male';
                                } elseif ($gen == '2') {
                                    $gender = 'Female';
                                } else {
                                    $gender = $gen;
                                }
                            }
                        @endphp
                        <div class="d-flex justify-content-between mt-2">
                            <span class="text-white">Gender / Age :</span>
                            <span class="text-white-camera">{{ $gender }} /
                                {{ $patient['birthdate'] != 'TEST CAMERA' ? age_form_bd(@$patient['birthdate']) : $patient['birthdate'] }}</span>
                        </div>
                        <div class="toggle-detail mt-3">
                            <div class="row mb-3">
                                <div class="col-6 align-self-center">
                                    <span class="text-white">Physician :</span>
                                </div>
                                <div class="col-6 text-end">
                                    <span id="text_doctorname"> {{ $case->doctorname }}</span>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-6 align-self-center">
                                    <span class="text-white">Room :</span>
                                </div>
                                <div class="col-6 text-end">
                                    <span id="room_text">{{ @$this_room }}</span>
                                </div>
                            </div>
                            <div class="row mt-3">
                                <div class="col-12 d-flex justify-content-between mt-2">
                                    <span class="text-white">Attendant :</span>
                                    <a class="btn btn-primary" data-bs-toggle="offcanvas" href="#attendant_offcanvas"
                                        role="button" aria-controls="offcanvasExample">
                                        User Setting
                                    </a>
                                </div>
                                <div class="col-12 text-white-camera">
                                    <div class="scroll p-3  ">
                                        <div class="box-users-list">
                                            @if (isset($doctor_select))
                                                @foreach ($doctor_select as $data)
                                                    <div class=" mt-0 user_physician_{{ @$data['id'] }}"
                                                        id="user_{{ @$data['id'] }}">
                                                        <div class="row">
                                                            <div class="col-9">{{ fullname($data)}}</div>
                                                            @php
                                                                $class = 'user_assistant_' . $data['id'];
                                                                $uid = isset($data['id']) ? $data['id'] : '';
                                                            @endphp

                                                            <div class="col-3 text-end">
                                                                <i onclick='del_selectuser(".{{ $class }}","assistant", "{{ $uid }}")'
                                                                    class="ri-close-fill text-danger close-hover"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endforeach
                                            @endif

                                            @if (isset($nurse_select))
                                                @foreach ($nurse_select as $data)
                                                    <div class=" mt-0 user_nurse_{{ @$data['id'] }}"
                                                        id="user_{{ @$data['id'] }}">
                                                        <div class="row">
                                                            <div class="col-9">{{ fullname($data)}}</div>
                                                            @php
                                                                $class = 'user_assistant_' . $data['id'];
                                                                $uid = isset($data['id']) ? $data['id'] : '';
                                                            @endphp
                                                            <div class="col-3 text-end">
                                                                <i onclick='del_selectuser(".{{ $class }}","assistant", "{{ $uid }}")'
                                                                    class="ri-close-fill text-danger close-hover"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endforeach
                                            @endif

                                            @if (isset($nurse_a_select))
                                                @foreach ($nurse_a_select as $data)
                                                    <div class=" mt-0 user_assistant_{{ @$data['id'] }}"
                                                        id="user_{{ @$data['id'] }}">
                                                        <div class="row">
                                                            <div class="col-9">{{ fullname($data)}}</div>
                                                            @php
                                                                $class = 'user_assistant_' . $data['id'];
                                                                $uid = isset($data['id']) ? $data['id'] : '';
                                                            @endphp
                                                            <div class="col-3 text-end">
                                                                <i onclick='del_selectuser(".{{ $class }}","nurse_assistant", "{{ $uid }}")'
                                                                    class="ri-close-fill text-danger ri-close-fill"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endforeach
                                            @endif
                                            @if (isset($register_select))
                                                @foreach ($register_select as $data)
                                                    <div class=" mt-0 user_assistant_{{ @$data['id'] }}"
                                                        id="user_{{ @$data['id'] }}">
                                                        <div class="row">
                                                            <div class="col-9">{{ fullname($data)}}</div>
                                                            @php
                                                                $class = 'user_assistant_' . $data['id'];
                                                                $uid = isset($data['id']) ? $data['id'] : '';
                                                            @endphp
                                                            <div class="col-3 text-end">
                                                                <i onclick='del_selectuser(".{{ $class }}","register", "{{ $uid }}")'
                                                                    class="ri-close-fill text-danger ri-close-fill"></i>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endforeach
                                            @endif
                                            @if (isset($viewer_select))
                                            @foreach ($viewer_select as $data)
                                                <div class=" mt-0 user_assistant_{{ @$data['id'] }}"
                                                    id="user_{{ @$data['id'] }}">
                                                    <div class="row">
                                                        <div class="col-9">{{ fullname($data)}}</div>
                                                        @php
                                                            $class = 'user_assistant_' . $data['id'];
                                                            $uid = isset($data['id']) ? $data['id'] : '';
                                                        @endphp
                                                        <div class="col-3 text-end">
                                                            <i onclick='del_selectuser(".{{ $class }}","viewer", "{{ $uid }}")'
                                                                class="ri-close-fill text-danger ri-close-fill"></i>
                                                        </div>
                                                    </div>
                                                </div>
                                            @endforeach
                                        @endif

                                        @if (isset($sci_select))
                                        @foreach ($sci_select as $data)
                                            <div class=" mt-0 user_assistant_{{ @$data['id'] }}"
                                                id="user_{{ @$data['id'] }}">
                                                <div class="row">
                                                    <div class="col-9">{{ fullname($data)}}</div>
                                                    @php
                                                        $class = 'user_assistant_' . $data['id'];
                                                        $uid = isset($data['id']) ? $data['id'] : '';
                                                    @endphp
                                                    <div class="col-3 text-end">
                                                        <i onclick='del_selectuser(".{{ $class }}","viewer", "{{ $uid }}")'
                                                            class="ri-close-fill text-danger ri-close-fill"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    @endif
                                        </div>
                                    </div>
                                </div>
                                <div class="row my-2">
                                    <div class="col-2"></div>
                                    <div class="col-8 " style="border-bottom: 1px solid #707070"></div>
                                    <div class="col-2"></div>
                                </div>
                                <div class="col-12 mt-2 ">
                                    <div class="d-flex justify-content-between">
                                        <span class="text-white text-nowrap">Patient in time :</span>
                                        <div class="input-group width-time-custom ">
                                            <input type="text" onkeypress="return onlyNumbersWithColon(event);"
                                                name="time_patientin"
                                                class="form-control form-control-sm time_camera_format1 py-1 text-center text-time savejson"
                                                onfocusout="edit_time(this.value, this.id)" time="0"
                                                id="time_patientin" value="{{ @$case->time_patientin }}">
                                            <button class="btn btn-sm btn-light time-btn" id="btn_time_patientin"
                                                onclick="set_time('time_patientin')"><i
                                                    class="ri-timer-fill"></i></button>
                                        </div>
                                    </div>
                                    <div class="d-flex justify-content-between mt-2">
                                        <span class="text-white text-nowrap">Start time :</span>
                                        <div class="input-group width-time-custom ">
                                            <input type="text" onkeypress="return onlyNumbersWithColon(event);"
                                                name="time_start"
                                                class="form-control form-control-sm py-1 text-center text-time savejson time_camera_format2 "
                                                onfocusout="edit_time(this.value, this.id)" time="1"
                                                id="time_start" value="{{ @$case->time_start }}">
                                            <button class="btn btn-sm btn-light time-btn" id="btn_time_start"
                                                onclick="set_time('time_start')"><i
                                                    class="ri-timer-fill"></i></button>
                                        </div>
                                    </div>
                                    @if (@$this_procedure['code'] == 'gi002')
                                        <div class="d-flex justify-content-between mt-2">
                                            <span class="text-white text-nowrap">Withdrawal time :</span>
                                            <div class="input-group width-time-custom ">
                                                <input type="text" onkeypress="return onlyNumbersWithColon(event);"
                                                    name="time_withdrawal"
                                                    onfocusout="edit_time(this.value, this.id)"
                                                    class="form-control form-control-sm py-1     time_camera_format3 text-center text-time savejson"
                                                    time="2" id="time_withdrawal"
                                                    value="{{ @$case->time_withdrawal }}">
                                                <button class="btn btn-sm btn-light time-btn" id="btn_time_3"
                                                    onclick="set_time('time_withdrawal')"><i
                                                        class="ri-timer-fill"></i></button>
                                            </div>
                                        </div>
                                    @endif

                                    <div class="d-flex justify-content-between mt-2">
                                        <span class="text-white text-nowrap">End time :</span>
                                        <div class="input-group width-time-custom ">
                                            <input type="text" onkeypress="return onlyNumbersWithColon(event);"
                                                name="time_end"
                                                class="form-control form-control-sm py-1 text-center time_camera_format4 text-time savejson"
                                                onfocusout="edit_time(this.value, this.id)" time="3"
                                                id="time_end" value="{{ @$case->time_end }}">
                                            <button class="btn btn-sm btn-light time-btn" id="btn_time_4"
                                                onclick="set_time('time_end')"><i class="ri-timer-fill"></i></button>
                                        </div>
                                    </div>
                                    <div class="col-12 text-center mt-2"><button class="btn btn-dark-primary btn-sm  "
                                            data-bs-toggle="modal" data-bs-target="#medi_modal">Nurse Record
                                            (Interoperation)</button></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-12">
                        <span class="text-white h5">Images (<span id="img_num">{{ count($imgall) }}</span>)</span>
                    </div>
                    <div class="box-capture mt-2" id="box_showcapture" hide="true">
                        @foreach ($imgall as $key => $val)
                            <div class='box-capture-list mt-2'>
                                <img src="../../ScreenRecord/{{ $val['img'] }}" class="w-100 ">
                                <span class='number-cap'>{{ $val['num'] }}</span>
                            </div><br>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-9">
            @if ($type == 'test')
                <div class="col-12 p-0 m-0 ">
                    <div class="bar-header">
                        <div class="++ bg-danger text-center h3 p-2"
                            style="color:rgb(245, 245, 245); border-radius: 4px;"> ท่านกำลังทดสอบระบบกล้อง</div>
                    </div>
                </div>
            @endif
            <div class="col-12 p-0 m-0 ">
                <div id="no_signal_div" class="bar-header" style="display: none">
                    <div class="bar_test  bg-danger text-center h3 p-2" style="color:rgb(245, 245, 245)">
                        กรุณาตรวจสอบสายสัญญาณกล้อง</div>
                </div>
            </div>
            <div class="row">
                {{-- canvas --}}
                <div id="div_video" class="col-12" style="height: 80vh;background-color: coral;margin: 10px;" >
                    <video id="video1"></video>
                </div>
                <div class="col-auto" style="display: none;">
                    <span id="video_source" hidden>1</span>
                    <span id="current_brightness1" hidden>128</span>
                    <span id="current_hue1" hidden>128</span>
                    <span id="current_saturation1" hidden>128</span>
                    <span id="current_sharpness1" hidden>128</span>
                    <span id="current_contrast1" hidden>128</span>
                    <button id="brighteness_modal_btn1" data-bs-toggle="modal" data-bs-target="#modal_brightness"
                        hidden></button>
                </div>
                <div class="row">
                    <div class="col-4  ">
                        <div class="row ms-1 box-detail p-custom ">
                            <div class="col-5 mt-2 text-nowrap ">
                                Switch Status
                            </div>
                            <div class="col-7 mt-2 text-success m-0 p-0">
                                Connected
                            </div>
                            <div class="row  text-nowrap" style="margin-top: 0.8rem;">
                                <div class="col-5 align-self-center">
                                    Camera Signal
                                </div>
                                <div class="col-7">
                                    <button type="button" id="reload_btn1"onclick="refresh_scope(1)"
                                        class="btn btn-danger btn-sm btn-label wave-effect waves-light w-lg">
                                        <i class="las la-undo-alt  me-2  label-icon align-middle"></i> Reset Camera
                                    </button>
                                </div>
                                <div class="col-5 align-self-center">
                                    Live Solution
                                </div>
                                <div class="col-7">
                                    <button id="btn_liveconsult"
                                        class="btn btn-primary btn-label wave-effect waves-light  btn-sm mt-2 w-lg ">
                                        <i class="mdi mdi-cast-variant label-icon align-middle"></i>
                                        Live
                                        Solution</button>
                                </div>
                            </div>
                            <div class="row align-self-center mb-3">
                                <div class="col-5 ">
                                    Storage
                                </div>
                                <div class="col-7 mt-2">
                                    <div class="progress">
                                        <div class="progress-bar {{ $drive_color }}" role="progressbar"
                                            style="width: {{ $persen }}%" aria-valuenow="80" aria-valuemin="0"
                                            aria-valuemax="100"></div>
                                    </div>
                                    <span class="text-nowrap">{{ $ds - $drive }} GB / {{ $ds }} GB
                                        ({{ $persen }}%)</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-7 ">
                        <div class="row ms-1 box-detail p-custom-2 ">
                            <div class="col-3 text-nowrap align-self-center">
                                Camera Setting
                                <button id="set_brightness_btn1 " class="btn text-white" data-bs-toggle="offcanvas"
                                    href="#camera_offcanvas" role="button" aria-controls="offcanvasExample"><i
                                        class="ri-settings-3-line"></i> </button>
                            </div>
                            <div class="col-12 mb-4">
                                <input type="hidden" id="vdoname">
                                <input type="text" class="form-control" id="change_camera"
                                    placeholder="Select Camera" value="{{ @$scope_data }}">

                            </div>
                            <div class="col-2">
                            </div>
                            <div class="row mt-2">
                                <div class="col-8" style="border-right: 1px solid #707070">
                                    <div class="form-check mb-2" style="display: none">
                                        <input class="form-check-input" type="checkbox" id="ck_source1"
                                            value="1">
                                        <label class="form-check-label" for="ck_source1">
                                            Source 1
                                        </label>
                                    </div>
                                    <div class="form-check mb-2" id="cks2_div" style="display: none">
                                        <input class="form-check-input" type="checkbox" id="ck_source2"
                                            value="2">
                                        <label class="form-check-label" for="ck_source2">
                                            Source 2
                                        </label>
                                    </div>
                                    <div class="row mt-2 ">
                                        <div class="col-12  d-flex justify-content-between  ">
                                            <div>
                                                <button type="button"
                                                    class="btn btn-icon btn-white-camera  btn-capture waves-effect waves-light"
                                                    id="btn-capture"><i class="ri-camera-fill ri-xl"></i></button>
                                                <button type="button"
                                                    class="btn btn-icon btn-record  waves-effect waves-light  btn-record"
                                                    id="record1" onclick="record(this.id)">
                                                    <i class="ri-record-circle-line ri-xl"></i></button>
                                                <small class="text-danger" style="font-size: 14px">
                                                    <span id="pleasereload1" style="display: none;">การบันทึก VDO
                                                        ขัดข้องกรุณา Reload Source1</span></small>
                                            </div>
                                            <div class="mt-2 text-end">
                                                <span class="text-danger " id="timer1">00:00:00 <br></span>

                                                Size &nbsp; <span class="text-white text-nowrap  "id="size1"
                                                    style="font-size: 10px;">
                                                    0 </span> &nbsp; mb.
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-1 m-0 ps-1">
                        @if ($type == 'camera')
                            <div class="col-12 ">
                                <button
                                    class="btn btn-success btn-label waves-effect waves-light make_report w-lg h-button fs-12">
                                    <i class="mdi mdi-clipboard-text-outline
                                label-icon align-middle fs-14 me-2"></i>MAKE
                                    REPORT</button>
                            </div>
                            <div class="col-12 ">
                                <button id="case_btn"
                                    class="btn mt-2 btn-primary btn-label waves-effect waves-light w-lg h-button fs-12">
                                    <i class="ri-list-unordered label-icon align-middle fs-14 me-2"></i> CASE
                                    LIST</button>
                            </div>
                            <div class="col-12 ">
                                <button type="button" id="back_btn"
                                    class="btn mt-2 btn-danger btn-label waves-effect waves-light w-lg h-button fs-12">
                                    <i class="ri-arrow-go-back-line label-icon align-middle fs-14 me-2"></i> BACK</a>
                            </div>
                        @else
                            <div class="col-12">
                                <form action="{{ url('camera') }}" method="post" id="delete_photo_form">
                                    @csrf
                                    <input type="hidden" name="event" value="pictest_delete">
                                    <button type="button" type="submit" id="back_btn"
                                        class="btn mt-1 btn-danger btn-label waves-effect waves-light w-100"><i
                                            class="ri-arrow-go-back-line label-icon align-middle fs-16 me-2"></i>
                                        BACK</a>
                                </form>
                            </div>
                        @endif
                        <button hidden id="new_case_btn" type="button" class="btn btn-primary"
                            data-bs-toggle="modal" data-bs-target="#modal_new_case">
                            Launch demo modal
                        </button>
                    </div>

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

    </div>

    <div style="display: none">
        <form id="finish_record" action="{{ url('camera') }}" method="post">
            @csrf
            <input name="event" value="finish_record" type="hidden">
            <input name="hn" value="{{ $hn }}" type="hidden">
            <input name="cid" value="{{ $cid }}" type="hidden">
            <input name="caseuniq" value="{{ $case->caseuniq }}" type="hidden">
            <button type="submit">save</button>
        </form>
    </div>


    <div style="display:none">
        <canvas id="canvas_video" style="z-index:1;"></canvas>
        <canvas id="canvas_video99"></canvas>
        <canvas id="canvas_video01" style="z-index:1;"></canvas>
        <canvas id="canvas_video02" style="z-index:1;"></canvas>
        <canvas id="canvas_video03" style="z-index:1;"></canvas>
        <video  id="recorded" playsinline loop></video>
        <div>
            <button id="record">Start Recording</button>
            <button id="play" disabled>Play</button>
            <button id="download" disabled>Download</button>
        </div>
    </div>




    @include("endocapture.camera.obs.00test")



    <script src="{{ url('assets/libs/dropzone/dropzone-min.js') }}"></script>
    <script src="{{ url('assets/libs/filepond/filepond.min.js') }}"></script>
    <script src="{{ url('assets/libs/filepond-plugin-image-preview/filepond-plugin-image-preview.min.js') }}"></script>
    <script src="{{ url('assets/libs/filepond-plugin-file-validate-size/filepond-plugin-file-validate-size.min.js') }}">
    </script>
    <script
        src="{{ url('assets/libs/filepond-plugin-image-exif-orientation/filepond-plugin-image-exif-orientation.min.js') }}">
    </script>
    <script src="{{ url('assets/libs/filepond-plugin-file-encode/filepond-plugin-file-encode.min.js') }}"></script>
    <script src="{{ url('assets/libs/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
    <script src="{{ url('assets/libs/simplebar/simplebar.min.js') }}"></script>
    <script src="{{ url('assets/libs/node-waves/waves.min.js') }}"></script>
    <script src="{{ url('assets/libs/feather-icons/feather.min.js') }}"></script>
    <script src="{{ url('assets/js/pages/plugins/lord-icon-2.1.0.js') }}"></script>

    @include('layouts.layouts_index.plugins')
    <script src="{{ url('assets/libs/@simonwep/pickr/pickr.min.js') }}"></script>
    <script src="{{ url('assets/js/pages/form-pickers.init.js') }}"></script>
    <script src="{{ url('assets/js/select2.min.js') }}"></script>
    <script src="{{ url('assets/js/pages/select2.init.js') }}"></script>
    <script src="{{ url('assets/libs/fullcalendar/main.min.js') }}"></script>
    <script src="{{ url('assets/libs/cleave.js/cleave.min.js') }}"></script>
    <script src="{{ url('assets/js/pages/form-masks.init.js') }}"></script>
    <script src="{{ url('assets/js/pages/form-pickers.init.js') }}"></script>
    {{-- <script src="{{ url('assets/js/app.js') }}"></script> --}}

    <script src="{{url('public/camera/DetectRTC.js')}}"> </script>
    {{-- <script src="{{url('public/camera/RecordRTC.js')}}"></script> --}}
    <script src="{{url('public/camera/EBML.js')}}"></script>


<script>
        let camera_first = "";
let deviceId = 0;

DetectRTC.load(function(){
    let camera_source=1;

    DetectRTC.videoInputDevices.forEach(function(device, idx) {
        if(camera_source==1){camera_first = device.deviceId;}
        deviceId = device.deviceId;
        $(".mini_select").append("<option class='camera_source' id='camera_source"+camera_source+"' value='" + device.deviceId + "'>กล้อง " + camera_source + "</option>");
        camera_source++;
    });
});

DetectRTC.load(function(){
    navigator.getUserMedia({
            audio: false,
            video: {
                deviceId: camera_first,
                width: 1920,
                height: 1080
            }
        },
        function(stream){
            var video = document.querySelector('#video1');
            video.srcObject = stream;
            video.onloadedmetadata = function(e) {video.play();};
            var mediaRecorder = new MediaRecorder(video.srcObject, {mimeType: 'video/webm;codecs=vp9,opus',bitsPerSecond: 5000000});
            var chunks = [];

            mediaRecorder.ondataavailable = function(e) {chunks.push(e.data);};

            mediaRecorder.onstop = function(e) {
            vdo_render = true;

            getSeekableBlob( new Blob(chunks, { 'type' : 'video/mp4' }), function(seekableBlob) {
                chunks          = [];
                var fileType    = 'video'; // or "audio"
                var fileName    = '{{@$case->case_id}}_'+'.mp4';  // or "wav"
                var scope       = $('#select_scope').val();
                var hn          = '{{$case->case_hn}}';
                var cid         = '{{$case->case_id}}';
                var vdo_time    = $('#txt').html();


                console.log('vdo_time',vdo_time);
                // var saveData = (function () {
                //     var a = document.createElement("a");
                //     document.body.appendChild(a);
                //     a.style = "display: none";
                //     return function (data, fileName) {
                //             url = window.URL.createObjectURL(data);
                //         a.href = url;
                //         a.download = fileName;
                //         a.click();
                //         window.URL.revokeObjectURL(url);
                //     };
                // }());

                // var data = { x: 42, s: "hello, world", d: new Date() },
                //     fileName = "my-download.webm";

                // saveData(seekableBlob, fileName);

                var formData    = new FormData();
                formData.append("_token"    , '{{csrf_token()}}');
                formData.append("event"     , 'savevdo');
                formData.append('hn'        , hn);
                formData.append('cid'       , cid);
                formData.append('scope'     , scope);
                formData.append('vdo_time'  , vdo_time);
                formData.append('filename'  , fileName);
                formData.append('blob'      , seekableBlob);

                xhr('{{url("camera")}}', formData, function (fName) {});
                function xhr(url, data, callback) {
                    var request = new XMLHttpRequest();
                    request.onreadystatechange = function () {
                        // console.log(request.status,"mmmm");
                        if(request.status==200){
                            vdo_render = false;
                            window.location.reload();
                        }
                        $('#modal_vdo_render').modal('hide');
                    };
                    request.open('POST', url);
                    request.send(data);
                }
            });
        };

        mediaRecorder.ondataavailable = function(e) {chunks.push(e.data);};

        $('#btn-start-recording').click(function(){

            @if($vdo_recording==false)
            recording_start.play();
            @endif
            $.post('{{url('camera')}}',{
                event   : "vdostart",
                cid     : "{{@$case->case_id}}",
            },function(data,status){
                console.log(data);
            });


            $(this).hide();
            $('#btn-stop-recording').show();
            mediaRecorder.start();
            $('#vdo_play').val('start');

            var myVar = setInterval(myTimer, 1000);
            var H = {{$H}};
            var M = {{$M}};
            var S = {{$S}};
            var tS = "{{$tS}}";
            var tM = "{{$tM}}";
            var tH = "{{$tH}}";
            var is_time = "{{$vdo_time}}";
            function myTimer(){
                S = S+1;
                if(S>=60){
                    M = M+1;
                    S = 0;
                    console.log(M);
                }
                if(M>=60){
                    H = H+1;
                    M=0;
                }
                if (S < 10) {tS = "0" + S}else{tS=S};
                if (M < 10) {tM = "0" + M}else{tM=M};
                if (H< 10) {tH = "0" + H}else{tH=H};
                is_time = tH+":"+tM+":"+tS;
                document.getElementById('txt').innerHTML = is_time;
            };

            var vdo_minute = {{webconfig('vdo_minute')}}*60000;

            var refreshId = setInterval(function() {
                console.log('ถึงเวลาบันทึกวิดีโอ')
                mediaRecorder.stop();
                setTimeout(function(){
                    mediaRecorder.start();
                    myTimer();
                }, 10);
                localStorage.clear();
            //แก้วินาที ตรงนี้นะครับผม
            // }, 900000);
            }, vdo_minute);


            $('#btn-stop-recording').click(function(){
                recording_stop.play();
                setTimeout(() => {
                    $.post('{{url('camera')}}',{
                        event   : "vdostop",
                        cid     : "{{@$case->case_id}}",
                    },function(data,status){});

                    $('#vdo_play').val('stop');
                    $(this).hide();
                    $('#btn-start-recording').show();
                    $('#modal_vdo_render').modal('show');
                    clearInterval(refreshId);
                    clearInterval(myVar);
                    mediaRecorder.stop();
                }, 2000);
            });
        });


        },
        function(err){
            console.log("The following error occurred: " + err.name);
        }
    );
});

var canvas  = document.getElementById('canvas_video');
    canvas.width  = 1570;
    canvas.height = 883;
    var ctx     = canvas.getContext('2d');
    var video1  = document.getElementById('video1');
    ctx.beginPath();
    ctx.rect(0, 0, 1570, 883);
    ctx.fillStyle = "black";
    ctx.fill();

    setTimeout(function(){
        (function loop() {
            ctx.beginPath();
            ctx.rect(0, 0, 1570, 883);
            ctx.fillStyle = "black";
            ctx.fill();
            ctx.drawImage(canvas, 0, 0,1570,883);
            })();
     }, 1000);



    setTimeout(function(){
        var heightvdo1 = $('#video1').height();
        DetectRTC.load(function(){
            navigator.getUserMedia({
                    audio: false,
                    video: {
                        deviceId: deviceId,
                        width: 1920,
                        height: 1080
                    }
                },
                function(stream){
                    var video = document.querySelector('#video1');
                    video.srcObject = stream;
                    video.onloadedmetadata = function(e) {video.play();};
                },
                function(err){
                    console.log("The following error occurred: " + err.name);
                }
            );
        });

    }, 2000);






    // $('#btn-capture').click(function() {
    //     var canvas = document.getElementById('canvas_video');
    //     var dataURL = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
    //     $.post('{{ url('camera') }}', {
    //         event   : 'takephoto',
    //         datapic : dataURL,
    //         scope   : $('#select_scope').val(),
    //         hn      : '{{$case->case_hn}}',
    //         case_id : "{{ $cid }}"
    //     }, function(data, status) {
    //         var numtext = $("#num_img").text();
    //         $("#num_img").text(parseInt(numtext) + 1);
    //         var number =  $("#num_img").text();
    //         const arr = JSON.parse(data);
    //         $("#box_showcapture").prepend("<img src='../../ScreenRecord/" + arr.picname +"' width='100%' class='imgnew'><div class='count_img'>"+number+"</div>");
    //     });
    // });









</script>




































    <script>
        $(document).on('select2:open', () => {
            document.querySelector('.select2-search__field').focus();
        });
        $(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>
        $("#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");
                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");
                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
        });

        $('#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>

        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("{{ fileconfig('sound/capture/alert.mp3') }}");
        var audio_incorrect = new Audio("{{ fileconfig('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('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").html();
            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() {
            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);
                });
            }, 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>
        $.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);


        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', '')

        socket.on('chat message', function(msg) {
            console.log(msg, msg != '', msg != undefined);
            if (msg != '' && msg != undefined) {
                if (msg == 1) {
                    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");
                    }
                }

                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) {
                    $(".btn-record").trigger('click');
                }
            }
        })


        $('.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() {
            socket.emit('chat message',
                `{"case":"true","cid":"{{ $cid }}","hn":"{{ $hn }}","procedure":"{{ @$case->procedurename . '' }}","operationdate":"${operation_date}","caseuniq":"{{ @$case->caseuniq . '' }}"}`
            );
        }

        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)
                })
            }
        }


        socket.on('filename', function(msg) {
            var cid = '{{ @$cid }}'
            var caseuniq = '{{ @$caseuniq }}'
            var is_photocaseuniq = '{{ @$feature->photocaseuniq }}' // boolean: true : 1, false or none : ''
            var check_img = is_photocaseuniq == 1 ? msg.includes(caseuniq) : msg.includes(cid)
            if (msg.includes(cid) && msg.includes('.mp4')) {
                $('#vdoname').val(msg)
                vdo_file_interval = setInterval(() => {
                    check_vdofile_size(msg)
                }, 3 * 1000);

                $.post("{{ url('api/camera') }}", {
                    event: "recordvdo",
                    vdoname: msg,
                    cid: cid
                }, function(d, s) {
                    console.log(d);
                });


            }

            if (check_img && msg.includes('.jpg')) {
                setTimeout(() => {
                    imageSHOW(msg);
                }, 500);


                @if (@$feature->liveconsult)
                    liveconsult(msg);
                @endif
            }
        })

        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) {
                    $('#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)
            // audio.play();
            // 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() {
            $(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) {
            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);
            setTimeout(() => {
                window.location.reload()
            }, 5000);
        }

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

        /// set video properties ///
        // initial video properties from cameratemp

        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 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')) {
                $(`#${btn_id}`).removeClass('active')
                socket.emit('chat message', `vdo_stop${first_source}`)
                stop_timer(source_num)
                if (btn_id == 'record1') {
                    is_video1 = false
                } else {
                    is_video2 = false
                }

                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);
            } else {
                $(`#${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)
            });
        });

        $('#back_btn').on('click', function() {
            let time_end = $("#time_end").val();
            if (time_end == "") {
                set_time('time_end');
            }
            $.post("{{ url('api/camera') }}", {
                event: "back2home",
                cid: "{{ $cid }}",
                hn: "{{ $hn }}",
            }, function(d, s) {});
            socket.emit('chat message', 'to_page')
            socket.emit('chat message', "camera_stop1");
            setTimeout(() => {
                window.location.href = "{{ url('') }}"
            }, 1 * 1000);
        })

        $('#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()
        })


        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) {});
        }

        $('.select-source').change(function() {
            if ($(this).val() == 1) {
                $($('.vdo-source')[1]).removeClass('active')
                $($('.vdo-shows')[1]).removeClass('active')
                console.log($('#full_screendiv2'));
                $('#full_screendiv2').css('display', 'none')
                $('#cks2_div').css('display', 'none')
                $('#source2_div').css('display', 'none')
                $('#reload2_div').css('display', 'none')
            } else {
                $($('.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')
            }
        })
        $('.change-user').change(function() {
            var data_id = $(this).val()
            // alert(data_id)
            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("{{ @Request::segment(2) }}", 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("{{ @Request::segment(2) }}", 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>

</body>

</html>
