var located = new URLSearchParams(location.search);
var schoolid;
var student;
var page;
var numPages;
var qtyForPage = 10;
var order = "";
var like = located.get('like');

//Variables para entrada por excel
var totally = 0;
var studentsPerSection = [];
var validStudents = {};
var studentCi = [];
var grades = [];
var calculates = [];
var id;
var numOfRecords = 0;

var registerEnabled = 1;

// Manejo de colegio si es privado o publico
var isPrivate;

function disabledEstimatedBtn () {
    let params = {
        id: 7
    }
    loadScreen();
    callWS("GET", "settings/entryregister", params, respx);
    
    //Obtenemos los datos del servicio
    function respx(status, respText){
        var json = JSON.parse(respText);
        closeLoad();
        if (status == 200){
            if (json.entry.content == 0) {
                showLabelEstimated(json.entry.content)
            }
        }else{
            console.log(json.msg);
        }
    }
}

window.onload = function carga() {
    
    getRegisterEnabled();
    
    disabledEstimatedBtn();
    
    clearQtyPupils();
    
    var located = new URLSearchParams(location.search);
    document.getElementsByClassName('userName')[0].innerHTML = located.get('name');
    
    document.getElementById('schoolName').innerHTML = located.get('school');
    
    //Logout
    document.getElementById('logOut').addEventListener("click", function(){
        gotoPage('login','main',{});
    });
    
    page = located.get("page") == null ? 1 : parseInt(located.get("page"));
    
    var params = {
        ssid: getSessionId(),  
    };
    
    loadScreen()
    callWS("GET", "schools/entry", params, respx);
    
    function respx(status, respText){
        var located = new URLSearchParams(location.search);
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        if (status == 200){
            
            showLabelPrivate(json.privat);
            
            isPrivate = json.privat;
            
            document.getElementsByClassName('userName')[0].innerHTML = json.contact;
            document.getElementById('schoolName').innerHTML = json.name;
            json.editlocked ? disabledButton() : changeButtonLink();
            json.privat ? null : document.getElementById("estimatedLink").innerHTML = "Estimaci\u00F3n";
            //json.privat ? null : document.getElementById("responsiveEstimated").innerHTML = "Estimaci\u00F3n";
        }
        
        validStudents = json.estimatedpupils;
        id = json.id;
        grades = Object.keys(validStudents);
        
        for(let i = 0; i < grades.length; i++){
            studentsPerSection[grades[i]] = Object.values(validStudents[grades[i]]);
        }
        
        for(let i = 0; i < Object.keys(studentsPerSection).length ; i++){
            for(let j = 0; j < studentsPerSection[grades[0]].length; j++){
                if (studentsPerSection[grades[i]][j] != null && studentsPerSection[grades[i]][j] != undefined) {
                    totally += parseInt(studentsPerSection[grades[i]][j]);
                }
            }
        }
        
        calculates[0] = `Cupos estimados: ${totally}`;
        
        schoolid = json.id;
        order = located.get('order');
        like = located.get('like');
        
        var paramsList = {
            sessionid: getSessionId(),
            schoolid: json.id,
            filter: located.get('like') == 'null' || located.get('like') == null  ? `` : located.get('like'),
            offset: (page - 1) * qtyForPage,
            order: located.get('order') == 'null' || located.get('order') == null ? 'id ASC' : located.get('order'),
            numofrecords: qtyForPage,
        };
        
        callListOfPupils(paramsList);
        
        let paramsListExcel = {
            sessionid: getSessionId(),
            schoolid: json.id,
            filter: ``,
            offset: 0,
            order: `id ASC`,
            numofrecords: totally,
        };
        
        loadExcelValidator(paramsListExcel);
    }
}

function disabledButton(){
    document.getElementsByClassName('registerStudents')[0].style.opacity = 0.5;
    document.getElementById('studentLink').style.cursor = "default";
    document.getElementById('studentLink').setAttribute('href','javascript:void(0)');
    
    document.getElementById('linkPupils').style.opacity = 0.5;
    document.getElementById('linkPupils').style.cursor = "default";
    document.getElementById('linkPupils').setAttribute('href','javascript:void(0)');
}

function changeButtonLink(){
    var link = document.getElementById('studentLink');
    link.setAttribute('href',`javascript:navigationMenu('searchStudent')`);
}

function changeOrder(event){
    var located = new URLSearchParams(location.search);
    
    var paramsList = {
        sessionid: getSessionId(),
        schoolid: schoolid,
        filter: like == 'null' || like == null ? `` : like,
        offset: (page - 1) * qtyForPage,
        order: located.get('order'),
        numofrecords: qtyForPage,
    };
    
    var arrowsUp = document.getElementsByClassName('up');
    var arrowsDown = document.getElementsByClassName('down');
    
    for(let i = 0; i< arrowsUp.length; i++){
        arrowsDown[i].setAttribute('onclick','changeOrder(this)');
        arrowsUp[i].setAttribute('onclick','changeOrder(this)');
        
        arrowsDown[i].style.borderColor = "#FFF";
        arrowsUp[i].style.borderColor = "#FFF";
        arrowsDown[i].style.cursor = "pointer";
        arrowsUp[i].style.cursor = "pointer";
    }
    
    
    var arrow = document.getElementById(event.id);
    arrow.setAttribute('onclick','');
    arrow.style.cursor = "auto";
    arrow.style.borderColor = "#BBB";
    
    
    switch(event.id){
        case "idUp":
            order = "id ASC";
            break;
        case "idDown":
            order = "id DESC";
            break;
        case "gradeUp":
            order = "level ASC";
            break;
        case "gradeDown":
            order = "level DESC";
            break;
        case "sectionUp":
            order = "section ASC";
            break;
        case "sectionDown":
            order = "section DESC";
            break;
        case "nameUp":
            order = "name ASC";
            break;
        case "nameDown":
            order = "name DESC";
            break;
        case "ciUp":
            order = "ci ASC";
            break;
        case "ciDown":
            order = "ci DESC";
            break;
        case "birthdateUp":
        case "ageUp":
            order = "birthdate  ASC";
            break;
        case "birthdateDown":
        case "ageDown":
            order = "birthdate DESC";
            break;
        case "genderUp":
            order = "gender ASC";
            break;
        case "genderDown":
            order = "gender DESC";
            break;
    }
    
    paramsList.order = order;
    
    var table = document.getElementsByClassName("tableResult")[0].rows;
    var rowCount = table.length;
    
    for(let i = rowCount - 1; i > 0; i--){
        table[i].closest('tr').remove();
    }
    callListOfPupils(paramsList);
}

function loadExcelValidator(paramsList){
    callWS("GET", "pupils/list", paramsList, respxList);
    
    var interactions = totally;
    
    function respxList(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        
        if (status == 200){
            calculates[1] = `Alumnos registrados: ${json.numofrecords}`;
            if(json.records != null){
                for(let i = 0; i < json.records.length ; i++){
                    if(json.records[i].id !== null){
                        totally--;
                        studentCi[i] = json.records[i].ci;
                    }
                }
            }
        }
        calculates[2] = `Cupos disponibles: ${totally}`;
    }
}

function callListOfPupils(paramsList){
    callWS("GET", "pupils/list", paramsList, respxList);
    
    var interactions = totally;
    
    function respxList(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        student = json.records;
        if (status == 200){
            numPages = Math.ceil(json.numofrecords/10);
            putValues(json);
            numOfRecords =json.numofrecords;
        }
        
        closeLoad();
    }
    
}

function putValues(json){
    if(json.records != null){
        for(let i = 0; i < json.records.length; i++){
            if(json.records[i].name !== null ){
                document.getElementsByClassName('tableResult')[0].insertRow(-1).innerHTML = `
                <td>${json.records[i].code}</td>
                <td>${json.records[i].level}${abrev(json.records[i].level)}</td>
                <td class="section">${json.records[i].grade}</td>
                <td>${json.records[i].name + " " + json.records[i].surname}</td>
                <td>${json.records[i].ci}</td>
                <td class="birth">${json.records[i].birthdate.formatted}</td>
                <td class="age">${calculateAge(json.records[i].birthdate.formatted)}</td>
                <td class="gender">${json.records[i].gender.dsc}</td>
                <td class="idStudent">${json.records[i].id}</td>`;
                addEvent();
            }
        }
        
        
    }
    makeNumbers();
}

const abrev = level => {
    return level == "3" || level == "1" ? "ro" : (level == "2" ? "do" : "to");
}

const makeNumbers = () => {
    var container = document.getElementsByClassName('listPages')[0];
    var linkers = "";
    for(let i = 0; i < numPages; i++){
        if(numPages == 1){
            linkers += `<li><a href='javascript:paginationNavigate(${i+1})' class="pagination" id="${i+1}">${i+1}</a></li>`;
        }else if(i === 0){
            linkers +=`<li><a href='javascript:paginationNavigate(${1})' class="pagination"><<</a></div>`;
            linkers +=`<li><a href='javascript:paginationNavigate(${page == 1 ? 1 : page-1})' class="pagination"><</a></li>`;
            linkers += `<li><a href='javascript:paginationNavigate(${i+1})' class="pagination" id="${i+1}">${i+1}</a></li>`;
        }else if(i == numPages-1){
            linkers += `<li><a href='javascript:paginationNavigate(${i+1})' class="pagination" id="${i+1}">${i+1}</a></li>`;
            
            linkers +=`<li><a href='javascript:paginationNavigate(${page == numPages ? numPages : page + 1})' class="pagination">></a></li>`;
            
            linkers +=`<li><a href='javascript:paginationNavigate(${numPages})' class="pagination">>></a></li>`;
        }else{
            linkers += `<li><a href='javascript:paginationNavigate(${i+1})' class="pagination" id="${i+1}">${i+1}</a></li>`;
        }
    }
    container.innerHTML = linkers;
    if(document.getElementById(`${page}`) != null){
        document.getElementById(`${page}`).style.color = '#F68E1E';
    }
    
}

function addEvent() {
  var table = document.getElementsByClassName("tableResult")[0];
  var rows = document.getElementsByTagName("tr");
  for (i = 0; i < rows.length; i++) {
    var actRow = table.rows[i];
    var createClickHandler = function(row) {
      return function() {
        var cell = row.getElementsByClassName("idStudent")[0];
        
        if(cell === undefined){
            return 0;
        }
        
        var id = cell.innerHTML;
        
        var popup = document.getElementsByClassName("popup")[0];
        var information = {};
        
        for(let i = 0; i < student.length; i ++){
            if(student[i].id == id){
                information = student[i];
            }
        }
    
        var style = document.createElement('style');
        document.head.appendChild(style);
        gotoTop();
        style.sheet.insertRule(`.popup {position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                overflow: auto;
                height: ${window.screen.height <= 635 ? "auto" : '100%'};
                background-color: rgba(0,0,0,0.5); display:flex; align-items: center;
                ${window.screen.height <= 635 ? 'padding: 10px 0px;' : null}}`);
        
        document.body.style.overflow = window.screen.height <= 635 ? "scroll" : "hidden";
        
        popup.innerHTML = `<div class='infoWindow'>
            <div class="close" onclick="closeWithX()">
                <span name="popup">X</span>
            </div>
            <h2>Editar Registro</h2>
            <form class="modifyForm"> 
                <div class="inputRow">
                    <div class="inputLabel">
                        <label for="nameInput">Nombre</label>
                        <input type="text" placeholder="Nombre..." class="inputInfo" id="nameInput" value="${information.name}">
                    </div>
                    <div class="inputLabel">
                        <label for="surnameInput">Apellido</label>
                        <input type="text" placeholder="Apellido..." class="inputInfo" id="surnameInput" value="${information.surname}">
                    </div>
                </div>
                <div class="inputRow">
                    <div class="inputLabel">
                        <label for="genderInput">G\u00E9nero</label>
                        <select class="inputInfo" id="genderInput">
                            <option value="${information.gender.id != "M" ? "F" : "M"}" selected>${information.gender.id != "M" ? "Femenino" : "Masculino"}</option>
                            <option value="${information.gender.id == "M" ? "F" : "M"}">${information.gender.id == "M" ? "Femenino" : "Masculino"}</option>
                        </select>
                    </div>
                    <div class="inputLabel">
                        <label for="birthDateInput">Fecha de Nacimiento</label>
                        <input type="date" class="inputInfo" id="birthDateInput" value="${information.birthdate.formatted}">
                    </div>
                </div>
                <div class="inputRow">
                    <div class="inputLabel">
                        <label for="ciInput">C\u00E9dula Escolar</label>
                        <input type="text" placeholder="Cedula..." id="ciInput" class="inputInfo" value="${information.ci}">
                    </div>
                    <div class="inputSelections">
                        <div Class="inputLabel">
                            <label for="gradeInput">Grado</label>
                            <select id="gradeInput" class="sectionGrade">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="5">5</option>
                                <option value="6">6</option>
                            </select>
                        </div>
                        <div Class="inputLabel">
                            <label for="sectionInput">Secci\u00F3n</label>
                            <select id="sectionInput" class="sectionGrade">
                                <option value="A">A</option>
                                <option value="B">B</option>
                                <option value="C">C</option>
                                <option value="D">D</option>
                                <option value="E">E</option>
                                <option value="F">F</option>
                                <option value="G">G</option>
                                <option value="H">H</option>
                                <option value="I">I</option>
                                <option value="J">J</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="inputRow">
                    <button type="button" class="buttonModify" onclick="updateStudent(${information.id})">Guardar</button>
                    <button type="button" class="buttonModify" onclick="deleteStudent(${information.id})">Eliminar</button>
                </div>
            </form>
        </div>`;
        
        var dateNow = document.getElementById('birthDateInput');
        dateNow.max = new Date().toISOString().split("T")[0];
        
        var selectSection = document.getElementById('sectionInput');
        var selectGrade = document.getElementById('gradeInput');
        
        selectSection.value = information.grade;
        selectGrade.value = information.level;
      };
    };
    actRow.onclick = createClickHandler(actRow);
  }
}

function gotoTop(){
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
}

function closeWithX(){
    var style = document.createElement('style');
    document.head.appendChild(style);
    style.sheet.insertRule(`.popup {display: none}`);
    document.body.style.overflow = "visible";
}

function closeExcelWithX(){
    var style = document.createElement('style');
    document.head.appendChild(style);
    style.sheet.insertRule(`.excelEntry {display: none}`);
    document.body.style.overflow = "visible";
}

function closeWindow(){
    var modal = document.getElementsByClassName('popup')[0];
    window.onclick = function(event) {
        if (event.target == modal) {
            var style = document.createElement('style');
            document.head.appendChild(style);
            style.sheet.insertRule(`.popup {display: none}`);
            document.body.style.overflow = "visible";
        }
    }
}

function closeExcelEntry(){
    var modal = document.getElementsByClassName('excelEntry')[0];
    window.onclick = function(event) {
        if (event.target == modal) {
            var style = document.createElement('style');
            document.head.appendChild(style);
            style.sheet.insertRule(`.excelEntry {display: none}`);
            document.body.style.overflow = "visible";
        }
    }
}

function calculateAge(birthdate){
    birthdate = new Date(birthdate);
    let today = new Date();
    let age = today.getFullYear() - birthdate.getFullYear();
    let month = today.getMonth() - birthdate.getMonth();
    
    if (month < 0 || (month === 0 && today.getDate() < birthdate.getDate())) {
        age--;
    }
    
    return age;
}

function updateStudent(id){
    var information = {};
    
    for(let i = 0; i < student.length; i ++){
        if(student[i].id == id){
            information = student[i];
        }
    }
    
    var params = {
      sessionid: getSessionId(),
      id: information.id,
      name: document.getElementById('nameInput').value,
      schoolid: schoolid,
      surname: document.getElementById('surnameInput').value,
      ci: document.getElementById('ciInput').value,
      gender: document.getElementById('genderInput').value,
      birthdate: document.getElementById('birthDateInput').value,
      level: document.getElementById('gradeInput').value,
      section: document.getElementById('sectionInput').value,
    };
    
    loadScreen();
    callWS("POST", "pupils/update", params, respx);
    
    function respx(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        if (status == 200){
            navigationMenu('searchStudent');
        }
        closeLoad();
    }
}

function deleteStudent(id){
    let params = {
        sessionid: getSessionId(),
        id: id,
    }
    
    loadScreen();
    callWS("GET", "pupils/delete", params, respx);
    
    function respx(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        if (status == 200){
            navigationMenu('searchStudent');
        }
        closeLoad();
    }
}

function paginationNavigate(page){
    var params = {
        page: page,
        like: like,
    }
    
    if(order != ""){
        params.order = order;
    }
    
    gotoPage('home','searchStudent',params);
}

function searching(e){
    if(e.keyCode == 13){
        var located = new URLSearchParams(location.search);
        
        like = e.target.value;
        page = 1;
        var paramsList = {
            sessionid: getSessionId(),
            schoolid: schoolid,
            filter: like,
            offset: (page - 1) * qtyForPage,
            order: located.get('order') == 'null' || located.get('order') == null ? 'id ASC' : located.get('order'),
            numofrecords: qtyForPage,
        };
        
        var table = document.getElementsByClassName("tableResult")[0].rows;
        var rowCount = table.length;
    
        for(let i = rowCount - 1; i > 0; i--){
            table[i].closest('tr').remove();
        }
    
        loadScreen()
        callListOfPupils(paramsList);
    }
}

function showPopup(){
    
    var popup = document.getElementsByClassName("excelEntry")[0];
    
    var style = document.createElement('style');
    document.head.appendChild(style);
    gotoTop();
    style.sheet.insertRule(`.excelEntry {position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        overflow: auto;
        height: ${window.screen.height <= 635 ? "auto" : '100%'};
        background-color: rgba(0,0,0,0.5); display:flex; align-items: center;
        ${window.screen.height <= 635 ? 'padding: 10px 0px;' : null}}`);
        
    document.body.style.overflow = window.screen.height <= 635 ? "scroll" : "hidden";
    
    popup.innerHTML =`<div class='infoExcel'>
            <div class="close" onclick="closeExcelWithX()">
                <span name="popup">X</span>
            </div>
            <div class='excelContent'>
                
                <ol>
                    <li>Descargue la plantilla de Excel desde <a class='template' href="templates/formato_datosOR.xlsx" download>AQU&Iacute;</a></li>
                    <li>Llene la informaci&oacute;n de los alumnos siguiendo los ejemplos de la plantilla</li>
                    <li>Una vez cargados todos los datos, remarque toda la informaci&oacute;n <b>(Incluyendo la cabecera de las columnas)</b> y haga un copiar/pegar en el siguiente espacio:</li>
                </ol>
                
                <form class="excelProcess">
                    <div class="qtyPupils">
                        <span class="estimatedPupil">${calculates[0]}</span>
                        <span class="pupilsReg" style="${calculates[1] == undefined ? "display:none;" : null}">${calculates[1]}</span>
                        ${ isPrivate ? `<span class="pupilsAval">${calculates[2]}</span>` : '' }
                    </div>
                    
                    <span class="errorExcel"></span>
                    <textarea class="excelInfo" rows="10"></textarea>
                    <button type="button" class="saveExcelData" onclick="giveFormatt()">Continuar</button>
                </form>
            </div>
    </div>`;
}

function giveFormatt(){
    let student = [];
    let valores = document.getElementsByClassName("excelInfo")[0];
    let rows = valores.value.split("\n");
    let cells = [];
    let valId=/^(([0-9])|(ext|x)){1,12}$/;
    let today = new Date();
    let validDate;
    let error = document.getElementsByClassName("errorExcel")[0];
    let validCells = 0;
    let located = new URLSearchParams(location.search);
    let validateSection = /[^A-Ja-j]/;
    let validateGender = /(^[FMfm])/;
    let dateParts;
    let buttonCharge = document.getElementsByClassName("saveExcelData")[0];
    
    if(valores.value == ""){
        error.innerHTML = "Caja de texto vac\u00EDa";
        return 0;
    }
    
    for(let i = 1; i < rows.length; i++){
        cells.push(rows[i].split("\t"));
    }
 
    
    buttonCharge.setAttribute('disabled','');
    buttonCharge.style.opacity= 0.5;
    loadScreen();
    
    for(let i = 0; i<cells.length; i++){
        if(cells[i].length > 1 && cells[i][0] != "JUAN VICENTE" || cells[i][1] != "RIVAS RAMOS" || cells[i][2] != 30000000){
            validCells++;
            if(cells[i][0] != "" && cells[i][1] != "" && cells[i][3] != "" && cells[i][4] != "" && cells[i][5] != "" && cells[i][6] != "" && cells[i].length == 7){
                
                dateParts = cells[i][4].split("-");
                
                validDate = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
                
                if(validDate.getFullYear() > today.getFullYear() || validDate.getFullYear() < 2004 || isNaN(validDate.getTime())){
                    activeButton(buttonCharge);
                     closeLoad();
                    error.innerHTML = "Contiene una fecha de Nacimiento incorrecta";
                    return 0;
                }else if(!valId.test(cells[i][2]) && cells[i][2] != "" || (cells[i][2] > 99999999999 && cells[i][2] != "")){
                    console.log(cells[i][2] > 99999999999, cells[i])
                    activeButton(buttonCharge);
                     closeLoad();
                    error.innerHTML = "Contiene una Identificaci\u00F3n incorrecta";
                    return 0;
                }else if(evaluateStudent(validCells)){
                    activeButton(buttonCharge);
                     closeLoad();
                    error.innerHTML = "Excedi\u00F3 el n\u00FAmero de alumnos estimados";
                    return 0;
                }else if(validateCi(cells[i][2])){
                    activeButton(buttonCharge);
                     closeLoad();
                    error.innerHTML = "Contiene c\u00E9dulas ya ingresadas";
                    return 0;
                }else if(cells[i][5] < 1 || cells[i][5] > 6){
                    activeButton(buttonCharge);
                     closeLoad();
                    error.innerHTML = "Contiene un grado incorrecto";
                    return 0;
                }else if(validateSection.test(cells[i][6])){
                    activeButton(buttonCharge);
                    closeLoad();
                    error.innerHTML = "Contiene una secci\u00F3n incorrecta";
                    return 0;
                }else if(!validateGender.test(cells[i][3])){
                    activeButton(buttonCharge);
                    closeLoad();
                    error.innerHTML = "Contiene un g\u00E9nero incorrecto";
                    return 0;
                }else{
                    if( validCells === 1 ){
                
                        student['name'] = capitalize(cells[i][0]);
                        student['lastName'] = capitalize(cells[i][1]);
                        student['ci'] = cells[i][2];
                        student['gender'] = cells[i][3];
                        student['birthDate'] = validDate.toISOString().split('T')[0];
                        student['grade'] = cells[i][5];
                        student['section'] = cells[i][6];
                
                    }else{
                
                        student['name'] += "~" + capitalize(cells[i][0]);
                        student['lastName'] += "~" + capitalize(cells[i][1]);
                        student['ci'] += "~" + cells[i][2];
                        student['gender'] += "~" + cells[i][3];
                        student['birthDate'] += "," + validDate.toISOString().split('T')[0];
                        student['grade'] += "~" + cells[i][5];
                        student['section'] += "~" + cells[i][6];
                    }
                }
            }else{
                if(cells[i].length != 1){
                    activeButton(buttonCharge);
                    closeLoad();
                    error.innerHTML = "Campos Vac\u00EDos";
                    return 0;
                }
            }
        }else{
            activeButton(buttonCharge);
            closeLoad();
            error.innerHTML = "Debe borrar la linea de ejemplo";
            return 0;
        }
    }
    
    if(student['name'].length > 0){
        error.innerHTML = "";
        var params = {
            name: student['name'],
            surname: student['lastName'],
            gender: student['gender'].toUpperCase(),
            birthdate: student['birthDate'],
            ci: student['ci'],
            level: student['grade'],
            section: student['section'].toUpperCase(),
            sessionid: getSessionId(),
            schoolid: id,
            id: 0,
        }
        
        loadScreen();
        callWS("POST", "pupils/update", params, respx);
        
        function respx(status, respText){
            console.log(JSON.parse(respText));
            var json = JSON.parse(respText);
            if (status == 200){
                let timerVal = 0;
                var timer = setInterval(function(){
                    timerVal++;
                    if(timerVal == 2){
                        clearInterval(timer);
                        closeLoad();
                        navigationMenu('searchStudent');
                    }
                },1000);
            }else if( status == 404){
                activeButton(buttonCharge);
                error.innerHTML = "No se pudo modificar";
            }else if(status == 414){
                closeLoad();
                activeButton(buttonCharge);
                error.innerHTML = "Lista muy larga";
            }
            
            closeLoad();
        }
    }
    
}

const activeButton = button => {
    button.style.opacity= 1;
    button.removeAttribute('disabled','');
}

function validateCi(id){
    if(id == ""){
        return false;
    }else{
        for(let i = 0; i < studentCi.length ; i++){
            if(id == studentCi[i]){
                return true;
            }
        }
        return false;
    }
}

function evaluateStudent(registered){
    
    if(isPrivate){
        let validator = totally-registered;
        calculates[2] = `Cupos disponibles: ${validator < 0 ? 0 : totally}`;
        if(validator < 0){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

function deleteSavedPupils(){
    if(confirm("Seguro que desea eliminar todos los estudiantes ya ingresados?\nEsta informaci\u00F3n no podr\u00E1 ser recuperada.")){
        let params = {
            sessionid: getSessionId(),
            id: id,
            deleteall: 1,
        }
        
        loadScreen()
        callWS("GET", "pupils/delete", params, respx);
    
        function respx(status, respText){
            console.log(JSON.parse(respText));
            var json = JSON.parse(respText);
            if (status == 200){
                navigationMenu('searchStudent');
            }
            closeLoad();
        }
    }
}

const capitalize = string => {
    let names = string.split(" ");
    if(names.length > 1){
        let allName = "";
        for(let i = 0; i < names.length; i++){
            if(i == 0){
                allName += names[i].charAt(0).toUpperCase() + names[i].slice(1);
            }else{
                allName += " " + names[i].charAt(0).toUpperCase() + names[i].slice(1);
            }
        }
        return allName;
    }else{
        return names[0].charAt(0).toUpperCase() + names[0].slice(1);
    }
}

function exportTableToExcel(){
    let paramsList = {
        sessionid: getSessionId(),
        schoolid: schoolid,
        filter: ``,
        offset: 0,
        order: `id ASC`,
        numofrecords: numOfRecords,
    };
    
    callWS("GET", "pupils/list", paramsList, respxList);

    function respxList(status, respText){
        var json = JSON.parse(respText);
        if (status == 200){
            arrayObjToCsv(json.records);
        }
    }
}

function arrayObjToCsv(ar) {
    var arr = []
    for(let i = 0; i < ar.length; i++){
        arr[i] = {
            id: ar[i].code,
            grado: ar[i].level,
            seccion: ar[i].grade,
            nombre: ar[i].name,
            apellido: ar[i].surname,
            cedula: ar[i].ci,
            nacimiento: ar[i].birthdate.formatted,
            genero: ar[i].gender.id,
        }
    }

	if(window.Blob && (window.URL || window.webkitURL)){
		let contenido = "";
		contenido = "sep=,\n";
		let encoding = "data:text/csv;charset=utf-8,%EF%BB%BF";
		for (let i = 0; i < ar.length; i++) {
			//cabecera del csv
			if (i == 0){
				contenido += "ID,Grado,Secci\u00F3n,Nombre,Apellido,C\u00E9dula,Fecha de nacimiento,G\u00E9nero" + "\n";
			}
			//resto del contenido
			contenido += Object.keys(arr[i]).map(function(key){
							return arr[i][key];
						}).join(",") + "\n";
						
		}
		var encodedUri = encodeURI(contenido);
        var link = document.createElement("a");
        link.setAttribute("href", encoding + escape(contenido));
        link.setAttribute("download", "student_data.csv");
        link.click();
	}
	
};

function loadScreen() {
    var popup = document.getElementsByClassName("popupLoad")[0];
    
    var style = document.createElement('style');
    document.head.appendChild(style);
    gotoTop();
    style.sheet.insertRule(`.popupLoad {position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: ${window.screen.height <= 635 ? "auto" : '100%'};
        background-color: rgba(0,0,0,0.5); display:flex; align-items: center;
        ${window.screen.height <= 635 ? 'padding: 10px 0px;' : null}}`);
    
    document.body.style.overflowY = window.screen.height <= 635 ? "scroll" : "hidden";
        
    popup.innerHTML = `
    <div class="loaded">
        <div class="loaderWrapper">
            <div class="loader"></div>
        </div>
    </div>`;
}

function closeLoad() {
    var popup = document.getElementsByClassName("popupLoad")[0];
    var style = document.createElement('style');
    document.head.appendChild(style);
    
    style.sheet.insertRule(`.popupLoad {display: none}`);
        document.body.style.overflowY = "scroll";
}

function getRegisterEnabled(){
    let params = {
        id: 7
    }
    loadScreen();
    callWS("GET", "settings/entryregister", params, respx);
    
    //Obtenemos los datos del servicio
    function respx(status, respText){
        var json = JSON.parse(respText);
        closeLoad();
        if (status == 200){
            registerEnabled = parseInt(json.entry.content);
            
            if(registerEnabled == 0){
                document.getElementById('addNewPupils').style.opacity = 0.5;
                document.getElementById('addNewPupils').style.cursor = 'default';
                document.getElementById('addNewPupils').setAttribute("onclick", "")
                
                
                document.getElementById('loadByExcel').style.opacity = 0.5;
                document.getElementById('loadByExcel').style.cursor = 'default';
                document.getElementById('loadByExcel').setAttribute("onclick", "")
            }
        }else{
            console.log(json.msg);
        }
    }
}