WS_waitscreen = true;

window.onload = function(){
    
    document.getElementsByClassName('pageCnt')[0].style.visibility="visible";
    // Window Load
    var waitScreen = document.getElementById("waitScreen");
    document.body.removeChild(waitScreen);
    WS_waitscreen = false;
    
    document.getElementById('email').value = getParameterByName('usr');
    
    if( getParameterByName('usr')!== '' ){
        error('password','epassword','Introduzca una contraseña.');
        error('confirmPassword','econfirm','Introduzca una contraseña.');
        if (screen.width <= 650){
            document.getElementById('epass').style.bottom = '34px';
            document.getElementById('econf').style.bottom = '34px'; 
        }
    }
    
    // Go to Register Term Page
    document.getElementById('previous-button').addEventListener("click", function(){
        gotoPage('register','register-term','');
    }); 
    
    // Go to Register Verification Page
    document.getElementById('next-button').addEventListener("click", function(){
        noError('email','euser');
        noError('password','epassword');
        document.getElementById('epass').style.bottom = '10px';
        noError('confirmPassword','econfirm');
        document.getElementById('econf').style.bottom = '10px';
        insert();
    }); 
    
    // Show or hide icon eye password
    document.getElementById('iconEye').addEventListener("click", function(){
        show('iconEye','password');
    }); 
    
    // Show or hide icon eye password confirm
    document.getElementById('iconEyeConfirm').addEventListener("click", function(){
        show('iconEyeConfirm','confirmPassword');
    }); 
    
    // Remove red errors 
    document.getElementsByTagName('body')[0].addEventListener("click", function(){
        if (document.getElementById('email').value !== '' && document.getElementById('email').validity.valid && isOkPass(document.getElementById('confirmPassword').value).result ){
            noError('email','euser');
        }
        if (document.getElementById('password').value !== '' && isOkPass(document.getElementById('confirmPassword').value).result){
            noError('password','epassword');
            document.getElementById('epass').style.bottom = '10px';
        }
        if (document.getElementById('confirmPassword').value !== '' 
            && document.getElementById('econfirm').innerHTML !== getLangById('usersinsert2')[lang] && isOkPass(document.getElementById('confirmPassword').value).result){
            noError('confirmPassword','econfirm');
            document.getElementById('econf').style.bottom = '10px';
        }
        if(!document.getElementById('email').validity.valid){
            error('email','euser',getLangById('usersinsert3')[lang]);
        }
    }); 
    
    // Focus
    document.getElementById('email').addEventListener('keydown', (event) => emailE(event));
    document.getElementById('email').addEventListener('keydown', (event) => focusE(event, 'password'));
    document.getElementById('password').addEventListener('keydown', (event) => focusE(event, 'confirmPassword'));
    document.getElementById('confirmPassword').addEventListener('keydown', (event) => focusE(event, 'next-button'));
    
    setLang();
}

// Show or Hide Password
function show(iconId,passwordId) {
    var icon = document.getElementById(iconId);
    var passwordInput = document.getElementById(passwordId);
    if (passwordInput.getAttribute('type') == "password") {
        icon.removeAttribute("class");
        icon.setAttribute("class","fas fa-eye");
        passwordInput.removeAttribute("type");
        passwordInput.setAttribute("type","text");
    } else {
        passwordInput.removeAttribute("type");
        passwordInput.setAttribute('type','password');
        icon.removeAttribute("class");
        icon.setAttribute("class","fas fa-eye-slash");
    };
}

// Service users/insert
function insert(){
    var user = document.getElementById('email');
    var pwd = document.getElementById('password');
    var cnf = document.getElementById('confirmPassword');
    if ( user.value === "" ) {
        error('email','euser',getLangById('usersinsert1')[lang]);
    } else if (!user.validity.valid){
        error('email','euser',getLangById('usersinsert3')[lang]);
    }
    if ( pwd.value === "" ){
        error('password','epassword',getLangById('usersinsert4')[lang]);
        if (screen.width<= 650){
            document.getElementById('epass').style.bottom = '34px';   
        }
    }
    if ( cnf.value === "" ){
        error('confirmPassword','econfirm',getLangById('usersinsert4')[lang]);
        if (screen.width<= 650){
            document.getElementById('econf').style.bottom = '34px';   
        }
    }
    
    if ( pwd.value == cnf.value && pwd.value !== '' && user.validity.valid ){
        if(isOkPass(pwd.value).result){
            var req = {
                "usr": user.value,
                "pwd": MD5(pwd.value),
                "lang": lang
            }
            callWS("GET", "users/insert", req, response);
                        
            function response(status, rsp){
                switch(status){
                    case 200:
                        gotoPage('register','register-verification',{ 'usr': req.usr });
                        break;
                    case 401:
                        error('confirmPassword','econfirm',getLangById('usersinsert401')[lang]);
                        if (screen.width<= 650){
                            document.getElementById('econf').style.bottom = '34px';   
                        }
                        break;
                    case 409:
                        document.getElementById('euser').innerHTML = getLangById('usersinsert409')[lang];
                        break;
                    default:
                        document.getElementById('econfirm').innerHTML =  getLangById('usersinsertdefault')[lang];
                        break;
                }
            }       
        }else{
            error('password','epassword',getLangById('usersinsert5')[lang]);
            error('confirmPassword','econfirm','');
            document.getElementById('epassword').style.width = '200%'
            document.getElementsByClassName('buttons')[0].style.marginTop = '60px'
            
            if (screen.width<= 650){
                document.getElementById('econf').style.bottom = '50px';   
                error('password','epassword','');
                error('confirmPassword','econfirm',getLangById('usersinsert5')[lang]);
                document.getElementById('epassword').style.width = '100%';
                document.getElementsByClassName('buttons')[0].style.marginTop = '30px';
            
                if (screen.width<= 532){
                    document.getElementById('econf').style.bottom = '65px';   
                }
                
                if (screen.width<= 368){
                    document.getElementById('econf').style.bottom = '81px';   
                }
                    
            }
            
        }
    } else if (cnf.value !== '' && pwd.value !== cnf.value) {
        error('confirmPassword','econfirm',getLangById('usersinsert2')[lang]);
        if (screen.width<= 650){
            document.getElementById('econf').style.bottom = '34px';   
        }
    }
}

// Error email
function emailE(event) {
    if (document.getElementById('email').validity.valid) {
        noError('email','euser')
    } else{
        error('email','euser',getLangById('usersinsert3')[lang]);
    }
}

function isOkPass(p){
    var anUpperCase = /[A-Z]/;
    var aLowerCase = /[a-z]/; 
    var aNumber = /[0-9]/;
    var aSpecial = /[!|@|#|$|%|^|&|*|(|)|-|_|.|=|+|\/]/;
    var obj = {};
    obj.result = true;

    if(p.length < 8){
        obj.result=false;
        obj.error="Not long enough!"
        return obj;
    }

    var numUpper = 0;
    var numLower = 0;
    var numNums = 0;
    var numSpecials = 0;
    for(var i=0; i<p.length; i++){
        if(anUpperCase.test(p[i]))
            numUpper++;
        else if(aLowerCase.test(p[i]))
            numLower++;
        else if(aNumber.test(p[i]))
            numNums++;
        else if(aSpecial.test(p[i]))
            numSpecials++;
    }

    if(numUpper < 1 || numLower < 1 || numNums < 1 || numSpecials <1){
        obj.result=false;
        obj.error="Wrong Format!";
        return obj;
    }
    return obj;
}

function setLang(){
    
    lang = lang = localStorage.getItem('lang') ? lang = localStorage.getItem('lang') : 'esp';
    
    /* inner HTML */
    setWordLanginnerHTML('register','register');
    setWordLanginnerHTML('register1','register1');
    setWordLanginnerHTML('register2','register2');
    setWordLanginnerHTML('register3','register3');
    setWordLanginnerHTML('register4','register4');
    setWordLanginnerHTML('titleRegister','register2');
    setWordLanginnerHTML('emailLabel','emailLabel');
    setWordLanginnerHTML('passwordLabel','passwordLabel');
    setWordLanginnerHTML('confirmPasswordLabel','confirmPasswordLabel');
    setWordLanginnerHTML('previous-button','previous');
    setWordLanginnerHTML('next-button','next');
    setWordLanginnerHTML('ts','ts');
    
    /* placeholder */
    setWordLangPlaceHolder('email','exampleEmail');
    setWordLangPlaceHolder('confirmPassword','confirmPasswordLabel');
    setWordLangPlaceHolder('password','passwordLabel');
    
    //Mostrar HTML cargado
    esconderHTML(false);   
}
