var asociations = '';
var show;

function saveInformation(){
    var rgx = /^[-\w.%+]{1,64}@(?:[A-Z0-9-]{1,63}\.){1,125}[A-Z]{2,63}$/i;
    var valNumber=/^([\(\)\-0-9]+){13,13}?$/;
    var error = document.getElementById('error');

    var params = {
        contact: document.getElementById('contactName').value,
        email: document.getElementById('email').value,
        position: document.getElementById('position').value,
        phone: document.getElementById('cellphone1').value,
        pwd: null,
        phonesecundary: document.getElementById('cellphone2').value,
        contactalt: document.getElementById('nameAlt').value,
        positionalt:  document.getElementById('positionAlt').value,
        emailalt: document.getElementById('emailAlt').value,
        phonealt:  document.getElementById('cellphoneAlt').value,
        hash: 1,
    };
    
    var groups = [...document.getElementsByName('checkboxAsociation')].filter((x) => x.checked).map((x)=>{
        if(x.value !== ''){
            return x.value;
         }
    });
    
    if(groups.length > 0 ){
        params.groups = groups.join('|');
    }
    
    if(!rgx.test(params.email)) {
        error.innerHTML = "El Correo Electrónico no es válido";
        scroll.scrollTop = 0;
        gotoTop();
    }else if (!rgx.test(params.emailalt) && params.emailalt !== ""){
        error.innerHTML = "El Correo Electrónico alternativo no es válido";
        gotoTop();
    }else if(!valNumber.test(params.phone) || params.phone.length != 13){
        error.innerHTML = "El número de teléfono 1 no es válido";
        gotoTop();
    }else if(!valNumber.test(params.phonesecundary) && params.phonesecundary !== "" || params.phonesecundary.length != 13 && params.phonesecundary.length != 0){
        error.innerHTML = "El número de teléfono 2 no es válido";
        gotoTop();
    }else if(!valNumber.test(params.phonealt) && params.phonealt !== "" || params.phonealt.length != 13 && params.phonealt.length != 0){
        error.innerHTML = "El número de teléfono alternativo no es válido";
        gotoTop();
    }else if(params.position === "" || params.contact === ""){
        error.innerHTML = "Campos De Contacto y Cargo no pueden estar vac\u00EDos";
        gotoTop();
    }else{
        error.innerHTML = "";
        loadScreen()
        callWS("GET", "login/saveregister", params, respx);
    }
    
    function gotoTop(duration = 1000){
        let element = document.documentElement;
        
        let to = document.getElementById('confirmation').offsetTop - 200;

        var difference = to - element.scrollTop;
        var perTick = difference / duration * 10;

        setTimeout(function() {
            element.scrollTop = element.scrollTop + perTick;
            if (element.scrollTop === to) return;
            gotoTop(duration - 10);
            }, 10);
    }
    
    function respx(status, respText){
        console.log(JSON.parse(respText));
        
        if ( status == 200 ){
            gotoTop();
            document.getElementById('confirmation').innerHTML = "Modificaci\u00F3n de Datos Exitosa";
            let timerVal = 0;
            var timer = setInterval(function(){
                timerVal++;
                if(timerVal == 2){
                    clearInterval(timer);
                    navigationMenu('infoCollege');
                }
            },1000);
        } else if ( status == 401 ) {
        }
        closeLoad();
    }
}

window.onload = function carga() {
    
    clearQtyPupils();
    
    var cellphone1 = document.getElementById('cellphone1');
    var cellphone2 = document.getElementById('cellphone2');
    var cellphonealt = document.getElementById('cellphoneAlt');
    //Logout
    document.getElementById('logOut').addEventListener("click", function(){
        gotoPage('login','main',{});
    });
    
    var params = {
        ssid: getSessionId(),  
    };
    
    loadScreen();
    callWS("GET", "schools/entry", params, respx);
    
    function respx(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        if (status == 200){
            asociations = json.asociations;
            showLabelPrivate(json.privat);
            json.editlocked ? disabledButton() : changeButton();
            //json.privat ? null : document.getElementById("estimatedLink").innerHTML = "Estimaci\u00F3n";
            //json.privat ? null : document.getElementById("responsiveEstimated").innerHTML = "Estimaci\u00F3n";
            
            document.getElementsByClassName('userName')[0].innerHTML = json.contact;
            document.getElementById('schoolName').innerHTML = json.name;
            //document.getElementsByClassName('registerPay')[0].style.display = json.privat ? 'block' : 'none';
        
            show = json.payment === null ? 0 : 1;
            document.getElementById('collegeName').value = json.name;
            document.getElementById('email').value = json.email;
            document.getElementById('idCollege').value = json.code;
            document.getElementById('state').value = json.region.name;
            document.getElementById('contactName').value = json.contact;
            document.getElementById('position').value = json.position;
            document.getElementById('cellphone1').value = json.phone;
            document.getElementById('cellphone2').value = json.phonesecundary == undefined ? "" : json.phonesecundary;
            document.getElementById('nameAlt').value = json.contactalt == undefined ? "" : json.contactalt;
            document.getElementById('positionAlt').value = json.positionalt == undefined ? "" : json.positionalt;
            document.getElementById('emailAlt').value = json.emailalt == undefined ? "" : json.emailalt;
            document.getElementById('cellphoneAlt').value = json.phonealt == undefined ? "" : json.phonealt;
        }
        closeLoad();
        
        loadGroups(getSessionId(), 3);
        disabledEstimatedBtn();
    }
    
    cellphone1.addEventListener('keydown',function(){formatedphone(cellphone1)});
    cellphone2.addEventListener('keydown',function(){formatedphone(cellphone2)});
    cellphonealt.addEventListener('keydown',function(){formatedphone(cellphonealt)});
    
    function formatedphone(input){
        var valNumber=/^(([0-9])|(ext|x)){1,11}$/;
        var originalNumber = "";
        var number = input.value.replace(/[(,),-]/g,"");
        input.value = "";
        var numbers = number.split("");
        
        for(let i = 0; i < numbers.length; i++){
            
            if(i === 0){
                originalNumber += "(" + numbers[i];
            }else if( i == 3){
                originalNumber += ")" + numbers[i];
            }else if( i == 6){
                originalNumber += "-" + numbers[i];
            }else{
                originalNumber += numbers[i];
            }
        }
        input.value = originalNumber;
        
        
    }
}

function loadGroups(sessionid, id){
    let params = {};
    
    params.sessionid = sessionid;
    params.id = id;
    
    loadScreen();
    callWS("GET", "settings/entry", params, respx);
    
    function respx(status, respText){
        console.log(JSON.parse(respText));
        var json = JSON.parse(respText);
        
        switch(status){
            case 200:
                var arrAcc = json.entry.content.split('|');
                var currentAs = asociations.split('|');
                arrAcc.forEach(el => {
                    var div = document.createElement('div');
                    var label = document.createElement('label');
                    var option = document.createElement('input');
                    
                    div.classList.add('checkBoxLabel');
                    
                    option.type = 'checkbox';
                    option.name = "checkboxAsociation";
                    option.id = el;
                    option.value = el;
                    option.classList.add('inputCheck');
                    
                    currentAs.forEach(elem => {
                        if(el == elem){
                            option.checked = true;
                        }
                    })
                    
                    label.setAttribute("for",el);
                    label.innerHTML = el;
                    
                    div.appendChild(option);
                    div.appendChild(label);
                    
                    document.getElementById('checkBoxDiv').appendChild(div);
                }) 
                break;
            default:
                console.log(json);
                break;
        }
        closeLoad();
    }
}

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

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 gotoTop(){
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
}

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