$(document).ready(function () {

    $('.close-modal').on('click', function(){
        $('#standart_modal').modal('toggle');
    });

    $('#short_std').on('click', function(){
        standart_load($('#cur_modal_std').val(), false, $('#cur_modal_tag_id').val());
        $('#short_std').hide();
        $('#long_std').show();
    });

    $('#long_std').on('click', function(){
        standart_load($('#cur_modal_std').val(), true, $('#cur_modal_tag_id').val());
        $('#short_std').show();
        $('#long_std').hide();
    });

    $('.custom-input').on('focus focusout', function(){
        if($(this).val() == null || $(this).val() == '')
        {
            $($(this).parent()).removeClass('hastext');
        }
        else
        {
            $($(this).parent()).addClass('hastext');
        }
    });


    function previewIMG(input, preview) {
        var reader = new FileReader();
        reader.onload = function(e) {
          $(preview).attr('src', e.target.result);
        }
        reader.readAsDataURL(input);
    }

    $("#file_input").change(function(){
        $('#imgs_preview').empty();
        $('#file-input-greenspan').html('');
        if ($(this)[0].files[0]) {
            $('#pre_load').hide();
            $('#file-input-greenspan').html('Загружено снимков: ' + $(this)[0].files.length);
            for(i=0;i<$(this)[0].files.length;i++)
            {
                if (($(this)[0].files[i].type.includes('image')))
                {

                    div = document.createElement('div');
                    div.setAttribute('class', 'col-3 p-1 m-0');
                    img = document.createElement('img');
                    img.setAttribute('class', 'preview_img');
                    previewIMG($(this)[0].files[i], $(img));

                    div.appendChild(img);
                    document.getElementById("imgs_preview").appendChild(div);
                }
            }
        }
    });

    $('#endo_tab_link').on('click', function()
    {
        load__endo_history(true);
    });

    $('#nn_tab_link').on('click', function()
    {
        load__endo_history(true);
    });

    function reload_visit_info(){
        lang = getUrlParameter('lang');
        $.ajax({
            type:'GET',
            url: '/reload_visit_info/' + $('#visit_id').val() + '?task=off'+'&lang='+lang,
            processData: false,
            contentType: false,
            success: (data) => {
                load__endo_history(false);
            }
        });
    }


    function load__endo_history(rvn){
        $('#endo_history').empty();
        if(rvn)
            reload_visit_info();
        $.ajax({
            type:'GET',
            url: '/get_visit_info/'+$('#visit_id').val(),
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentTypestatus
            success: (data) => {
                $('#endo_history').empty();
                var label_id = 0
                // Восстановил старый код (как у меня было)
                for (untask_num in data['untask_pics'])
                {
                    pic = data['untask_pics'][untask_num]
                    organ = ''
                    if (pic['organ'])
                    {
                        organ = pic['organ']
                    }
                    if($('#language').val() == 'ru')
                        $('#endo_history').append('<tr><td scope="col"><img src=/img/'+pic['file']+' class="preview_img"></td><td scope="col">'+organ+'</td><td scope="col"><span class="expert_diagnos" data-img='+pic['file']+'></span><span class="standart_modal btn btn-secondary btn-sm" data-code="">Стандарт</span></td><td scope="col"><select data-img='+pic['file']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select"><option value="" disabled="" selected="">Диагноз</option></select><span class="standart_modal btn btn-secondary btn-sm" data-code="">Стандарт</span></td></tr>');
                    else
                        $('#endo_history').append('<tr><td scope="col"><img src=/img/'+pic['file']+' class="preview_img"></td><td scope="col">'+organ+'</td><td scope="col"><span class="expert_diagnos" data-img='+pic['file']+'></span><span class="standart_modal btn btn-secondary btn-sm" data-code="">Standart</span></td><td scope="col"><select data-img='+pic['file']+' id="ds'+label_id+'" type="select" class="form-control diagnoses_select"><option value="" disabled="" selected="">Диагноз</option></select><span class="standart_modal btn btn-secondary btn-sm" data-code="">Standart</span></td></tr>');
                    label_id = label_id + 1
                }
                for (untask_num in data['tasks'])
                {
                    pic = data['tasks'][untask_num]
                    console.log(pic)
                    organ = ''
                    if (pic['organ'])
                    {
                        organ = pic['organ']
                    }
                    if (pic["task"]['error']==null) {
                        tr = document.createElement('tr');
                        td1 = document.createElement('td');
                        td1.setAttribute('scope', 'col');
                        img = document.createElement('img');
                        img.setAttribute('src', '/img/'+pic['pictures'][0]['hash_name']);
                        //
                        img.setAttribute('class', 'preview_img');
                        td1.appendChild(img);
                        tr.appendChild(td1);
                        //
                        td2 = document.createElement('td');
                        td2.setAttribute('scope', 'col');
                        td2.innerHTML = organ;
                        tr.appendChild(td2);
                        //
                        //
                        td3 = document.createElement('td');
                        td3.setAttribute('scope', 'col');
                        //
                        span = document.createElement('span');
                        span.setAttribute('class', 'expert_diagnos');
                        span.setAttribute('data-img', pic['file']);
                        span.innerHTML = data['tasks'][untask_num]['task']['class'];
                        td3.appendChild(span); 
                        //
                        span = document.createElement('span');
                        span.setAttribute('class', 'standart_modal btn btn-secondary btn-sm')
                        span.setAttribute('data-code', '');
                        if($('#language').val() == 'ru') {
                            span.innerHTML = 'Стандарт';
                        } else {
                            span.innerHTML = "Standart"
                        }
                        td3.appendChild(span);
                        tr.appendChild(td3);
                        //
                        td4 = document.createElement('td');
                        td4.setAttribute('scope', 'col');
                        //
                        select = document.createElement('select');
                        select.setAttribute('data-img', pic['pictures'][0]['hash_name']);
                        select.setAttribute('id', 'ds'+label_id);
                        select.setAttribute('type', 'select');
                        select.setAttribute('class', 'form-control diagnoses_select')
                        //
                        option = document.createElement('option');
                        option.setAttribute('value', '');
                        option.setAttribute('disabled', '');
                        option.setAttribute('selected', '');
                        if ($('#language').val() == 'ru') {
                            option.innerHTML = 'Диагноз';
                        } else {
                            option.innerHTML = 'Diagnos';
                        }

                        select.appendChild(option);
                        td4.appendChild(select);
                        //
                        span = document.createElement('span');
                        span.setAttribute('class', 'standart_modal btn btn-secondary btn-sm')
                        span.setAttribute('data-code', '');
                        if($('#language').val() == 'ru') {
                            span.innerHTML = 'Стандарт';
                        } else {
                            span.innerHTML = "Standart"
                        }
                        td4.appendChild(span);
                        tr.appendChild(td4)
                        //
                        $('#endo_history').append(tr);
                    } 
//                    else {
//
//                        tr = document.createElement('tr');
//                        td1 = document.createElement('td');
//                        td1.setAttribute('scope', 'col');
//                        img = document.createElement('img');
//                        img.setAttribute('src', '/img/'+data['untask_pics'][untask_num]['file']);
//                        //
//                        img.setAttribute('class', 'preview_img');
//                        td1.appendChild(img);
//                        tr.appendChild(td1);
//                        //
//                        td2 = document.createElement('td');
//                        td2.setAttribute('scope', 'col');
//                        td2.innerHTML = organ;
//                        tr.appendChild(td2);
//                        //
//                        //
//                        td3 = document.createElement('td');
//                        td3.setAttribute('scope', 'col');
//                        //
//                        span = document.createElement('span');
//                        span.setAttribute('class', 'expert_diagnos');
//                        span.setAttribute('data-img', pic['file']);
//                        span.innerHTML = data['tasks'][untask_num]['task']['class'];
//                        td3.appendChild(span);
//                        //
//                        span = document.createElement('span');
//                        span.setAttribute('class', 'standart_modal btn btn-secondary btn-sm')
//                        span.setAttribute('data-code', '');
//                        if($('#language').val() == 'ru') {
//                            span.innerHTML = 'Стандарт';
//                        } else {
//                            span.innerHTML = "Standart"
//                        }
//                        td3.appendChild(span);
//                        tr.appendChild(td3);
//                        //
//                        td4 = document.createElement('td');
//                        td4.setAttribute('scope', 'col');
//                        //
//                        select = document.createElement('select');
//                        select.setAttribute('data-img', pic['file']);
//                        select.setAttribute('id', 'ds'+label_id);
//                        select.setAttribute('type', 'select');
//                        select.setAttribute('class', 'form-control diagnoses_select')
//                        //
//                        option = document.createElement('option');
//                        option.setAttribute('value', '');
//                        option.setAttribute('disabled', '');
//                        option.setAttribute('selected', '');
//                        if ($('#language').val() == 'ru') {
//                            option.innerHTML = 'Диагноз';
//                        } else {
//                            option.innerHTML = 'Diagnos';
//                        }
//
//                        select.appendChild(option);
//                        td4.appendChild(select);
//                        //
//                        span = document.createElement('span');
//                        span.setAttribute('class', 'standart_modal btn btn-secondary btn-sm')
//                        span.setAttribute('data-code', '');
//                        if($('#language').val() == 'ru') {
//                            span.innerHTML = 'Стандарт';
//                        } else {
//                            span.innerHTML = "Standart"
//                        }
//                        td4.appendChild(span);
//                        tr.appendChild(td4)
//                        //
//                        $('#endo_history').append(tr);
//                    }
                    label_id = label_id + 1
                }

                //Если не прошел запрос к API
                //for (untask_num in data['tasks']){
                //    pic = data['tasks'][untask_num]
                //    organ = ''
                //    if (pic['organ'])
                //    {
                //        organ = pic['organ']
                //    }
                //    console.log(pic)
                //    tr = document.createElement('tr');
                //    td1 = document.createElement('td');
                //    td1.setAttribute('scope', 'col');
                //    img = document.createElement('img');
                //    img.setAttribute('src', '/img/'+data['untask_pics'][untask_num]['file']);
                //    //
                //    img.setAttribute('class', 'preview_img');
                //    td1.appendChild(img);
                //    tr.appendChild(td1);
                //    //
                //    td2 = document.createElement('td');
                //    td2.setAttribute('scope', 'col');
                //    td2.innerHTML = organ;
                //    tr.appendChild(td2);
                //    //
                //    //
                //    td3 = document.createElement('td');
                //    td3.setAttribute('scope', 'col');
                //    //
                //    span = document.createElement('span');
                //    span.setAttribute('class', 'expert_diagnos');
                //    span.setAttribute('data-img', pic['file']);
                //    span.innerHTML = data['tasks'][untask_num]['task']['class'];
                //    td3.appendChild(span); 
                //    //
                //    span = document.createElement('span');
                //    span.setAttribute('class', 'standart_modal btn btn-secondary btn-sm')
                //    span.setAttribute('data-code', '');
                //    if($('#language').val() == 'ru') {
                //        span.innerHTML = 'Стандарт';
                //    } else {
                //        span.innerHTML = "Standart"
                //    }
                //    td3.appendChild(span);
                //    tr.appendChild(td3);
                //    //
                //    td4 = document.createElement('td');
                //    td4.setAttribute('scope', 'col');
                //    //
                //    select = document.createElement('select');
                //    select.setAttribute('data-img', pic['file']);
                //    select.setAttribute('id', 'ds'+label_id);
                //    select.setAttribute('type', 'select');
                //    select.setAttribute('class', 'form-control diagnoses_select')
                //    //
                //    option = document.createElement('option');
                //    option.setAttribute('value', '');
                //    option.setAttribute('disabled', '');
                //    option.setAttribute('selected', '');
                //    if ($('#language').val() == 'ru') {
                //        option.innerHTML = 'Диагноз';
                //    } else {
                //        option.innerHTML = 'Diagnos';
                //    }
                //    
                //    select.appendChild(option);
                //    td4.appendChild(select);
                //    //
                //    span = document.createElement('span');
                //    span.setAttribute('class', 'standart_modal btn btn-secondary btn-sm')
                //    span.setAttribute('data-code', '');
                //    if($('#language').val() == 'ru') {
                //        span.innerHTML = 'Стандарт';
                //    } else {
                //        span.innerHTML = "Standart"
                //    }
                //    td4.appendChild(span);
                //    tr.appendChild(td4)
                //    //
                //    $('#endo_history').append(tr);
                //    label_id = label_id + 1
                //}



                select_fill();
                for (pic_num in data['pics'])
                {
                    pic = data['pics'][pic_num]
                    if (pic.length > 0){
                        if(pic.length > 1)
                        {
//                            $('#exception').html('Обнаружены снимки с дублирующимся описанием, перейдите в подробный отчет');
//                            $('#exception').slideDown(500);
//                            $('#exception').delay(2000).slideUp();
                            console.log('Обнаружены снимки с дублирующимся описанием')
                        }

                        $.each($('.diagnoses_select'), function(e) {
                            if($(this).data('img') == pic[0]['hash_name'])
                            {
//                                console.log(pic[0]['tag_id'])
                                $(this).val(pic[0]['tag_id']);
                                $(this).parent().children('.standart_modal').data('code', pic[0]['icd']);
                                $(this).parent().children('.standart_modal').removeClass('btn-secondary');
                                $(this).parent().children('.standart_modal').addClass('btn-primary');
//                                $(this).select2('data', {id: pic[0]['tag_id'], text: 'Lorem Ipsum'});
                            }
                        })
                    }
                }

                for (pic_num in data['expert_pics'])
                {
                    pic = data['expert_pics'][pic_num]
                    if (pic.length > 0){
                        if(pic.length > 1)
                        {
//                            $('#exception').html('Обнаружены снимки с дублирующимся описанием, перейдите в подробный отчет');
//                            $('#exception').slideDown(500);
                            console.log('Обнаружены снимки с дублирующимся экспертым описанием')
                        }

                        $.each($('.expert_diagnos'), function(e) {
                            if($(this).data('img') == pic[0]['hash_name'])
                            {
                                console.log(pic[0]['icd']);
                                $(this).html(pic[0]['icd']+' '+pic[0]['tag'])
                                $(this).parent().children('.standart_modal').data('tag_id', pic[0]['tag_id']);
                                $(this).parent().children('.standart_modal').data('code', pic[0]['icd']);
                                $(this).parent().children('.standart_modal').removeClass('btn-secondary');
                                $(this).parent().children('.standart_modal').addClass('btn-primary');
//                                $(this).select2('data', {id: pic[0]['tag_id'], text: 'Lorem Ipsum'});
                            }
                        })
                    }
                }
                $('.standart_modal').on('click', function(){
                    $('#standart_modal').modal('toggle');
//                    console.log($(this).data('code'))
                    standart_load($(this).data('code'), false, $(this).data('tag_id'));
                })
                $('.diagnoses_select').on('change', function() {
//                    console.log( this.value );
                    save_select(this);
                    $(this).parent().children('.standart_modal').removeClass('btn-secondary');
                    $(this).parent().children('.standart_modal').addClass('btn-primary');
                });
                $('.diagnoses_select').select2();
            },
            error:function (jqXHR, exception) {

            }
        });

    }
    //saving on select change OK FOR MULTIPROFILE
    function save_select(element){
//        console.log(element.value);
//        console.log($(element).data('img'));
        var message = {
            diagnos_id: element.value,
            pic_name: $(element).data('img'),
            visit_id: $('#visit_id').val(),
        }
        $.ajax({
            type:'POST',
            url: '/save_pic_diagnos',
            async: !1,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            data: JSON.stringify(message),
            success: (data) => {
                if(data['success'] == true)
                {
                    $(element).parent().children('.standart_modal').data('code', data['icd']);
                    $(element).parent().children('.standart_modal').data('tag_id', data['tag_id']);
                    $('#success').html('Диагноз сохранен');
                    $('#success').slideDown(500);
                    $('#success').delay(2000).slideUp();
                }
                else
                {
                    after_error();
                    $('#request_waiting').hide();
                    $('#start_rec').attr("disabled", false);
                    $('#save_picture').attr("disabled", false);
                }
            },
            error:function (jqXHR, exception) {
                after_error();
                $('#request_waiting').hide();
                $('#start_rec').attr("disabled", false);
                $('#save_picture').attr("disabled", false);
            }
        });

    }

    function getId(str)
    {
        return(str.replaceAll(' ','').replaceAll(',','').replaceAll('.','').replaceAll(';','').replaceAll(':','').replaceAll('(','').replaceAll(')','').replaceAll('-','').replaceAll('/','').replaceAll('\\',''))
    }

    var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
        return false;
    };

    function standart_load(code, full, tag_id){
        $('#cur_modal_std').val(code);
        $('#cur_modal_tag_id').val(tag_id);
        lang = getUrlParameter('lang');
        console.log('lang - '+lang);
        $.ajax({
            type:'GET',
            url: '/get_diagnos_standart?icd='+code+'&tag_id='+tag_id+'&lang='+lang,
            async: true,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                $('#standart_body').empty();
                $('#standart_name').html(data['standart_name']);
                if(lang == 'en'){
                    $('#standart_diagnos').html('Diagnosis: <b>' + data['name']+'</b>');
                    $('#standart_type').html('Type of standard: <b>'+data['standart_type']+'</b>');
                    $('#standart_icd_code').html('ICD-10 code: <b>'+data['icd']+'</b>');
                    $('#standart_time').html('Treatment time (days): <b>'+data['days_min']+' - '+data['days_max']+'</b>');
                }
                else
                {
                    $('#standart_diagnos').html('Диагноз: <b>' + data['name']+'</b>');
                    $('#standart_type').html('Вид стандарта: <b>'+data['standart_type']+'</b>');
                    $('#standart_icd_code').html('Код по МКБ-10: <b>'+data['icd']+'</b>');
                    $('#standart_time').html('Сроки лечения (дней): <b>'+data['days_min']+' - '+data['days_max']+'</b>');
                }
                var groups = [];
                for (std_num in data['standart'])
                {
                    var std = data['standart'][std_num]
                    if (!(groups.includes(std['service_type'])))
                    {
                        groups.push(std['service_type'])
                        $('#standart_body').append('<h5>'+std['service_type']+'</h5><div id="group'+getId(std['service_type'])+'"></div>');
                    }
                }
                var sub_groups = [];
                for (std_num in data['standart'])
                {
                    var std = data['standart'][std_num]
                    for (group in groups){
                        if(!($('#group'+getId(std['service_type'])).data('dt'+getId(std['service_subtype'])) == true))
                        {
                            $('#group'+getId(std['service_type'])).data('dt'+getId(std['service_subtype']), true);
                            $('#group'+getId(std['service_type'])).append('<p>'+std['service_subtype']+'</p>');
                            if(lang == 'en')
                                $('#group'+getId(std['service_type'])).append('<table style="width: 100%;" class="table table-striped table-bordered custom-font"><thead><tr><th scope="col">Medical Service Code</th><th scope="col">Name</th><th scope="col">Approximate frequency of presentation</th></tr></thead><tbody id="table'+ getId(std['service_subtype']) + getId(std['service_type'])+'"></tbody></table>');
                            else
                                $('#group'+getId(std['service_type'])).append('<table style="width: 100%;" class="table table-striped table-bordered custom-font"><thead><tr><th scope="col">Код медицинской услуги</th><th scope="col">Наименование</th><th scope="col">Примерная частота представления</th></tr></thead><tbody id="table'+ getId(std['service_subtype']) + getId(std['service_type'])+'"></tbody></table>');
                        }
                    }
                }
                for (std_num in data['standart'])
                {
                    if(full == true){
                        var std = data['standart'][std_num]
                        service_code = ''
                        if (!(std['service_code'] == 'NULL'))
                            service_code = std['service_code']
                        $('#table'+ getId(std['service_subtype']) + getId(std['service_type'])).append(
                            '<tr><td>'+service_code+'</td><td>'+std['standart_name']+'</td><td>'+std['periodicity']+'</td></td>'
                        );
                    }
                    else
                    {
                        var std = data['standart'][std_num]
                        if(std['periodicity'] == '1'){
                            service_code = ''
                            if (!(std['service_code'] == 'NULL'))
                                service_code = std['service_code']
                            $('#table'+ getId(std['service_subtype']) + getId(std['service_type'])).append(
                                '<tr><td>'+service_code+'</td><td>'+std['standart_name']+'</td><td>'+std['periodicity']+'</td></td>'
                            );
                        }
                    }

                }
                $('#copy_text').data('text', data['for_copy'])

            },
            error:function (jqXHR, exception) {
                $('#standart_body').empty();
                $('#standart_name').html('');
                $('#standart_diagnos').html('');
                $('#standart_type').html('');
                $('#standart_icd_code').html('');
                $('#standart_time').html('');
            }
        });
    }

    $('#copy_text').on("click", function(){
        $('#text_to_copy').html($('#copy_text').data('text'));
        function listener(e) {
            str = document.getElementById('text_to_copy').innerHTML
            e.clipboardData.setData("text/html", str);
            e.clipboardData.setData("text/plain", str);
            e.preventDefault();
        }
        document.addEventListener("copy", listener);
        document.execCommand("copy");
        document.removeEventListener("copy", listener);

        $('#copy_text').addClass('check-icn');
        setTimeout(function() {
           $('#copy_text').removeClass('check-icn');
        }, 2000);
    });

    $('#start_rec').on("click", function()
    {
        if($('#btnradio_ear').is(":checked"))
            startRec('source');
        else
            loadWOrec('source');
    });

    $('#save_picture').on("click", function()
    {
        if($('#btnradio_ear').is(":checked"))
            startRec('webcam');
        else
            loadWOrec('webcam');
    });

    function makeblob(dataURL) {
        var BASE64_MARKER = ';base64,';
        if (dataURL.indexOf(BASE64_MARKER) == -1) {
            var parts = dataURL.split(',');
            var contentType = parts[0].split(':')[1];
            var raw = decodeURIComponent(parts[1]);
            return new Blob([raw], { type: contentType });
        }
        var parts = dataURL.split(BASE64_MARKER);
        var contentType = parts[0].split(':')[1];
        var raw = window.atob(parts[1]);
        var rawLength = raw.length;

        var uInt8Array = new Uint8Array(rawLength);

        for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        return new Blob([uInt8Array], { type: contentType });
    }

    function loadWOrec(from){
        $('#start_rec').attr("disabled", true);
        $('#save_picture').attr("disabled", true);
        $('#request_waiting').show();
        $('#progress_text').html('Загрузка снимков');
        var organ = 0

        var fileList = document.getElementById('file_input').files;
        var formData = new FormData();
        var poll = null;
        var i = 0
        if (from == 'source')
            for(i=0;i<fileList.length;i++)
            {
                if (fileList[i].type.includes('image'))
                {
                    formData.append("files", fileList[i]);
                    i += 1;
                }
            }
        if (from == 'webcam')
            $.each($('.endo_image'), function(e) {
                formData.append("files", makeblob($(this).attr('src')));
                i += 1;
            });
        if (i > 0)
        {
            $.ajax({
                type:'POST',
                data: formData,
                url: '/save_images?patient_id='+$('#patient_id').val()+'&organ='+organ+'&visit_id='+$('#visit_id').val()+'&profarea_id='+'3',
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success: (data) => {
                    $('#photos').empty();
                    $('#imgs_preview').empty();
                    $('#file_input').val(null);
                    $('#pre_load').show();
                    $('#file-input-greenspan').html('');
                    $('#start_rec').attr("disabled", false);
                    $('#save_picture').attr("disabled", false);
                    $('#request_waiting').hide();
                },
                error:function (jqXHR, exception) {
                    $('#start_rec').attr("disabled", false);
                    $('#save_picture').attr("disabled", false);
                    $('#request_waiting').hide();
                    after_error();
                }
            });
        }
        else
        {
            $('#start_rec').attr("disabled", false);
            $('#save_picture').attr("disabled", false);
            $('#request_waiting').hide();
            after_error();
        }
    }

    function startRec(from){
        $('#start_rec').attr("disabled", true);
        $('#save_picture').attr("disabled", true);
        $('#request_waiting').show();
        $('#progress_text').html('Загрузка снимков');
        var lang = getUrlParameter('lang');
        var fileList = document.getElementById('file_input').files;
        var formData = new FormData();
        var poll = null;
        var i = 0
        var img_in_params = ''
        if (from == 'source')
            for(i=0;i<fileList.length;i++)
            {
                if (fileList[i].type.includes('image'))
                {
                    formData.append("files", fileList[i]);
                    i += 1;
                }
            }
        if (from == 'webcam')
            $.each($('.endo_image'), function(e) {
                if($(this).data('type') == "blob")
                    formData.append("files", makeblob($(this).attr('src')));
                else
                {
                    formData.append("files", $(this).attr('src'));
                    img_in_params = img_in_params + $(this).data('name') + ','
                }
                i += 1;
            });
        let searchParams = new URLSearchParams(window.location.search)
        force_ear = searchParams.has('force_ear');

        if (i > 0)
        {
            console.log('ajax sending')
            $.ajax({
                type:'POST',
                data: formData,
                url: '/start_skinive_image_diagnostics?patient_id='+$('#patient_id').val()+'&visit_id='+$('#visit_id').val() + '&imgs='+img_in_params + '&force_ear='+force_ear+'&lang=' + lang,
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success: (data) => {
                    $('#photos').empty();
                    $('#imgs_preview').empty();
                    $('#file_input').val(null);
                    $('#pre_load').show();
                    $('#file-input-greenspan').html('');
                    $('#progress_text').html('Распознание диагноза');
                    if(data['status_id'] == 0)
                        poll = setTimeout(function() { check_image_output(data['id']); }, 2500);
                    if(data['status_id'] == 1)
                        poll = setTimeout(function() { check_image_output(data['id']); }, 2500);
                    if(data['status_id'] == 2)
                    {
                        $('#start_rec').attr("disabled", false);
                        $('#save_picture').attr("disabled", false);
                        $('#request_waiting').hide();
                        $('#success').html('Загрузка завершена, снимок доступен в истории')
                        $('#success').slideDown(500);
                        $('#success').delay(2000).slideUp();
                        load__endo_history(true);
                    }
                    if(data['status_id'] == 3) {
                        after_error();
                        $('#request_waiting').hide();
                        $('#start_rec').attr("disabled", false);
                        $('#save_picture').attr("disabled", false);
                    };
                    if (data['status_id'] == 4) {
                        $('#start_rec').attr("disabled", false);
                        $('#save_picture').attr("disabled", false);
                        $('#request_waiting').hide();
                        $('#exception').html('Плохое качество снимка')
                        $('#exception').slideDown(500);
                        $('#exception').delay(2000).slideUp();
                        load__endo_history(true);
                    }
                },
                error:function (jqXHR, exception) {
                    console.log('ajax error')
                    $('#photos').empty();
                    $('#imgs_preview').empty();
                    $('#file_input').val(null);
                    $('#pre_load').show();
                    $('#file-input-greenspan').html('');
                    $('#start_rec').attr("disabled", false);
                    $('#save_picture').attr("disabled", false);
                    $('#request_waiting').hide();
                    after_error();
                }
            });
        }
        else
        {
            $('#start_rec').attr("disabled", false);
            $('#save_picture').attr("disabled", false);
            $('#request_waiting').hide();
            after_error();
        }
    }

    function check_image_output(task_id)
    {
        $.ajax({
            type:'GET',
            url: '/flebo_status/'+task_id,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
//                console.log(data);
                if('status_id' in data){
                    if(data['status_id'] == 0)
                        poll = setTimeout(function() { check_image_output(data['id']); }, 2500);
                    if(data['status_id'] == 1)
                        poll = setTimeout(function() { check_image_output(data['id']); }, 2500);
                    if(data['status_id'] == 2)
                    {
                        $('#start_rec').attr("disabled", false);
                        $('#save_picture').attr("disabled", false);
                        $('#request_waiting').hide();
                        $('#success').html('Загрузка завершена, снимок доступен в истории')
                        $('#success').slideDown(500);
                        $('#success').delay(2000).slideUp();
                        load__endo_history(true);
                    }
                    if(data['status_id'] == 3)
                    {
                        $('#request_waiting').hide();
                        $('#start_rec').attr("disabled", false);
                        $('#save_picture').attr("disabled", false);
                        after_error();
                    }
                }
                else
                {
                    $('#request_waiting').hide();
                    $('#start_rec').attr("disabled", false);
                    $('#save_picture').attr("disabled", false);
                    after_error();
                }
            },
            error:function (jqXHR, exception) {
                $('#request_waiting').hide();
                $('#start_rec').attr("disabled", false);
                $('#save_picture').attr("disabled", false);
                after_error();
            }
        });
    }

    function select_fill(){
        lang = getUrlParameter('lang');
        $.ajax({
            type:'GET',
            url: '/get_diagnos_tags/3'+'?lang='+lang,
            async: false,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                 $.each($('.diagnoses_select.diagnoses_select'), function(e) {
                    console.log($(this).data('img'));
                    for(tag_num in data)
                    {
                        var tag = data[tag_num]
                        if(tag['category_id'] == null && tag['diagnos'] == true)
                        {
                            var icd = ''
                            if (tag['icd'])
                            {
                                icd = tag['icd'] + ' '
                            }
                            $(this).append('<option value="'+tag['id']+'">'+icd+tag['standart_name']+'</option>');
//                            $('#diagnoses_tags').append('<div class="custom-control custom-checkbox my-1 mr-sm-2 checktag"><input type="checkbox" id="tag'+tag['id']
//                            +'" data-name="'+tag['name']+'" class="custom-control-input checkitem"><label for="tag'+tag['id']+'" class="custom-control-label">'+icd+tag['name']+'</label></div>');
                        }

                    }
                });

            },
            error:function (jqXHR, exception) {

            }
        });
    }

    function getRandomInt(max) {
        return Math.floor(Math.random() * Math.floor(max));
    }

    function makeid(length) {
       var result           = '';
       var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
       var charactersLength = characters.length;
       for ( var i = 0; i < length; i++ ) {
          result += characters.charAt(Math.floor(Math.random() * charactersLength));
       }
       return result;
    }

});
