/*

***Funciones globales utilizadas (main.js)***
gotoPage(id, sid, params); esconderHTML(hide); drawSelectN(select,id, read, rsp, selected, first = "");

***Funciones globales utilizadas (register.js)***
countriesLoad(success); uploadsLoad(parms,success); uploadsDraw(rsp);
userEntry(success); expiredSession(); showInf(id);  closeAll(); getAge(dateString)
verifyData(files); clearErrors()

***Variables Globales utilizadas ***
upLoad (boolean) ; countriesJSON (json); 

*/
var wait = "";
var entry = {};
function start(){  
    //Cargar idiomas en textos de la pagina
    htmlLang(texts);
    formLang(filesLang);

    //Mostrar HTML cargado
    esconderHTML(false);

    //Asignar evento cerrar popup
    var close = document.getElementsByClassName("clickClose");
    for(var i=0;i<close.length;i++){
        close[i].addEventListener("click",function(){
            closeAll();
        });
    }
    
    //Actualizar información y avanzar al siguiente nivel
    document.getElementById("next-button").addEventListener("click",function(){
        updateSave("kyc","jurInitEconom");
    });
    // Regresr pantalla anterior
    document.getElementById('previous-button').addEventListener("click", function(){
        gotoPage("kyc","jurInitReg",{});
    });
    // Complete later salir sin guardar
    document.getElementById('later-button').addEventListener("click", function(){
        document.getElementsByClassName('completeLater')[0].style.display = 'table';
    });
    getEntry();

    //Refrescar los bloques de socios si se cambia el campo
    document.getElementById("partners").addEventListener("change",function(){
        var dif = this.value - this.oldvalue;
        if(dif>0){
            addPartners(dif);
        }else{
            delPartners(dif);
        }
        this.oldvalue = this.value;
    });

    document.getElementById("partners").addEventListener("focus",function(){
        this.oldvalue = this.value;
    });

    //Pep evento ocultar campos o mostrar
    document.getElementById("reppep").addEventListener("click",function(){
        pepFiles(this);
    });

    //
    document.getElementById("reppartner").addEventListener("change",function(){
        if(this.checked){
            legalPartner();
        }else{
            removeFirst();
        }
    });

    //Eventos al primer campo del socio
    var cnt = document.getElementById("prtnrsList");
    var nwnode = cnt.firstElementChild;
    //Evento del eliminar
    var del = nwnode.getElementsByClassName("prtnrDel")[0];
    del.addEventListener("click",function(){
        if(!document.getElementById("partners").disabled){
            var num = document.getElementById("partners");
            if((num.value-1)>0){
                num.value = num.value-1;
                var pid = this.parentElement.querySelector("input[name='name']").getAttribute("prtnrid");       

                if(pid!=undefined&&pid!==null&&pid!==""&&pid!='0'){
                    deletedpartners += pid+"-";
                }  
                cnt.removeChild(this.parentElement);
                var num = document.getElementById("partners").value;
                for(var i=0;i<num;i++){            
                    //Actualizar Label izquierdo superior del bloque
                    var lbl =  cnt.getElementsByClassName("lblPrtnr")[i];
                    lbl.innerText = getLangById("subtitPrtnr")[sessionStorage.getItem('lang')]+(i+1);
                }                
            }
        }
        /*
        if((num.value-1)>0){
            num.value = num.value-1;
            cnt.removeChild(this.parentElement);
            num = num.value;
            for(var i=0;i<num;i++){ 
                //Actualizar Label izquierdo superior del bloque
                var lbl =  cnt.getElementsByClassName("lblPrtnr")[i];
                lbl.innerText = getLangById("subtitPrtnr")[sessionStorage.getItem('lang')]+(i+1);
            }          
        }*/
    });
    //Evento de mostrar los campos activos si el socio es pep
    var pep = nwnode.getElementsByClassName("switch")[0].children[0];
    pep.addEventListener("click",function(){
        pepFiles(this);
    });

    formatFields2(["repphone","prtnrPhn"],["tel","tel"]);
}
//Se carga el entry y se pinta la data que corresponde
function getEntry(){
    //Load data del usuarios       
    //Funcion que se ejecuta al obtener respuesta
    var userResp = function(status, rsp){
    var rsp = JSON.parse(rsp);
        switch(status){
            case 200:
                entry = rsp.entry;
                //Se setea el oldvalue a 0               
                document.getElementById("partners").oldvalue = 1;
                drawEntry(rsp);//Se arma la variable global entry con la respuesta y se cargan las llamadas adicionales
                
                getCountries();
            break;
            case 204:
            break;
            case 400:
            break;
            case 401:
                expiredSession();
            break;
            case 500:
            break;
            default:
            break;
        }
    }           
    userEntry(userResp);
}
//Pintar select opciones de códigos de país
function drawSelCod(select, read, rsp, selected, first = ""){
    //rsp - (array) Registros
    //select - donde se insertan las opciones
    //first - si no está vacío crea un opcion sin value
    //selected - selecciona una opción especifica
    //read - campo a partir del cual muestra el LBL
    select.innerHTML = "";
    var opt;
    if(first !== ""){
        opt = "";
        opt = document.createElement("option");
        opt.setAttribute("value", "");
        opt.innerHTML = first;
        select.appendChild(opt);
    }
    for(var i=0; i<rsp.length; i++){
        opt = document.createElement("option");
        opt.setAttribute("value", rsp[i][read]);
        opt.innerHTML = "+"+rsp[i][read];
        if(selected !== null && selected !== "" && selected !== undefined){
            if(rsp[i].id == selected)
                opt.setAttribute("selected", "");
        }
        select.appendChild(opt);
    }
}
//Save partners
function savePartners(){    
    //Datos del representante legal primero 
    var filesrep = ["repname","repdoc","repphone"];    
    var frparms = ["name","doc","phone"];
    
    if(document.getElementById("reppep").checked){
        filesrep.push("reppeprelatedid","reppepcountryid","reppositionheld","repaffiliationbody");
        frparms.push("peprelatedid","pepcountryid","positionheld","affiliationbody");
    }
    

    var cnt = document.getElementById("prtnrsList");
    var prtnrsBlocks = cnt.getElementsByClassName("prtnrCnt");
    var prtnrNo = 0;
    var reploaded = false;
    var valid = false;
    for(var x=0;x<prtnrsBlocks.length;x++){  
        if((prtnrsBlocks[prtnrNo].querySelector("input[name='name']").getAttribute("prtnrid")) !== "isrep"){
            var files = ["name","doc","phone",];    
            var fparms = ["name","doc","phone"];    
            //Se validan los campos adicionales del pep si los socios lo tienen activo        
            if(prtnrsBlocks[prtnrNo].querySelector("input[name='politicallyexposed']").checked){
                files.push("peprelatedid","pepcountryid","positionheld","affiliationbody");
                fparms.push("peprelatedid","pepcountryid","positionheld","affiliationbody");
            }
                //Se recorren todos los socios
            if(!verifyPartners(prtnrsBlocks[prtnrNo],files) || !verifyData(filesrep)){ 
                valid = false;
                    if(!erroractive){   
                        erroractive = true;
                        setTimeout(function(){
                            clearErrors(); // Se blanquean todos los errores            
                            erroractive = false;
                        },6000);
                    }
                return;
            }  
        }
        prtnrNo = prtnrNo + 1;
    }
    valid = true;
    //Se guardan si pasan las validaciones
    prtnrNo = 0;
    for(var x=0;x<prtnrsBlocks.length;x++){ 
        var files = ["name","doc","phone",];    
        var fparms = ["name","doc","phone"];
        //Se validan los campos adicionales del pep si los socios lo tienen activo        
        if(prtnrsBlocks[prtnrNo].querySelector("input[name='politicallyexposed']").checked){
            files.push("peprelatedid","pepcountryid","positionheld","affiliationbody");
            fparms.push("peprelatedid","pepcountryid","positionheld","affiliationbody");
        }
        if(valid){
            if(!reploaded){//El representante legal se guarda solo una vez
                filesrep.push("reppep");
                frparms.push("politicalexp");
                reploaded = true;
                var parms = new FormData();
                //Session
                parms.append("sessionid",sessionStorage.getItem('sessionid'));
                parms.append("legalrep",1);//Se marca que es el representante legal
                parms.append("id",(document.getElementById("repname").getAttribute("prtnrid")));//Se marca que es el representante legal
                //Parametros generales definidos en arreglos
                for(var i=0;i<filesrep.length;i++){
                    if(document.getElementById(filesrep[i]).getAttribute("type")=="checkbox"){
                        var val = 0;
                        if(document.getElementById(filesrep[i]).checked)val = 1;
                        parms.append(frparms[i],val);
                    }else{                
                        parms.append(frparms[i],document.getElementById(filesrep[i]).value);
                    }
                }
                savePartner(parms);         
            }



            files.push("politicallyexposed");
            fparms.push("politicalexp");
            var parms = new FormData();
            //Session
            parms.append("sessionid",sessionStorage.getItem('sessionid'));
            parms.append("legalrep",0);//Se marca que es el representante legal
            parms.append("id",(prtnrsBlocks[prtnrNo].querySelector("input[name='name']").getAttribute("prtnrid")));//Se marca que es el representante legal
            
            //Parametros generales definidos en arreglos
            for(var i=0;i<files.length;i++){
                var ele = null;
                ele = prtnrsBlocks[prtnrNo].querySelector("input[name='"+files[i]+"']");
                if(ele==null)ele = prtnrsBlocks[prtnrNo].querySelector("select[name='"+files[i]+"']");
                if(ele!==null){
                    if(ele.getAttribute("type")=="checkbox"){
                        var val = 0;
                        if(ele.checked)val = 1;
                        parms.append(fparms[i],val);
                    }else{                
                        parms.append(fparms[i],ele.value);                    
                    }
                }
            }
            if((prtnrsBlocks[prtnrNo].querySelector("input[name='name']").getAttribute("prtnrid"))!=='isrep')
                savePartner(parms);         
        }
        prtnrNo = prtnrNo + 1;
    }
     
}
//Pintar cajas de socios según valor seleccionado en "select"
function addPartners(news){
    var cnt = document.getElementById("prtnrsList");
    var clone = cnt.firstElementChild.cloneNode(true);
    var nwnode;
    var num = document.getElementById("partners").value;
    if(num>0){                          
        //Objeto abiert si existe
        for(var i=0;i<news;i++){            
            nwnode = "";
            nwnode = clone.cloneNode(true);
            nwnode.style.display = "";
            //Blanquear iconos de validado rechazado
            var icons = nwnode.getElementsByClassName("spanIc");
            var icln = icons.length;// Se define acá para que no varíe el length dentro del form
            for(var x=(icln-1);x>=0;x--){
                icons[x].parentElement.removeChild(icons[x]);
            }

            var inpts = nwnode.getElementsByTagName("input");
            for(var x=0;x<inpts.length;x++){ 
                if(inpts[x].getAttribute("type")=="checkbox"){
                    inpts[x].checked = false;   
                    inpts[x].dispatchEvent(new Event("click"));
                }else{
                    inpts[x].value = "";  
                }   
                if(inpts[x].getAttribute("type") == "tel"){                    
                    inpts[x].addEventListener("keyup", function(e){
                        this.value = formatPhone(this.value); 
                    });
                }
                inpts[x].removeAttribute("disabled");         
                if(inpts[x].getAttribute("name")=="name"){
                    inpts[x].setAttribute("prtnrid",0);
                }
            }
            var selects = nwnode.getElementsByTagName("select");
            for(var x=0;x<selects.length;x++){
                selects[x].selectedIndex = 0;   
                selects[x].removeAttribute("disabled");         
            }
            var lastno = cnt.getElementsByClassName("prtnrCnt").length;
            //Label izquierdo superior del bloque
            var lbl =  nwnode.getElementsByClassName("lblPrtnr")[0];
            lbl.innerText = getLangById("subtitPrtnr")[sessionStorage.getItem('lang')]+(lastno+1);
            //Evento del eliminar
            var del = nwnode.getElementsByClassName("prtnrDel")[0];
            del.addEventListener("click",function(){
                if(!document.getElementById("partners").disabled){
                    var num = document.getElementById("partners");    
                    if((num.value-1)>0){
                        num.value = num.value-1;
                        var pid = this.parentElement.querySelector("input[name='name']").getAttribute("prtnrid");       

                        if(pid!=undefined&&pid!==null&&pid!==""&&pid!='0'){
                            deletedpartners += pid+"-";
                        }  
                        cnt.removeChild(this.parentElement);
                        var num = document.getElementById("partners").value;
                        for(var i=0;i<num;i++){            
                            //Actualizar Label izquierdo superior del bloque
                            var lbl =  cnt.getElementsByClassName("lblPrtnr")[i];
                            lbl.innerText = getLangById("subtitPrtnr")[sessionStorage.getItem('lang')]+(i+1);
                        }                
                    }
                }
            });
            //Evento de mostrar los campos activos si el socio es pep
            var pep = nwnode.getElementsByClassName("switch")[0].children[0];
            pep.addEventListener("click",function(){
                pepFiles(this);
            });
            //Ocultar el pep si se copia y está activo
            var txtlng = nwnode.getElementsByClassName("txtLngAct");
            if(txtlng){
                if(txtlng.length>0){
                    txtlng[0].style.height = "";
                    txtlng[0].classList.remove("txtLngAct");
                }
            }
            var first = sessionStorage.getItem('lang') == 'esp' ? "Seleccione" : 'Select'
            //Pintar select de paises
            drawSelectN(nwnode.getElementsByClassName("prtnrCountry")[0],'id','dsc',countriesL,"",first);
            cnt.appendChild(nwnode);                
        }
    }else{
        nwnode = clone.cloneNode(true);
        nwnode.style.display = "none";
        cnt.innerHTML = "";
        cnt.appendChild(nwnode);
    }
}
//Pintar cajas de socios según valor seleccionado en "select"
var deletedpartners = "";
function delPartners(del){
    var cnt = document.getElementById("prtnrsList");
    var num = document.getElementById("partners").value;                       
    //Objeto abiert si existe
    for(var i=0;i<Math.abs(del);i++){   
        var lastele = num;
        var delalways = cnt.getElementsByClassName("prtnrCnt")[lastele]; 
        var pid = delalways.querySelector("input[name='name']").getAttribute("prtnrid");       
        if(pid!=undefined&&pid!==null&&pid!==""&&pid!=="0"){
            deletedpartners += pid+"-";
        }     
        cnt.removeChild(delalways);                
    }
}
var loaded = 0;
function savePartner(params){
    callWS("POSTUP", "partners/update", params, response);
    function response(status, rsp){
        switch(status){
            case 200:        
                loaded=loaded+1;
                //if(loaded==size)gotoPage('kyc','jurInitEconom', "");
                //else setTimeout(function(){validLoaded()},500);
            break;
            case 204:
                isOk = false;
                break;
            case 400:
                // Parametros incorrectos
                 isOk = false;
                break;
            case 401:
                expiredSession();
                break;
            case 409:
                loaded=loaded+1;
                if(loaded==(parseFloat(document.getElementById("partners").value+1)))gotoPage('kyc','jurInitEconom', "");
                break;
            case 500:
                break;
            default:
                isOk = false;
            break;
        }
    }
}
function validCheck(ele,prtnr){
    //Se crea la marca de validado o no  
    var span = document.createElement("span");
    span.classList.add("spanIc","poppins-italic");
    ele.removeAttribute("disabled");
    if(prtnr['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(prtnr['valid']==-1){
        span.innerHTML = '<i class="fas fa-times-circle"></i>';
        span.classList.add("iconRed");                                                                
        ele.parentElement.insertBefore(span,ele.previousElementSibling);
    }
}
function entryPartners(prtnrs){
    var cnt = document.getElementById("prtnrsList");
    var prtnrsBlocks = cnt.getElementsByClassName("prtnrCnt");
    var prtnrNo = 0;
    for(var i=0;i<prtnrs.length;i++){  
        if(!prtnrs[i].legalrep.value){            
            prtnrsBlocks[prtnrNo].querySelector("input[name='name']").value = prtnrs[i].name.value;
            prtnrsBlocks[prtnrNo].querySelector("input[name='name']").setAttribute("prtnrid",prtnrs[i].id);            
            validCheck(prtnrsBlocks[prtnrNo].querySelector("input[name='name']"),prtnrs[i].name);
            prtnrsBlocks[prtnrNo].querySelector("input[name='doc']").value = prtnrs[i].document.value;
            validCheck(prtnrsBlocks[prtnrNo].querySelector("input[name='doc']"),prtnrs[i].document);
            prtnrsBlocks[prtnrNo].querySelector("input[name='phone']").value = prtnrs[i].phone.value;
            validCheck(prtnrsBlocks[prtnrNo].querySelector("input[name='phone']"),prtnrs[i].phone);
            prtnrsBlocks[prtnrNo].querySelector("input[name='politicallyexposed']").checked = false;
            var obj = prtnrsBlocks[prtnrNo].querySelector("input[name='politicallyexposed']");
            var span = document.createElement("span");
            span.classList.add("spanIc","poppins-italic","iconCheckBox");
            var ele = obj.parentElement.parentElement.parentElement.parentElement.lastElementChild.children[0];
            if(prtnrs[i].politicalexposed['valid']==1){
                span.innerHTML = '<i class="fas fa-check-circle"></i>';
                obj.setAttribute("disabled","");
                span.classList.add("iconGreen");                                                                
                ele.appendChild(span);
            }else if(prtnrs[i].politicalexposed['valid']==-1){
                span.innerHTML = '<i class="fas fa-times-circle"></i>';
                span.classList.add("iconRed"); 
                obj.removeAttribute("disabled","");                                                               
                ele.appendChild(span);
            }
            if(prtnrs[i].politicalexposed.value){
                prtnrsBlocks[prtnrNo].querySelector("input[name='politicallyexposed']").checked = true;
                prtnrsBlocks[prtnrNo].querySelector("input[name='politicallyexposed']").dispatchEvent(new Event("click"));
                //Campos pep
                prtnrsBlocks[prtnrNo].querySelector("input[name='affiliationbody']").value = prtnrs[i].affiliationbody.value;
                validCheck(prtnrsBlocks[prtnrNo].querySelector("input[name='affiliationbody']"),prtnrs[i].affiliationbody);
                prtnrsBlocks[prtnrNo].querySelector("input[name='positionheld']").value = prtnrs[i].positionheld.value;
                validCheck(prtnrsBlocks[prtnrNo].querySelector("input[name='positionheld']"),prtnrs[i].positionheld);
                prtnrsBlocks[prtnrNo].querySelector("select[name='pepcountryid']").value = prtnrs[i].pepcountryid.value;
                validCheck(prtnrsBlocks[prtnrNo].querySelector("select[name='pepcountryid']"),prtnrs[i].pepcountryid);
                prtnrsBlocks[prtnrNo].querySelector("input[name='peprelatedid']").value = prtnrs[i].peprelatedid.value;
                validCheck(prtnrsBlocks[prtnrNo].querySelector("input[name='peprelatedid']"),prtnrs[i].peprelatedid);
            }

            
            /*
            if(document.getElementById("reppartner").checked && prtnrNo==0){
                prtnrsBlocks[prtnrNo].querySelector("input[name='name']").setAttribute("disabled","");
                prtnrsBlocks[prtnrNo].querySelector("input[name='doc']").setAttribute("disabled","");
                prtnrsBlocks[prtnrNo].querySelector("input[name='phone']").setAttribute("disabled","");
                prtnrsBlocks[prtnrNo].querySelector("input[name='politicallyexposed']").setAttribute("disabled","");
                prtnrsBlocks[prtnrNo].querySelector("input[name='affiliationbody']").setAttribute("disabled","");
                prtnrsBlocks[prtnrNo].querySelector("input[name='positionheld']").setAttribute("disabled","");
                prtnrsBlocks[prtnrNo].querySelector("select[name='pepcountryid']").setAttribute("disabled","");
                prtnrsBlocks[prtnrNo].querySelector("input[name='peprelatedid']").setAttribute("disabled","");
            }*/
            prtnrNo = prtnrNo + 1;
        }
    }
    //Cuando se termina el ciclo de mostrar/cargar el representante legal
    if(document.getElementById("reppartner").checked){
        document.getElementById("reppartner").dispatchEvent(new Event("change"));
    }
}
function entryLegalRep(prtnrs){
    for(var i=0;i<prtnrs.length;i++){  
        if(prtnrs[i].legalrep.value){
            document.getElementById("repname").value = prtnrs[i].name.value;
            validCheck(document.getElementById("repname"),prtnrs[i].name);
            document.getElementById("repname").setAttribute("prtnrid",prtnrs[i].id);
            document.getElementById("repdoc").value = prtnrs[i].document.value;
            validCheck(document.getElementById("repdoc"),prtnrs[i].document);
            document.getElementById("repphone").value = prtnrs[i].phone.value;
            validCheck(document.getElementById("repphone"),prtnrs[i].phone);
            document.getElementById("reppep").checked = false;
            var obj = document.getElementById("reppep");
            var span = document.createElement("span");
            span.classList.add("spanIc","poppins-italic","iconCheckBox");
            var ele = obj.parentElement.parentElement.parentElement.parentElement.lastElementChild.children[0];
            if(prtnrs[i].politicalexposed['valid']==1){
                span.innerHTML = '<i class="fas fa-check-circle"></i>';
                obj.setAttribute("disabled","");
                span.classList.add("iconGreen");                                                                
                ele.appendChild(span);
            }else if(prtnrs[i].politicalexposed['valid']==-1){
                span.innerHTML = '<i class="fas fa-times-circle"></i>';
                span.classList.add("iconRed"); 
                obj.removeAttribute("disabled","");                                                               
                ele.appendChild(span);
            }
            if(prtnrs[i].politicalexposed.value){
                document.getElementById("reppep").checked = true;
                document.getElementById("reppep").dispatchEvent(new Event("click"));
                //Campos pep
                document.getElementById("repaffiliationbody").value = prtnrs[i].affiliationbody.value;
                validCheck(document.getElementById("repaffiliationbody"),prtnrs[i].affiliationbody);
                document.getElementById("reppositionheld").value = prtnrs[i].positionheld.value;
                validCheck(document.getElementById("reppositionheld"),prtnrs[i].positionheld);
                document.getElementById("reppepcountryid").value = prtnrs[i].pepcountryid.value;
                validCheck(document.getElementById("reppepcountryid"),prtnrs[i].pepcountryid);
                document.getElementById("reppeprelatedid").value = prtnrs[i].peprelatedid.value;
                validCheck(document.getElementById("reppeprelatedid"),prtnrs[i].peprelatedid);
            }
        }
    }
}
function legalPartner(){
    var lang = sessionStorage.getItem('lang');
    var cnt = document.getElementById("prtnrsList");
    var clone = cnt.firstElementChild.cloneNode(true);
    var nwnode;
    var num = document.getElementById("partners").value;
    document.getElementById("partners").value = parseFloat(num) + 1;

    nwnode = "";
    nwnode = clone.cloneNode(true);
    nwnode.style.display = "";
    //Blanquear iconos de validado rechazado
    var icons = nwnode.getElementsByClassName("spanIc");
    var icln = icons.length;// Se define acá para que no varíe el length dentro del form
        for(var x=(icln-1);x>=0;x--){
            icons[x].parentElement.removeChild(icons[x]);
        }
    
    var inpts = nwnode.getElementsByTagName("input");
    //Blanquear todos los inputs del clone que se hace
    for(var x=0;x<inpts.length;x++){
        if(inpts[x].getAttribute("type")=="checkbox"){
            inpts[x].checked = false;
        }else{
            inpts[x].value = "";
        }
        inpts[x].disabled = true;
    }
    var select = nwnode.getElementsByTagName("select");
    //Blanquear todos los inputs del clone que se hace
    for(var x=0;x<select.length;x++){                
        select[x].value = "";
        select[x].disabled = true;
    }
    //SE cierran los pep
    var txtlng = nwnode.getElementsByClassName("txtLngAct"); 
    if(txtlng){
        if(txtlng.length>0){
            txtlng[0].style.height = "";
            txtlng[0].classList.remove("txtLngAct");
        }
    }

    //Evento del eliminar
    var del = nwnode.getElementsByClassName("prtnrDel")[0];
    //Evento de mostrar los campos activos si el socio es pep
    var pep = nwnode.getElementsByClassName("switch")[0].children[0];
    pep.addEventListener("click",function(){
        pepFiles(this);
    });
    //Ocultar el pep si se copia y está activo
    var txtlng = nwnode.getElementsByClassName("txtLngAct");
    if(txtlng){
        if(txtlng.length>0){
            txtlng[0].style.height = "";
            txtlng[0].classList.remove("txtLngAct");
        }
    }
    var first = lang == 'esp' ? "Seleccione" : 'Select'
    //Pintar select de paises
    drawSelectN(nwnode.getElementsByClassName("prtnrCountry")[0],'id','dsc',countriesL,"",first);
    cnt.insertBefore(nwnode,cnt.firstElementChild);
    nwnode.querySelector("input[name='name']").value = document.getElementById("repname").value;
    var elecnt = nwnode.querySelector("input[name='name']").parentElement;
    if(document.getElementById("repname").parentElement.children[0].classList.contains("spanIc"))
        elecnt.insertBefore(document.getElementById("repname").parentElement.children[0].cloneNode(true),elecnt.firstElementChild);

    nwnode.querySelector("input[name='name']").setAttribute("prtnrid","isrep");
    
    nwnode.querySelector("input[name='doc']").value = document.getElementById("repdoc").value;
    var elecnt = nwnode.querySelector("input[name='doc']").parentElement;
    if(document.getElementById("repdoc").parentElement.children[0].classList.contains("spanIc"))
        elecnt.insertBefore(document.getElementById("repdoc").parentElement.children[0].cloneNode(true),elecnt.firstElementChild);

    nwnode.querySelector("input[name='phone']").value = document.getElementById("repphone").value;
    var elecnt = nwnode.querySelector("input[name='phone']").parentElement;
    if(document.getElementById("repphone").parentElement.children[0].classList.contains("spanIc"))
        elecnt.insertBefore(document.getElementById("repphone").parentElement.children[0].cloneNode(true),elecnt.firstElementChild);

    nwnode.querySelector("input[name='politicallyexposed']").checked = false;
    var elecnt = nwnode.querySelector("input[name='politicallyexposed']").parentElement.parentElement.parentElement.parentElement;
    var span = document.getElementById("reppep").parentElement.parentElement.parentElement.parentElement.getElementsByClassName("lblStat")[0].lastElementChild;
    if(span.classList.contains("spanIc"))
        elecnt.lastElementChild.lastElementChild.appendChild(span.cloneNode(true));

    if(document.getElementById("reppep").checked){
        nwnode.querySelector("input[name='politicallyexposed']").checked = true;
        nwnode.querySelector("input[name='politicallyexposed']").dispatchEvent(new Event("click"));
        //Campos pep
        nwnode.querySelector("input[name='affiliationbody']").value = document.getElementById("repaffiliationbody").value;
        var elecnt = nwnode.querySelector("input[name='affiliationbody']").parentElement;
        if(document.getElementById("repaffiliationbody").parentElement.children[0].classList.contains("spanIc"))
            elecnt.insertBefore(document.getElementById("repaffiliationbody").parentElement.children[0].cloneNode(true),elecnt.firstElementChild);
        nwnode.querySelector("input[name='positionheld']").value = document.getElementById("reppositionheld").value;
        var elecnt = nwnode.querySelector("input[name='positionheld']").parentElement;
        if(document.getElementById("reppositionheld").parentElement.children[0].classList.contains("spanIc"))
            elecnt.insertBefore(document.getElementById("reppositionheld").parentElement.children[0].cloneNode(true),elecnt.firstElementChild);
        nwnode.querySelector("select[name='pepcountryid']").value = document.getElementById("reppepcountryid").value;
        var elecnt = nwnode.querySelector("select[name='pepcountryid']").parentElement;
        if(document.getElementById("reppepcountryid").parentElement.children[0].classList.contains("spanIc"))
            elecnt.insertBefore(document.getElementById("reppepcountryid").parentElement.children[0].cloneNode(true),elecnt.firstElementChild);
        nwnode.querySelector("input[name='peprelatedid']").value = document.getElementById("reppeprelatedid").value;
        var elecnt = nwnode.querySelector("input[name='peprelatedid']").parentElement;
        if(document.getElementById("reppeprelatedid").parentElement.children[0].classList.contains("spanIc"))
            elecnt.insertBefore(document.getElementById("reppeprelatedid").parentElement.children[0].cloneNode(true),elecnt.firstElementChild);
    }

    //Repintar datos accionistas
    var num = document.getElementById("partners").value;
    for(var i=0;i<num;i++){            
            //Actualizar Label izquierdo superior del bloque
        var lbl =  cnt.getElementsByClassName("lblPrtnr")[i];
        lbl.innerText = getLangById("subtitPrtnr")[lang]+(i+1);
    } 
}
function removeFirst(){
    var cnt = document.getElementById("prtnrsList");
    var delalways = cnt.getElementsByClassName("prtnrCnt")[0];  
    var num = document.getElementById("partners").value; 
    var pid = delalways.querySelector("input[name='name']").getAttribute("prtnrid");       
    if(pid!=undefined&&pid!==null&&pid!==""&&pid!='0'){
        deletedpartners += pid+"-";
    } 
    if(num==1){
        var inpts = cnt.getElementsByTagName("input");
        for(var i=0;i<inpts.length;i++){
            if(inpts[i].getAttribute("type")=="checkbox"){
                inpts[i].checked = false;   
                inpts[i].dispatchEvent(new Event("click"));
            }else{
                inpts[i].value = "";  
            }   
            inpts[i].removeAttribute("disabled");         
        }
        var selects = cnt.getElementsByTagName("select");
        for(var i=0;i<selects.length;i++){
            selects[i].selectedIndex = 0;   
            selects[i].removeAttribute("disabled");         
        }

    }else{
        document.getElementById("partners").value = parseFloat(num) - 1;      
        cnt.removeChild(delalways); 
        //Repintar datos accionistas
        var num = document.getElementById("partners").value;
        for(var i=0;i<num;i++){            
            //Actualizar Label izquierdo superior del bloque
            var lbl =  cnt.getElementsByClassName("lblPrtnr")[i];
            lbl.innerText = getLangById("subtitPrtnr")[sessionStorage.getItem('lang')]+(i+1);
        }    
    }
    
}

//Se carga el listado de paises y se arma el select correspondiente si la respuesta es exitosa
var countriesL = [];
function getCountries(){        
    //Funcion si tiene exito el request  
    var cntryRsp = function(status, rsp){
        var rsp = JSON.parse(rsp);
        switch(status){
            case 200:
                countriesL = rsp.records;
                //Listado pais pepcountryid
                //Listado socio 1
                var prtnrCid = entry.company.partners;                
                var isRep = "";
                if(prtnrCid){
                    prtnrCid = prtnrCid[0].pepcountryid.value;
                    if(entry.company.partners[0].legalrep.value)isRep = prtnrCid;
                }else{
                    prtnrCid = "";
                }           
                var first = sessionStorage.getItem('lang') == 'esp' ? "Seleccione" : 'Select'     
                drawSelectN(document.getElementById("reppepcountryid"),'id','dsc',countriesL,isRep,first);                
                drawSelectN(document.getElementsByClassName("prtnrCountry")[0],'id','dsc',countriesL,prtnrCid,first);                
                //Se pintan los socios
                if(entry.company.partners){
                    if(entry.company.partners.length>=2){
                        document.getElementById("partners").value = entry.company.partners.length-1;                    
                        document.getElementById("partners").dispatchEvent(new Event("change"));
                        entryLegalRep(entry.company.partners);
                        entryPartners(entry.company.partners);
                    }else{
                        document.getElementById("partners").value = 1;
                        entryLegalRep(entry.company.partners);
                        if(entry.company.partners[0].legalrep){
                            legalPartner();
                        }
                    }  
                    /* Resuetlo ticket de Dayco #5010 al comentar la sección inferior desconozco el motivo de por qué se había agregado eso 
                    creo que era para eliminar el adicional que daba la posiblidad de crear 
                    if(document.getElementById("partners").disabled){
                        document.getElementById("partners").value = document.getElementById("partners").value-1;
                        delPartners(1);
                    }*/
                }else if(document.getElementById("partners").value==""){
                    document.getElementById("partners").value = 1;
                }
                entry = null;
            break;
            case 204:
            break;
            default:
            break;
        }
    } 
    countriesLoad(cntryRsp);
}
function updateSave(id,sid){
    savePartners();
    var x = setInterval(function(){    
        var pnrs = (parseFloat(document.getElementById("partners").value)+1);
        if(document.getElementById("reppartner").checked){
            pnrs = pnrs-1;
        }     
        if(loaded==pnrs){  
            if(deletedpartners!==""){
                removePartners();
            }
            var success = function(status, rsp){
                switch(status){
                    case 200:
                        gotoPage(id,sid,"");                    
                        break;
                    case 204:
                        break;
                    case 400:
                        // Parametros incorrectos
                        break;
                    case 409:
                        // Ya existe esa cedula
                        break;
                    case 401:
                        expiredSession();
                        break;
                    case 500:
                        // Error
                        
                        break;
                    default:
                    
                        break;
                }
            }
            var parms = new FormData();
            //Session
            parms.append("sessionid",sessionStorage.getItem('sessionid')); 
            //Validamos el valor del campo que indica si el representante legal es jurídico
            if(document.getElementById("reppartner").getAttribute("type")=="checkbox"){
                var val = 0;
                if(document.getElementById("reppartner").checked)val = 1;
                parms.append("reppartner",val);
            }   
            //Paso actual
            parms.append("step",3);
            updateCompany(parms,success);
            clearInterval(x);
        }
    },2000);    
}
function removePartners(){
    var parms = {};    
    deletedpartners = deletedpartners.slice(0,-1); //Se elimina el ultimo "-"         
    parms.ids = deletedpartners;
    parms.sessionid = sessionStorage.getItem('sessionid');
    var response = function(status, rsp){
        switch(status){
            case 200:        
            break;
            case 204:
                break;
            case 400:
                console.log(parms)
                break;
            case 401:
                expiredSession();
                break;
            case 409:
                break;
            case 500:
                break;
            default:
            break;
        }
    }
    callWS("GET", "partners/delete", parms, response);    
}