WS_waitscreen = true;
window.onload = function(){
    
    // Call Entry
    getEntry(getParameterByName('sessionid'));
    document.getElementById('example-element-toggle').checked = false;
     
    // Go to preferences
    document.getElementById('home').addEventListener("click", function(){
        goToStart()
    });
    
    // Go to preferences
    document.getElementById('homeR').addEventListener("click", function(){
        goToStart()
    });
    
    // Go to balance
    document.getElementById('balance').addEventListener("click", function(){
        gotoPage('balance','balance',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to balance
    document.getElementById('balanceR').addEventListener("click", function(){
        gotoPage('balance','balance',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    getCountries()
    
    document.getElementById('logouticon').addEventListener("click", function(){
        logout();
    });
    document.getElementById('logouticon2').addEventListener("click", function(){
        logout();
    });
    
    document.getElementById('seeTerms').addEventListener("click", function(){
        //window.open('./img/termandconditions.pdf', '_blank');
        gotoNewPage('register','termsandconditions');
    }); 
    
    var selector = document.getElementsByName('bank')[0];
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = 'Forma de pago'
    firstOopcion.value =''
    firstOopcion.selected = true
    selector.add(firstOopcion);
    
    var selector = document.getElementsByName('currency')[0];
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = 'Moneda'
    firstOopcion.value =''
    firstOopcion.selected = true
    selector.add(firstOopcion);
    
    document.getElementById('status').value = '';
    document.getElementById('detail1').value = '';
    document.getElementById('detail2').value = '';
    document.getElementById('detail3').value = '';
    document.getElementById('detail4').value = '';
    
    // Add
    document.getElementById('add').addEventListener("click", function(){
        document.getElementById("modalTit").innerHTML = "Agregar Cuenta";
        var el = document.getElementById('addView')
        //el.style.display = 'block';
        //el.style.display = (el.style.display == 'none') ? 'block' : 'none';
        //document.getElementById('datas').style.display = 'none';
        document.getElementById('addView').style.display = 'block';
        document.getElementById('status').value = '';
        document.getElementById('country').value = '';
        document.getElementById('detail1').value = '';
        document.getElementById('detail2').value = '';
        document.getElementById('detail3').value = '';
        document.getElementById('detail4').value = '';
        
        document.getElementById("addAccount").setAttribute("accid",0);
        
        if(!document.getElementById('example-element-toggle').checked){
            setTimeout(function(){ 
                document.getElementById('example-element-toggle').checked = !document.getElementById('example-element-toggle').checked;
            }, 15);   
        }
        var camposIn = document.getElementById("example-toggled-element").getElementsByTagName("input");
        for(var i=0;i<camposIn.length;i++){
            camposIn[i].removeAttribute("disabled");
        }
        var camposSel = document.getElementById("example-toggled-element").getElementsByTagName("select");
        for(var i=0;i<camposSel.length;i++){
            camposSel[i].removeAttribute("disabled");
        }
        document.getElementById("addAccount").style.display = "";
        
    });
    
    document.getElementById('levelP').addEventListener("click", function(){
        
        var el = document.getElementById('addView3')
        //el.style.display = 'block';
        //el.style.display = (el.style.display == 'none') ? 'block' : 'none';
        //document.getElementById('datas').style.display = 'none';
    
        if(!document.getElementById('example-element-toggle3').checked){
            document.getElementById('addView3').style.display = 'block';
        }
        //document.getElementById('example-element-toggle3').checked = !document.getElementById('example-element-toggle3').checked;
    
        setTimeout(function(){ 
            document.getElementById('example-element-toggle3').checked = !document.getElementById('example-element-toggle3').checked;
            /*if(document.getElementById('example-element-toggle3').checked){
                document.getElementById('addView3').style.display = 'block';
            }else{
                document.getElementById('addView3').style.display = 'none';
            }*/
            setTimeout(function(){ 
                if(!document.getElementById('example-element-toggle3').checked){
                    document.getElementById('addView3').style.display = 'none';
                }
            }, 1020); 
        }, 15);   
        
        
    });
    
    // Bar
    document.getElementById('togglebar').addEventListener("click", function(){
        console.log('hola')
        var el = document.getElementById('addView2')
        //el.style.display = 'block';
        //el.style.display = (el.style.display == 'none') ? 'block' : 'none';
        //document.getElementById('datas').style.display = 'none'
        document.getElementById('addView2').style.display = 'block'
        
        setTimeout(function(){ 
            document.getElementById('example-element-toggle2').checked = !document.getElementById('example-element-toggle2').checked;
        }, 15);   
        
    });
    
    if (screen.width < 700){
        clonar();   
    }
    
    
    // ChangePassword
    document.getElementById('changePassword').addEventListener("click", function(){
        document.getElementsByClassName('changepassword')[0].style.display = "table"
    });
    
    // NoChangePassword
    document.getElementById('goback').addEventListener("click", function(){
        document.getElementsByClassName('changepassword')[0].style.display = "none"
        document.getElementById('passwordOld').value = ''
        document.getElementById('password').value = ''
        document.getElementById('passwordNew').value = ''
        
    });
    
    // ChangePassword
    document.getElementById('change').addEventListener("click", function(){
        changePassword()
    });
    
    // Remove red errors 
    document.getElementsByTagName('body')[0].addEventListener("click", function(){
        if (document.getElementById('status').value !== ''){
            document.getElementById('status').style.border ="1px solid #D5DCE5";
        }
        if (document.getElementById('detail1').value !== ''){
            document.getElementById('detail1').style.border ="1px solid #D5DCE5";
        }
        if (document.getElementById('currency').value !== ''){
            document.getElementById('currency').style.border ="1px solid #D5DCE5";
        }
        if (document.getElementById('country').value !== ''){
            document.getElementById('country').style.border ="1px solid #D5DCE5";
        }
        if (document.getElementById('bank').value !== ''){
            document.getElementById('bank').style.border ="1px solid #D5DCE5";
        }
        if(document.getElementById('status').value !== '' && document.getElementById('detail1').value !== '' && document.getElementById('currency').value !== '' && 
            document.getElementById('country').value !== '' &&  document.getElementById('bank').value !== ''){
                document.getElementById('generalerror').innerHTML = '';
            }
        for ( var i = 0 ; i < document.getElementsByClassName('errorspecial').length ; i++){
            document.getElementsByClassName('errorspecial')[i].innerHTML = ''
        }
        
        if (document.getElementById('passwordOld').value !== ''){
            noError('passwordOld','epasswordold')
            document.getElementById('epasswordold').style.bottom = '10px';
        }
        
        if (document.getElementById('password').value !== ''){
            noError('password','epassword')
            document.getElementById('epassword').style.bottom = '10px';
        }
        
        if (document.getElementById('passwordNew').value !== ''  && document.getElementById('epasswordnew').innerHTML != 'Las contraseñas no coinciden.' && 
        document.getElementById('epasswordnew').innerHTML != 'La contraseña debe tener una longitud mínima  de 8 caracteres con una letra mayúscula, una letra minúscula, un número y un símbolo.'){
                noError('passwordNew','epasswordnew')
                document.getElementById('epasswordnew').style.bottom = '10px';
        
        }
        
        
    }); 
    
    // Close
    document.getElementById('close').addEventListener("click", function(){
        document.getElementById('example-element-toggle').checked = !document.getElementById('example-element-toggle').checked;
        setTimeout(function(){ 
            document.getElementById('datas').style.display = 'block'; document.getElementById('addView').style.display = 'none'
            document.getElementById('status').value = '';
            document.getElementById('country').value = '';
            document.getElementById('bank').value = '';
            document.getElementById('currency').value = '';
            document.getElementById('detail1').value = '';
            document.getElementById('detail2').value = '';
            document.getElementById('detail3').value = '';
            document.getElementById('detail4').value = '';
            document.getElementById('status').style.border ="1px solid #D5DCE5";
            document.getElementById('detail1').style.border ="1px solid #D5DCE5";
            document.getElementById('currency').style.border ="1px solid #D5DCE5";
            document.getElementById('country').style.border ="1px solid #D5DCE5";
            document.getElementById('bank').style.border ="1px solid #D5DCE5";
            document.getElementById('generalerror').innerHTML = '';
        
        }, 1000);
        var el = document.getElementById('addView')
    });
    
    accountsList();
    
    document.getElementById('country').addEventListener("change", function(){
        paymentmethodsListFunction(document.getElementById('country').value);
        removeOptions('currency')
        var selector = document.getElementsByName('currency')[0];
        console.log(selector)
        var firstOopcion = document.createElement("option");
        firstOopcion.disabled = true;
        firstOopcion.text = 'Selecciona'
        firstOopcion.value =''
        firstOopcion.selected = true
        selector.add(firstOopcion);
    });
    
    document.getElementById('bank').addEventListener("change", function(){
        addOptionsCurrency(document.getElementById('bank').value)
    });
    
    document.getElementById('addAccount').addEventListener("click", function(){
        accountsUpdate(this.getAttribute("accid"));
    });
    
    document.addEventListener('click', function (evt) {
        if (evt.target.className === 'fas fa-trash-alt'){
            accountsDelete(evt.target);
        }
        if (evt.target.id=="checkbox"){
            if(entrydata.level.id>0)
                updateActiveAccount(evt.target.parentNode.parentNode.parentNode.parentNode.parentNode.name);
        }
        if (evt.target.name='bankP'){
            /*document.getElementById('datas').style.display = 'none'
            document.getElementById('addView').style.display = 'block'
            document.getElementById('detail1').value = '';
            document.getElementById('detail2').value = '';
            document.getElementById('detail3').value = '';
            document.getElementById('detail4').value = '';
            
            
            if(!document.getElementById('example-element-toggle').checked){
                setTimeout(function(){ 
                    document.getElementById('example-element-toggle').checked = !document.getElementById('example-element-toggle').checked;
                }, 15);   
            }*/
        }
    });
    
    // Hide or show old password
    document.getElementById('changeOldPass').addEventListener("click", function(){
        show('changeOldPass','passwordOld')
    }); 
    // Hide or show password
    document.getElementById('changePass').addEventListener("click", function(){
        show('changePass',"password")
    }); 
    // Hide or show new password
    document.getElementById('changeNewPass').addEventListener("click", function(){
        show('changeNewPass','passwordNew')
    }); 
    
    // Focus
    document.getElementById('passwordOld').addEventListener('keydown', (event) => focusE(event, 'password'));
    document.getElementById('password').addEventListener('keydown', (event) => focusE(event, 'passwordNew'));
    document.getElementById('passwordNew').addEventListener('keydown', (event) => focusE(event, 'change'));
    
    
    
    // entryperson y entrycompany
    document.getElementById('registry').addEventListener("click", function(){
        if (entryperson){
            console.log(entryperson)   
            goToRegisterPerson(1)
        }
        if (entrycompany){
            console.log(entrycompany)
            goToRegisterCompany(1)
        }
    }); 
    
    // Session Update
    document.getElementById('expSessionButton').addEventListener("click",function(){
        var req = {
            'sessionid': getParameterByName('sessionid')
        }
        sessionUpdate(req)
    })
    
    //Mostrar HTML cargado
    esconderHTML(false);
    
}

function clonar() {
  var c = document.getElementById("informationUser");
  var clon0 = c.children[0].children[0].cloneNode("informationUser");
  var clon1 = c.children[0].children[1].cloneNode("informationUser");
  var clon2 = c.children[0].children[2].cloneNode("informationUser");
  c.removeChild(c.children[0])
  c.appendChild(clon1)
  c.appendChild(clon0)
  c.appendChild(clon2)
  
  for( var i = 0; i < 3; i++){
      document.getElementsByClassName('levelDivs')[0].children[i].style.display = 'none'
  }
  console.log('aaa')
  for ( var i = 0; i < document.getElementById('informationUser').children.length; i++){
      console.log('hola')
        document.getElementById('informationUser').children[i].classList.remove("cellForm20");
        document.getElementById('informationUser').children[i].classList.remove("cellForm60");
        document.getElementById('informationUser').children[i].classList.remove("cellForm");
        document.getElementById('informationUser').children[i].classList.add("table100");
  }
  
  for( var i = 0; i < document.getElementsByClassName('tableButton')[0].children.length; i++){
      document.getElementsByClassName('tableButton')[0].children[i].style.display = 'table'
      document.getElementsByClassName('tableButton')[0].children[i].style.width = '100%'
      
  }
}

function goToRegisterPerson(numberStep){
    switch(numberStep){
        case 1:
            gotoPage('register','regPerson',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 2:
            gotoPage('register','regPersonRes',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 3:
            gotoPage('register','regPersonInf',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 4:
            gotoPage('register','regPersonImg',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 5:
            gotoPage('register','regPersonTr',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 6:
            gotoPage('register','regPersonStatement',{ 'sessionid': getParameterByName('sessionid') });
        break;
        case 7:
            gotoPage('register','regPersonStatement',{ 'sessionid': getParameterByName('sessionid') });
        break;
    }
}

function goToRegisterCompany(numberStep){
    switch(numberStep){
        case 1:
            gotoPage('register','regCompany',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 2:
            gotoPage('register','regCompanyPartner',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 3:
            gotoPage('register','regCompanyRes',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 4:
            gotoPage('register','regCompanyInf',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 5:
            gotoPage('register','regCompanyImg',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 6:
            gotoPage('register','regCompanyTr',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 7:
            gotoPage('register','regCompanyStatement',{ 'sessionid': getParameterByName('sessionid') });
            break;
        case 8:
            gotoPage('register','regCompanyStatement',{ 'sessionid': getParameterByName('sessionid') });
            break;
    }
}



var entryperson = '';
var entrycompany = '';
function getEntry(sessionid){
    callWS("GET", "users/entry", { 'sessionid' : sessionid}, response);
        
    function response(status, rsp){
        switch(status){
            case 200:
                if(JSON.parse(rsp).entry.person){
                    entryperson = JSON.parse(rsp).entry.person
                    console.log(JSON.parse(rsp).entry)
                    console.log(document.getElementById('dataName'))
                    document.getElementById('dataName').innerHTML = JSON.parse(rsp).entry.person.firstname.value + ' ' + JSON.parse(rsp).entry.person.firstlastname.value
                    document.getElementById('dataEmail').innerHTML = JSON.parse(rsp).entry.usr
                    document.getElementById('dataIdent').innerHTML = JSON.parse(rsp).entry.person.document.dsc.value
                    document.getElementById('dataCountryE').innerHTML = JSON.parse(rsp).entry.person.document.country.dsc
                    document.getElementById('dataPhone').innerHTML = JSON.parse(rsp).entry.person.phone.value
                    document.getElementById('dataAddress').innerHTML = ''
                    if (JSON.parse(rsp).entry.person.street.value){
                        document.getElementById('dataAddress').innerHTML = JSON.parse(rsp).entry.person.street.value
                        if (JSON.parse(rsp).entry.person.home.value){
                            document.getElementById('dataAddress').innerHTML = document.getElementById('dataAddress').innerHTML + ', ' + JSON.parse(rsp).entry.person.home.value
                            if (JSON.parse(rsp).entry.person.city.dsc){
                                document.getElementById('dataAddress').innerHTML = document.getElementById('dataAddress').innerHTML + ', ' + JSON.parse(rsp).entry.person.city.dsc
                                if (JSON.parse(rsp).entry.person.region.dsc){
                                    document.getElementById('dataAddress').innerHTML = document.getElementById('dataAddress').innerHTML + ', ' + JSON.parse(rsp).entry.person.region.dsc
                                    if (JSON.parse(rsp).entry.person.postalcode.value){
                                        document.getElementById('dataAddress').innerHTML = document.getElementById('dataAddress').innerHTML + ', ' + JSON.parse(rsp).entry.person.postalcode.value
                                        if(JSON.parse(rsp).entry.person.country.dsc){
                                            document.getElementById('dataAddress').innerHTML = document.getElementById('dataAddress').innerHTML + ', ' + JSON.parse(rsp).entry.person.country.dsc
                                        }
                                    }
                                }
                            }
                        }
                        
                    }
                    if(JSON.parse(rsp).entry.person.step<7){
                        document.getElementById('registry').innerHTML = 'COMPLETAR REGISTRO'
                        document.getElementById('seeTerms').style.opacity = '0.5'
                        document.getElementById('seeTerms').style.cursor = 'initial'
                        document.getElementById('seeTerms').disabled = true
                    }
                }else if(JSON.parse(rsp).entry.company){
                    entrycompany = JSON.parse(rsp).entry.company
                    document.getElementById('dataName').innerHTML = JSON.parse(rsp).entry.company.name.value
                    document.getElementById('dataEmail').innerHTML = JSON.parse(rsp).entry.usr
                    document.getElementById('dataIdent').innerHTML = JSON.parse(rsp).entry.company.document.dsc.value
                    document.getElementById('dataCountryE').innerHTML = JSON.parse(rsp).entry.company.document.country.dsc
                    document.getElementById('dataPhone').innerHTML = JSON.parse(rsp).entry.company.phone.value
                    document.getElementById('dataAddress').innerHTML = ''
                    if (JSON.parse(rsp).entry.company.street.value){
                        document.getElementById('dataAddress').innerHTML = JSON.parse(rsp).entry.company.street.value
                        if (JSON.parse(rsp).entry.company.home.value){
                            document.getElementById('dataAddress').innerHTML = document.getElementById('dataAddress').innerHTML + ', ' + JSON.parse(rsp).entry.company.home.value
                            if (JSON.parse(rsp).entry.company.city.dsc){
                                document.getElementById('dataAddress').innerHTML = document.getElementById('dataAddress').innerHTML + ', ' + JSON.parse(rsp).entry.company.city.dsc
                                if (JSON.parse(rsp).entry.company.region.dsc){
                                    document.getElementById('dataAddress').innerHTML = document.getElementById('dataAddress').innerHTML + ', ' + JSON.parse(rsp).entry.company.region.dsc
                                    if (JSON.parse(rsp).entry.company.document.postalcode.value){
                                        document.getElementById('dataAddress').innerHTML = document.getElementById('dataAddress').innerHTML + ', ' + JSON.parse(rsp).entry.company.document.postalcode.value
                                        if(JSON.parse(rsp).entry.company.country.dsc){
                                            document.getElementById('dataAddress').innerHTML = document.getElementById('dataAddress').innerHTML + ', ' + JSON.parse(rsp).entry.company.country.dsc
                                        }
                                    }
                                }
                            }
                        }
                        
                    }
                    if(JSON.parse(rsp).entry.company.step<8){
                        document.getElementById('registry').innerHTML = 'COMPLETAR REGISTRO'
                        document.getElementById('seeTerms').style.opacity = '0.5'
                        document.getElementById('seeTerms').style.cursor = 'initial'
                        document.getElementById('seeTerms').disabled = true
                    }
                }

                for( var i = 0 ; i < JSON.parse(rsp).entry.level.id; i++){
                    document.getElementsByClassName('levelbar')[i].classList.remove("grayLevel");
                    document.getElementsByClassName('levelbar')[i].classList.add("blueLevel");
                }
                
                document.getElementById('levelP').innerHTML = JSON.parse(rsp).entry.level.name
                arrayLevel = JSON.parse(rsp).entry.level.dsc.split('\n')
                
                document.getElementById('levelP1').innerHTML = arrayLevel.length > 0 ? arrayLevel[0] : ''
                document.getElementById('levelP2').innerHTML = arrayLevel.length > 1 ? arrayLevel[1] : ''
                entrydata = (JSON.parse(rsp).entry)
                console.log(JSON.parse(rsp).entry)
                putName(entrydata);
                //Bloquear cuentas
                if(entrydata.level.id<=0){
                    var ckecks = document.getElementById("datas").querySelectorAll('[type="checkbox"]');
                    for(var x=0;x<ckecks.length;x++){
                        ckecks[x].setAttribute("disabled","");
                    }
                }
                
                levelsList()
                
                break;
            case 204:
                break;
            case 400:
                // Parametros incorrectos
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                // Error
                break;
            default:
                break;
        }
    }    
}

function levelsList(){
    callWS("GET", "levels/list", { 'sessionid' : getParameterByName('sessionid')}, response);
    function response(status, rsp){
        switch(status){
            case 200:
                loadLevelsList(JSON.parse(rsp))
                break;
            case 401:
                expiredSession();
                break;
            default:
                break;
        }
    }    
}


function show(a,password) {
    var icon = document.getElementById(a);
    var passwordInput = document.getElementById(password);
    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");
    }
}

var entrydata;
function putName(entrydata){
    var name;
    if(entrydata.company){
        if(entrydata.company.name.value=="" || entrydata.company.name.value== null){
            name = entrydata.usr
        }else{
            name = entrydata.company.name.value
        }
    }
    else if(entrydata.person){
        if(entrydata.person.firstname.value=="" || entrydata.person.firstname.value==null){
            name = entrydata.usr
        }else{
            name = entrydata.person.firstname.value + ' '+ entrydata.person.firstlastname.value
        }
    }
    document.getElementById('name').innerHTML = name
    document.getElementById('name2').innerHTML = name
}

function listDraw(rsp, changeName){
    var tbl;
    var node;
    if(changeName==='data'){
        tbl = document.getElementsByClassName("card2")[0];
        var node = tbl.children[3].children[0].cloneNode(true);
        tbl.children[3].innerHTML = "";
    }
    var tmp = null; tmp = node.cloneNode(true);
    //tbl.children[2].innerHTML = "";
    if(changeName==='data'){
        //tbl.removeChild(document.getElementById('tableMarks'))   
    }
    if(!(rsp.length>0)){
        var ele = null;
        ele = tmp.cloneNode(true);
        ele.style.display = "none";
        tbl.children[3].appendChild(ele);
    }else{
        for(var i=0; i<rsp.length; i++){
            var ele = null;
            ele = tmp.cloneNode(true);
            ele.style.display = "table";
            if(rsp[i].name !== ""){
                if(changeName==='data'){
                    ele.name = i
                    ele.setAttribute("id","iddata"+i);
                    ele.classList.add("datas");
                    if (rsp[i].status == 'green'){
                        ele.children[0].children[0].innerHTML = '<i class="fas fa-check-circle" style="font-size: 55%; top: -4px; position: relative; color: #85BB4F"></i>'
                    }
                    else if (rsp[i].status == 'red'){
                        ele.children[0].children[0].innerHTML = '<i class="fas fa-times-circle" style="font-size: 55%; top: -4px; position: relative; color: #C04F5D"></i>'
                    }
                    else if (rsp[i].status == 'yellow'){
                        ele.children[0].children[0].innerHTML = '<i class="fas fa-pause-circle" style="font-size: 55%; top: -4px; position: relative; color: #f2c542"></i>'
                    }

                    ele.children[0].children[1].innerHTML = '<i class="fas fa-qrcode" style="font-size: 55%; top: -4px; position: relative;"></i>'

                    ele.children[0].children[2].children[0].textContent = rsp[i].currency;
                    ele.children[0].children[3].children[0].textContent = rsp[i].bank;
                    ele.children[0].children[6].children[0].setAttribute("accid",rsp[i].id);
                    ele.children[0].children[6].children[0].setAttribute("valid",rsp[i].valid);
                    ele.children[0].children[6].children[0].setAttribute("countryid",rsp[i].countryid);
                    ele.children[0].children[6].children[0].addEventListener("click",function(){
                        document.getElementById('add').dispatchEvent(new Event("click"));
                        document.getElementById("modalTit").innerHTML = "Editar Cuenta";
                        entryInf(this.getAttribute("accid"),this.getAttribute("countryid"));
                        
                    });
                    ele.children[0].children[4].children[0].textContent = rsp[i].number;
                    if(rsp[i].toggle=="true"){
                        ele.children[0].children[5].children[0].children[0].children[0].checked=true;
                    }else{
                        ele.children[0].children[5].children[0].children[0].children[0].checked=false;
                    }
                    
                    if(i % 2 != 0){
                        ele.children[0].style.backgroundColor = 'rgba(245, 246, 248, 0.800000011920929)'
                    }
                    tbl.children[3].appendChild(ele);
                }

            }
            
        }
    }
    document.getElementsByClassName('pageCnt')[0].style.display="table";
    
}
// Window Load
var waitScreen = document.getElementById("waitScreen");
waitScreen.style.opacity = 0;
setTimeout(function(){
    document.body.removeChild(document.getElementById("waitScreen"));
},600);
WS_waitscreen = false;
var accountSel = "";
function entryInf(id,countryid){
    console.log(id, countryid)
    var req = {
        'sessionid': getParameterByName('sessionid'),
        'id' : id
    }
    
    callWS('GET', 'accounts/entry', req, response);

    function response(status, rsp){
        switch(status){
            case 200:
                accountSel = "";
                /*
                var paymentmethodid = JSON.parse(rsp).entry.paymentmethod.id;
                var currencyid = JSON.parse(rsp).entry.currency.id;
                var details1 = JSON.parse(rsp).entry.details1;
                var details2 = JSON.parse(rsp).entry.details2;
                var details3 = JSON.parse(rsp).entry.details3;
                var details4 = JSON.parse(rsp).entry.details4;
                var status;
                if (JSON.parse(rsp).entry.status === 1) status = 0;
                if (JSON.parse(rsp).entry.status === 0) status = 1;
                
                var req = {
                    'sessionid': getParameterByName('sessionid'),
                    'id' : id,
                    'paymentmethodid' : parseInt(paymentmethodid),
                    'currencyid' : parseInt(currencyid),
                    'details1' : details1,
                    'details2' : details2,
                    'details3' : details3,
                    'details4' : details4,
                    'status' : parseInt(status)
                }
                
                console.log(req)
                
                callWS('POST', 'accounts/update', req, response);
            
                function response(status, rsp){
                    switch(status){
                        case 200:
                            window.location.reload()
                            break;
                        case 400:
                            break;
                        case 401:
                            break;
                        case 500:
                            break;
                        default:
                            break;
                    }
                } */
                document.getElementById("country").value = countryid;
                var resp = JSON.parse(rsp);
                document.getElementById("status").value = resp.entry.status;
                accountSel = resp.entry;
                paymentmethodsListFunction(countryid,resp.entry.paymentmethod.id);
                document.getElementById("addAccount").setAttribute("accid",resp.entry.id);
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

var varAccountsList;
// accounts/list
function accountsList(){
    
    var sessionid = getParameterByName('sessionid');
    var offset = 0;
    var numofrec;
    
    var req = {
        'sessionid': sessionid,
        'offset' : offset,
        'paym':0,
    }
    
    callWS('GET', 'accounts/list', req, response);

    function response(status, rsp){
        switch(status){
            case 200:
                console.log(JSON.parse(rsp));
                varAccountsList = JSON.parse(rsp)
                chargeData2(JSON.parse(rsp))
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

// accounts/update
function accountsUpdate(id){
    var sessionid = getParameterByName('sessionid');
    var id = id;
    var paymentmethodid = document.getElementById('bank').value;
    var currencyid = document.getElementById('currency').value;
    var details1 = capitalize(document.getElementById('detail1').value);
    var details2 = capitalize(document.getElementById('detail2').value);
    var details3 = capitalize(document.getElementById('detail3').value);
    var details4 = capitalize(document.getElementById('detail4').value);
    var status = document.getElementById('status').value
    var country = document.getElementById('country').value
    
    var req = {
        'sessionid': sessionid,
        'id' : id,
        'paymentmethodid' : parseInt(paymentmethodid),
        'currencyid' : parseInt(currencyid),
        'details1' : details1,
        'details2' : details2,
        'details3' : details3,
        'details4' : details4,
        'status' : parseInt(status)
    }
    if (paymentmethodid == '' || currencyid == '' || status == '' || country == '' || details1 == ''){
        
        if (paymentmethodid == ''){
            document.getElementById('bank').style.border ="2px solid #D0021B";
            document.getElementById('generalerror').innerHTML = 'Por favor seleccione los datos obligatorios.';
        }
        if (currencyid == ''){
            document.getElementById('currency').style.border ="2px solid #D0021B";
            document.getElementById('generalerror').innerHTML = 'Por favor seleccione los datos obligatorios.';
        }
        if (status == ''){
            document.getElementById('status').style.border ="2px solid #D0021B";
            document.getElementById('generalerror').innerHTML = 'Por favor seleccione los datos obligatorios.';
        }
        if (country == ''){
            document.getElementById('country').style.border ="2px solid #D0021B";
            document.getElementById('generalerror').innerHTML = 'Por favor seleccione los datos obligatorios.';
        }
        if (details1 == ''){
            document.getElementById('detail1').style.border ="2px solid #D0021B";
            document.getElementById('generalerror').innerHTML = 'Por favor seleccione los datos obligatorios.';
        }
        
    }else{
     
        console.log(req)
    
        callWS('POST', 'accounts/update', req, response);
    
        function response(status, rsp){
            console.log(status)
            switch(status){
                case 200:
                    console.log('se creo exitosamente la cuenta')
                    //window.location.reload()
                    accountsList();
                    document.getElementById('example-element-toggle').checked = !document.getElementById('example-element-toggle').checked;
                    setTimeout(function(){ 
                        document.getElementById('datas').style.display = 'block'; document.getElementById('addView').style.display = 'none'
                    }, 1000);
                    break;
                case 304:
                    accountsList();
                    document.getElementById('example-element-toggle').checked = !document.getElementById('example-element-toggle').checked;
                    setTimeout(function(){ 
                        document.getElementById('datas').style.display = 'block'; document.getElementById('addView').style.display = 'none'
                    }, 1000);
                    break;
                case 400:
                    break;
                case 401:
                    expiredSession();
                    break;
                case 403:
                    document.getElementById('generalerror').innerHTML = 'Para realizar esta operación debe ser al menos nivel 1.';
                    break;
                case 500:
                    document.getElementById('generalerror').innerHTML = 'La cuenta ya existe.';
                    break;
                default:
                    break;
            }
        }   
        
    }
}

var paymentmethodsList;
// paymentmethods/list
function paymentmethodsListFunction(countryid, sel=""){
    
    var sessionid = getParameterByName('sessionid');
    var countryid = countryid;
    
    var req = {
        'sessionid': sessionid,
        'countryid' : countryid // Cambiar
    }
    console.log(req)
    
    callWS('GET', 'paymentmethods/list', req, response);

    function response(status, rsp){
        console.log(JSON.parse(rsp));
        console.log(status)
        switch(status){
            case 200:
                this.paymentmethodsList = JSON.parse(rsp)
                removeOptions('bank')
                addOptionsBanks('bank',JSON.parse(rsp),sel);
                if(sel !== ""){
                    for (var i=0;i<paymentmethodsList.records.length;i++){
                        if(sel == paymentmethodsList.records[i].id){
                            var defcurr = accountSel.currency.id;
                            addEntryCurrency(paymentmethodsList.records[i],defcurr);
                        }
                    }
                }
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

var dataaccountsEntry;
// accounts/entry
function accountsEntry(id){
    
    var req = {
        'sessionid': getParameterByName('sessionid'),
        'id' : id
    }
    
    callWS('GET', 'accounts/entry', req, response);

    function response(status, rsp){
        switch(status){
            case 200:
                console.log(dataaccountsEntry)
                var paymentmethodid = JSON.parse(rsp).entry.paymentmethod.id;
                var currencyid = JSON.parse(rsp).entry.currency.id;
                var details1 = JSON.parse(rsp).entry.details1;
                var details2 = JSON.parse(rsp).entry.details2;
                var details3 = JSON.parse(rsp).entry.details3;
                var details4 = JSON.parse(rsp).entry.details4;
                var status;
                if (JSON.parse(rsp).entry.status === 1) status = 0;
                if (JSON.parse(rsp).entry.status === 0) status = 1;
                
                var req = {
                    'sessionid': getParameterByName('sessionid'),
                    'id' : id,
                    'paymentmethodid' : parseInt(paymentmethodid),
                    'currencyid' : parseInt(currencyid),
                    'details1' : nullTxt(details1.value),
                    'details2' : nullTxt(details2.value),
                    'details3' : nullTxt(details3.value),
                    'details4' : nullTxt(details4.value),
                    'status' : parseInt(status)
                }
                
                console.log(req)
                
                callWS('POST', 'accounts/update', req, response);
            
                function response(status, rsp){
                    switch(status){
                        case 200:
                            //window.location.reload()
                            accountsList();
                            break;
                        case 400:
                            break;
                        case 403:
                            document.getElementById('generalerror').innerHTML = 'Para realizar esta operación debe ser al menos nivel 1.';
                            accountsList();
                        break;
                        case 401:
                            expiredSession();
                            break;
                        case 500:
                            break;
                        default:
                            break;
                    }
                } 
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

function nullTxt(val){
    if(val == null || val == "null")return "";
    else return val;
}

// accounts/portfolio

// accounts/delete
function accountsDelete(element){
    var id = varAccountsList.records[element.parentNode.parentNode.parentNode.name].id

    var req = {
        'sessionid': getParameterByName('sessionid'),
        'id' : id
    }
    
    callWS('GET', 'accounts/entry', req, response);

    function response(status, rsp){
        switch(status){
            case 200:
                if(JSON.parse(rsp).entry.deleteable==true){
                    callWS('GET', 'accounts/delete', req, response);
                        console.log(req)
                    
                        function response(status, rsp){
                            console.log(rsp)
                            console.log(status)
                            switch(status){
                                case 200:
                                    accountsList();
                                    document.getElementById('example-element-toggle').checked = !document.getElementById('example-element-toggle').checked;
                                    setTimeout(function(){ 
                                        document.getElementById('datas').style.display = 'block'; document.getElementById('addView').style.display = 'none'
                                    }, 1000);
                                    break;
                                case 304:
                                    element.parentNode.parentNode.parentNode.children[1].innerHTML = 'No se pueden eliminar cuentas verificadas.'
                                    break;
                                case 400:
                                    break;
                                case 401:
                                    expiredSession();
                                    break;
                                case 500:
                                    break;
                                default:
                                    break;
                            }
                        }
                }else{
                    console.log( element.parentNode.parentNode.parentNode)
                    element.parentNode.parentNode.parentNode.children[1].innerHTML = 'No se pueden eliminar cuentas activas.'
                }
                
                
                
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
    /*var req = {
        'sessionid': getParameterByName('sessionid'),
        'id' : id
    }
    
    callWS('GET', 'accounts/delete', req, response);
    console.log(req)

    function response(status, rsp){
        console.log(rsp)
        console.log(status)
        switch(status){
            case 200:
                window.location.reload()
                document.getElementById('example-element-toggle').checked = !document.getElementById('example-element-toggle').checked;
                setTimeout(function(){ 
                    document.getElementById('datas').style.display = 'block'; document.getElementById('addView').style.display = 'none'
                }, 1000);
                break;
            case 400:
                break;
            case 401:
                break;
            case 500:
                break;
            default:
                break;
        }
    }  */ 
}

function chargeData2(chargeData){
    
    var data =[]
    
    var status = new Array(chargeData.numofrecords);
    var qr = new Array(chargeData.numofrecords);
    var currency = new Array(chargeData.numofrecords);
    var bank = new Array(chargeData.numofrecords);
    var number = new Array(chargeData.numofrecords);
    var toggle = new Array(chargeData.numofrecords);
    var trash = new Array(chargeData.numofrecords);
    var id = new Array(chargeData.numofrecords);
    var countryid = new Array(chargeData.numofrecords);
    for (var i = 0; i < chargeData.numofrecords ; i++ ){
        
        if(chargeData.records[i].valid.id == 1){
            status[i] = 'green'
        }
        else if(chargeData.records[i].valid.id == -1){
            status[i] = 'red'
        }
        else if(chargeData.records[i].valid.id == 0){
            status[i] = 'yellow'
        }
        
        qr[i] = 'qr'
        currency[i] = chargeData.records[i].currency.symbol;
        bank[i] = chargeData.records[i].paymentmethod.dsc;
        number[i] = chargeData.records[i].details1;
        id[i] = chargeData.records[i].id;
        countryid[i] = chargeData.records[i].country.id;
        if(chargeData.records[i].status === 1){
            toggle[i] = 'true'
        }else{
            toggle[i] = 'false'
        }
        //console.log(toggle)
        //console.log(toggle[i])
        
        trash[i] = 'trash'
        
        data.push({
            'status' : status[i],
            'valid': chargeData.records[i].valid.id,
            'qr' : 'qr',
            'currency' : currency[i],
            'bank' : bank[i],
            'number' : number[i],
            'toggle' : toggle[i],
            'trash' : 'trash',
            'id': id[i],
            'countryid': countryid[i]
        })
    }
    listDraw(data, 'data')
}

function getCountries(){
    var req = {
        "sessionid": getParameterByName('sessionid'),
        "paymentmethods":1
    }
        
    callWS("GET", "demographics/countries", req, response);
        
    function response(status, rsp){
        switch(status){
            case 200:
                countries = JSON.parse(rsp);
                console.log(countries)
                addOptions("country", countries)
                break;
            case 204:
                break;
            case 400:
                // Parametros incorrectos
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                // Error
                break;
            default:
                break;
        }
    }    
}

function addOptions(domElement, array) { 
    var selector = document.getElementsByName(domElement)[0];
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = 'País'
    firstOopcion.value =''
    firstOopcion.selected = true
    selector.add(firstOopcion);
    for (var countrie in array.records) {
        var opcion = document.createElement("option");
        opcion.text = array.records[countrie].dsc;
        opcion.value = array.records[countrie].id
        selector.add(opcion);   
    }
}

function addOptionsBanks(domElement, array, sel) { 
    console.log(array)
    console.log(domElement)
    var selector = document.getElementById(domElement);
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = 'Forma de pago'
    firstOopcion.value =''
    if(sel === "" || sel === undefined || sel === null)
        firstOopcion.selected = true
    selector.add(firstOopcion);
    for (var bank in array.records) {
        var opcion = document.createElement("option");
        if(sel !== "" && sel !== undefined && sel !== null)
            if(array.records[bank].id == sel)opcion.selected = true
        opcion.text = array.records[bank].dsc;
        opcion.value = array.records[bank].id
        selector.add(opcion);
    }
    
}

function removeOptions(selectElement) {
    x = document.getElementById(selectElement)
    var i, L = x.options.length - 1;
    for(i = L; i >= 0; i--) {
       x.remove(i);
    }
}

function addOptionsCurrency(id){
    console.log('addOptionsCurrency')
    removeOptions('currency');
    console.log(id)
    console.log(this.paymentmethodsList)
    var selector = document.getElementById('currency');
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = 'Moneda';
    firstOopcion.value ='';
    firstOopcion.selected = true;
        
    selector.add(firstOopcion);
    console.log(document.getElementById('bank').selectedIndex) // 1 o 2
    for (var paymentmethod in this.paymentmethodsList.records[(document.getElementById('bank').selectedIndex) -1].currencies){
        var opcion = document.createElement("option");
        opcion.text = this.paymentmethodsList.records[(document.getElementById('bank').selectedIndex) -1].currencies[paymentmethod].dsc
        opcion.value = this.paymentmethodsList.records[(document.getElementById('bank').selectedIndex) -1].currencies[paymentmethod].id
        selector.add(opcion);
    }
    
    document.getElementById('detail1').placeholder = this.paymentmethodsList.records[(document.getElementById('bank').selectedIndex) -1].details1
    document.getElementById('detail2').placeholder = this.paymentmethodsList.records[(document.getElementById('bank').selectedIndex) -1].details2
    document.getElementById('detail3').placeholder = this.paymentmethodsList.records[(document.getElementById('bank').selectedIndex) -1].details3
    document.getElementById('detail4').placeholder = this.paymentmethodsList.records[(document.getElementById('bank').selectedIndex) -1].details4
    
    
    console.log(document.getElementById('detail4').placeholder)
    
    if(document.getElementById('detail1').placeholder=='' || document.getElementById('detail1').placeholder ==null){
        document.getElementById('detail1').disabled = true;
    }else{
        document.getElementById('detail1').disabled = false;
        document.getElementById('detail1').placeholder=='Email' ? document.getElementById('detail1').classList.add('no-cap') : document.getElementById('detail1').classList.remove('no-cap')
    }
    if(document.getElementById('detail2').placeholder=='' || document.getElementById('detail2').placeholder ==null){
        document.getElementById('detail2').disabled = true;
    }else{
        document.getElementById('detail2').disabled = false;
        document.getElementById('detail2').placeholder=='Email' ? document.getElementById('detail2').classList.add('no-cap') : document.getElementById('detail2').classList.remove('no-cap')
    }
    if(document.getElementById('detail3').placeholder=='' || document.getElementById('detail3').placeholder ==null){
        document.getElementById('detail3').disabled = true;
    }else{
        document.getElementById('detail3').disabled = false;
        document.getElementById('detail3').placeholder=='Email' ? document.getElementById('detail3').classList.add('no-cap') : document.getElementById('detail3').classList.remove('no-cap')
    }
    if(document.getElementById('detail4').placeholder=='' || document.getElementById('detail4').placeholder ==null){
        document.getElementById('detail4').disabled = true;
    }else{
        document.getElementById('detail4').disabled = false;
        document.getElementById('detail4').placeholder=='Email' ? document.getElementById('detail4').classList.add('no-cap') : document.getElementById('detail4').classList.remove('no-cap')
    }
}
function addEntryCurrency(rsp,sel){
    removeOptions('currency');
    
    var selector = document.getElementById('currency');
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = 'Moneda';
    firstOopcion.value ='';
    if(sel === "" || sel === undefined || sel === null)
        firstOopcion.selected = true
    selector.add(firstOopcion);
    console.log(document.getElementById('bank').selectedIndex) // 1 o 2
    for (var i=0;i<rsp.currencies.length;i++){
        var opcion = document.createElement("option");
        opcion.text = rsp.currencies[i].dsc;
        opcion.value = rsp.currencies[i].id;
        
        if(sel === "" || sel === undefined || sel === null)
            if(sel === rsp.currencies[i].id){
                opcion.selected = true
            }
        
        selector.add(opcion);
    }
    
    var campos = document.getElementById("example-toggled-element").getElementsByTagName("input");
    for(var i=0;i<campos.length;i++){
        campos[i].removeAttribute("disabled");
    }
    var camposSel = document.getElementById("example-toggled-element").getElementsByTagName("select");
    for(var i=0;i<camposSel.length;i++){
        camposSel[i].removeAttribute("disabled");
    }
    document.getElementById("addAccount").style.display = "";
    document.getElementById('detail1').placeholder = rsp.details1;
    document.getElementById('detail2').placeholder = rsp.details2;
    document.getElementById('detail3').placeholder = rsp.details3;
    document.getElementById('detail4').placeholder = rsp.details4;
    if(accountSel.details1.valid==1)document.getElementById('detail1').disabled=true;
    document.getElementById('detail1').value = accountSel.details1.value;
    if(accountSel.details2.valid==1)document.getElementById('detail2').disabled=true;
    document.getElementById('detail2').value = accountSel.details2.value;
    if(accountSel.details3.valid==1)document.getElementById('detail3').disabled=true;
    document.getElementById('detail3').value = accountSel.details3.value;
    if(accountSel.details4.valid==1)document.getElementById('detail4').disabled=true;
    document.getElementById('detail4').value = accountSel.details4.value;
    if(accountSel.valid.id==1){
        
        var camposSel = document.getElementById("example-toggled-element").getElementsByTagName("select");
        for(var i=0;i<camposSel.length;i++){
            camposSel[i].disabled = true;
        }
        document.getElementById("addAccount").style.display = "none";
    }
    
    
}

function updateActiveAccount(id){
    var sessionid = getParameterByName('sessionid');
    var id = id;
    accountsEntry(varAccountsList.records[id].id)
    /*console.log(dataaccountsEntry)
    
    
    var paymentmethodid = data.entry.paymentmethod.id;
    var currencyid = data.entry.currency.id;
    var details1 = data.entry.details1;
    var details2 = data.entry.details2;
    var details3 = data.entry.details3;
    var details4 = data.entry.details4;
    var status;
    if (data.entry.status === 1) status = 0;
    if (data.entry.status === 0) status = 1;
    
    
    var req = {
        'sessionid': sessionid,
        'id' : id,
        'paymentmethodid' : parseInt(paymentmethodid),
        'currencyid' : parseInt(currencyid),
        'details1' : details1,
        'details2' : details2,
        'details3' : details3,
        'details4' : details4,
        'status' : parseInt(status)
    }
    
    console.log(req)
    
    callWS('POST', 'accounts/update', req, response);

    function response(status, rsp){
        console.log(JSON.parse(rsp));
        console.log(status)
        switch(status){
            case 200:
                window.location.reload()
                break;
            case 400:
                break;
            case 401:
                break;
            case 500:
                break;
            default:
                break;
        }
    }  */
}

function changePassword(){
    var oldpass = document.getElementById('passwordOld')
    var pass = document.getElementById('password')
    var newpass = document.getElementById('passwordNew')
    
    if (oldpass.value == '' || pass.value == '' || newpass.value == ''){
        if (oldpass.value == ''){
            error('passwordOld','epasswordold','Introduzca la contraseña actual.')
        }
        if (pass.value == ''){
            error('password','epassword','Introduzca la nueva contraseña.')
        }
        if (newpass.value == ''){
            error('passwordNew','epasswordnew','Confirme la nueva contraseña.')
        }
        return;
    }
    
    if (pass.value != newpass.value){
        document.getElementById('epasswordnew').innerHTML = 'Las contraseñas no coinciden.'
        return;
    }
    
    if(!isOkPass(pass.value).result){
        document.getElementById('epasswordnew').innerHTML = 'La contraseña debe tener una longitud mínima  de 8 caracteres con una letra mayúscula, una letra minúscula, un número y un símbolo.'
        return;
    }
    
    var req = {
        'sessionid': getParameterByName('sessionid'),
        'pwd' : MD5(oldpass.value),
        'newpwd' : MD5(pass.value),
    }
    
    console.log(req)
    
    callWS('GET', 'users/update', req, response);

    function response(status, rsp){
        console.log(status)
        switch(status){
            case 200:
                document.getElementById('epasswordnew').innerHTML = 'La contraseña se ha cambiado exitosamente.'
                break;
            case 400:
                document.getElementById('epasswordnew').innerHTML = 'Contraseña actual incorrecta.'
                break;
            case 401:
                expiredSession();
                break;
            case 409:
                document.getElementById('epasswordnew').innerHTML = 'No puede introducir la misma contraseña actual y nueva.'
                break;
            case 500:
                document.getElementById('epasswordnew').innerHTML = 'Error.'
                break;
            default:
                document.getElementById('epasswordnew').innerHTML = 'Error.'
                break;
        }
    }
    
}




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 logout(){
    var sessionid = getParameterByName('sessionid')
    var req ={
        'sessionid': sessionid,
    }
    
    callWS('GET', 'login/logout', req, response);

    function response(status, rsp){
        console.log(JSON.parse(rsp));
        console.log(status)
        switch(status){
            case 200:
                gotoPage('login','main','')
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

function expiredSession(){
    document.getElementsByClassName('expired')[0].style.display = "table"
    WS_waitscreen = false;
    var seconds = 30;
    var countdown = setInterval(countDown, 1000);
    
    function countDown(){
        seconds--;
        if(seconds == 0){
            if(document.getElementsByClassName('expired')[0].style.display == "table"){
                gotoPage('login','main','');
                clearInterval(countdown);
            }
        }
        if(document.getElementsByClassName('expired')[0].style.display == "none"){
            clearInterval(countdown)
        }
    }
}

function sessionUpdate(req){
    callWS('GET', 'session/update', req, response);
    function response(status, rsp){
        console.log('session/update')
        console.log(JSON.parse(rsp));
        console.log(status) 
        switch(status){
            case 200:
                document.getElementsByClassName('expired')[0].style.display = "none"
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

function loadLevelsList(list){
    for( var i = 0; i < list.records.length ; i++){
        level = "textLevel" + i
        arrayLevelName = list.records[i].name
        arrayLeveldsc = list.records[i].dsc.split('\n')
        document.getElementById(level).children[0] = arrayLeveldsc[0] ? arrayLeveldsc[0] : ''
        for (var j = 0; j < arrayLeveldsc.length; j++ ){
            itm = document.getElementById(level).children[1];
            cln = itm.cloneNode(true);
            cln.children[0].innerHTML = arrayLeveldsc[j]
            if(arrayLeveldsc[j]) document.getElementById(level).appendChild(cln); 
        }
    }
}











