HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/demo-telemedicina.teky.com.co/public/js/clinic_document/core.js
arrayBaseDocumentID = [
  "estado",
  "hospital",
  "usuario_solicitante",
  "finalizado",
  "tipo_documento",
  "documento",
  "nombre1",
  "nombre2",
  "apellido1",
  "apellido2",
  "sexo",
  "fecha_nacimiento",
  "edad",
  "telefono",
  "aseguradora",
  "resumen_telefono",
  "recomendaciones_iniciales",
  "motivo_consulta",
  "enf_actual_lab",
  "examen_fisico",
  "estado_conciencia",
  "t_ar_sist1",
  "t_ar_sist2",
  "f_respiratoria",
  "temperatura",
  "frecuencia_cardiaca",
  "saturacion",
  "analisis_conducta",
  "medico_especialista",
  "btn_fin_tratamiento",
  "btn_analisis_conducta",
  "btn_fin_consulta",
  "bt_record_session",
  "btn-modal-text",
  "text-area-modal",
  "department_id",
  "city_id",
  "country_id",
  "direccion",
  "email",
  "formulacion",
];

function saveDocument(silentInfo) {
  //datos del usuario 1
  if (
    !$("#documento").val() ||
    !$("#nombre1").val() ||
    !$("#apellido1").val() ||
    !$("#sexo").val() ||
    !$("#fecha_nacimiento").val() ||
    !$("#email").val() ||
    !$("#telefono").val() ||
    !$("#barrio").val()
  ) {
    documento = Lang.get("messages.corejs.ID");
    nombre1 = Lang.get("messages.corejs.name");
    apellido1 = Lang.get("messages.corejs.last_name");
    sexo = Lang.get("messages.corejs.sex");
    fecha = Lang.get("messages.corejs.dob");
    email = Lang.get("messages.corejs.email");
    telefono = Lang.get("messages.corejs.telefono");
    barrio = Lang.get("messages.corejs.barrio");
    if ($("#documento").val()) {
      documento = "";
    }
    if ($("#nombre1").val()) {
      nombre1 = "";
    }
    if ($("#apellido1").val()) {
      apellido1 = "";
    }
    if ($("#sexo").val()) {
      sexo = "";
    }
    if ($("#fecha_nacimiento").val()) {
      fecha = "";
    }
    if ($("#email").val()) {
      email = "";
    }
    if ($("#telefono").val()) {
      telefono = "";
    }
    if ($("#barrio").val()) {
      barrio = "";
    }

    swal(
      Lang.get("messages.corejs.error"),
      Lang.get("messages.corejs.please_fill") + documento + nombre1 + apellido1 + sexo + fecha + email + telefono + barrio +Lang.get("messages.corejs.for_continue"),
      "warning"
    );
    return;
  }
  //datos del usuario 2
  if (!$("#direccion").val() || !$("#department_id").val() || !$("#city_id").val()) {
    direccion = Lang.get("messages.corejs.address");
    departamento = Lang.get("messages.corejs.department");
    ciudad = Lang.get("messages.corejs.city");
    if ($("#direccion").val()) {
      direccion = "";
    }
    if ($("#department_id").val()) {
      departamento = "";
    }
    if ($("#city_id").val()) {
      ciudad = "";
    }
    swal(
      Lang.get("messages.corejs.error"),
      Lang.get("messages.corejs.please_fill") + direccion + departamento + ciudad + Lang.get("messages.corejs.for_continue"),
      "warning"
    );
    return;
  }

  rol = JSON.parse(window.localStorage.getItem("rol")).id;

  if (rol == 3) {
    // Analisis y conducta
    diagnosticos = $(".codigo-diagnostics").serializeArray();
    if (diagnosticos.length <= 0) {
      swal("Error", Lang.get("messages.corejs.fill_diagnostics"), "error");
      return;
    }
  }

  var that = this;
  that.disableButtonWhileLoad();
  var obj = {};

  obj = this.getHistoriaJSON(obj);

  if (obj.specific_data && obj.specific_data.isValid == false) {
    swal("Error", obj.specific_data.messages.join("\n"), "error");
    that.enableButtonWhileLoad();
    return;
  }

  var current_id = window.localStorage.getItem("current_id") ? "/" + window.localStorage.getItem("current_id") : "";

  var method = current_id ? "PUT" : "POST";
  if (__currentProposeId) {
    obj.__currentProposeId = __currentProposeId;
  }
  $("#modalLoader").modal("show");
  $.ajax({
    url: "/clinic_document" + current_id ,
    type: method,
    contentType: "application/json",
    headers: {
      "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
      "Content-Type": "application/json",
    },
    data: JSON.stringify(obj),
    success: function (res) {
      if (res.r) {
        $("#modalLoader").modal("hide");
        $("#guest_id").val(res.user_id);
        if (!silentInfo) {
          swal(res.message, "", "success");

          if (method == "POST") {
            $("#id").val(res.id);
            $("#rfast_invoice").val(res.invoice);
            $("#estado").val("Solicitado");
            $("#estado").css("background-color", "#f39c12");
          }
        }
        window.localStorage.setItem("current_id", res.id);
        that.enableButtonWhileLoad();
      } else {
        $("#modalLoader").modal("hide");
        swal(res.message, "", "warning");
        that.enableButtonWhileLoad();
        setTimeout("history.back()", 3000);
      }
    },
    error: function (err) {
      swal("Error al guardar", err.responseJSON.message, "error");
      that.enableButtonWhileLoad();
    },
  });
}

function printDocument() {
  let document_id = window.localStorage.getItem("current_id");
  if (!document_id) {
    swal("", Lang.get("messages.gineco.attacheds.first_save"), "error");
    return;
  }

  $.ajax({
    method: "GET",
    url: "/clinic_document/print/" + document_id,
    success: function (s) {
      window.open(s.url, "_blank");
    },
    error: function (err) {},
  });
}

function getDiagnostics(_obj) {
  column1 = $(".codigo-diagnostics").serializeArray();
  column2 = $(".text-diagnostics").serializeArray();
  var arrayDiagnostics = [];
  for (let i = 0; i < column1.length; i++) {
    var obj = {
      code: column1[i].value,
      description: column2[i].value,
    };
    arrayDiagnostics.push(obj);
  }

  _obj.info_diag = arrayDiagnostics;
  return _obj;
}

function disableButtonWhileLoad() {
  $("#btn-save").prop("disabled", true);
}

function enableButtonWhileLoad() {
  $("#btn-save").prop("disabled", false);
}

function getHistoriaJSON() {
  var dob = $("#fecha_nacimiento").val();
  if (dob) {
    dob = dob.split("/");
    dob = dob[2] + "-" + dob[1] + "-" + dob[0];
  }

  var obj = {
    tipo_solicitud: $("#type_care_id").val(),
    tipo_especialidad: $("#specialty_id").val(),
    hospital: $("#hospital").val(),
    hospital_id: JSON.parse(window.localStorage.getItem("hospital")).id,
    usuario_solicitante: $("#usuario_solicitante").val(),
    finalizado: false,

    event_id: $("#event_id").val(),

    // Paciente
    tipo_documento: $("#tipo_documento").val(),
    documento: $("#documento").val(),
    nombre1: $("#nombre1").val(),
    nombre2: $("#nombre2").val(),
    apellido1: $("#apellido1").val(),
    apellido2: $("#apellido2").val(),
    sexo: $("#sexo").val(),
    fecha_nacimiento: dob,
    edad: $("#edad").val(),
    telefono: $("#telefono").val(),
    aseguradora: $("#aseguradora").val(),
    department_id: $("#department_id").val(),
    city_id: $("#city_id").val(),
    country_id: $("#country_id").val(),
    direccion: $("#direccion").val(),
    barrio: $("#barrio").val(),
    email: $("#email").val(),

    // Datos iniciales
    resumen_telefono: $("#resumen_telefono").val(),
    recomendaciones_iniciales: $("#recomendaciones_iniciales").val(),

    // Datos clinicos generales
    motivo_consulta: $("#motivo_consulta").val(),
    enf_actual_lab: $("#enf_actual_lab").val(),
    examen_fisico: $("#examen_fisico").val(),
    estado_conciencia: $("#estado_conciencia").val(),
    t_ar_sist1: $("#t_ar_sist1").val(),
    t_ar_sist2: $("#t_ar_sist2").val(),
    f_respiratoria: $("#f_respiratoria").val(),
    temperatura: $("#temperatura").val(),
    frecuencia_cardiaca: $("#frecuencia_cardiaca").val(),
    saturacion: $("#saturacion").val(),

    // Analisis y conducta
    analisis_conducta: $("#analisis_conducta").val(),
    formulacion: $("#formulacion").val(),
    medico_especialista: $("#medico_especialista").val(),
  };

  obj = getDiagnostics(obj);
  obj = getSpecificDataHistory(obj);

  return obj;
}

function setValueToXFELD(caseTrue, caseFalse, val) {
  switch (val) {
    case 1:
    case true:
      $("#" + caseFalse).prop("checked", false);
      $("#" + caseTrue).prop("checked", true);
      return true;
      break;
    case 0:
    case false:
      $("#" + caseFalse).prop("checked", true);
      $("#" + caseTrue).prop("checked", false);
      return false;
      break;
    case null:
      $("#" + caseFalse).prop("checked", false);
      $("#" + caseTrue).prop("checked", false);
      return false;
      break;
  }
}

function getValueFromXFELD(caseTrue, caseFalse) {
  if (!$("#" + caseTrue).is(":checked") && !$("#" + caseFalse).is(":checked")) {
    return null;
  }

  if ($("#" + caseTrue).is(":checked") && !$("#" + caseFalse).is(":checked")) {
    return true;
  }

  if (!$("#" + caseTrue).is(":checked") && $("#" + caseFalse).is(":checked")) {
    return false;
  }
}

function getSpecificDataHistory(obj) {
  if (window._SPECIFIC_DATA) {
    obj.specific_data = getValuesSpecificData();
  }
  return obj;
}

function loadProposeDocumentPortal(userInfo){
  userInfo = window.atob(userInfo);
  userInfo = JSON.parse(userInfo);
  $("#modalLoader").modal("show");
  setTimeout(function () {
    $("#modalLoader").modal("hide");

    // User info
    $("#codigo").val("N/A");
    $("#estado").val(Lang.get("messages.document_states.pending"));

    $("state_id").val(1);

    // Paciente
    $("#tipo_documento").val(userInfo.identification_type_id);
    $("#documento").val(userInfo.document);
    $("#telefono").val(userInfo.phone);
    $("#email").val(userInfo.email);
    $("#nombre1").val(userInfo.name);
    $("#apellido1").val(userInfo.last_name);
    $("#sexo").val(userInfo.sex);
    $("#country_id").val(userInfo.city.department.country.id);
    setCity(userInfo.city.department.country.id, userInfo.city.department.id, userInfo.city.id);

    $("#direccion").val(userInfo.address);

    if (userInfo.dob) {
      var d = userInfo.dob;
      d = d.split("-");
      d = d[2] + "/" + d[1] + "/" + d[0];
      $("#fecha_nacimiento").val(d);
    }
    _calculateAge();

    $("#btn-lock").hide();
    window.localStorage.setItem("view", true);
    $(".select2").select2();

  }, 2000);
}

var __currentProposeId = "";
function loadProposeDocument(proposeData, userLogin) {
  proposeData = window.atob(proposeData);
  proposeData = JSON.parse(proposeData);
  __currentProposeId = proposeData.id;

  userLogin = window.atob(userLogin);
  userLogin = JSON.parse(userLogin);

  $("#modalLoader").modal("show");
  setTimeout(function () {
    $("#modalLoader").modal("hide");

    // User info
    $("#codigo").val("N/A");
    $("#estado").val(Lang.get("messages.document_states.pending"));

    $("state_id").val(1);

    // Paciente
    $("#tipo_documento").val(proposeData.user.identification_type_id);
    $("#documento").val(proposeData.user.document);
    $("#email").val(proposeData.user.email);
    $("#nombre1").val(proposeData.user.name);
    $("#apellido1").val(proposeData.user.last_name);
    $("#sexo").val(proposeData.user.sex);
    $("#country_id").val(proposeData.user.city.department.country.id);
    setCity(proposeData.user.city.department.country.id, proposeData.user.city.department.id, proposeData.user.city.id);

    $("#direccion").val(proposeData.user.address);

    if (proposeData.user.dob) {
      var d = proposeData.user.dob;
      d = d.split("-");
      d = d[2] + "/" + d[1] + "/" + d[0];
      $("#fecha_nacimiento").val(d);
    }
    _calculateAge();

    $("#hospital").val(userLogin.centro.name);
    $("#usuario_solicitante").val(userLogin.name + " " + userLogin.last_name);
    $("#telefono").val(proposeData.user.phone);
    $("#resumen_telefono").val(proposeData.summary);

    // especialidad
    let dataToLoad = {
      header_value: proposeData,
    };
    setValuesSpecificData(dataToLoad);

    $("#btn-lock").hide();
    window.localStorage.setItem("view", true);
    $(".select2").select2();
  }, 2000);
}

function loadDocumentGOView(id) {
  // Buscar la historia.
  $.ajax({
    url: "/clinic_document/" + id,
    type: "GET",
    success: function (res) {
      $("#modalLoader").modal("show");
      setTimeout(function () {
        $("#modalLoader").modal("hide");

        loadBaseDocument(res, true);
        loadInfoEspecialidad(res);
        makeViewable();
        $("#btn-save").hide();
        $("#btn-lock").hide();
        window.localStorage.setItem("view", true);
      }, 1000);
    },
    error: function (err) {},
  });
}

function loadDocumentGOEdit(id) {
  // Buscar la historia.
  $.ajax({
    url: "/clinic_document/" + id,
    type: "GET",
    success: function (res) {
      $("#modalLoader").modal("show");
      setTimeout(function () {
        $("#modalLoader").modal("hide");
        console.log(res);
        loadBaseDocument(res, false);
        loadInfoEspecialidad(res);
        window.localStorage.setItem("current_id", res.id);
        window.localStorage.setItem("view", false);
        $("#documento").attr("readonly", true);
        $("#nombre1").attr("readonly", true);
        $("#apellido1").attr("readonly", true);
        $("#email").attr("readonly", true);
        $("#tipo_documento").attr("readonly", true);
      }, 1000);
    },
    error: function (err) {},
  });
}

function recreateLocalStorageQ(res) {
  var obj = {
    type_care_id: res.type_care.id,
    specialty_id: res.specialty.id,
    type_care: res.type_care.name,
    specialty: res.specialty.name,
  };

  obj = JSON.stringify(obj);
  obj = window.btoa(obj);
  window.localStorage.setItem("q", obj);
}

function setCurrentStateDocument(objState) {
  switch (objState.id) {
    case 1:
      $("#estado").val(objState.name);
      $("#estado").css("background-color", "#dd4b39");
      break;
    case 2:
      $("#estado").val(objState.name);
      $("#estado").css("background-color", "#f39c12");
      break;
    case 3:
      $("#estado").val(objState.name);
      $("#estado").css("background-color", "#00a65a");
      break;
    case 4:
      $("#estado").val(objState.name);
      $("#estado").css("background-color", "#pf42c1");
      break;
    case 5:
      $("#estado").val(objState.name);
      $("#estado").css("background-color", "#00c0ef");
      break;
    case 6:
      $("#estado").val(objState.name);
      $("#estado").css("background-color", "#d2d6de");
      break;
  }
}

function setCity(country, d, c) {
  if (!d || !c || !country) return;

  $.ajax({
    url: "/states/get/" + country,
    type: "GET",
    async: false,
    contentType: "application/json",
    headers: {
      "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
      "Content-Type": "application/json",
    },
    success: function (r) {
      if (r[0]["respuesta"]) {
        $("#modalLoader").modal("hide");
        var states = r[0]["states"];

        $("#department_id").empty();
        var sel = '<option value="">-- Seleccione</option>';
        $("#department_id").append(sel);
        for (var i in states) {
          var row = '<option value="' + states[i].id + '">' + states[i].name + "</option>";
          $("#department_id").append(row);
        }
        $("#department_id").val(d);
      } else {
        $("#department_id").empty();
      }
    },
    error: function (err) {
      $("#modalLoader").modal("hide");
    },
  });

  $.ajax({
    url: "/city/get/" + d,
    type: "GET",
    contentType: "application/json",
    headers: {
      "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
      "Content-Type": "application/json",
    },
    success: function (r) {
      if (r[0]["respuesta"]) {
        $("#modalLoader").modal("hide");
        var cities = r[0]["cities"];

        $("#city_id").empty();
        var sel = '<option value="">' + Lang.get("messages.corejs.select");
        +"</option>";
        $("#city_id").append(sel);
        for (var i in cities) {
          var row = '<option value="' + cities[i].id + '">' + cities[i].name + "</option>";
          $("#city_id").append(row);
        }
        $("#city_id").val(c);
      } else {
        $("#city_id").empty();
      }
    },
    error: function (err) {
      $("#modalLoader").modal("hide");
    },
  });
}

function loadBaseDocument(res, isView) {
  var that = this;
  window.localStorage.setItem("current_id", res.id);
  $("#id").val(res.id);
  $("#guest_id").val(res.user_id);
  $("#hospital").val(res.hospital);
  $("#usuario_solicitante").val(res.usuario_solicitante);
  $("#finalizado").val(res.finalizado);

  // User info
  $("#tipo_solicitud").val(res.type_care.name);
  $("#especialidad").val(res.specialty.name);
  $("#codigo").val(res.sap_id ? res.sap_id : "N/A");
  $("#estado").val(res.state.name);
  $("#rfast_invoice").val(res.rfast_invoice);
  $("#medico").val(res.events.medic.medic_code+' - '+res.events.medic.name+' '+res.events.medic.last_name);
  $("#centro_produccion").val(res.events.speciality.code_cp);
  setCurrentStateDocument(res.state);

  $("tipo_especialidad").val(res.specialty.id);
  $("tipo_solicitud").val(res.type_care.id);
  $("state_id").val(res.state.id);

  // Paciente
  $("#tipo_documento").val(res.user.identification_type_id);
  $("#documento").val(res.user.document);
  $("#email").val(res.user.email);
  $("#nombre1").val(res.user.name);
  $("#apellido1").val(res.user.last_name);
  $("#sexo").val(res.user.sex);
  $("#country_id").val(res.user.city.department.country.id);
  setCity(res.user.city.department.country.id, res.user.city.department.id, res.city_id);

  $("#direccion").val(res.user.address);
  $("#barrio").val(res.barrio);

  if (res.user.dob) {
    var d = res.user.dob;
    d = d.split("-");
    d = d[2] + "/" + d[1] + "/" + d[0];
    $("#fecha_nacimiento").val(d);
  }

  $("#edad").val(res.edad);
  $("#telefono").val(res.user.phone);
  $("#aseguradora").val(res.aseguradora);

  // Datos iniciales
  $("#resumen_telefono").val(res.resumen_telefono);
  $("#recomendaciones_iniciales").val(res.recomendaciones_iniciales);

  // Datos clinicos generales
  $("#motivo_consulta").val(res.motivo_consulta);
  $("#enf_actual_lab").val(res.enf_actual_lab);
  $("#examen_fisico").val(res.examen_fisico);
  $("#estado_conciencia").val(res.estado_conciencia);
  $("#t_ar_sist1").val(res.t_ar_sist1);
  $("#t_ar_sist2").val(res.t_ar_sist2);
  $("#f_respiratoria").val(res.f_respiratoria);
  $("#temperatura").val(res.temperatura);
  $("#frecuencia_cardiaca").val(res.frecuencia_cardiaca);
  $("#saturacion").val(res.saturacion);

  // Analisis y conducta
  $("#analisis_conducta").val(res.analisis_conducta);
  $("#formulacion").val(res.formulacion);
  $("#medico_especialista").val(res.medico_especialista);

  // Attacheds
  res.files.forEach(function (e) {
    switch (e.pos) {
      case "1": // Documento de identidad
        $("#file-doc").prop("disabled", true);
        $("#file-doc").css("visibility", "hidden");
        $("#txt-file-doc").show();
        $("#txt-file-doc").text(e.filename);
        $("#up-file-doc").css("visibility", "hidden");
        $("#btn-file-doc").prop("href", `/attachments/${e.id}`);
        if (isView) {
          $("#btn-file-doc").css("visibility", "visible");
        } else {
          $("#btn-file-doc").css("visibility", "visible");
          $("#btn-delete-file-doc").css("visibility", "visible");
          $("#btn-delete-file-doc").attr("data-idFile", e.id);
        }
        break;
      case "2": // Carne de entidad
        $("#file-carne").prop("disabled", true);
        $("#file-carne").css("visibility", "hidden");
        $("#txt-file-carne").show();
        $("#txt-file-carne").text(e.filename);
        $("#up-file-carne").css("visibility", "hidden");
        $("#btn-file-carne").prop("href", `/attachments/${e.id}`);
        if (isView) {
          $("#btn-file-carne").css("visibility", "visible");
        } else {
          $("#btn-delete-file-carne").css("visibility", "visible");
          $("#btn-file-carne").css("visibility", "visible");
          $("#btn-delete-file-carne").attr("data-idFile", e.id);
        }
        break;
      case "3": // Autorizacion de la entidad
        $("#file-autorizacion").prop("disabled", true);
        $("#file-autorizacion").css("visibility", "hidden");
        $("#txt-file-autorizacion").show();
        $("#txt-file-autorizacion").text(e.filename);
        $("#up-file-autorizacion").css("visibility", "hidden");
        $("#btn-file-autorizacion").prop("href", `/attachments/${e.id}`);
        if (isView) {
          $("#btn-file-autorizacion").css("visibility", "visible");
        } else {
          $("#btn-delete-file-autorizacion").css("visibility", "visible");
          $("#btn-file-autorizacion").css("visibility", "visible");
          $("#btn-delete-file-autorizacion").attr("data-idFile", e.id);
        }
        break;
      case "4": // Consentimiento informado.
        $("#file-consentimiento").prop("disabled", true);
        $("#file-consentimiento").css("visibility", "hidden");
        $("#txt-file-consentimiento").show();
        $("#txt-file-consentimiento").text(e.filename);
        $("#up-file-consentimiento").css("visibility", "hidden");
        $("#btn-file-consentimiento").prop("href", `/attachments/${e.id}`);
        if (isView) {
          $("#btn-file-consentimiento").css("visibility", "visible");
        } else {
          $("#btn-delete-file-consentimiento").css("visibility", "visible");
          $("#btn-file-consentimiento").css("visibility", "visible");
          $("#btn-delete-file-consentimiento").attr("data-idFile", e.id);
        }
        break;
      default:
        // Se debe crear una nueva linea y anexar los datos correspondientes.
        that.newRowAttached(e, isView);
    }
  });
  removeFileAnexos();

  // Audios
  let contAudio = 0;
  res.audios.forEach((e) => {
    contAudio++;
    let name = "Session" + contAudio;
    that.newRowAudio(e, name);
  });

  // Diagnostics
  res.diagnostics.forEach(function (e) {
    that.newRowDiagnostics(e, isView, res.state_id);
  });

  // Disable up button
  if (isView) {
    $(".upFile").hide();
    $(".fa-trash").hide();
  }

  if (res.state_id >= 4) {
    setEndTreatment();
  }
}

function newRowAudio(obj, name) {
  var recordingsList = document.getElementById("recording_lists");
  var li = document.createElement("li");
  var link = document.createElement("a");

  link.href = "/clinic_document/get/audio/" + obj.id;
  link.target = "_blank";
  link.innerHTML = name + ".mp3";
  //add the new audio and a elements to the li element
  li.appendChild(link); //add the li element to the ordered list
  recordingsList.appendChild(li);
}

// Fill table attached.
function newRowAttached(obj, b) {
  var readonly = b ? "readonly" : "";
  var td = $("<tr></tr>");
  var sel = "<td><p>" + obj.description + "</p></td>" + "<td><p>" + obj.filename + "</p></td>";

  if (b) {
    sel =
      sel +
      '<a href="/attachments/' +
      obj.id +
      '" id="btn-file_' +
      obj.pos +
      '" target="_blank" ><i class="fa fa-eye iconMini  a-icon" style="cursor:pointer;"></i></a>';
  } else {
    sel =
      sel +
      "<td>" +
      '<a href="/attachments/' +
      obj.id +
      '" id="btn-file_' +
      obj.pos +
      '" target="_blank"><i class="fa fa-eye iconMini a-icon" style="cursor:pointer;"></i></a>' +
      '<a href="#" class="deleteFileAnexo" id="btn-delete-file_' +
      obj.pos +
      '" data-id="file_' +
      obj.pos +
      '" data-idFile="' +
      obj.id +
      '"><i class="fa fa-trash iconMini a-icon" style="cursor:pointer;" ></i></a></td>';
    removeFileAnexos();
  }

  td.data("idx", parseInt(obj.pos));
  td.append(sel);
  $("#tab-attacheds").append(td);
}
// Fill table diagnostics.
function newRowDiagnostics(obj, b, state) {
  var readonly = b ? "readonly" : "";
  var sel =
    " <tr>" +
    '<td><input class="form-control codigo-diagnostics" name="codigo" value="' +
    obj.code +
    '" readonly></td> ' +
    '<td><input class="form-control text-diagnostics" name="text" value="<des>" readonly></td>';
  if (!b && state < 4) {
    sel =
      sel +
      '<td><a href="#" onclick="deleteAnexo(this)"><i class="fa fa-trash iconMini a-icon analysis-trash" style="cursor:pointer;" ></i></a></td></tr>';
  }

  findDiagnostic(obj.code, sel);
}

function findDiagnostic(code, sel) {
  $.ajax({
    url: "/diagnostic/description/" + code,
    type: "GET",
    headers: {
      "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
      "Content-Type": "application/json",
    },
    success: function (res) {
      sel = sel.replace("<des>", res.description);
      $("#tab-analysis").append(sel);
    },
    error: function (err) {},
  });
}

// Fill table fcf.
function newRowFCF(obj, b) {
  var readonly = b ? "readonly" : "";
  var index = 1;

  var sel =
    "<tr>" +
    '<td style="display:flex; align-items: center;justify-content: center;">' +
    index +
    "</td>" +
    '<td><input class="form-control fcf-especific-data" name="fcf" value="' +
    obj.fcf +
    '"' +
    readonly +
    "></td>" +
    '<td><input class="form-control observation-especific-data" id="observaciones_feto' +
    obj.id +
    '"  name="observation" value="' +
    obj.description +
    '"' +
    readonly +
    '></td> <td>  <i class="fa fa-search-plus iconMini verInfoFeto" style="cursor:pointer; font-size:20px;" title="Ampliar info" data-toggle="modal" data-target="#enlarge-text" data-id="observaciones_feto' +
    obj.id +
    '"></i></td> </tr>';
  $("#tab-specific").append(sel);

  index++;
}

function loadInfoEspecialidad(obj) {
  setValuesSpecificData(obj);
}

function makeViewable() {
  // base document
  arrayBaseDocumentID.forEach((e) => {
    $("#" + e).prop("disabled", true);
  });

  let formControls = JSON.parse(window.atob(window.__DYNAMIC_FORM));
  formControls.fields.forEach((e) => {
    $("#" + e.name_control).attr("disabled", true);
  });
}

function _calculateAge() {
  if ($("#fecha_nacimiento").val()) {
    var dob = $("#fecha_nacimiento").val().split("/");
    var DOB = new Date(dob[2], dob[1] - 1, dob[0]);
    var today = new Date();
    var age = today.getTime() - DOB.getTime();
    var elapsed = new Date(age);
    var year = elapsed.getYear() - 70;
    var month = Math.abs(elapsed.getMonth());
    var day = elapsed.getDay();
    var ageTotal = Lang.get("messages.age") + " " + year + " " + Lang.get("messages.years") + " " + month + " " + Lang.get("messages.months");

    $("#edad").val(ageTotal);
  } else {
    $("#edad").val("");
  }
}

function setEndTreatment() {
  $("#analisis_conducta").prop("readonly", true);
  $("#formulacion").prop("readonly", true);
  $("#add-analysis").prop("disabled", true);
  $(".analysis-trash").hide();
  $("#btn_fin_tratamiento").prop("disabled", true);
  $("#btn_analisis_conducta").prop("disabled", true);
}

setTimeout(function () {
  $(".select2").select2();
}, 2000);