<?php
// --- INICIO BLOQUE PHP AÑADIDO ---
session_start(); // Iniciar sesión al principio

// 1. Verificación de sesión y obtención del rol
if (!isset($_SESSION['Inicio']) || $_SESSION['Inicio'] !== "Ok" || !isset($_SESSION['Rol'])) {
    header("Location: ../login.php?m=5"); 
    exit;
}

// 2. Determinar la URL del menú basada en el rol
$urlMenuCorrespondiente = ""; 
switch ($_SESSION['Rol']) {
    case "Administrativo":
        $urlMenuCorrespondiente = "../MenuAdministrativo.php";
        break;
    case "Titular":
        $urlMenuCorrespondiente = "../MenuTitular.php";
        break;
    case "Pasante":
        $urlMenuCorrespondiente = "../MenuPasante.php";
        break;
    default:
        header("Location: ../login.php?m=6"); 
        exit;
}
// --- FIN BLOQUE PHP AÑADIDO ---

$clave_paciente = isset($_GET['clave_paciente']) ? htmlspecialchars($_GET['clave_paciente']) : '';
$codigo_paciente = isset($_GET['codigo_paciente']) ? htmlspecialchars($_GET['codigo_paciente']) : '';
$nombre_paciente = isset($_GET['nombre_paciente']) ? htmlspecialchars($_GET['nombre_paciente']) : '';
$apellido_paterno_paciente = isset($_GET['apellido_paterno_paciente']) ? htmlspecialchars($_GET['apellido_paterno_paciente']) : '';
$apellido_materno_paciente = isset($_GET['apellido_materno_paciente']) ? htmlspecialchars($_GET['apellido_materno_paciente']) : '';
$fecha_nacimiento_paciente = isset($_GET['fecha_nacimiento_paciente']) ? htmlspecialchars($_GET['fecha_nacimiento_paciente']) : '';
$sexo_paciente = isset($_GET['sexo_paciente']) ? htmlspecialchars($_GET['sexo_paciente']) : '';
$semanas_gestacion = isset($_GET['semanas_gestacion']) ? htmlspecialchars($_GET['semanas_gestacion']) : ''; 
?>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Montserrat:wght@700&display=swap" rel="stylesheet">
    <link rel="icon" type="image/png" href="./img/UNAM amarillo.png"> 
    <link rel="stylesheet" type="text/css" href="../Css/EstilosUpdateWi.css">
    <title>PLS-5</title>
    <style>
        .is-invalid { border-color: red !important; }
.auto-filled { background-color: #e9ecef; cursor: not-allowed; }

/* --- AÑADE ESTAS CLASES --- */
.header-section { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px solid #f0f0f0; }
.main-tittle { margin: 0; padding: 0; border: none; }
.btn-salir { white-space: nowrap; padding: 8px 20px; flex-shrink: 0; font-size: 0.9rem; }
.hidden { display: none; }
.age-fields-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 1rem; align-items: flex-end; /* Añadido para alinear mejor */ }.edad-activa { background-color: #e0e8f0; border-color: #0056b3; box-shadow: 0 0 5px rgba(0, 86, 179, 0.3); }
.instruccion-evaluacion { font-size: 0.9em; color: #555; background-color: #f8f9fa; padding: 10px; border-left: 4px solid #007bff; margin-top: 0; margin-bottom: 15px; border-radius: 0 4px 4px 0; }
.instruccion-evaluacion strong { color: #0056b3; }
.input-box-fullwidth { grid-column: span 2; }
.baremo-container { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }

    </style>
</head>
<body>
    <div class="container">
    <div class="header-section"> <!-- Contenedor nuevo -->
        <h1 class="main-tittle"> PLS-5 </h1>
        <a href="CPLS.php" class="btn-salir">Volver a la lista</a> 
        </div>
<form method="POST" action="IPLS.php" id="myForm">

<div class="form-section">
    <h2 class="section-tittle">Datos Personales del Paciente</h2>
    <div class="input-grid">
        <!-- Campos ocultos para los cálculos -->
        <input type="hidden" name="clave_paciente" value="<?php echo $clave_paciente; ?>">
        <input type="hidden" id="semanas_gestacion_hidden" value="<?php echo $semanas_gestacion; ?>">

        <div class="input-box"><label>Código</label><input type="text" value="<?php echo $codigo_paciente; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>Nombre</label><input type="text" value="<?php echo $nombre_paciente; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>A. Paterno</label><input type="text" value="<?php echo $apellido_paterno_paciente; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>A. Materno</label><input type="text" value="<?php echo $apellido_materno_paciente; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>F. Nacimiento</label><input type="date" id="fecha_nacimiento_paciente" value="<?php echo $fecha_nacimiento_paciente; ?>" readonly class="auto-filled"></div>
        <div class="input-box"><label>Semanas Gestación</label><input type="text" value="<?php echo $semanas_gestacion; ?>" readonly class="auto-filled"></div>
    </div>

    <h2 class="section-tittle" style="margin-top: 20px;">Datos de Evaluación</h2>
    <p class="instruccion-evaluacion">
        <strong>Instrucción:</strong> Elige la fecha de evaluación para calcular las edades y activar el formulario.
    </p>
    <div class="age-fields-grid">
    <div class="input-box">
        <label>Fecha de Evaluación</label>
        <input type="date" class="input-field" id="fecha_evaluacion" name="fecha_evaluacion" required>
    </div>
    <div class="input-box">
        <label>Edad Cronológica</label>
        <input type="text" class="input-field" placeholder="Seleccione fechas" id="edad" name="edad" readonly>
    </div>
    <div class="input-box">
        <label>Edad Corregida</label>
        <input type="text" class="input-field" placeholder="Cálculo automático" id="edad_corregida" name="edad_corregida" readonly>
    </div>
    <div class="input-box">
        <label>Condición</label>
        <input type="text" id="condicion_paciente" value="" readonly>
    </div>
    <div class="baremo-container input-box-fullwidth">
        <div class="input-box">
            <label>Baremo de Edad Utilizado</label>
            <input type="text" id="rango_edad" name="rango_edad" readonly class="input-field">
        </div>
        <div class="input-box">
            <!-- La etiqueta se oculta si el select está oculto -->
            <label id="baremo_manual_label" class="hidden">&nbsp;</label>
            <select id="baremo_manual_select" class="input-field hidden">
                <option value="0">Seleccione baremo</option>
                <!-- Opciones generadas por JS -->
            </select>
        </div>
    </div>
</div>

    <!-- Sección 2: Comprensión Auditiva -->
    <div class="form-section">
        <h2 class="section-tittle">Comprensión Auditiva</h2>
        <div class="input-grid">
            <div class="input-box">
                <label for="comp_audi_punt_bruta">Puntuación Bruta</label>
                <input type="text" autocomplete="off" placeholder="Puntuación" id="comp_audi_punt_bruta" name="comp_audi_punt_bruta" class="input-field" required>
            </div>
            <div class="input-box">
                <label for="compren_audit_punt_stand">Puntuación Estándar</label>
                <input type="text" autocomplete="off" placeholder="Se genera automáticamente / Ingreso manual" id="compren_audit_punt_stand" name="compren_audit_punt_stand" class="input-field" required>
            </div>
            <div class="input-box">
                <label for="compre_audit_rango_percent">Rango Percentil</label>
                <input type="text" autocomplete="off" placeholder="Se genera automáticamente / Ingreso manual" id="compre_audit_rango_percent" name="compre_audit_rango_percent" class="input-field" required>
            </div>
        </div>
        <div class="input-box input-box-fullwidth">
            <label for="comp_audit_interpre">Interpretación</label>
            <textarea id="comp_audit_interpre" name="comp_audit_interpre" rows="3" class="input-field" required></textarea>
            <select id="comp_audit_interpre_select" name="comp_audit_interpre" class="input-field" style="display: none;" required></select>
        </div>
    </div>

    <!-- Sección 3: Comunicación Expresiva -->
    <div class="form-section">
        <h2 class="section-tittle">Comunicación Expresiva</h2>
         <div class="input-grid">
            <div class="input-box">
                <label for="expre_comuni_puntua_bruta">Puntuación Bruta</label>
                <input type="text" autocomplete="off" placeholder="Puntuación" id="expre_comuni_puntua_bruta" name="expre_comuni_puntua_bruta" class="input-field" required>
            </div>
            <div class="input-box">
                <label for="expr_comun_punt_estandar">Puntuación Estándar</label>
                <input type="text" autocomplete="off" placeholder="Se genera automáticamente / Ingreso manual" id="expr_comun_punt_estandar" name="expr_comun_punt_estandar" class="input-field" required>
            </div>
            <div class="input-box">
                <label for="expr_comunic_rango_percent">Rango Percentil</label>
                <input type="text" autocomplete="off" placeholder="Se genera automáticamente / Ingreso manual" id="expr_comunic_rango_percent" name="expr_comunic_rango_percent" class="input-field" required>
            </div>
         </div>
         <div class="input-box input-box-fullwidth">
            <label for="expr_comunic_interpret">Interpretación</label>
            <textarea id="expr_comunic_interpret" name="expr_comunic_interpret" rows="3" class="input-field" required></textarea>
            <select id="expr_comunic_interpret_select" name="expr_comunic_interpret" class="input-field" style="display: none;" required></select>
        </div>
    </div>

    <!-- Sección 4: Lenguaje Total -->
         <div class="form-section">
        <h2 class="section-tittle">Lenguaje Total</h2>
         <div class="input-grid">
            <div class="input-box">
                <label for="leng_tota_punt_bruta">Puntuación Bruta (Suma P. Bruta CA+CE)</label> 
                <input type="text" autocomplete="off" placeholder="Suma de P. Brutas" id="leng_tota_punt_bruta" name="leng_tota_punt_bruta" class="input-field">
            </div>
            <div class="input-box">
                <label for="leng_tota_punt_standa_sum">Puntuación Estándar (Suma P. Estándar CA+CE)</label> 
                <input type="text" autocomplete="off" placeholder="Suma de P. Estándar" id="leng_tota_punt_standa_sum" name="leng_tota_punt_standa_sum" class="input-field">
            </div>

            <div class="input-box">
                <label for="leng_tota_punt_standa">Puntuación Estándar</label>
                <input type="text" autocomplete="off" placeholder="Se genera automáticamente / Ingreso manual" id="leng_tota_punt_standa" name="leng_tota_punt_standa" class="input-field" required>
            </div>
            <div class="input-box">
                <label for="leng_tota_rang_percent">Rango Percentil</label>
                <input type="text" autocomplete="off" placeholder="Se genera automáticamente / Ingreso manual" id="leng_tota_rang_percent" name="leng_tota_rang_percent" class="input-field" required>
            </div>
         </div>
         <div class="input-box input-box-fullwidth">
            <label for="lengua_tot_interpret">Interpretación</label>
            <textarea id="lengua_tot_interpret" name="lengua_tot_interpret" rows="3" class="input-field" required></textarea>
            <select id="lengua_tot_interpret_select" name="lengua_tot_interpret" class="input-field" style="display: none;" required></select>
        </div>
    </div>

    <!-- Sección 5: Datos Clínicos -->
    <div class="form-section">
        <h2 class="section-tittle">Datos Clínicos</h2>
         <div class="input-grid">
            <div class="input-box">
    <label for="dato_clini_referir_terapia">Referir a Terapia</label>
    <select class="input-field" id="dato_clini_referir_terapia" name="dato_clini_referir_terapia">
        <option value="No">No</option>
        <option value="Si">Sí</option>
        <option value="Habla">Habla</option>
        <option value="Lenguaje">Lenguaje</option>
        <option value="Ambas">Ambas</option>
    </select>
</div>
            <div class="input-box input-box-fullwidth">
                <label for="datos_clini_observ_clini">Observaciones Clínicas</label>
                <textarea id="datos_clini_observ_clini" name="datos_clini_observ_clini" rows="3" class="input-field"></textarea>
            </div>
            <div class="input-box input-box-fullwidth">
                <label for="dat_clini_otra_observa">Otras Observaciones</label>
                <textarea id="dat_clini_otra_observa" name="dat_clini_otra_observa" rows="3" class="input-field"></textarea>
            </div>
         </div>
    </div>

    <input type="submit" class="btn-submit" value="Registrar" id="registrar">

</form>

<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="../Jquery/jquery-3.6.0.min.js"></script>
<script>
   function setupFieldValidation(selector, regex) {
    document.querySelectorAll(selector).forEach(input => {
        // Guardar el valor inicial por si acaso
        input.setAttribute('data-prev-value', input.value);

        // Valida caracteres mientras se escribe (silencioso)
        input.addEventListener('input', e => {
            if (e.target.readOnly) return;
            let valor = e.target.value;
            if (!regex.test(valor)) {
                e.target.value = e.target.getAttribute('data-prev-value') || '';
            }
            e.target.setAttribute('data-prev-value', e.target.value);
        });

        // Valida el valor máximo al salir del campo (con alerta)
        input.addEventListener('blur', e => {
            // Obtener el maxValue dinámicamente desde un atributo del input
            const maxValue = parseInt(e.target.getAttribute('data-max-value'), 10);
            const valor = e.target.value;

            // Si no hay maxValue, o el campo está vacío/NA, no hacemos nada
            if (isNaN(maxValue) || valor === '' || valor.toUpperCase() === 'NA') return;

            const numValue = parseInt(valor, 10);

            if (!isNaN(numValue) && numValue > maxValue) {
                const labelText = e.target.labels[0]?.textContent || 'este campo';
                Swal.fire({
                    icon: 'error',
                    title: 'Valor fuera de rango',
                    text: `El puntaje para "${labelText}" no puede ser mayor a ${maxValue} para este rango de edad.`
                }).then(() => {
                    e.target.value = '';
                    e.target.focus();
                });
            }
        });
    });
}
    // --- TABLAS DE DATOS (SIN CAMBIOS) ---
 const pls5AgeTables = [
        {
            ageRange: '0:3-0:5', minAgeMonths: 3, maxAgeMonths: 5,
            caScores: [ { rawScore: "0-1", standardScore: 50, percentileRank: 1 },{ rawScore: 2, standardScore: 54, percentileRank: 1 },{ rawScore: 3, standardScore: 61, percentileRank: 1 },{ rawScore: 4, standardScore: 69, percentileRank: 2 },{ rawScore: 5, standardScore: 76, percentileRank: 5 },{ rawScore: 6, standardScore: 83, percentileRank: 13 },{ rawScore: 7, standardScore: 90, percentileRank: 25 },{ rawScore: 8, standardScore: 96, percentileRank: 39 },{ rawScore: 9, standardScore: 102, percentileRank: 55 },{ rawScore: 10, standardScore: 109, percentileRank: 73 },{ rawScore: 11, standardScore: 115, percentileRank: 84 },{ rawScore: 12, standardScore: 121, percentileRank: 92 },{ rawScore: 13, standardScore: 127, percentileRank: 96 },{ rawScore: 14, standardScore: 133, percentileRank: 99 },{ rawScore: 15, standardScore: 139, percentileRank: 99 },{ rawScore: 16, standardScore: 145, percentileRank: 99 },{ rawScore: "17-67", standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-1", standardScore: 50, percentileRank: 1 },{ rawScore: 2, standardScore: 58, percentileRank: 1 },{ rawScore: 3, standardScore: 65, percentileRank: 1 },{ rawScore: 4, standardScore: 71, percentileRank: 3 },{ rawScore: 5, standardScore: 78, percentileRank: 7 },{ rawScore: 6, standardScore: 84, percentileRank: 14 },{ rawScore: 7, standardScore: 90, percentileRank: 25 },{ rawScore: 8, standardScore: 96, percentileRank: 39 },{ rawScore: 9, standardScore: 103, percentileRank: 58 },{ rawScore: 10, standardScore: 109, percentileRank: 73 },{ rawScore: 11, standardScore: 114, percentileRank: 82 },{ rawScore: 12, standardScore: 119, percentileRank: 90 },{ rawScore: 13, standardScore: 125, percentileRank: 95 },{ rawScore: 14, standardScore: 130, percentileRank: 98 },{ rawScore: 15, standardScore: 135, percentileRank: 99 },{ rawScore: 16, standardScore: 140, percentileRank: 99 },{ rawScore: 17, standardScore: 145, percentileRank: 99 },{ rawScore: 18, standardScore: 148, percentileRank: 99 },{ rawScore: "19-60", standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '0:6-0:8', minAgeMonths: 6, maxAgeMonths: 8,
            caScores: [ { rawScore: "0-3", standardScore: 50, percentileRank: 1 },{ rawScore: 4, standardScore: 53, percentileRank: 1 },{ rawScore: 5, standardScore: 59, percentileRank: 1 },{ rawScore: 6, standardScore: 66, percentileRank: 1 },{ rawScore: 7, standardScore: 72, percentileRank: 3 },{ rawScore: 8, standardScore: 77, percentileRank: 6 },{ rawScore: 9, standardScore: 83, percentileRank: 13 },{ rawScore: 10, standardScore: 89, percentileRank: 23 },{ rawScore: 11, standardScore: 94, percentileRank: 34 },{ rawScore: 12, standardScore: 100, percentileRank: 50 },{ rawScore: 13, standardScore: 106, percentileRank: 66 },{ rawScore: 14, standardScore: 111, percentileRank: 77 },{ rawScore: 15, standardScore: 116, percentileRank: 86 },{ rawScore: 16, standardScore: 122, percentileRank: 93 },{ rawScore: 17, standardScore: 127, percentileRank: 96 },{ rawScore: 18, standardScore: 132, percentileRank: 98 },{ rawScore: 19, standardScore: 137, percentileRank: 99 },{ rawScore: 20, standardScore: 141, percentileRank: 99 },{ rawScore: 21, standardScore: 146, percentileRank: 99 },{ rawScore: "22-67", standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-3", standardScore: 50, percentileRank: 1 },{ rawScore: 4, standardScore: 55, percentileRank: 1 },{ rawScore: 5, standardScore: 61, percentileRank: 1 },{ rawScore: 6, standardScore: 67, percentileRank: 1 },{ rawScore: 7, standardScore: 72, percentileRank: 3 },{ rawScore: 8, standardScore: 78, percentileRank: 7 },{ rawScore: 9, standardScore: 84, percentileRank: 14 },{ rawScore: 10, standardScore: 89, percentileRank: 23 },{ rawScore: 11, standardScore: 94, percentileRank: 34 },{ rawScore: 12, standardScore: 99, percentileRank: 47 },{ rawScore: 13, standardScore: 105, percentileRank: 63 },{ rawScore: 14, standardScore: 110, percentileRank: 75 },{ rawScore: 15, standardScore: 115, percentileRank: 84 },{ rawScore: 16, standardScore: 121, percentileRank: 92 },{ rawScore: 17, standardScore: 126, percentileRank: 96 },{ rawScore: 18, standardScore: 131, percentileRank: 98 },{ rawScore: 19, standardScore: 137, percentileRank: 99 },{ rawScore: 20, standardScore: 142, percentileRank: 99 },{ rawScore: 21, standardScore: 146, percentileRank: 99 },{ rawScore: 22, standardScore: 149, percentileRank: 99 },{ rawScore: "23-60", standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '0:9-0:11', minAgeMonths: 9, maxAgeMonths: 11,
            caScores: [ { rawScore: "0-5", standardScore: 50, percentileRank: 1 },{ rawScore: 6, standardScore: 53, percentileRank: 1 },{ rawScore: 7, standardScore: 59, percentileRank: 1 },{ rawScore: 8, standardScore: 64, percentileRank: 1 },{ rawScore: 9, standardScore: 69, percentileRank: 2 },{ rawScore: 10, standardScore: 75, percentileRank: 5 },{ rawScore: 11, standardScore: 80, percentileRank: 9 },{ rawScore: 12, standardScore: 85, percentileRank: 16 },{ rawScore: 13, standardScore: 90, percentileRank: 25 },{ rawScore: 14, standardScore: 94, percentileRank: 34 },{ rawScore: 15, standardScore: 99, percentileRank: 47 },{ rawScore: 16, standardScore: 105, percentileRank: 63 },{ rawScore: 17, standardScore: 108, percentileRank: 70 },{ rawScore: 18, standardScore: 113, percentileRank: 81 },{ rawScore: 19, standardScore: 117, percentileRank: 87 },{ rawScore: 20, standardScore: 122, percentileRank: 93 },{ rawScore: 21, standardScore: 126, percentileRank: 96 },{ rawScore: 22, standardScore: 130, percentileRank: 98 },{ rawScore: 23, standardScore: 135, percentileRank: 99 },{ rawScore: 24, standardScore: 139, percentileRank: 99 },{ rawScore: 25, standardScore: 143, percentileRank: 99 },{ rawScore: 26, standardScore: 147, percentileRank: 99 },{ rawScore: "27-67", standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-5", standardScore: 50, percentileRank: 1 },{ rawScore: 6, standardScore: 53, percentileRank: 1 },{ rawScore: 7, standardScore: 57, percentileRank: 1 },{ rawScore: 8, standardScore: 61, percentileRank: 1 },{ rawScore: 9, standardScore: 66, percentileRank: 1 },{ rawScore: 10, standardScore: 71, percentileRank: 3 },{ rawScore: 11, standardScore: 76, percentileRank: 5 },{ rawScore: 12, standardScore: 82, percentileRank: 12 },{ rawScore: 13, standardScore: 87, percentileRank: 19 },{ rawScore: 14, standardScore: 92, percentileRank: 30 },{ rawScore: 15, standardScore: 97, percentileRank: 42 },{ rawScore: 16, standardScore: 102, percentileRank: 55 },{ rawScore: 17, standardScore: 107, percentileRank: 68 },{ rawScore: 18, standardScore: 112, percentileRank: 79 },{ rawScore: 19, standardScore: 117, percentileRank: 87 },{ rawScore: 20, standardScore: 123, percentileRank: 94 },{ rawScore: 21, standardScore: 128, percentileRank: 97 },{ rawScore: 22, standardScore: 133, percentileRank: 99 },{ rawScore: 23, standardScore: 138, percentileRank: 99 },{ rawScore: 24, standardScore: 143, percentileRank: 99 },{ rawScore: 25, standardScore: 147, percentileRank: 99 },{ rawScore: "26-60", standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '1:0-1:5', minAgeMonths: 12, maxAgeMonths: 17,
            caScores: [ { rawScore: "0-8", standardScore: 50, percentileRank: 1 },{ rawScore: 9, standardScore: 54, percentileRank: 1 },{ rawScore: 10, standardScore: 58, percentileRank: 1 },{ rawScore: 11, standardScore: 63, percentileRank: 1 },{ rawScore: 12, standardScore: 67, percentileRank: 1 },{ rawScore: 13, standardScore: 72, percentileRank: 3 },{ rawScore: 14, standardScore: 76, percentileRank: 5 },{ rawScore: 15, standardScore: 81, percentileRank: 10 },{ rawScore: 16, standardScore: 85, percentileRank: 16 },{ rawScore: 17, standardScore: 89, percentileRank: 23 },{ rawScore: 18, standardScore: 93, percentileRank: 32 },{ rawScore: 19, standardScore: 97, percentileRank: 42 },{ rawScore: 20, standardScore: 101, percentileRank: 53 },{ rawScore: 21, standardScore: 105, percentileRank: 63 },{ rawScore: 22, standardScore: 109, percentileRank: 73 },{ rawScore: 23, standardScore: 113, percentileRank: 81 },{ rawScore: 24, standardScore: 116, percentileRank: 86 },{ rawScore: 25, standardScore: 120, percentileRank: 91 },{ rawScore: 26, standardScore: 124, percentileRank: 95 },{ rawScore: 27, standardScore: 128, percentileRank: 97 },{ rawScore: 28, standardScore: 131, percentileRank: 98 },{ rawScore: 29, standardScore: 135, percentileRank: 99 },{ rawScore: 30, standardScore: 139, percentileRank: 99 },{ rawScore: 31, standardScore: 142, percentileRank: 99 },{ rawScore: 32, standardScore: 146, percentileRank: 99 },{ rawScore: 33, standardScore: 149, percentileRank: 99 },{ rawScore: "34-67", standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-8", standardScore: 50, percentileRank: 1 },{ rawScore: 9, standardScore: 52, percentileRank: 1 },{ rawScore: 10, standardScore: 56, percentileRank: 1 },{ rawScore: 11, standardScore: 60, percentileRank: 1 },{ rawScore: 12, standardScore: 64, percentileRank: 1 },{ rawScore: 13, standardScore: 68, percentileRank: 2 },{ rawScore: 14, standardScore: 73, percentileRank: 4 },{ rawScore: 15, standardScore: 77, percentileRank: 6 },{ rawScore: 16, standardScore: 82, percentileRank: 12 },{ rawScore: 17, standardScore: 87, percentileRank: 19 },{ rawScore: 18, standardScore: 92, percentileRank: 30 },{ rawScore: 19, standardScore: 97, percentileRank: 42 },{ rawScore: 20, standardScore: 102, percentileRank: 55 },{ rawScore: 21, standardScore: 107, percentileRank: 68 },{ rawScore: 22, standardScore: 112, percentileRank: 79 },{ rawScore: 23, standardScore: 117, percentileRank: 87 },{ rawScore: 24, standardScore: 121, percentileRank: 92 },{ rawScore: 25, standardScore: 127, percentileRank: 96 },{ rawScore: 26, standardScore: 132, percentileRank: 98 },{ rawScore: 27, standardScore: 137, percentileRank: 99 },{ rawScore: 28, standardScore: 142, percentileRank: 99 },{ rawScore: 29, standardScore: 146, percentileRank: 99 },{ rawScore: "30-60", standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '1:6-1:11', minAgeMonths: 18, maxAgeMonths: 23,
            caScores: [ { rawScore: "0-11", standardScore: 50, percentileRank: 1 },{ rawScore: 12, standardScore: 54, percentileRank: 1 },{ rawScore: 13, standardScore: 58, percentileRank: 1 },{ rawScore: 14, standardScore: 62, percentileRank: 1 },{ rawScore: 15, standardScore: 66, percentileRank: 1 },{ rawScore: 16, standardScore: 71, percentileRank: 3 },{ rawScore: 17, standardScore: 75, percentileRank: 5 },{ rawScore: 18, standardScore: 78, percentileRank: 7 },{ rawScore: 19, standardScore: 82, percentileRank: 12 },{ rawScore: 20, standardScore: 85, percentileRank: 16 },{ rawScore: 21, standardScore: 89, percentileRank: 23 },{ rawScore: 22, standardScore: 92, percentileRank: 30 },{ rawScore: 23, standardScore: 95, percentileRank: 37 },{ rawScore: 24, standardScore: 98, percentileRank: 45 },{ rawScore: 25, standardScore: 101, percentileRank: 53 },{ rawScore: 26, standardScore: 104, percentileRank: 61 },{ rawScore: 27, standardScore: 107, percentileRank: 68 },{ rawScore: 28, standardScore: 111, percentileRank: 77 },{ rawScore: 29, standardScore: 114, percentileRank: 82 },{ rawScore: 30, standardScore: 117, percentileRank: 87 },{ rawScore: 31, standardScore: 120, percentileRank: 91 },{ rawScore: 32, standardScore: 124, percentileRank: 95 },{ rawScore: 33, standardScore: 127, percentileRank: 96 },{ rawScore: 34, standardScore: 130, percentileRank: 98 },{ rawScore: 35, standardScore: 133, percentileRank: 99 },{ rawScore: 36, standardScore: 136, percentileRank: 99 },{ rawScore: 37, standardScore: 139, percentileRank: 99 },{ rawScore: 38, standardScore: 142, percentileRank: 99 },{ rawScore: 39, standardScore: 145, percentileRank: 99 },{ rawScore: 40, standardScore: 148, percentileRank: 99 },{ rawScore: "41-67", standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-11", standardScore: 50, percentileRank: 1 },{ rawScore: 12, standardScore: 54, percentileRank: 1 },{ rawScore: 13, standardScore: 58, percentileRank: 1 },{ rawScore: 14, standardScore: 62, percentileRank: 1 },{ rawScore: 15, standardScore: 66, percentileRank: 1 },{ rawScore: 16, standardScore: 70, percentileRank: 2 },{ rawScore: 17, standardScore: 74, percentileRank: 4 },{ rawScore: 18, standardScore: 78, percentileRank: 7 },{ rawScore: 19, standardScore: 82, percentileRank: 12 },{ rawScore: 20, standardScore: 87, percentileRank: 19 },{ rawScore: 21, standardScore: 91, percentileRank: 27 },{ rawScore: 22, standardScore: 96, percentileRank: 39 },{ rawScore: 23, standardScore: 101, percentileRank: 53 },{ rawScore: 24, standardScore: 105, percentileRank: 63 },{ rawScore: 25, standardScore: 110, percentileRank: 75 },{ rawScore: 26, standardScore: 114, percentileRank: 82 },{ rawScore: 27, standardScore: 119, percentileRank: 90 },{ rawScore: 28, standardScore: 124, percentileRank: 95 },{ rawScore: 29, standardScore: 129, percentileRank: 97 },{ rawScore: 30, standardScore: 134, percentileRank: 99 },{ rawScore: 31, standardScore: 139, percentileRank: 99 },{ rawScore: 32, standardScore: 144, percentileRank: 99 },{ rawScore: 33, standardScore: 148, percentileRank: 99 },{ rawScore: "34-60", standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '2:0-2:5', minAgeMonths: 24, maxAgeMonths: 29,
            caScores: [ { rawScore: "0-15", standardScore: 50, percentileRank: 1 },{ rawScore: 16, standardScore: 54, percentileRank: 1 },{ rawScore: 17, standardScore: 58, percentileRank: 1 },{ rawScore: 18, standardScore: 61, percentileRank: 1 },{ rawScore: 19, standardScore: 65, percentileRank: 1 },{ rawScore: 20, standardScore: 69, percentileRank: 2 },{ rawScore: 21, standardScore: 73, percentileRank: 4 },{ rawScore: 22, standardScore: 76, percentileRank: 5 },{ rawScore: 23, standardScore: 79, percentileRank: 8 },{ rawScore: 24, standardScore: 82, percentileRank: 12 },{ rawScore: 25, standardScore: 85, percentileRank: 16 },{ rawScore: 26, standardScore: 88, percentileRank: 21 },{ rawScore: 27, standardScore: 91, percentileRank: 27 },{ rawScore: 28, standardScore: 94, percentileRank: 34 },{ rawScore: 29, standardScore: 97, percentileRank: 42 },{ rawScore: 30, standardScore: 100, percentileRank: 50 },{ rawScore: 31, standardScore: 102, percentileRank: 55 },{ rawScore: 32, standardScore: 105, percentileRank: 63 },{ rawScore: 33, standardScore: 108, percentileRank: 70 },{ rawScore: 34, standardScore: 111, percentileRank: 77 },{ rawScore: 35, standardScore: 114, percentileRank: 82 },{ rawScore: 36, standardScore: 117, percentileRank: 87 },{ rawScore: 37, standardScore: 119, percentileRank: 90 },{ rawScore: 38, standardScore: 122, percentileRank: 93 },{ rawScore: 39, standardScore: 125, percentileRank: 95 },{ rawScore: 40, standardScore: 128, percentileRank: 97 },{ rawScore: 41, standardScore: 131, percentileRank: 98 },{ rawScore: 42, standardScore: 134, percentileRank: 99 },{ rawScore: 43, standardScore: 136, percentileRank: 99 },{ rawScore: 44, standardScore: 139, percentileRank: 99 },{ rawScore: 45, standardScore: 142, percentileRank: 99 },{ rawScore: 46, standardScore: 145, percentileRank: 99 },{ rawScore: 47, standardScore: 147, percentileRank: 99 },{ rawScore: "48-67", standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-13", standardScore: 50, percentileRank: 1 },{ rawScore: 14, standardScore: 53, percentileRank: 1 },{ rawScore: 15, standardScore: 56, percentileRank: 1 },{ rawScore: 16, standardScore: 60, percentileRank: 1 },{ rawScore: 17, standardScore: 63, percentileRank: 1 },{ rawScore: 18, standardScore: 67, percentileRank: 1 },{ rawScore: 19, standardScore: 71, percentileRank: 3 },{ rawScore: 20, standardScore: 75, percentileRank: 5 },{ rawScore: 21, standardScore: 79, percentileRank: 8 },{ rawScore: 22, standardScore: 83, percentileRank: 13 },{ rawScore: 23, standardScore: 87, percentileRank: 19 },{ rawScore: 24, standardScore: 92, percentileRank: 30 },{ rawScore: 25, standardScore: 96, percentileRank: 39 },{ rawScore: 26, standardScore: 100, percentileRank: 50 },{ rawScore: 27, standardScore: 105, percentileRank: 63 },{ rawScore: 28, standardScore: 109, percentileRank: 73 },{ rawScore: 29, standardScore: 113, percentileRank: 81 },{ rawScore: 30, standardScore: 117, percentileRank: 87 },{ rawScore: 31, standardScore: 121, percentileRank: 92 },{ rawScore: 32, standardScore: 125, percentileRank: 95 },{ rawScore: 33, standardScore: 130, percentileRank: 98 },{ rawScore: 34, standardScore: 134, percentileRank: 99 },{ rawScore: 35, standardScore: 138, percentileRank: 99 },{ rawScore: 36, standardScore: 142, percentileRank: 99 },{ rawScore: 37, standardScore: 146, percentileRank: 99 },{ rawScore: "38-60", standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '2:6-2:11', minAgeMonths: 30, maxAgeMonths: 35,
            caScores: [ { rawScore: "0-19", standardScore: 50, percentileRank: 1 },{ rawScore: 20, standardScore: 53, percentileRank: 1 },{ rawScore: 21, standardScore: 56, percentileRank: 1 },{ rawScore: 22, standardScore: 59, percentileRank: 1 },{ rawScore: 23, standardScore: 63, percentileRank: 1 },{ rawScore: 24, standardScore: 66, percentileRank: 1 },{ rawScore: 25, standardScore: 69, percentileRank: 2 },{ rawScore: 26, standardScore: 73, percentileRank: 4 },{ rawScore: 27, standardScore: 76, percentileRank: 5 },{ rawScore: 28, standardScore: 79, percentileRank: 8 },{ rawScore: 29, standardScore: 82, percentileRank: 12 },{ rawScore: 30, standardScore: 85, percentileRank: 16 },{ rawScore: 31, standardScore: 87, percentileRank: 19 },{ rawScore: 32, standardScore: 90, percentileRank: 25 },{ rawScore: 33, standardScore: 93, percentileRank: 32 },{ rawScore: 34, standardScore: 96, percentileRank: 39 },{ rawScore: 35, standardScore: 99, percentileRank: 47 },{ rawScore: 36, standardScore: 102, percentileRank: 55 },{ rawScore: 37, standardScore: 105, percentileRank: 63 },{ rawScore: 38, standardScore: 107, percentileRank: 68 },{ rawScore: 39, standardScore: 110, percentileRank: 75 },{ rawScore: 40, standardScore: 113, percentileRank: 81 },{ rawScore: 41, standardScore: 116, percentileRank: 86 },{ rawScore: 42, standardScore: 118, percentileRank: 88 },{ rawScore: 43, standardScore: 121, percentileRank: 92 },{ rawScore: 44, standardScore: 124, percentileRank: 95 },{ rawScore: 45, standardScore: 126, percentileRank: 96 },{ rawScore: 46, standardScore: 129, percentileRank: 97 },{ rawScore: 47, standardScore: 132, percentileRank: 98 },{ rawScore: 48, standardScore: 134, percentileRank: 99 },{ rawScore: 49, standardScore: 137, percentileRank: 99 },{ rawScore: 50, standardScore: 139, percentileRank: 99 },{ rawScore: 51, standardScore: 142, percentileRank: 99 },{ rawScore: 52, standardScore: 144, percentileRank: 99 },{ rawScore: 53, standardScore: 147, percentileRank: 99 },{ rawScore: 54, standardScore: 149, percentileRank: 99 },{ rawScore: "55-67", standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-15", standardScore: 50, percentileRank: 1 },{ rawScore: 16, standardScore: 54, percentileRank: 1 },{ rawScore: 17, standardScore: 57, percentileRank: 1 },{ rawScore: 18, standardScore: 60, percentileRank: 1 },{ rawScore: 19, standardScore: 63, percentileRank: 1 },{ rawScore: 20, standardScore: 67, percentileRank: 1 },{ rawScore: 21, standardScore: 70, percentileRank: 2 },{ rawScore: 22, standardScore: 73, percentileRank: 4 },{ rawScore: 23, standardScore: 77, percentileRank: 6 },{ rawScore: 24, standardScore: 80, percentileRank: 9 },{ rawScore: 25, standardScore: 84, percentileRank: 14 },{ rawScore: 26, standardScore: 88, percentileRank: 21 },{ rawScore: 27, standardScore: 92, percentileRank: 30 },{ rawScore: 28, standardScore: 96, percentileRank: 39 },{ rawScore: 29, standardScore: 100, percentileRank: 50 },{ rawScore: 30, standardScore: 104, percentileRank: 61 },{ rawScore: 31, standardScore: 108, percentileRank: 70 },{ rawScore: 32, standardScore: 112, percentileRank: 79 },{ rawScore: 33, standardScore: 116, percentileRank: 86 },{ rawScore: 34, standardScore: 120, percentileRank: 91 },{ rawScore: 35, standardScore: 124, percentileRank: 95 },{ rawScore: 36, standardScore: 127, percentileRank: 96 },{ rawScore: 37, standardScore: 131, percentileRank: 98 },{ rawScore: 38, standardScore: 134, percentileRank: 99 },{ rawScore: 39, standardScore: 138, percentileRank: 99 },{ rawScore: 40, standardScore: 142, percentileRank: 99 },{ rawScore: 41, standardScore: 146, percentileRank: 99 },{ rawScore: 42, standardScore: 149, percentileRank: 99 },{ rawScore: "43-60", standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '3:0-3:5', minAgeMonths: 36, maxAgeMonths: 41,
            caScores: [ { rawScore: "0-23", standardScore: 50, percentileRank: 1 },{ rawScore: 24, standardScore: 52, percentileRank: 1 },{ rawScore: 25, standardScore: 55, percentileRank: 1 },{ rawScore: 26, standardScore: 58, percentileRank: 1 },{ rawScore: 27, standardScore: 61, percentileRank: 1 },{ rawScore: 28, standardScore: 64, percentileRank: 1 },{ rawScore: 29, standardScore: 67, percentileRank: 1 },{ rawScore: 30, standardScore: 70, percentileRank: 2 },{ rawScore: 31, standardScore: 73, percentileRank: 4 },{ rawScore: 32, standardScore: 76, percentileRank: 5 },{ rawScore: 33, standardScore: 79, percentileRank: 8 },{ rawScore: 34, standardScore: 82, percentileRank: 12 },{ rawScore: 35, standardScore: 85, percentileRank: 16 },{ rawScore: 36, standardScore: 88, percentileRank: 21 },{ rawScore: 37, standardScore: 91, percentileRank: 27 },{ rawScore: 38, standardScore: 94, percentileRank: 34 },{ rawScore: 39, standardScore: 97, percentileRank: 42 },{ rawScore: 40, standardScore: 99, percentileRank: 47 },{ rawScore: 41, standardScore: 103, percentileRank: 58 },{ rawScore: 42, standardScore: 105, percentileRank: 63 },{ rawScore: 43, standardScore: 107, percentileRank: 68 },{ rawScore: 44, standardScore: 111, percentileRank: 77 },{ rawScore: 45, standardScore: 113, percentileRank: 81 },{ rawScore: 46, standardScore: 116, percentileRank: 86 },{ rawScore: 47, standardScore: 119, percentileRank: 90 },{ rawScore: 48, standardScore: 121, percentileRank: 92 },{ rawScore: 49, standardScore: 124, percentileRank: 95 },{ rawScore: 50, standardScore: 126, percentileRank: 96 },{ rawScore: 51, standardScore: 129, percentileRank: 97 },{ rawScore: 52, standardScore: 131, percentileRank: 98 },{ rawScore: 53, standardScore: 134, percentileRank: 99 },{ rawScore: 54, standardScore: 136, percentileRank: 99 },{ rawScore: 55, standardScore: 139, percentileRank: 99 },{ rawScore: 56, standardScore: 141, percentileRank: 99 },{ rawScore: 57, standardScore: 143, percentileRank: 99 },{ rawScore: 58, standardScore: 146, percentileRank: 99 },{ rawScore: 59, standardScore: 148, percentileRank: 99 },{ rawScore: "60-67", standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-16", standardScore: 50, percentileRank: 1 },{ rawScore: 17, standardScore: 53, percentileRank: 1 },{ rawScore: 18, standardScore: 55, percentileRank: 1 },{ rawScore: 19, standardScore: 58, percentileRank: 1 },{ rawScore: 20, standardScore: 61, percentileRank: 1 },{ rawScore: 21, standardScore: 64, percentileRank: 1 },{ rawScore: 22, standardScore: 67, percentileRank: 1 },{ rawScore: 23, standardScore: 70, percentileRank: 2 },{ rawScore: 24, standardScore: 73, percentileRank: 4 },{ rawScore: 25, standardScore: 76, percentileRank: 5 },{ rawScore: 26, standardScore: 79, percentileRank: 8 },{ rawScore: 27, standardScore: 82, percentileRank: 12 },{ rawScore: 28, standardScore: 85, percentileRank: 16 },{ rawScore: 29, standardScore: 88, percentileRank: 21 },{ rawScore: 30, standardScore: 92, percentileRank: 30 },{ rawScore: 31, standardScore: 95, percentileRank: 37 },{ rawScore: 32, standardScore: 99, percentileRank: 47 },{ rawScore: 33, standardScore: 102, percentileRank: 55 },{ rawScore: 34, standardScore: 106, percentileRank: 66 },{ rawScore: 35, standardScore: 109, percentileRank: 73 },{ rawScore: 36, standardScore: 113, percentileRank: 81 },{ rawScore: 37, standardScore: 116, percentileRank: 86 },{ rawScore: 38, standardScore: 120, percentileRank: 91 },{ rawScore: 39, standardScore: 123, percentileRank: 94 },{ rawScore: 40, standardScore: 127, percentileRank: 96 },{ rawScore: 41, standardScore: 130, percentileRank: 98 },{ rawScore: 42, standardScore: 134, percentileRank: 99 },{ rawScore: 43, standardScore: 137, percentileRank: 99 },{ rawScore: 44, standardScore: 141, percentileRank: 99 },{ rawScore: 45, standardScore: 144, percentileRank: 99 },{ rawScore: 46, standardScore: 147, percentileRank: 99 },{ rawScore: "47-60", standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '3:6-3:11', minAgeMonths: 42, maxAgeMonths: 47,
            caScores: [ { rawScore: "0-27", standardScore: 50, percentileRank: 1 }, { rawScore: 28, standardScore: 53, percentileRank: 1 }, { rawScore: 29, standardScore: 56, percentileRank: 1 }, { rawScore: 30, standardScore: 59, percentileRank: 1 }, { rawScore: 31, standardScore: 62, percentileRank: 1 }, { rawScore: 32, standardScore: 65, percentileRank: 1 }, { rawScore: 33, standardScore: 68, percentileRank: 2 }, { rawScore: 34, standardScore: 71, percentileRank: 3 }, { rawScore: 35, standardScore: 74, percentileRank: 4 }, { rawScore: 36, standardScore: 77, percentileRank: 6 }, { rawScore: 37, standardScore: 80, percentileRank: 9 }, { rawScore: 38, standardScore: 83, percentileRank: 13 }, { rawScore: 39, standardScore: 85, percentileRank: 16 }, { rawScore: 40, standardScore: 88, percentileRank: 21 }, { rawScore: 41, standardScore: 91, percentileRank: 27 }, { rawScore: 42, standardScore: 94, percentileRank: 34 }, { rawScore: 43, standardScore: 96, percentileRank: 39 }, { rawScore: 44, standardScore: 100, percentileRank: 50 }, { rawScore: 45, standardScore: 103, percentileRank: 58 }, { rawScore: 46, standardScore: 106, percentileRank: 66 }, { rawScore: 47, standardScore: 109, percentileRank: 73 }, { rawScore: 48, standardScore: 111, percentileRank: 77 }, { rawScore: 49, standardScore: 114, percentileRank: 82 }, { rawScore: 50, standardScore: 117, percentileRank: 87 }, { rawScore: 51, standardScore: 120, percentileRank: 91 }, { rawScore: 52, standardScore: 122, percentileRank: 93 }, { rawScore: 53, standardScore: 125, percentileRank: 95 }, { rawScore: 54, standardScore: 127, percentileRank: 96 }, { rawScore: 55, standardScore: 130, percentileRank: 98 }, { rawScore: 56, standardScore: 132, percentileRank: 98 }, { rawScore: 57, standardScore: 135, percentileRank: 99 }, { rawScore: 58, standardScore: 137, percentileRank: 99 }, { rawScore: 59, standardScore: 140, percentileRank: 99 }, { rawScore: 60, standardScore: 142, percentileRank: 99 }, { rawScore: 61, standardScore: 144, percentileRank: 99 }, { rawScore: 62, standardScore: 147, percentileRank: 99 }, { rawScore: 63, standardScore: 149, percentileRank: 99 }, { rawScore: "64-67", standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-18", standardScore: 50, percentileRank: 1 }, { rawScore: 19, standardScore: 53, percentileRank: 1 }, { rawScore: 20, standardScore: 56, percentileRank: 1 }, { rawScore: 21, standardScore: 59, percentileRank: 1 }, { rawScore: 22, standardScore: 61, percentileRank: 1 }, { rawScore: 23, standardScore: 64, percentileRank: 1 }, { rawScore: 24, standardScore: 67, percentileRank: 1 }, { rawScore: 25, standardScore: 70, percentileRank: 2 }, { rawScore: 26, standardScore: 72, percentileRank: 3 }, { rawScore: 27, standardScore: 75, percentileRank: 5 }, { rawScore: 28, standardScore: 78, percentileRank: 7 }, { rawScore: 29, standardScore: 81, percentileRank: 10 }, { rawScore: 30, standardScore: 84, percentileRank: 14 }, { rawScore: 31, standardScore: 87, percentileRank: 19 }, { rawScore: 32, standardScore: 89, percentileRank: 23 }, { rawScore: 33, standardScore: 92, percentileRank: 30 }, { rawScore: 34, standardScore: 95, percentileRank: 37 }, { rawScore: 35, standardScore: 98, percentileRank: 45 }, { rawScore: 36, standardScore: 101, percentileRank: 53 }, { rawScore: 37, standardScore: 104, percentileRank: 61 }, { rawScore: 38, standardScore: 107, percentileRank: 68 }, { rawScore: 39, standardScore: 110, percentileRank: 75 }, { rawScore: 40, standardScore: 114, percentileRank: 82 }, { rawScore: 41, standardScore: 117, percentileRank: 87 }, { rawScore: 42, standardScore: 120, percentileRank: 91 }, { rawScore: 43, standardScore: 123, percentileRank: 94 }, { rawScore: 44, standardScore: 126, percentileRank: 96 }, { rawScore: 45, standardScore: 130, percentileRank: 98 }, { rawScore: 46, standardScore: 133, percentileRank: 99 }, { rawScore: 47, standardScore: 136, percentileRank: 99 }, { rawScore: 48, standardScore: 139, percentileRank: 99 }, { rawScore: 49, standardScore: 142, percentileRank: 99 }, { rawScore: 50, standardScore: 145, percentileRank: 99 }, { rawScore: 51, standardScore: 148, percentileRank: 99 }, { rawScore: "52-60", standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '4:0-4:5', minAgeMonths: 48, maxAgeMonths: 53,
            caScores: [ { rawScore: "0-29", standardScore: 50, percentileRank: 1 }, { rawScore: 30, standardScore: 52, percentileRank: 1 }, { rawScore: 31, standardScore: 55, percentileRank: 1 }, { rawScore: 32, standardScore: 57, percentileRank: 1 }, { rawScore: 33, standardScore: 60, percentileRank: 1 }, { rawScore: 34, standardScore: 63, percentileRank: 1 }, { rawScore: 35, standardScore: 66, percentileRank: 1 }, { rawScore: 36, standardScore: 68, percentileRank: 2 }, { rawScore: 37, standardScore: 71, percentileRank: 3 }, { rawScore: 38, standardScore: 74, percentileRank: 4 }, { rawScore: 39, standardScore: 76, percentileRank: 5 }, { rawScore: 40, standardScore: 79, percentileRank: 8 }, { rawScore: 41, standardScore: 82, percentileRank: 12 }, { rawScore: 42, standardScore: 84, percentileRank: 14 }, { rawScore: 43, standardScore: 87, percentileRank: 19 }, { rawScore: 44, standardScore: 90, percentileRank: 25 }, { rawScore: 45, standardScore: 92, percentileRank: 30 }, { rawScore: 46, standardScore: 95, percentileRank: 37 }, { rawScore: 47, standardScore: 98, percentileRank: 45 }, { rawScore: 48, standardScore: 101, percentileRank: 53 }, { rawScore: 49, standardScore: 104, percentileRank: 61 }, { rawScore: 50, standardScore: 107, percentileRank: 68 }, { rawScore: 51, standardScore: 110, percentileRank: 75 }, { rawScore: 52, standardScore: 112, percentileRank: 79 }, { rawScore: 53, standardScore: 115, percentileRank: 84 }, { rawScore: 54, standardScore: 118, percentileRank: 88 }, { rawScore: 55, standardScore: 120, percentileRank: 91 }, { rawScore: 56, standardScore: 123, percentileRank: 94 }, { rawScore: 57, standardScore: 125, percentileRank: 95 }, { rawScore: 58, standardScore: 128, percentileRank: 97 }, { rawScore: 59, standardScore: 130, percentileRank: 98 }, { rawScore: 60, standardScore: 133, percentileRank: 99 }, { rawScore: 61, standardScore: 135, percentileRank: 99 }, { rawScore: 62, standardScore: 138, percentileRank: 99 }, { rawScore: 63, standardScore: 141, percentileRank: 99 }, { rawScore: 64, standardScore: 143, percentileRank: 99 }, { rawScore: 65, standardScore: 146, percentileRank: 99 }, { rawScore: "66-67", standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-20", standardScore: 50, percentileRank: 1 }, { rawScore: 21, standardScore: 52, percentileRank: 1 }, { rawScore: 22, standardScore: 55, percentileRank: 1 }, { rawScore: 23, standardScore: 57, percentileRank: 1 }, { rawScore: 24, standardScore: 60, percentileRank: 1 }, { rawScore: 25, standardScore: 63, percentileRank: 1 }, { rawScore: 26, standardScore: 65, percentileRank: 1 }, { rawScore: 27, standardScore: 68, percentileRank: 2 }, { rawScore: 28, standardScore: 71, percentileRank: 3 }, { rawScore: 29, standardScore: 73, percentileRank: 4 }, { rawScore: 30, standardScore: 76, percentileRank: 5 }, { rawScore: 31, standardScore: 79, percentileRank: 8 }, { rawScore: 32, standardScore: 82, percentileRank: 12 }, { rawScore: 33, standardScore: 84, percentileRank: 14 }, { rawScore: 34, standardScore: 87, percentileRank: 19 }, { rawScore: 35, standardScore: 90, percentileRank: 25 }, { rawScore: 36, standardScore: 93, percentileRank: 32 }, { rawScore: 37, standardScore: 95, percentileRank: 37 }, { rawScore: 38, standardScore: 98, percentileRank: 45 }, { rawScore: 39, standardScore: 101, percentileRank: 53 }, { rawScore: 40, standardScore: 103, percentileRank: 58 }, { rawScore: 41, standardScore: 106, percentileRank: 66 }, { rawScore: 42, standardScore: 109, percentileRank: 73 }, { rawScore: 43, standardScore: 112, percentileRank: 79 }, { rawScore: 44, standardScore: 115, percentileRank: 84 }, { rawScore: 45, standardScore: 118, percentileRank: 88 }, { rawScore: 46, standardScore: 120, percentileRank: 91 }, { rawScore: 47, standardScore: 123, percentileRank: 94 }, { rawScore: 48, standardScore: 126, percentileRank: 96 }, { rawScore: 49, standardScore: 129, percentileRank: 97 }, { rawScore: 50, standardScore: 132, percentileRank: 98 }, { rawScore: 51, standardScore: 135, percentileRank: 99 }, { rawScore: 52, standardScore: 138, percentileRank: 99 }, { rawScore: 53, standardScore: 141, percentileRank: 99 }, { rawScore: 54, standardScore: 144, percentileRank: 99 }, { rawScore: 55, standardScore: 147, percentileRank: 99 }, { rawScore: "56-60", standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '4:6-4:11', minAgeMonths: 54, maxAgeMonths: 59,
            caScores: [ { rawScore: "0-31", standardScore: 50, percentileRank: 1 }, { rawScore: 32, standardScore: 52, percentileRank: 1 }, { rawScore: 33, standardScore: 54, percentileRank: 1 }, { rawScore: 34, standardScore: 57, percentileRank: 1 }, { rawScore: 35, standardScore: 59, percentileRank: 1 }, { rawScore: 36, standardScore: 61, percentileRank: 1 }, { rawScore: 37, standardScore: 64, percentileRank: 1 }, { rawScore: 38, standardScore: 66, percentileRank: 1 }, { rawScore: 39, standardScore: 69, percentileRank: 2 }, { rawScore: 40, standardScore: 71, percentileRank: 3 }, { rawScore: 41, standardScore: 74, percentileRank: 4 }, { rawScore: 42, standardScore: 76, percentileRank: 5 }, { rawScore: 43, standardScore: 79, percentileRank: 8 }, { rawScore: 44, standardScore: 81, percentileRank: 10 }, { rawScore: 45, standardScore: 84, percentileRank: 14 }, { rawScore: 46, standardScore: 86, percentileRank: 18 }, { rawScore: 47, standardScore: 89, percentileRank: 23 }, { rawScore: 48, standardScore: 91, percentileRank: 27 }, { rawScore: 49, standardScore: 94, percentileRank: 34 }, { rawScore: 50, standardScore: 97, percentileRank: 42 }, { rawScore: 51, standardScore: 99, percentileRank: 47 }, { rawScore: 52, standardScore: 101, percentileRank: 53 }, { rawScore: 53, standardScore: 104, percentileRank: 61 }, { rawScore: 54, standardScore: 107, percentileRank: 68 }, { rawScore: 55, standardScore: 110, percentileRank: 75 }, { rawScore: 56, standardScore: 113, percentileRank: 81 }, { rawScore: 57, standardScore: 116, percentileRank: 86 }, { rawScore: 58, standardScore: 118, percentileRank: 88 }, { rawScore: 59, standardScore: 121, percentileRank: 92 }, { rawScore: 60, standardScore: 124, percentileRank: 95 }, { rawScore: 61, standardScore: 127, percentileRank: 96 }, { rawScore: 62, standardScore: 130, percentileRank: 98 }, { rawScore: 63, standardScore: 133, percentileRank: 99 }, { rawScore: 64, standardScore: 136, percentileRank: 99 }, { rawScore: 65, standardScore: 140, percentileRank: 99 }, { rawScore: 66, standardScore: 144, percentileRank: 99 }, { rawScore: 67, standardScore: 150, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-23", standardScore: 50, percentileRank: 1 }, { rawScore: 24, standardScore: 53, percentileRank: 1 }, { rawScore: 25, standardScore: 55, percentileRank: 1 }, { rawScore: 26, standardScore: 58, percentileRank: 1 }, { rawScore: 27, standardScore: 60, percentileRank: 1 }, { rawScore: 28, standardScore: 63, percentileRank: 1 }, { rawScore: 29, standardScore: 66, percentileRank: 1 }, { rawScore: 30, standardScore: 68, percentileRank: 2 }, { rawScore: 31, standardScore: 71, percentileRank: 3 }, { rawScore: 32, standardScore: 74, percentileRank: 4 }, { rawScore: 33, standardScore: 76, percentileRank: 5 }, { rawScore: 34, standardScore: 79, percentileRank: 8 }, { rawScore: 35, standardScore: 82, percentileRank: 12 }, { rawScore: 36, standardScore: 84, percentileRank: 14 }, { rawScore: 37, standardScore: 87, percentileRank: 19 }, { rawScore: 38, standardScore: 90, percentileRank: 25 }, { rawScore: 39, standardScore: 92, percentileRank: 30 }, { rawScore: 40, standardScore: 95, percentileRank: 37 }, { rawScore: 41, standardScore: 98, percentileRank: 45 }, { rawScore: 42, standardScore: 100, percentileRank: 50 }, { rawScore: 43, standardScore: 103, percentileRank: 58 }, { rawScore: 44, standardScore: 105, percentileRank: 63 }, { rawScore: 45, standardScore: 108, percentileRank: 70 }, { rawScore: 46, standardScore: 110, percentileRank: 75 }, { rawScore: 47, standardScore: 113, percentileRank: 81 }, { rawScore: 48, standardScore: 115, percentileRank: 84 }, { rawScore: 49, standardScore: 118, percentileRank: 88 }, { rawScore: 50, standardScore: 121, percentileRank: 92 }, { rawScore: 51, standardScore: 124, percentileRank: 95 }, { rawScore: 52, standardScore: 126, percentileRank: 96 }, { rawScore: 53, standardScore: 129, percentileRank: 97 }, { rawScore: 54, standardScore: 132, percentileRank: 98 }, { rawScore: 55, standardScore: 135, percentileRank: 99 }, { rawScore: 56, standardScore: 138, percentileRank: 99 }, { rawScore: 57, standardScore: 141, percentileRank: 99 }, { rawScore: 58, standardScore: 144, percentileRank: 99 }, { rawScore: 59, standardScore: 147, percentileRank: 99 }, { rawScore: 60, standardScore: 150, percentileRank: 99 }]
        },
        {
            ageRange: '5:0-5:5', minAgeMonths: 60, maxAgeMonths: 65,
            caScores: [ { rawScore: "0-33", standardScore: 50, percentileRank: 1 }, { rawScore: 34, standardScore: 52, percentileRank: 1 }, { rawScore: 35, standardScore: 54, percentileRank: 1 }, { rawScore: 36, standardScore: 56, percentileRank: 1 }, { rawScore: 37, standardScore: 58, percentileRank: 1 }, { rawScore: 38, standardScore: 60, percentileRank: 1 }, { rawScore: 39, standardScore: 62, percentileRank: 1 }, { rawScore: 40, standardScore: 64, percentileRank: 1 }, { rawScore: 41, standardScore: 66, percentileRank: 1 }, { rawScore: 42, standardScore: 69, percentileRank: 2 }, { rawScore: 43, standardScore: 71, percentileRank: 3 }, { rawScore: 44, standardScore: 73, percentileRank: 4 }, { rawScore: 45, standardScore: 76, percentileRank: 5 }, { rawScore: 46, standardScore: 78, percentileRank: 7 }, { rawScore: 47, standardScore: 81, percentileRank: 10 }, { rawScore: 48, standardScore: 83, percentileRank: 13 }, { rawScore: 49, standardScore: 86, percentileRank: 18 }, { rawScore: 50, standardScore: 88, percentileRank: 21 }, { rawScore: 51, standardScore: 91, percentileRank: 27 }, { rawScore: 52, standardScore: 93, percentileRank: 32 }, { rawScore: 53, standardScore: 96, percentileRank: 39 }, { rawScore: 54, standardScore: 98, percentileRank: 45 }, { rawScore: 55, standardScore: 101, percentileRank: 53 }, { rawScore: 56, standardScore: 103, percentileRank: 58 }, { rawScore: 57, standardScore: 106, percentileRank: 66 }, { rawScore: 58, standardScore: 108, percentileRank: 70 }, { rawScore: 59, standardScore: 111, percentileRank: 77 }, { rawScore: 60, standardScore: 115, percentileRank: 84 }, { rawScore: 61, standardScore: 118, percentileRank: 88 }, { rawScore: 62, standardScore: 121, percentileRank: 92 }, { rawScore: 63, standardScore: 124, percentileRank: 95 }, { rawScore: 64, standardScore: 129, percentileRank: 97 }, { rawScore: 65, standardScore: 134, percentileRank: 99 }, { rawScore: 66, standardScore: 138, percentileRank: 99 }, { rawScore: 67, standardScore: 143, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-25", standardScore: 50, percentileRank: 1 }, { rawScore: 26, standardScore: 51, percentileRank: 1 }, { rawScore: 27, standardScore: 53, percentileRank: 1 }, { rawScore: 28, standardScore: 56, percentileRank: 1 }, { rawScore: 29, standardScore: 58, percentileRank: 1 }, { rawScore: 30, standardScore: 61, percentileRank: 1 }, { rawScore: 31, standardScore: 63, percentileRank: 1 }, { rawScore: 32, standardScore: 66, percentileRank: 1 }, { rawScore: 33, standardScore: 68, percentileRank: 2 }, { rawScore: 34, standardScore: 71, percentileRank: 3 }, { rawScore: 35, standardScore: 74, percentileRank: 4 }, { rawScore: 36, standardScore: 76, percentileRank: 5 }, { rawScore: 37, standardScore: 79, percentileRank: 8 }, { rawScore: 38, standardScore: 81, percentileRank: 10 }, { rawScore: 39, standardScore: 84, percentileRank: 14 }, { rawScore: 40, standardScore: 86, percentileRank: 18 }, { rawScore: 41, standardScore: 89, percentileRank: 23 }, { rawScore: 42, standardScore: 92, percentileRank: 30 }, { rawScore: 43, standardScore: 94, percentileRank: 34 }, { rawScore: 44, standardScore: 97, percentileRank: 42 }, { rawScore: 45, standardScore: 99, percentileRank: 47 }, { rawScore: 46, standardScore: 101, percentileRank: 53 }, { rawScore: 47, standardScore: 104, percentileRank: 61 }, { rawScore: 48, standardScore: 106, percentileRank: 66 }, { rawScore: 49, standardScore: 109, percentileRank: 73 }, { rawScore: 50, standardScore: 111, percentileRank: 77 }, { rawScore: 51, standardScore: 114, percentileRank: 82 }, { rawScore: 52, standardScore: 117, percentileRank: 87 }, { rawScore: 53, standardScore: 120, percentileRank: 91 }, { rawScore: 54, standardScore: 123, percentileRank: 94 }, { rawScore: 55, standardScore: 125, percentileRank: 95 }, { rawScore: 56, standardScore: 128, percentileRank: 97 }, { rawScore: 57, standardScore: 131, percentileRank: 98 }, { rawScore: 58, standardScore: 134, percentileRank: 99 }, { rawScore: 59, standardScore: 138, percentileRank: 99 }, { rawScore: 60, standardScore: 143, percentileRank: 99 }]
        },
        {
            ageRange: '5:6-5:11', minAgeMonths: 66, maxAgeMonths: 71,
            caScores: [ { rawScore: "0-36", standardScore: 50, percentileRank: 1 }, { rawScore: 37, standardScore: 52, percentileRank: 1 }, { rawScore: 38, standardScore: 55, percentileRank: 1 }, { rawScore: 39, standardScore: 57, percentileRank: 1 }, { rawScore: 40, standardScore: 59, percentileRank: 1 }, { rawScore: 41, standardScore: 62, percentileRank: 1 }, { rawScore: 42, standardScore: 64, percentileRank: 1 }, { rawScore: 43, standardScore: 66, percentileRank: 1 }, { rawScore: 44, standardScore: 68, percentileRank: 2 }, { rawScore: 45, standardScore: 70, percentileRank: 2 }, { rawScore: 46, standardScore: 72, percentileRank: 3 }, { rawScore: 47, standardScore: 74, percentileRank: 4 }, { rawScore: 48, standardScore: 77, percentileRank: 6 }, { rawScore: 49, standardScore: 79, percentileRank: 8 }, { rawScore: 50, standardScore: 82, percentileRank: 12 }, { rawScore: 51, standardScore: 84, percentileRank: 14 }, { rawScore: 52, standardScore: 87, percentileRank: 19 }, { rawScore: 53, standardScore: 89, percentileRank: 23 }, { rawScore: 54, standardScore: 92, percentileRank: 30 }, { rawScore: 55, standardScore: 94, percentileRank: 34 }, { rawScore: 56, standardScore: 96, percentileRank: 39 }, { rawScore: 57, standardScore: 99, percentileRank: 47 }, { rawScore: 58, standardScore: 101, percentileRank: 53 }, { rawScore: 59, standardScore: 104, percentileRank: 61 }, { rawScore: 60, standardScore: 107, percentileRank: 68 }, { rawScore: 61, standardScore: 110, percentileRank: 75 }, { rawScore: 62, standardScore: 114, percentileRank: 82 }, { rawScore: 63, standardScore: 118, percentileRank: 88 }, { rawScore: 64, standardScore: 122, percentileRank: 93 }, { rawScore: 65, standardScore: 127, percentileRank: 96 }, { rawScore: 66, standardScore: 132, percentileRank: 98 }, { rawScore: 67, standardScore: 138, percentileRank: 99 }],
            ceScores: [ { rawScore: "0-28", standardScore: 50, percentileRank: 1 }, { rawScore: 29, standardScore: 52, percentileRank: 1 }, { rawScore: 30, standardScore: 54, percentileRank: 1 }, { rawScore: 31, standardScore: 56, percentileRank: 1 }, { rawScore: 32, standardScore: 59, percentileRank: 1 }, { rawScore: 33, standardScore: 61, percentileRank: 1 }, { rawScore: 34, standardScore: 64, percentileRank: 1 }, { rawScore: 35, standardScore: 66, percentileRank: 1 }, { rawScore: 36, standardScore: 68, percentileRank: 2 }, { rawScore: 37, standardScore: 71, percentileRank: 3 }, { rawScore: 38, standardScore: 73, percentileRank: 4 }, { rawScore: 39, standardScore: 76, percentileRank: 5 }, { rawScore: 40, standardScore: 78, percentileRank: 7 }, { rawScore: 41, standardScore: 81, percentileRank: 10 }, { rawScore: 42, standardScore: 83, percentileRank: 13 }, { rawScore: 43, standardScore: 86, percentileRank: 18 }, { rawScore: 44, standardScore: 88, percentileRank: 21 }, { rawScore: 45, standardScore: 91, percentileRank: 27 }, { rawScore: 46, standardScore: 93, percentileRank: 32 }, { rawScore: 47, standardScore: 96, percentileRank: 39 }, { rawScore: 48, standardScore: 99, percentileRank: 47 }, { rawScore: 49, standardScore: 101, percentileRank: 53 }, { rawScore: 50, standardScore: 104, percentileRank: 61 }, { rawScore: 51, standardScore: 107, percentileRank: 68 }, { rawScore: 52, standardScore: 109, percentileRank: 73 }, { rawScore: 53, standardScore: 112, percentileRank: 79 }, { rawScore: 54, standardScore: 115, percentileRank: 84 }, { rawScore: 55, standardScore: 118, percentileRank: 88 }, { rawScore: 56, standardScore: 121, percentileRank: 92 }, { rawScore: 57, standardScore: 124, percentileRank: 95 }, { rawScore: 58, standardScore: 127, percentileRank: 96 }, { rawScore: 59, standardScore: 132, percentileRank: 98 }, { rawScore: 60, standardScore: 137, percentileRank: 99 }]
        }
    ];

    const pls5TotalScoreLookupTable = [ [100, 108, 50, 1],[109, 110, 51, 1],[111, 111, 52, 1],[112, 113, 53, 1],[114, 115, 54, 1],[116, 117, 55, 1],[118, 119, 56, 1],[120, 120, 57, 1],[121, 122, 58, 1],[123, 124, 59, 1],[125, 126, 60, 1],[127, 128, 61, 1],[129, 130, 62, 1],[131, 131, 63, 1],[132, 133, 64, 1],[134, 135, 65, 1],[136, 137, 66, 1],[138, 139, 67, 1],[140, 140, 68, 2],[141, 142, 69, 2],[143, 144, 70, 2],[145, 146, 71, 3],[147, 148, 72, 3],[149, 150, 73, 4],[151, 152, 74, 4],[153, 154, 75, 5],[155, 156, 76, 5],[157, 158, 77, 6],[159, 160, 78, 7],[161, 162, 79, 8],[163, 164, 80, 9],[165, 166, 81, 10],[167, 168, 82, 12],[169, 169, 83, 13],[170, 171, 84, 14],[172, 173, 85, 16],[174, 175, 86, 18],[176, 177, 87, 19],[178, 179, 88, 21],[180, 181, 89, 23],[182, 182, 90, 25],[183, 184, 91, 27],[185, 186, 92, 30],[187, 188, 93, 32],[189, 190, 94, 34],[191, 192, 95, 37],[193, 194, 96, 39],[195, 195, 97, 42],[196, 197, 98, 45],[198, 199, 99, 47],[200, 200, 100, 50],[201, 202, 101, 53],[203, 204, 102, 55],[205, 206, 103, 58],[207, 208, 104, 61],[209, 210, 105, 63],[211, 212, 106, 66],[213, 213, 107, 68],[214, 215, 108, 70],[216, 217, 109, 73],[218, 218, 110, 75],[219, 220, 111, 77],[221, 222, 112, 79],[223, 224, 113, 81],[225, 225, 114, 82],[226, 227, 115, 84],[228, 229, 116, 86],[230, 231, 117, 87],[232, 233, 118, 88],[234, 235, 119, 90],[236, 237, 120, 91],[238, 238, 121, 92],[239, 240, 122, 93],[241, 242, 123, 94],[243, 244, 124, 95],[245, 246, 125, 95],[247, 248, 126, 96],[249, 250, 127, 96],[251, 252, 128, 97],[253, 254, 129, 97],[255, 255, 130, 98],[256, 257, 131, 98],[258, 259, 132, 98],[260, 261, 133, 99],[262, 263, 134, 99],[264, 265, 135, 99],[266, 267, 136, 99],[268, 269, 137, 99],[270, 271, 138, 99],[272, 273, 139, 99],[274, 275, 140, 99],[276, 276, 141, 99],[277, 278, 142, 99],[279, 280, 143, 99],[281, 282, 144, 99],[283, 284, 145, 99],[285, 286, 146, 99],[287, 288, 147, 99],[289, 289, 148, 99],[290, 290, 149, 99],[291, 300, 150, 99], ];
    const interpretacionesEstandar = [ { minSS: null, maxSS: 69, text: "Muy por debajo del promedio." }, { minSS: 70, maxSS: 79, text: "Por debajo del promedio." }, { minSS: 80, maxSS: 89, text: "Algo por debajo del promedio." }, { minSS: 90, maxSS: 109, text: "Promedio." }, { minSS: 110, maxSS: 119, text: "Algo encima del promedio." }, { minSS: 120, maxSS: 129, text: "Encima del promedio." }, { minSS: 130, maxSS: null, text: "Muy por encima del promedio." }, { minSS: null, maxSS: null, text: "No aplicable" } ];

    
    
    function calculatePreciseAge(startDate, endDate) {
        if (!(startDate instanceof Date) || !(endDate instanceof Date) || isNaN(startDate) || isNaN(endDate)) {
            return { years: 0, months: 0, days: 0, totalMonths: 0 };
        }
        let years = endDate.getFullYear() - startDate.getFullYear();
        let months = endDate.getMonth() - startDate.getMonth();
        let days = endDate.getDate() - startDate.getDate();
        if (days < 0) {
            months--;
            const lastMonth = new Date(endDate.getFullYear(), endDate.getMonth(), 0);
            days += lastMonth.getDate();
        }
        if (months < 0) {
            years--;
            months += 12;
        }
        const totalMonths = (years * 12) + months;
        return { years, months, days, totalMonths };
    }

    function setPatientCondition() {
        const gestWeeksElem = document.getElementById('semanas_gestacion_hidden');
        const conditionElem = document.getElementById('condicion_paciente');
        if (!gestWeeksElem || !conditionElem) return;

        const gestWeeks = parseInt(gestWeeksElem.value, 10);
        if (gestWeeks > 0 && gestWeeks < 37) {
            conditionElem.value = "Prematuro";
        } else if (gestWeeks >= 37) {
            conditionElem.value = "Nacido a término";
        } else {
            conditionElem.value = "No especificado";
        }
    }

    // --- ELEMENTOS DEL DOM ---
    const ageInput = document.getElementById('edad');
    const baremoManualSelect = document.getElementById('baremo_manual_select');
    const rawScoreInputCA = document.getElementById('comp_audi_punt_bruta');
    const standardScoreOutputCA = document.getElementById('compren_audit_punt_stand');
    const percentileRankOutputCA = document.getElementById('compre_audit_rango_percent');
    const interpretationOutputCA = document.getElementById('comp_audit_interpre');
    const interpretationSelectCA = document.getElementById('comp_audit_interpre_select');
    const rawScoreInputCE = document.getElementById('expre_comuni_puntua_bruta');
    const standardScoreOutputCE = document.getElementById('expr_comun_punt_estandar');
    const percentileRankOutputCE = document.getElementById('expr_comunic_rango_percent');
    const interpretationOutputCE = document.getElementById('expr_comunic_interpret');
    const interpretationSelectCE = document.getElementById('expr_comunic_interpret_select');
    const sumRawOutputLT = document.getElementById('leng_tota_punt_bruta');
    const sumStandardOutputLT = document.getElementById('leng_tota_punt_standa_sum');
    const standardScoreOutputLT = document.getElementById('leng_tota_punt_standa');
    const percentileRankOutputLT = document.getElementById('leng_tota_rang_percent');
    const interpretationOutputLT = document.getElementById('lengua_tot_interpret');
    const interpretationSelectLT = document.getElementById('lengua_tot_interpret_select');
    let isManualMode = false;
    let activeAgeTable = null;

    // --- FUNCIONES DE CÁLCULO ---
    function parseAgeToMonths(ageString) { if (!ageString) return null; const match = ageString.match(/^(\d{1,2})A(\d{1,2})M/i); return match ? (parseInt(match[1], 10) * 12) + parseInt(match[2], 10) : null; }
    function findAgeTable(totalMonths) { if (totalMonths === null) return null; return pls5AgeTables.find(t => totalMonths >= t.minAgeMonths && totalMonths <= t.maxAgeMonths) || null; }
    function getInterpretation(ss) { if (ss === null || isNaN(ss)) return ""; const r = interpretacionesEstandar.find(r => (r.minSS === null || ss >= r.minSS) && (r.maxSS === null || ss <= r.maxSS)); return r ? r.text : ""; }
    function lookupSubtestScores(rawScoreInt, ageTable, type) {
        if (!ageTable || rawScoreInt === null || isNaN(rawScoreInt)) return { standardScore: null, percentileRank: null };
        const scores = ageTable[`${type}Scores`];
        for (const entry of scores) {
            if (typeof entry.rawScore === 'number') { if (rawScoreInt === entry.rawScore) return { standardScore: entry.standardScore, percentileRank: entry.percentileRank };
            } else if (typeof entry.rawScore === 'string' && entry.rawScore.includes('-')) {
                const [min, max] = entry.rawScore.split('-').map(s => parseInt(s, 10));
                if (rawScoreInt >= min && rawScoreInt <= max) return { standardScore: entry.standardScore, percentileRank: entry.percentileRank };
            }
        }
        return { standardScore: null, percentileRank: null };
    }
    
    function calculateComprensionAuditiva() {
    if (isManualMode) return;
    const rawScoreInt = parseInt(rawScoreInputCA.value, 10);
    // Ya no busca la tabla, usa la que está activa globalmente
    const scores = lookupSubtestScores(rawScoreInt, activeAgeTable, 'ca');
    standardScoreOutputCA.value = scores.standardScore ?? '';
    percentileRankOutputCA.value = scores.percentileRank ?? '';
    interpretationOutputCA.value = getInterpretation(scores.standardScore);
    calculateLenguajeTotal();
}
    function calculateComunicacionExpresiva() {
    if (isManualMode) return;
    const rawScoreInt = parseInt(rawScoreInputCE.value, 10);
    // Ya no busca la tabla, usa la que está activa globalmente
    const scores = lookupSubtestScores(rawScoreInt, activeAgeTable, 'ce');
    standardScoreOutputCE.value = scores.standardScore ?? '';
    percentileRankOutputCE.value = scores.percentileRank ?? '';
    interpretationOutputCE.value = getInterpretation(scores.standardScore);
    calculateLenguajeTotal();
}
        function calculateLenguajeTotal() {
        standardScoreOutputLT.value = ''; 
        percentileRankOutputLT.value = ''; 
        interpretationOutputLT.value = '';

        const caRaw = parseInt(rawScoreInputCA.value, 10);
        const ceRaw = parseInt(rawScoreInputCE.value, 10);
        const caSS = parseInt(standardScoreOutputCA.value, 10);
        const ceSS = parseInt(standardScoreOutputCE.value, 10);
        let sumOfStandardScores = NaN;

        // Calcular y mostrar la suma de Puntuaciones Brutas (si no es modo manual)
        if (!isManualMode) {
            if (!isNaN(caRaw) && !isNaN(ceRaw)) {
                sumRawOutputLT.value = caRaw + ceRaw;
            } else {
                sumRawOutputLT.value = '';
            }
        }
        
        //Calcular la suma de Puntuaciones Estándar
        if (isManualMode) {
            // En modo manual, la suma se toma directamente del campo de suma estándar
            sumOfStandardScores = parseInt(sumStandardOutputLT.value, 10);
        } else {
            // En modo automático, se calcula y se muestra
            if (!isNaN(caSS) && !isNaN(ceSS)) {
                sumOfStandardScores = caSS + ceSS;
                sumStandardOutputLT.value = sumOfStandardScores;
            } else {
                sumStandardOutputLT.value = '';
            }
        }
        
        //Buscar la Puntuación Estándar y Percentil del Lenguaje Total
        if (!isNaN(sumOfStandardScores)) {
            for (const row of pls5TotalScoreLookupTable) {
                if (sumOfStandardScores >= row[0] && sumOfStandardScores <= row[1]) {
                    standardScoreOutputLT.value = row[2];
                    percentileRankOutputLT.value = row[3];
                    if (!isManualMode) { 
                        interpretationOutputLT.value = getInterpretation(row[2]);
                    }
                    break;
                }
            }
        }
    }
    
    // --- LÓGICA DE CONTROL ---
    function gestionarCamposPLS(manual) {
        isManualMode = manual;
        const sections = [
            { ss: standardScoreOutputCA, pr: percentileRankOutputCA, ta: interpretationOutputCA, sel: interpretationSelectCA },
            { ss: standardScoreOutputCE, pr: percentileRankOutputCE, ta: interpretationOutputCE, sel: interpretationSelectCE },
            { ss: standardScoreOutputLT, pr: percentileRankOutputLT, ta: interpretationOutputLT, sel: interpretationSelectLT }
        ];
        
        sections.forEach(s => {
            [s.ss, s.pr].forEach(f => { f.readOnly = !manual; f.classList.toggle('auto-filled', !manual); });
            s.ta.style.display = manual ? 'none' : 'block'; s.ta.disabled = manual;
            s.sel.style.display = manual ? 'block' : 'none'; s.sel.disabled = !manual;
        });

        // CAMBIO: Gestionar el campo de suma de P.E.
        sumRawOutputLT.readOnly = !manual;
        sumRawOutputLT.classList.toggle('auto-filled', !manual);
        sumStandardOutputLT.readOnly = !manual;
        sumStandardOutputLT.classList.toggle('auto-filled', !manual);
    }

    function getDateDifference(startDate, endDate) {
        let years = endDate.getFullYear() - startDate.getFullYear();
        let months = endDate.getMonth() - startDate.getMonth();
        let days = endDate.getDate() - startDate.getDate();
        if (days < 0) { months--; days += new Date(endDate.getFullYear(), endDate.getMonth(), 0).getDate(); }
        if (months < 0) { years--; months += 12; }
        return { years, months, days };
    }
    
function calculateAllAgesAndUpdate_PLS5() {
    // 1. Obtener referencias a los elementos del DOM
    const birthDateElem = document.getElementById('fecha_nacimiento_paciente');
    const evalDateElem = document.getElementById('fecha_evaluacion');
    const gestWeeksElem = document.getElementById('semanas_gestacion_hidden');
    const cronoAgeElem = document.getElementById('edad');
    const correctedAgeElem = document.getElementById('edad_corregida');
    const rangoAplicadoElem = document.getElementById('rango_edad');
    const baremoManualSelect = document.getElementById('baremo_manual_select');
    const baremoManualLabel = document.getElementById('baremo_manual_label');

    // Referencias a los inputs de Puntuación Bruta para la validación
    const rawScoreInputCA = document.getElementById('comp_audi_punt_bruta');
    const rawScoreInputCE = document.getElementById('expre_comuni_puntua_bruta');

    // 2. Limpieza inicial del estado del formulario
    cronoAgeElem.value = '';
    correctedAgeElem.value = '';
    rangoAplicadoElem.value = '';
    baremoManualSelect.value = "0";
    cronoAgeElem.classList.remove('edad-activa');
    correctedAgeElem.classList.remove('edad-activa');
    gestionarCamposPLS(true); // Bloquea el formulario hasta que haya fechas válidas
    baremoManualSelect.classList.add('hidden');
    baremoManualLabel.classList.add('hidden');
    
    // Limpiar los atributos de validación y placeholders
    rawScoreInputCA.removeAttribute('data-max-value');
    rawScoreInputCE.removeAttribute('data-max-value');
    rawScoreInputCA.placeholder = 'Puntuación';
    rawScoreInputCE.placeholder = 'Puntuación';

    if (!birthDateElem.value || !evalDateElem.value) return; // Salir si no hay fechas

    const startDate = new Date(birthDateElem.value);
    const endDate = new Date(evalDateElem.value);

    if (startDate > endDate) {
        cronoAgeElem.value = 'Error en fechas';
        Swal.fire({ icon: 'error', title: 'Error', text: 'La fecha de nacimiento no puede ser posterior a la de evaluación.' });
        return;
    }

    // 3. Calcular Edad Cronológica
    const cronoAge = calculatePreciseAge(startDate, endDate);
    cronoAgeElem.value = `${cronoAge.years}A ${cronoAge.months}M ${cronoAge.days}D`;
    const chronologicalTotalMonths = (cronoAge.years * 12) + cronoAge.months;

    // RESTRICCIÓN 1: EDAD MÍNIMA
    if (chronologicalTotalMonths < 3) {
        rangoAplicadoElem.value = "No Aplica (Edad Mínima)";
        Swal.fire({ icon: 'warning', title: 'Atención', text: 'El paciente debe tener al menos 3 meses de edad para esta prueba.' });
        return;
    }

    // 4. Determinar la edad a usar (cronológica o corregida)
    let ageInMonthsForLookup = chronologicalTotalMonths;
    let tipoDeEdadUsada = "cronológica";
    cronoAgeElem.classList.add('edad-activa');

    const gestWeeks = parseInt(gestWeeksElem.value, 10);
    const esPrematuro = gestWeeks > 0 && gestWeeks < 37;
    const esMenorDe2Anos = chronologicalTotalMonths < 24;

    if (esPrematuro && esMenorDe2Anos) {
        const daysToCorrect = (40 - gestWeeks) * 7;
        let correctedEndDate = new Date(endDate.getTime() - (daysToCorrect * 24 * 60 * 60 * 1000));
        const correctedAge = calculatePreciseAge(startDate, correctedEndDate);
        correctedAgeElem.value = `${correctedAge.years}A ${correctedAge.months}M ${correctedAge.days}D`;
        const correctedTotalMonths = (correctedAge.years * 12) + correctedAge.months;
        
        if (correctedTotalMonths < 3) {
            rangoAplicadoElem.value = "No Aplica (Edad Mínima)";
            Swal.fire({ icon: 'warning', title: 'Atención', text: `La edad corregida es menor a 3 meses.` });
            return;
        }
        
        ageInMonthsForLookup = correctedTotalMonths;
        tipoDeEdadUsada = "corregida";
        cronoAgeElem.classList.remove('edad-activa');
        correctedAgeElem.classList.add('edad-activa');
    } else {
        correctedAgeElem.value = 'No Aplica';
    }

    // 5. Lógica de baremo y asignación de LÍMITE MÁXIMO
    activeAgeTable = findAgeTable(ageInMonthsForLookup);

    if (activeAgeTable) {
        rangoAplicadoElem.value = activeAgeTable.ageRange;
        gestionarCamposPLS(false); // Activa modo automático
        
        // --- ¡AQUÍ ESTABLECEMOS EL LÍMITE MÁXIMO DINÁMICO! ---
        const maxRawCA_entry = activeAgeTable.caScores[activeAgeTable.caScores.length - 1];
        const maxCA = parseInt(String(maxRawCA_entry.rawScore).split('-').pop(), 10);
        rawScoreInputCA.setAttribute('data-max-value', maxCA);
        rawScoreInputCA.placeholder = `0 - ${maxCA}`;

        const maxRawCE_entry = activeAgeTable.ceScores[activeAgeTable.ceScores.length - 1];
        const maxCE = parseInt(String(maxRawCE_entry.rawScore).split('-').pop(), 10);
        rawScoreInputCE.setAttribute('data-max-value', maxCE);
        rawScoreInputCE.placeholder = `0 - ${maxCE}`;

        calculateComprensionAuditiva();
        calculateComunicacionExpresiva();
    } else {
        // Si la edad está fuera de rango
        rangoAplicadoElem.value = "Fuera de Baremo";
        gestionarCamposPLS(true); // Activa modo manual
        baremoManualSelect.classList.remove('hidden');
        baremoManualLabel.classList.remove('hidden');

        Swal.fire({
            icon: 'warning',
            title: 'Atención',
            text: `La edad ${tipoDeEdadUsada} a usar (${ageInMonthsForLookup} meses) está fuera del baremo automático. Puede ingresar los puntajes manualmente.`
        });
    }
}
    // --- EVENTOS Y VALIDACIÓN ---
document.addEventListener('DOMContentLoaded', function() {
    // 1. APLICAR VALIDACIONES A LOS CAMPOS
    const numericRegex = /^(|NA|\d*)$/;
    setupFieldValidation('input[name="comp_audi_punt_bruta"]', numericRegex);
    setupFieldValidation('input[name="expre_comuni_puntua_bruta"]', numericRegex);

    // 2. POBLAR LOS SELECTS
    pls5AgeTables.forEach(table => {
        let option = document.createElement('option');
        option.value = table.minAgeMonths; 
        option.textContent = table.ageRange;
        baremoManualSelect.appendChild(option);
    });

    const allSelects = [interpretationSelectCA, interpretationSelectCE, interpretationSelectLT];
    allSelects.forEach(select => {
        let defaultOption = document.createElement('option');
        defaultOption.value = "";
        defaultOption.textContent = "Seleccione una interpretación...";
        defaultOption.disabled = true;
        defaultOption.selected = true;
        select.appendChild(defaultOption);
        interpretacionesEstandar.forEach(item => {
            let option = document.createElement('option');
            option.value = item.text;
            option.textContent = item.text;
            select.appendChild(option);
        });
    });
    
    // 3. ESTADO INICIAL DEL FORMULARIO
    setPatientCondition();
    gestionarCamposPLS(true); // El formulario empieza deshabilitado/manual

    // 4. ASIGNAR EVENT LISTENERS
    document.getElementById('fecha_evaluacion').addEventListener('change', calculateAllAgesAndUpdate_PLS5);
    rawScoreInputCA.addEventListener('input', calculateComprensionAuditiva);
    rawScoreInputCE.addEventListener('input', calculateComunicacionExpresiva);
    
    [standardScoreOutputCA, standardScoreOutputCE, sumStandardOutputLT].forEach(el => {
        el.addEventListener('input', () => {
            if (isManualMode) {
                calculateLenguajeTotal();
            }
        });
    });

    // Listener del baremo manual
    document.getElementById('baremo_manual_select').addEventListener('change', function() {
        const rangoAplicadoElem = document.getElementById('rango_edad');
        const selectedMinMonths = parseInt(this.value, 10);

        if (selectedMinMonths > 0) {
            activeAgeTable = pls5AgeTables.find(t => t.minAgeMonths === selectedMinMonths);
            if (activeAgeTable) {
                rangoAplicadoElem.value = activeAgeTable.ageRange;
                gestionarCamposPLS(false);
                
                // Actualizar límites también en modo manual
                const maxCA = parseInt(String(activeAgeTable.caScores[activeAgeTable.caScores.length-1].rawScore).split('-').pop(), 10);
                rawScoreInputCA.setAttribute('data-max-value', maxCA);
                rawScoreInputCA.placeholder = `0 - ${maxCA}`;
                
                const maxCE = parseInt(String(activeAgeTable.ceScores[activeAgeTable.ceScores.length-1].rawScore).split('-').pop(), 10);
                rawScoreInputCE.setAttribute('data-max-value', maxCE);
                rawScoreInputCE.placeholder = `0 - ${maxCE}`;

                calculateComprensionAuditiva();
                calculateComunicacionExpresiva();
            }
        } else {
            calculateAllAgesAndUpdate_PLS5();
        }
    });
    
    // Listener del submit
    document.getElementById('myForm').addEventListener('submit', function(event) {
        event.preventDefault(); 
        const requiredFields = this.querySelectorAll('[required]:not([disabled])');
        let allValid = true;
        let firstInvalidField = null;
        requiredFields.forEach(field => {
            if (!field.value.trim()) {
                allValid = false;
                field.classList.add('is-invalid');
                if (!firstInvalidField) firstInvalidField = field;
            } else {
                field.classList.remove('is-invalid');
            }
        });
        if (!allValid) {
            Swal.fire({
                icon: 'error',
                title: 'Campos incompletos',
                text: 'Por favor, complete todos los campos marcados en rojo.'
            }).then(() => { if (firstInvalidField) firstInvalidField.focus(); });
        } else {
            this.submit();
        }
    });
});
    baremoManualSelect.addEventListener('change', function() {
        // <-- CAMBIO: ID CORREGIDO -->
        const rangoAplicadoElem = document.getElementById('rango_edad');
        const selectedMinMonths = parseInt(this.value, 10);

        if (selectedMinMonths > 0) {
            // Usuario ha elegido un baremo específico
            activeAgeTable = pls5AgeTables.find(t => t.minAgeMonths === selectedMinMonths);
            
            if (activeAgeTable) {
                rangoAplicadoElem.value = activeAgeTable.ageRange;
                gestionarCamposPLS(false); // Cambiar a modo automático
                
                // Disparamos un recálculo inmediato con el nuevo baremo activo
                calculateComprensionAuditiva();
                calculateComunicacionExpresiva();
            }
        } else {
            // Si el usuario selecciona "Seleccione baremo", volvemos a calcular todo desde cero
            calculateAllAgesAndUpdate_PLS5();
        }
});
</script>
</div>
</body>
</html>