initReg();
//Se inicializan los eventos
function initReg(){
    htmlLang(textGlobal);
    
    //Aceptar completar luego
    document.getElementById('completeLaterAccept').addEventListener("click", function(){
        if(document.getElementById("lvlcripto")){
            if(document.getElementById("lvlcripto").value == 0){
                gotoPage('dashboard','home',"");
            }else{
                gotoPage('step','main',"");
            }
        }else{
            if(this.getAttribute("view") == 0){
                gotoPage('dashboard','home',"");
            }else{
                gotoPage('step','main',"");
            }
        }
    });
    //Cancelar completar luego
    document.getElementById('completeLaterCancel').addEventListener("click", function(){
        document.getElementsByClassName('completeLater')[0].style.display = 'none';
    });
    addFooter();
}
//Cargar listado paises
function countriesLoad(success){
    var parms = {
        "sessionid": sessionStorage.getItem('sessionid')
    }   
    callWS("GET", "demographics/countries", parms, success);    
}
//Cargar listado de estados
function regionsLoad(countryid,success){
    var req = {
        "sessionid": sessionStorage.getItem('sessionid'),
        "countryid": countryid
    }
     if (req.countryid != ''){
        callWS("GET", "demographics/regions", req, success);  
    }
        
}
//Cargar listado de ciudades
function citiesLoad(regionid,success){
    var req = {
        "sessionid": sessionStorage.getItem('sessionid'),
        "regionid": regionid
    }
     if (req.regionid != ''){
        callWS("GET", "demographics/cities", req, success);     
    }
        
}
//Cargar una lista de los uploads
var upLoad = false;
var idsloaded = "";//Se validan los uploadids enviados en pasos anteriores
function uploadsLoad(parms,success){    
    callWS("GET", "uploads/list", parms, success);
}
//Pintar uploads
function uploadsDraw(rsp,lvlid){
    var lang = sessionStorage.getItem('lang');
    var cnt = document.getElementById("upldsCnt");
    var clone = cnt.firstElementChild.cloneNode(true);
    var nwnode;
    if(rsp.length>0){          
        cnt.innerHTML = "";                      
        //Objeto abiert si existe
        for(var i=0;i<rsp.length;i++){            
            nwnode = "";
            nwnode = clone.cloneNode(true);
            nwnode.style.display = "";
            nwnode.setAttribute("id","upid"+rsp[i].id);
            var dsc = rsp[i].dsc;
            if(rsp[i].id==9 && rsp[i].type.id == 1){
                var dscarr = dsc.split("/");
                if(dscarr.length>=2){
                    dsc = dsc.replace("Contrato de alquiler","RIF");
                    dsc = dsc.replace("Comprobante de registro de información fiscal","RIF");
                    dsc = dsc.replace("Rental Agreement","RIF");  
                    dsc = dsc.replace("Proof of tax information registration","RIF");       
                }
            }
            nwnode.children[0].children[0].children[0].innerHTML = dsc;
            //Idioma Carga exitosa
            nwnode.getElementsByClassName("successfulUploadLabel")[0].innerHTML = getLangById('upSucces')[lang]

            var cells = nwnode.getElementsByClassName("cellForm");
            var del = nwnode.lastElementChild.getElementsByTagName("button")[1];
            del.innerHTML = getLangById('upDel')[lang];
            var pvw = nwnode.lastElementChild.getElementsByTagName("button")[0]; 
            pvw.innerHTML = getLangById('upPreview')[lang];           
            //Btn Eliminar
            del.setAttribute("loaded","false");
            del.addEventListener("click",function(){
                if(this.getAttribute("loaded")=="true"){
                    deleteUpload(this);
                }
            });
            //Btn previsualizar
            pvw.addEventListener("click",function(){
                if(this.getAttribute("src")!==null&&this.getAttribute("src")!==""){
                    if(this.getAttribute("src").indexOf("base64")>-1){
                        var body = document.createElement("body");
                        body.setAttribute("style","margin: 0px; background: #0e0e0e; height: 100%;width:100%;display:table;");
                        var cell = document.createElement("div");
                        cell.style.display = "table-cell";
                        cell.style.verticalAlign = "middle";
                        if(this.getAttribute("type")=='pdf'){
                            var iframe = document.createElement("iframe");                            
                            iframe.setAttribute("src",this.getAttribute("src"));
                            iframe.style.marginLeft = "auto";
                            iframe.style.marginRight = "auto";
                            iframe.style.height = "99.5%";
                            iframe.style.width = "99.5%";                            
                            cell.appendChild(iframe);
                        }else{ 
                            var image = new Image();
                            image.src = this.getAttribute("src");
                            image.setAttribute("style","max-width:100%;max-height:100%;display:table;-webkit-user-select: none;margin: auto;background-color: hsl(0, 0%, 90%);transition: background-color 300ms;");
                            cell.appendChild(image);
                        
                        }
                        
                        body.appendChild(cell);
                        var w = window.open("");
                        w.document.write(body.outerHTML);
                    }else{
                        window.open(this.getAttribute("src"),'_blank');
                    }
                }
            });
            //File
            var file = nwnode.getElementsByTagName("input")[0];
            file.nextElementSibling.innerHTML = getLangById('upSearch')[lang]; 
            file.setAttribute("label",rsp[i].id);
            file.setAttribute("id","file"+rsp[i].id);
            var lbltxt = file.parentElement.parentElement.parentElement.parentElement.parentElement;
            lbltxt.getElementsByClassName("searchText")[0].children[0].innerHTML = getLangById('upPh')[lang];
            file.addEventListener("change",function(){
                var cnt = this.parentElement.parentElement.parentElement.parentElement.parentElement;
                if(this.files.length>0 && validarFile(this)){
                    this.setAttribute("loaded",1);
                    cnt.lastElementChild.getElementsByTagName("button")[0].classList.add("viewActive");
                    cnt.lastElementChild.getElementsByTagName("button")[1].classList.add("viewActive");
                    cnt.lastElementChild.getElementsByTagName("button")[1].setAttribute("loaded",true);
                    //Nombre del archivo a cargar
                    cnt.getElementsByClassName("searchText")[0].children[0].setAttribute("title",this.files[0].name);
                    cnt.getElementsByClassName("searchText")[0].children[0].innerHTML = this.files[0].name;
                    var preview = cnt.lastElementChild.getElementsByTagName("button")[0];
                    if(this.files[0]){
                        if(this.files[0].type=='application/pdf'){
                            preview.setAttribute("type","pdf");
                        }else{
                            preview.setAttribute("type","img");
                        }
                            const reader = new FileReader();
                            reader.addEventListener("load",function(){
                                preview.setAttribute("src",this.result);
                            });
                            reader.readAsDataURL(this.files[0]);
                    }
                    if(cnt.getElementsByClassName("upProgCell").length>0)
                        cnt.getElementsByClassName("upProgCell")[0].classList.add("invisible"); 
                    cnt.setAttribute("loaded",0);
                    if(document.getElementById("declaration")){
                        document.getElementById("declarationTxt").setAttribute("loaded",false);
                        document.getElementById("declaration").checked = false; 
                        document.getElementById("declaration").removeAttribute("disabled");
                        document.getElementById("declaration").setAttribute("validated",0);
                    }
                }else{
                    cnt.setAttribute("loaded",0);

                    this.setAttribute("loaded",0);
                    cnt.lastElementChild.getElementsByTagName("button")[0].classList.remove("viewActive");
                    cnt.lastElementChild.getElementsByTagName("button")[1].classList.remove("viewActive");
                    if(cnt.getElementsByClassName("upProgCell").length>0)
                        cnt.getElementsByClassName("upProgCell")[0].classList.add("invisible"); 
                    //Nombre del archivo a cargar
                    cnt.getElementsByClassName("searchText")[0].children[0].innerHTML = getLangById('upPh')[lang];
                    cnt.getElementsByClassName("searchText")[0].children[0].removeAttribute("title");
                    cnt.lastElementChild.getElementsByTagName("button")[1].setAttribute("loaded",false);
                }     
            });
            if(rsp[i].level.id <= 0 && lvlid == 0 && rsp[i].type.id == 1){
                //Lbl
                var span = document.createElement("span");
                span.classList.add("infBtnLbl","poppins-regular");
                span.innerHTML = getLangById('upRec')[lang];
                nwnode.children[0].children[0].children[0].innerHTML = rsp[i].dsc;
                if(rsp[i].id=='01'){
                    span.addEventListener('click',function(){
                        showInf("infDocId");
                    });
                }else if(rsp[i].id=='02'){
                    span.addEventListener('click',function(){
                        showInf("infSelfie");
                    });
                }
                nwnode.children[0].children[0].children[0].appendChild(span);
                cnt.appendChild(nwnode);
            }else if(rsp[i].level.id <= 1 && lvlid == 1 && rsp[i].type.id == 2){
                //Lbl
                var span = document.createElement("span");
                span.classList.add("infBtnLbl","poppins-regular");
                span.innerHTML = getLangById('upRec')[lang];
                nwnode.children[0].children[0].children[0].innerHTML = rsp[i].dsc;
                if(rsp[i].id=='06'){
                    span.addEventListener('click',function(){
                        showInf("infDocId");
                    });
                    nwnode.children[0].children[0].children[0].appendChild(span);
                }else if(rsp[i].id=='07'){
                    span.addEventListener('click',function(){
                        showInf("infSelfie");
                    });

                    
                    nwnode.children[0].children[0].children[0].appendChild(span);                    
                }
                cnt.appendChild(nwnode);
            }else if(rsp[i].level.id == lvlid){
                cnt.appendChild(nwnode);
            }else if(lvlid === ""){
                cnt.appendChild(nwnode);
            }
        }
    }else{
        nwnode = clone.cloneNode(true);
        nwnode.style.display = "none";
        cnt.innerHTML = "";
        cnt.appendChild(nwnode);
    }
}
//Delete uploads
function deleteUpload(ele){
    //Eliminar clase delete
    ele.classList.remove("viewActive");
    ele.setAttribute("loaded","false");
    //Eliminar clase del vista previe y remover el src
    var view = ele.parentElement.previousElementSibling.children[0];
    view.classList.remove("viewActive");
    view.removeAttribute("src");
    var cnt = ele.parentElement.parentElement.parentElement.parentElement.parentElement;
    var prog = cnt.getElementsByClassName("progress")[0].parentElement;
    var file = cnt.children[0].getElementsByTagName("input")[0];
    //Blanquear file y barra de progreso
    file.value = "";
    prog.classList.add("invisible");
    //Volver label a empty
    var srcTxt = cnt.getElementsByClassName("searchText")[0].children[0];
    srcTxt.innerHTML = sessionStorage.getItem('lang') == 'esp' ? "Seleccione" : 'Select';
    cnt.setAttribute("loaded",0);
    //Se elimina de la variable de texto de documentos cargados
    var arr = (idsloaded.slice(0,-1)).split("-");
    var pos = arr.indexOf(file.getAttribute("label"));
    if(pos>-1){
        arr.splice(pos,1);
    }
    idsloaded = "";
    for(var i=0; i<arr.length; i++){
        idsloaded  += arr[i]+"-"; 
    }

}
//Mostrar y ocultar popups de recomendaciones para uploads
function showInf(id){
    document.getElementById(id).style.display = "table";
}
//Cerrar popups
function closeAll(){
    var pops = document.getElementsByClassName("expired");
    for(var i=0;i<pops.length;i++){
        pops[i].style.display = "";
    }
}
//Obtener datos actuales del usuario
function userEntry(success){
    //Parametros
    var parms = {
        "sessionid": sessionStorage.getItem('sessionid')
    }    
    callWS("GET", "users/entry", parms, success); 
    
}
//Lo más generico posible
function drawEntry(rsp){
    entrydata = null;
    //Aquí se valida a dónde te llevará en caso de abandonar temprano el registro (rgenerico)
    var lat = document.getElementById('completeLaterAccept');
    if(lat)lat.setAttribute("view",rsp.entry.view);
    var saveExit = document.getElementById("save-button");
    if(saveExit)saveExit.setAttribute("view",rsp.entry.view);
    var validated = false;
    var rejected = false;
    //LLenado de datos de campos
    for (let i in rsp) {
        if(i=='entry'){
            for (let j in rsp[i]) {
                if(j=='person' || j=='company'){
                    for (let k in rsp[i][j]) {                      
                        if(rsp[i][j][k]){
                            if(k=='uploads'){
                                for (let l in rsp[i][j][k]) {
                                    if(rsp[i][j][k][l]['url']!==""&&rsp[i][j][k][l]['url']!==undefined
                                    &&rsp[i][j][k][l]['url']!==null){
                                        idsloaded += rsp[i][j][k][l]['id']+"-";
                                    }
                                    if(document.getElementById("upid"+rsp[i][j][k][l]['id'])){
                                        var upid = document.getElementById("upid"+rsp[i][j][k][l]['id']);
                                        var del = upid.lastElementChild.getElementsByTagName("button")[1];
                                        var pvw = upid.lastElementChild.getElementsByTagName("button")[0];
                                        //Eliminar
                                        del.setAttribute("loaded","true");
                                        del.classList.add("viewActive");
                                        if(rsp[i][j][k][l]['url']!==""){
                                            var ele = upid.getElementsByClassName("divSearch")[0];
                                            if(ele.firstElementChild){
                                                var span = document.createElement("span");
                                                span.classList.add("spanIc","spanUpIc","poppins-italic");
                                                ele.getElementsByClassName("fileInpt")[0].removeAttribute("disabled");
                                                ele.firstElementChild.style.backgroundColor = "";
                                                if(rsp[i][j][k][l]['validated']==1){
                                                    span.innerHTML = '<i class="fas fa-check-circle"></i>';
                                                    ele.getElementsByClassName("fileInpt")[0].setAttribute("disabled","");
                                                    span.classList.add("iconGreen");     
                                                    del.classList.add("notReadyButton"); 
                                                    del.style.pointerEvents = "none";
                                                    del.style.cursor = 'normal';  
                                                    del.classList.remove("viewActive");                                                    
                                                    ele.firstElementChild.style.backgroundColor = "#fafafa";                                                        
                                                    ele.insertBefore(span,ele.firstElementChild);
                                                    validated = true;
                                                }else if(rsp[i][j][k][l]['validated']==-1){
                                                    span.innerHTML = '<i class="fas fa-times-circle"></i>';
                                                    span.classList.add("iconRed");                                                                
                                                    ele.insertBefore(span,ele.firstElementChild);
                                                }
                                            }
                                                        

                                            //Previsualizar imagen
                                            pvw.classList.add("viewActive");
                                            pvw.setAttribute("src",rsp[i][j][k][l]['url']);                                        
                                            
                                            //Input
                                            upid.setAttribute("loaded",1);
                                            //Barra de progreso cargada 
                                            upid.getElementsByClassName("progBar")[0].style.width = "100%";
                                            //Clase que oculta la barra en los no cargados se elimina si existe (ya acá sabemos que tiene url)
                                            if(upid.getElementsByClassName("upProgCell").length>0)
                                                upid.getElementsByClassName("upProgCell")[0].classList.remove("invisible");     
                                            //Nombre del archivo guardado
                                            upid.getElementsByClassName("searchText")[0].lastElementChild.innerHTML = rsp[i][j][k][l]['id']+rsp[i][j][k][l]['type'];
                                        }
                                    }
                                }
                                //idsloaded = idsloaded.slice(0,-1);
                            }
                            //Si llegamos acá y es un objeto debemos ir un nivel más adentro y no existe el "update" campo identificador
                            if(typeof rsp[i][j][k] === 'object' && rsp[i][j][k]['update'] == null){
                                for (let l in rsp[i][j][k]) {
                                    var obj = rsp[i][j][k][l];
                                    if(obj){
                                        if(obj['update']){
                                            if(document.getElementById(obj['update'])){
                                                var val = (document.getElementById(obj['update']).nodeName).toLowerCase();                                   
                                                var typ = document.getElementById(obj['update']).getAttribute("type");
                                                //Se crea la marca de validado o no                                                
                                                var ele = document.getElementById(obj['update']);                                                        
                                                var span = document.createElement("span");
                                                if(obj['update']=='company'||obj['update']=='comercialname'||obj['update']=='website'){
                                                    span.classList.add("iconOptional"); 
                                                }

                                                span.classList.add("spanIc","poppins-italic");
                                                ele.removeAttribute("disabled");
                                                var span = document.createElement("span");
                                                span.classList.add("spanIc","poppins-italic");
                                                ele.removeAttribute("disabled");
                                                if(obj['valid']==1){
                                                    span.innerHTML = '<i class="fas fa-check-circle"></i>';
                                                    ele.setAttribute("disabled","");
                                                    span.classList.add("iconGreen");                                                                
                                                    ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                }
                                                if(val=='input'){
                                                    switch(typ){
                                                        case 'text':
                                                            if(obj['value']!=""  && obj['value']!='null'&& obj['value']!=null)
                                                                document.getElementById(obj['update']).value = obj['value'];
                                                        break;
                                                        case 'number':
                                                            if(obj['number']!=="" && obj['number']!=null){
                                                                document.getElementById(obj['update']).value = obj['number'];
                                                            }else if(obj['value']!=="" && obj['value']!=null){
                                                                document.getElementById(obj['update']).value = obj['value'];
                                                            }
                                                            span.classList.add("spanIcNum");
                                                        break;
                                                        case 'date':
                                                            if(obj['date']!="" && obj['date']!=null)
                                                                document.getElementById(obj['update']).value = obj['date'];
                                                        break;
                                                        case 'phone':
                                                            if(obj['value']!=""  && obj['value']!='null'&& obj['value']!=null){
                                                                if(document.getElementById("phoneCode") && obj['update']=='phone'){
                                                                    document.getElementById("phoneCode").value = parseFloat(obj['value'].split(" ")[0]);
                                                                }
                                                                document.getElementById(obj['update']).value = obj['value'].split(" ")[1];
                                                            }
                                                        break;
                                                        case 'tel':
                                                            if(obj['value']!=""  && obj['value']!='null'&& obj['value']!=null){
                                                                if(document.getElementById("phoneCode") && obj['update']=='phone'){
                                                                    document.getElementById("phoneCode").value = parseFloat(obj['value'].split(" ")[0]);
                                                                    if(ele.previousElementSibling){
                                                                        var span = document.createElement("span");
                                                                        span.classList.add("spanIc","poppins-italic");
                                                                        ele.removeAttribute("disabled");
                                                                        if(obj['valid']==1){
                                                                            span.innerHTML = '<i class="fas fa-check-circle"></i>';
                                                                            ele.setAttribute("disabled","");
                                                                            span.classList.add("iconGreen");                                                                
                                                                            ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                                        }else if(obj['valid']==-1){
                                                                            span.innerHTML = '<i class="fas fa-times-circle"></i>';
                                                                            span.classList.add("iconRed");                                                                
                                                                            ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                                        }
                                                                    }
                                                                    ele = document.getElementById(obj['update']);
                                                                }
                                                                document.getElementById(obj['update']).value = obj['value'].split(" ")[1];
                                                                
                                                            }
                                                        break;
                                                        case 'checkbox':
                                                            if(obj['update']!=="declaration")
                                                                document.getElementById(obj['update']).value = obj['date'];

                                                                var span = document.createElement("span");
                                                                span.classList.add("spanIc","poppins-italic","iconCheckBox");
                                                                var ele = document.getElementById(obj['update']).parentElement.parentElement.parentElement.parentElement.lastElementChild.children[0];
                                                                if(obj['valid']==1){
                                                                    span.innerHTML = '<i class="fas fa-check-circle"></i>';
                                                                    document.getElementById(obj['update']).setAttribute("disabled","");
                                                                    span.classList.add("iconGreen");                                                                
                                                                    ele.appendChild(span);
                                                                    validated = true;
                                                                }else if(obj['valid']==-1){
                                                                    span.innerHTML = '<i class="fas fa-times-circle"></i>';
                                                                    span.classList.add("iconRed"); 
                                                                    document.getElementById(obj['update']).removeAttribute("disabled","");                                                               
                                                                    ele.appendChild(span);
                                                                    rejected = true;
                                                                }
                                                        break;
                                                    }
                                                        if(ele.previousElementSibling){
                                                            if(obj['valid']==1){
                                                                span.innerHTML = '<i class="fas fa-check-circle"></i>';
                                                                ele.setAttribute("disabled","");
                                                                span.classList.add("iconGreen");                                                                
                                                                ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                                validated = true;
                                                            }else if(obj['valid']==-1){
                                                                span.innerHTML = '<i class="fas fa-times-circle"></i>';
                                                                span.classList.add("iconRed");                                                                
                                                                ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                            }
                                                        }
                                                        
                                                }else if(val=='select'){
                                                    var sel = obj['value'];
                                                    if(!sel)sel = obj['id'];
                                                    if(!sel)sel = "";
                                                    if(obj['value']==0)sel = obj['value'];
                                                    document.getElementById(obj['update']).value = sel;
                                                    var ele = document.getElementById(obj['update']);
                                                        if(ele.previousElementSibling){
                                                            var span = document.createElement("span");
                                                            span.classList.add("spanIc","poppins-italic");
                                                            
                                                            ele.removeAttribute("disabled");
                                                            if(obj['valid']==1){
                                                                span.innerHTML = '<i class="fas fa-check-circle"></i>';
                                                                ele.setAttribute("disabled","");
                                                                span.classList.add("iconGreen");                                                                
                                                                ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                                validated = true;
                                                            }else if(obj['valid']==-1){
                                                                span.innerHTML = '<i class="fas fa-times-circle"></i>';
                                                                span.classList.add("iconRed");                                                                
                                                                ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                            }
                                                        }
                                                }
                                            }
                                        }
                                    }else{
                                    }
                                }
                            }else{ //Si no es un objeto podemos buscar los valores
                                if(rsp[i][j][k]['update']){
                                    if(document.getElementById(rsp[i][j][k]['update'])){
                                        var val = (document.getElementById(rsp[i][j][k]['update']).nodeName).toLowerCase();                                   
                                        var typ = document.getElementById(rsp[i][j][k]['update']).getAttribute("type");
                                        var obj = rsp[i][j][k];
                                        if(obj){
                                            if(val=='input'){
                                                
                                                var ele = document.getElementById(obj['update']);                                                        
                                                var span = document.createElement("span");
                                                span.classList.add("spanIc","poppins-italic");
                                                if(obj['update']=='company'||obj['update']=='comercialname'||obj['update']=='website'){
                                                    span.classList.add("iconOptional"); 
                                                }

                                                ele.removeAttribute("disabled");
                                                switch(typ){
                                                    case 'text':                                                    
                                                        if(obj['value']!="" && obj['value']!='null'&& obj['value']!=null)
                                                            document.getElementById(obj['update']).value = obj['value'];
                                                    break;
                                                    case 'date':                                     
                                                        if(obj['date']!="" && obj['date']!=null)
                                                            document.getElementById(obj['update']).value = obj['date'];
                                                    break;
                                                    case 'number':
                                                        if(obj['number']!=="" && obj['number']!=null){
                                                            document.getElementById(obj['update']).value = obj['number'];
                                                        }else if(obj['value']!=="" && obj['value']!=null){
                                                            document.getElementById(obj['update']).value = obj['value'];
                                                        }
                                                        span.classList.add("spanIcNum");
                                                    break;
                                                    case 'phone':
                                                        if(obj['value']!=""  && obj['value']!='null'&& obj['value']!=null){
                                                            if(document.getElementById("phoneCode") && obj['update']=='phone'){
                                                                document.getElementById("phoneCode").value = parseFloat(obj['value'].split(" ")[0]);
                                                            }
                                                            document.getElementById(obj['update']).value = obj['value'].split(" ")[1];
                                                        }
                                                    break;
                                                    case 'tel':
                                                        if(obj['value']!=""  && obj['value']!='null'&& obj['value']!=null){
                                                            if(document.getElementById("phoneCode") && obj['update']=='phone'){
                                                                document.getElementById("phoneCode").value = parseFloat(obj['value'].split(" ")[0]);
                                                                ele = document.getElementById("phoneCode");
                                                                if(ele.previousElementSibling){
                                                                    var span = document.createElement("span");
                                                                    span.classList.add("spanIc","poppins-italic");
                                                                    ele.removeAttribute("disabled");
                                                                    if(obj['valid']==1){
                                                                        span.innerHTML = '<i class="fas fa-check-circle"></i>';
                                                                        ele.setAttribute("disabled","");
                                                                        span.classList.add("iconGreen");        
                                                                        validated = true;                                                        
                                                                        ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                                    }else if(obj['valid']==-1){
                                                                        rejected = true;
                                                                        span.innerHTML = '<i class="fas fa-times-circle"></i>';
                                                                        span.classList.add("iconRed");                                                                
                                                                        ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                                    }
                                                                }
                                                                ele = document.getElementById(obj['update']);
                                                            }
                                                            document.getElementById(obj['update']).value = obj['value'].split(" ")[1];
                                                        }
                                                    break;
                                                    case 'checkbox':
                                                        if(obj['update']!=="declaration")
                                                            document.getElementById(obj['update']).checked = obj['value'];

                                                            var span = document.createElement("span");
                                                            span.classList.add("spanIc","poppins-italic","iconCheckBox");
                                                                var ele = document.getElementById(obj['update']).parentElement.parentElement.parentElement.parentElement.lastElementChild.children[0];
                                                                if(obj['valid']==1){
                                                                    span.innerHTML = '<i class="fas fa-check-circle"></i>';
                                                                    document.getElementById(obj['update']).setAttribute("disabled","");
                                                                    span.classList.add("iconGreen");                                                                
                                                                    ele.appendChild(span);
                                                                    validated = true;
                                                                }else if(obj['valid']==-1){
                                                                    span.innerHTML = '<i class="fas fa-times-circle"></i>';
                                                                    span.classList.add("iconRed"); 
                                                                    document.getElementById(obj['update']).removeAttribute("disabled","");                                                               
                                                                    ele.appendChild(span);
                                                                    rejected = true;
                                                                }
                                                    break;
                                                }
                                                        if(ele.previousElementSibling){
                                                            if(obj['valid']==1){
                                                                span.innerHTML = '<i class="fas fa-check-circle"></i>';
                                                                ele.setAttribute("disabled","");
                                                                span.classList.add("iconGreen");                                                                
                                                                ele.parentElement.insertBefore(span,ele.previousElementSibling);                                                                
                                                                validated = true;
                                                            }else if(obj['valid']==-1){
                                                                rejected = true;
                                                                span.innerHTML = '<i class="fas fa-times-circle"></i>';
                                                                span.classList.add("iconRed");                                                                
                                                                ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                            }
                                                        }

                                            }else if(val=='select'){
                                                var sel = obj['value'];
                                                if(!sel)sel = obj['id'];
                                                if(!sel)sel = "";
                                                if(obj['value']==0)sel = obj['value'];
                                                document.getElementById(obj['update']).value = sel;
                                                var ele = document.getElementById(obj['update']);
                                                        if(ele.previousElementSibling){
                                                            var span = document.createElement("span");
                                                            span.classList.add("spanIc","poppins-italic");
                                                            ele.removeAttribute("disabled");
                                                            if(obj['valid']==1){
                                                                span.innerHTML = '<i class="fas fa-check-circle"></i>';
                                                                ele.setAttribute("disabled","");
                                                                span.classList.add("iconGreen");                                   
                                                                if(obj['update']=='prefertypeop'){
                                                                    span.style.top = 0;
                                                                    span.style.width = '100%';
                                                                    span.style.textAlign = "right";
                                                                    span.style.zIndex = 501;
                                                                    ele.style.opacity = 0;
                                                                    ele.previousElementSibling.style.backgroundColor = '#fafafa';
                                                                }                             
                                                                ele.parentElement.insertBefore(span,ele.previousElementSibling);                                                                
                                                                validated = true;
                                                            }else if(obj['valid']==-1){
                                                                rejected = true;
                                                                span.innerHTML = '<i class="fas fa-times-circle"></i>';
                                                                span.classList.add("iconRed");                                                                
                                                                ele.parentElement.insertBefore(span,ele.previousElementSibling);
                                                            }
                                                        }
                                            }
                                        }
                                    }else{
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    //sE BLOQUEA LA DECLARACION SI HAY 1 CAMPO VALIDADO Y ESTA TIENE VALOR
    var ele = document.getElementById('declaration');
    if(ele){
        if(validated && !rejected && rsp['entry']['declaration']!=""&&rsp['entry']['declaration']!=null){
            ele.setAttribute("disabled","");
            ele.setAttribute("validated",1);
            if(drawStatment(rsp['entry'])){
                document.getElementById("declaration").checked = true;
                document.getElementById("declarationTxt").setAttribute("loaded",true);
            }            
        }else if(rsp['entry']['declaration']!=""&&rsp['entry']['declaration']!=null){
            ele.removeAttribute("disabled");
            ele.setAttribute("validated",1);
            if(drawStatment(rsp['entry'])){
                document.getElementById("declaration").checked = true;
                document.getElementById("declarationTxt").setAttribute("loaded",true);
            }
        }else {
            ele.removeAttribute("disabled");
            ele.setAttribute("validated",0);
            document.getElementById("declaration").checked = false;
            document.getElementById("declarationTxt").setAttribute("loaded",false);
        }
    }
}
//Refrescar la sesión del usuario
function updatePerson(parms,success){
    callWS("POSTUP", "users/updateperson", parms, success);
}
function updateCompany(parms,success){
    callWS("POSTUP", "users/updatecompany", parms, success);
}
//Funcion global para obtener la edad
function getAge(dateString) {
    let today = new Date()
    let birthdate = new Date(dateString)
    let age = today.getFullYear() - birthdate.getFullYear()
    let diffMonths = today.getMonth() - birthdate.getMonth()
    if (
      diffMonths < 0 ||
      (diffMonths === 0 && today.getDate() < birthdate.getDate())
    ) {
      age--
    }
    return age
}

function htmlLang(files){
    var lang = sessionStorage.getItem('lang');
    for(var i=0;i<files.length;i++){
        //Se valida que todos los campos "files" estén llenos
        var file = document.getElementById(files[i].id);
        if(file){//Validamos que existe     
            if((file.nodeName).toLowerCase()=='input'){
                file.setAttribute("placeholder",files[i][lang]);
            }else{
                file.innerHTML = files[i][lang];
            }
        }
    }
}
//Verificar campos formato de registro
function formLang(files){//Los ID que reciben estos lang son los del input directamente y en base a su posición según su tipo se ubica el label y se setea
    var error = false;
    //SE SETEA EL MENSAJE PREVIO SEGUN EL LANG
    var lang = sessionStorage.getItem('lang');
    for(var i=0;i<files.length;i++){
        //Se valida que todos los campos "files" estén llenos
        var file = document.getElementById(files[i].id);
        if(file){//Validamos que existe      
            var htmltag = (file.nodeName).toLowerCase();                                  
            if(htmltag == 'input' || htmltag == 'select'){
                var type = file.getAttribute("type");
                if(type=="checkbox"){//Marcas de switch
                    var lbl = file.parentElement.parentElement.parentElement.nextElementSibling.children[0].children[0];
                    lbl.innerHTML = files[i][lang];
                }else if(type=="file"){//Archivos cargados de uploads (no se usa)
                    var lbl = file.parentElement.parentElement.previousElementSibling.children[0];
                    lbl.innerHTML = files[i][lang];
                }else{ //Inputs y selectes simples incluido caso especial 
                    if(files[i].id=="prefertypeop"){
                        var lbl = file.parentElement.previousElementSibling;
                    }else{                        
                        var lbl = file.previousElementSibling;
                    }
                    lbl.innerHTML = files[i][lang];
                    if(files[i]['placeholder']){
                        if(htmltag == 'input'){
                            file.setAttribute("placeholder",files[i]['placeholder'][lang]);
                        }else if(htmltag == 'select'){
                            if(file.options.length>0){
                                var val = file.options[0].value;
                                if(val==""||val==null||val==undefined)
                                    file.options[0].innerHTML = files[i]['placeholder'][lang];
                            }
                        }
                    }
                }
            }
        }
    }    
}
var erroractive = false;
//Verificar campos formato de registro
function verifyData(files,labels){
    var error = false;
    //SE SETEA EL MENSAJE PREVIO SEGUN EL LANG
    var lang = sessionStorage.getItem('lang');
    var errm = "";
    var errmlast = "";
    switch(lang){
        case 'esp':
            errm = "Por favor complete el campo ";
        break;
        case 'eng':
            errm = "Please complete the ";
            errmlast = " field";
        break;
    }
    for(var i=0;i<files.length;i++){
        //Se valida que todos los campos "files" estén llenos
        var file = document.getElementById(files[i]);
        if(file){//Validamos que existe      
            var htmltag = (file.nodeName).toLowerCase();                                  
            if(htmltag == 'input' || htmltag == 'select'){
                var type = file.getAttribute("type");
                if(type=="checkbox"){
                    var lbl = file.parentElement.parentElement.parentElement.nextElementSibling.children[0].children[0];
                    var label = (lbl.innerHTML).toLowerCase();
                    if(!file.checked){//Validamos que esté chequeado
                        var err = file.parentElement.parentElement.parentElement.parentElement.nextElementSibling;
                        if(err){                    
                            if(err.classList.contains("errorReg")){
                                err.innerHTML = errm+label+errmlast;
                                err.style.display = "block";
                                error = true;
                            }
                        }
                    }
                }else if(type=="file"){
                    var lbl = file.parentElement.parentElement.previousElementSibling.cloneNode(true);
                    if(lbl.getElementsByTagName("span").length){
                        lbl.removeChild(lbl.getElementsByTagName("span")[0]);
                    }
                    var label = (lbl.innerHTML).toLowerCase();
                    var parent = file.parentElement.parentElement.parentElement.parentElement.parentElement;
                    if(file.files.length==0 && (parent.getAttribute("loaded")==0||parent.getAttribute("loaded")==null)){//Validamos que esté chequeado
                        var err = file.parentElement.parentElement.nextElementSibling;
                        if(err){                    
                            if(err.classList.contains("errorReg")){
                                err.innerHTML = errm+label+errmlast;
                                err.style.display = "block";
                                error = true;
                            }
                        }
                    }
                }else{
                    if(files[i]=="prefertypeop"){
                        var lbl = file.parentElement.previousElementSibling;
                    }else{                        
                        var lbl = file.previousElementSibling;
                    }
                    var label = (lbl.innerHTML).toLowerCase();
                    if(file.value == ""){//Validamos valor distinto de vacío
                        if(file.nextElementSibling){                    
                            var err = file.nextElementSibling;
                            if(err.classList.contains("errorReg")){
                                err.innerHTML = errm+label+errmlast;
                                err.style.display = "block";
                                error = true;
                            }
                        }
                    }else if(files[i]=="birthdate"){//Validación unicas del campo fecha de nacimiento
                        if(getAge(file.value)<18){
                            if(file.nextElementSibling){                    
                                var err = file.nextElementSibling;
                                if(err.classList.contains("errorReg")){
                                    err.innerHTML = getLangById("err1birthdate")[lang];
                                    err.style.display = "block";
                                    error = true;
                                }
                            }
                        }
                    }
                }
            }
        }
    } 
    if(error){
        return false;
    }
    return true;

}
//Función que muestra error de formato en archivos
function errFile(file,msg){
    var lang = sessionStorage.getItem('lang');
    var err = file.parentElement.parentElement.nextElementSibling;    
    //file.value = "";     
    if(msg==undefined)  
        err.innerHTML = getLangById('err1file')[lang];
    else
        err.innerHTML = msg;
    err.style.display = "block";
    if(!erroractive){   
        erroractive = true;
        setTimeout(function(){
            clearErrors(); // Se blanquean todos los errores            
            erroractive = false;
        },6000);
    }
}
//Verificar campos formato de registro
function verifyPartners(cnt,files){
    var error = false;
    var lang = sessionStorage.getItem('lang');
    var errm = "";
    var errmlast = "";
    switch(lang){
        case 'esp':
            errm = "Por favor complete el campo ";
        break;
        case 'eng':
            errm = "Please complete the ";
            errmlast = " field";
        break;
    }
    for(var i=0;i<files.length;i++){
        //Se valida que todos los campos "files" estén llenos
        var file = "";        
        if(cnt.querySelector("input[name='"+files[i]+"']")){
            file = cnt.querySelector("input[name='"+files[i]+"']");
        }else if(cnt.querySelector("select[name='"+files[i]+"']")){
            file = cnt.querySelector("select[name='"+files[i]+"']");
        }
        if(file){//Validamos que existe
            var htmltag = (file.nodeName).toLowerCase();                                  
            if(htmltag == 'input' || htmltag == 'select'){
                var type = file.getAttribute("type");
                if(type=="checkbox"){
                    var lbl = file.parentElement.parentElement.parentElement.nextElementSibling.children[0].children[0];
                    var label = (lbl.innerHTML).toLowerCase();                    
                    if(!file.checked){//Validamos que esté chequeado
                        var err = file.parentElement.parentElement.parentElement.parentElement.nextElementSibling;
                        if(err){                    
                            if(err.classList.contains("errorReg")){
                                err.innerHTML = errm+label+errmlast;
                                err.style.display = "block";
                                error = true;
                            }
                        }
                    }
                }else if(type=="file"){
                    if(file.files.length==0 && idsloaded.indexOf(file.getAttribute("label"))<0){//Validamos que esté chequeado
                        var lbl = file.parentElement.parentElement.previousElementSibling.cloneNode(true);
                        if(lbl.getElementsByTagName("span").length){
                            lbl.removeChild(lbl.getElementsByTagName("span")[0]);
                        }
                        var label = (lbl.innerHTML).toLowerCase();
                        var err = file.parentElement.parentElement.nextElementSibling;
                        if(err){                    
                            if(err.classList.contains("errorReg")){
                                err.innerHTML = errm+label+errmlast;
                                err.style.display = "block";
                                error = true;
                            }
                        }
                    }
                }else{
                    if(files[i]=="prefertypeop"){
                        var lbl = file.parentElement.previousElementSibling;
                    }else{                        
                        var lbl = file.previousElementSibling;
                    }
                    var label = (lbl.innerHTML).toLowerCase();
                    if(file.value == ""){//Validamos valor distinto de vacío
                        if(file.nextElementSibling){                    
                            var err = file.nextElementSibling;
                            if(err.classList.contains("errorReg")){
                                err.innerHTML = errm+label+errmlast;
                                err.style.display = "block";
                                error = true;
                            }
                        }
                    }else if(files[i]=="birthdate"){//Validación unicas del campo fecha de nacimiento
                        if(getAge(file.value)<18){
                            if(file.nextElementSibling){                    
                                var err = file.nextElementSibling;
                                if(err.classList.contains("errorReg")){
                                    err.innerHTML = getLangById("err1birthdate")[lang];
                                    err.style.display = "block";
                                    error = true;
                                }
                            }
                        }
                    }
                }
            }
        }
    } 
    if(error){
        return false;
    }
    return true;

}

function validarFile(all){
    var lang = sessionStorage.getItem('lang');
    //EXTENSIONES Y TAMANO PERMITIDO.
    var extensiones_permitidas = [".jpg",".pdf",".png",".jpeg"];
    var tamano = 10; // EXPRESADO EN MB.
    var rutayarchivo = all.value;
    var ultimo_punto = all.value.lastIndexOf(".");
    var extension = rutayarchivo.slice(ultimo_punto, rutayarchivo.length);
    var lbl = all.parentElement.parentElement.previousElementSibling.cloneNode(true);
    if(lbl.getElementsByTagName("span").length){
        lbl.removeChild(lbl.getElementsByTagName("span")[0]);
    }
    var label = (lbl.innerHTML).toLowerCase();
    var err = all.parentElement.parentElement.nextElementSibling;               
    if(err.classList.contains("errorReg")){            
        setTimeout(function(){
            clearErrors(); // Se blanquean todos los errores
        },5000);            
        if(extensiones_permitidas.indexOf(extension.toLowerCase()) == -1){                  
            document.getElementById(all.id).value = "";       
            err.innerHTML = getLangById('err1file')[lang];
            err.style.display = "block";
            return false;
        }else if((all.files[0].size / 1048576) > tamano){
            document.getElementById(all.id).value = "";              
            err.innerHTML = getLangById('err2file')[lang] +tamano+"MB.";
            err.style.display = "block";
            return false;
        }        
        return true;
    }
}

//Blanquear los errores formato de registro
function clearErrors(){
    var errors = document.getElementsByClassName("errorReg");
    for(var i=0;i<errors.length;i++){
        if(errors[i].style.display !== ""){
            errors[i].style.display = "";
            errors[i].innerHTML = "";
        }
    }
}
//Manejo de span en campo multiselect prefertypeop
function addSpan(string){
    var curren = document.getElementById("prefertypeop");
    var slectGroup = document.getElementById("selectGruop");
    var p = document.getElementById("divCurrencieAddSelectGruop");
    
    if(string){
        var array = string.split('-')
        for(var i = 0 ; i< array.length; i++){
            
            var span= document.createElement("span");
            span.setAttribute("id",array[i]);
            span.classList.add('poppins-regular')
            span.classList.add('firstSpan')
            var spanRemove = document.createElement("span");
            spanRemove.innerHTML = "&times";
            spanRemove.style.fontWeight="normal";
            spanRemove.style.zIndex="500";
            spanRemove.style.padding="3px"
            if(array[i] == 1){
                span.innerHTML= 'C-C'
            }else if(array[i]==2){
                span.innerHTML= 'C-DF'
            }else{
                span.innerHTML= 'DF-C'
            }
            curren.value = array[i]
            span.appendChild(spanRemove);
            const idParent = curren.value;
            spanRemove.addEventListener("click", function(){
                removeSpan("idCurrencie"+idParent);
            });
            spanRemove.style.cursor="pointer";
            slectGroup.appendChild(span);
            var idx = curren.selectedIndex
            curren.options[idx].disabled = true;
            
        }
    }else{
        if(p){
            slectGroup.removeChild(p);
        }
        var span= document.createElement("span");
        span.setAttribute("id",curren.value);
        span.classList.add('firstSpan')
        span.classList.add('poppins-regular')
        var textOp = curren[curren.selectedIndex].text.split('(')[1];
        var spanRemove = document.createElement("span");
        spanRemove.innerHTML = "&times";
        spanRemove.style.fontWeight="normal";
        spanRemove.style.zIndex="500";
        spanRemove.style.padding="3px"
        span.innerHTML= textOp.split(')')[0];
        span.appendChild(spanRemove);
        const idParent = curren.value;
        spanRemove.addEventListener("click", function(){
            removeSpan("idCurrencie"+idParent);
        });
        spanRemove.style.cursor="pointer";
        slectGroup.appendChild(span);
        var idx = curren.selectedIndex
        curren.options[idx].disabled = true;
    }
}
function removeSpan(id){
    var idSpan = id.replace("idCurrencie", "");
    var curren = document.getElementById("prefertypeop");
    curren.value = idSpan;
    var idx = curren.selectedIndex;
    curren.options[idx].disabled = false;
    var parent = document.getElementById("selectGruop");
    var spanParent = document.getElementById(idSpan);
    parent.removeChild(spanParent);
    curren.value = "";
}
//Obtener string armado de los spans
function getPrefertypeop(){
    var selectGruop = document.getElementById('selectGruop')
    var array = [];
    for(var i = 0; i < selectGruop.children.length; i ++){
        array.push(selectGruop.children[i].id)
    }
    return array.join('-')
}

//Funcion valida si el valor está activo o no y muestra u oculta los campos de pep
function pepFiles(ele){
    var box = ele.parentElement.parentElement.parentElement.parentElement.parentElement;
    var cntStat = box.getElementsByClassName("txtLngCnt")[0];
    if(!ele.checked){
        cntStat.style.height = "";
        cntStat.classList.remove("txtLngAct");
    }else{
        var stat = box.getElementsByClassName("pepFrmCnt")[0];
        nwHeight = stat.offsetHeight;
        cntStat.classList.add("txtLngAct");
        cntStat.style.height = nwHeight+"px";
    }
}

//OCULTAR EL BOTON PREVIO SI NO ES NUEVO SEGUN ENTRY ENVIADO
//Lo más generico posible
function hideNotNew(rsp){
    var somevalid = false;
    for (let i in rsp) {
        if(i=='entry'){
            for (let j in rsp[i]) {
                if(j=='person' || 'company'){
                    for (let k in rsp[i][j]) {                      
                        if(rsp[i][j][k]){
                            if(k=='uploads'){
                                for (let l in rsp[i][j][k]) {
                                    if(rsp[i][j][k][l]['validated']){
                                        somevalid = true;
                                    }
                                }
                            }
                            //Si llegamos acá y es un objeto debemos ir un nivel más adentro y no existe el "update" campo identificador
                            if(typeof rsp[i][j][k] === 'object' && rsp[i][j][k]['update'] == null){
                                for (let l in rsp[i][j][k]) {
                                    var obj = rsp[i][j][k][l];
                                    if(obj){
                                        if(obj['update']){
                                            if(obj['valid'])somevalid = true;
                                        }
                                    }
                                }
                            }else{ //Si no es un objeto podemos buscar los valores
                                if(rsp[i][j][k]['update']){
                                    var obj = rsp[i][j][k];                                                    
                                    if(obj['update']){
                                        if(obj['valid'])somevalid = true;
                                    }                                    
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if(somevalid){
        document.getElementById("previous").parentElement.removeChild(document.getElementById("previous"));
    }
}