WS_waitscreen = true;

window.onload = function(){
    
    // Window Load
    document.getElementsByClassName('pageCnt')[0].style.visibility="visible"
    var waitScreen = document.getElementById("waitScreen");
    document.body.removeChild(waitScreen);
    WS_waitscreen = false;
    document.getElementsByTagName('body')[0].style.opacity="1"
    
    // Go to Login Page
    document.getElementById('cancel').addEventListener("click", function(){
        gotoPage('login','main','')
    }); 
    
    // Recover
    document.getElementById('send').addEventListener("click", function(){
        //gotoPage('recover','alert','')
        noError('email','euser')
        recover()
    });
    
    // Remove red errors 
    document.getElementsByTagName('body')[0].addEventListener("click", function(){
        if (document.getElementById('email').value !== '' && document.getElementById('email').validity.valid ){
            noError('email','euser')
        }
        if(!document.getElementById('email').validity.valid){
            error('email','euser','El email no es válido.');
        }
    }); 
    
    // Focus 
    document.getElementById('email').addEventListener('keydown', (event) => emailE(event));
    
    
    //Mostrar HTML cargado
    esconderHTML(false);
}

function recover(){
    var email = document.getElementById('email');
    if ( email.value === "" ){
        error('email','euser','Introduzca un email.');
        return;
    } 
    else if (!email.validity.valid){
        error('email','euser','El email no es válido.');
    }else {
        var req = {
            "email": email.value,
        }
        console.log(req)
        document.getElementById('waitScreen').style.display ="table";
        callWS("GET", "login/forgot", req, response);
        
        function response(status, rsp){
            console.log(status)
            console.log(JSON.parse(status));
            switch(status){
                case 200:
                    gotoPage('recover','alert','')
                    break;
                case 400:
                    //document.getElementById('epassword').innerHTML = 'Error en la llamada del servicio.';
                    break;
                case 401:
                    document.getElementById('euser').innerHTML = 'El email no se encuentra registrado.';
                    break;
                case 500:
                    document.getElementById('epassword').innerHTML = 'Error inteno.';
                    break;
                default:
                    document.getElementById('epassword').innerHTML = 'Error.';
                    break;
            }
            document.getElementById('waitScreen').style.display ="none";
        }   
    }
}

// Error email
function emailE(event) {
    if (document.getElementById('email').validity.valid) {
        noError('email','euser')
    } else{
        error('email','euser','El email no es válido.');
    }
}