/*

***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();

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

*/
var wait = "";
var entry = {};
function start(){    
    //Select Tipo de documentos en doble idioma
    var qtymonthlyop = {};
    qtymonthlyop.esp = [{"id":"1 a 10","dsc":"1 a 10"},{"id":"10 a 100","dsc":"10 a 100"},
                        {"id":"100 a 1000","dsc":"100 a 1000"},{"id":"Más de 1.000","dsc":"Más de 1.000"}];
    qtymonthlyop.eng = [{"id":"1 a 10","dsc":"1 to 10"},{"id":"10 a 100","dsc":"10 to 100"},
                        {"id":"100 a 1000","dsc":"100 to 1000"},{"id":"Más de 1.000","dsc":"More than 1.000"}];
    var first = sessionStorage.getItem('lang') == 'esp' ? "Selecciona" : 'Select'
    drawSelectN(document.getElementById("qtymonthlyop"),'id','dsc',qtymonthlyop[sessionStorage.getItem('lang')],"",first); 
    //Select Tipo de documentos en doble idioma
    var amountmontlyop = {};
    amountmontlyop.esp = [{"id":"1 a 100","dsc":"1 a 100"},{"id":"100 a 1000","dsc":"100 a 1.000"},
                        {"id":"1000 a 10000","dsc":"1.000 a 10.000"},{"id":"Más de 10.000","dsc":"Más de 10.000"}];
    amountmontlyop.eng = [{"id":"1 a 100","dsc":"1 to 100"},{"id":"100 a 1000","dsc":"100 to 1.000"},
                        {"id":"1000 a 10000","dsc":"1.000 to 10.000"},{"id":"Más de 10.000","dsc":"More than 10.000"}];
    var first = sessionStorage.getItem('lang') == 'esp' ? "Selecciona" : 'Select'
    drawSelectN(document.getElementById("amountmontlyop"),'id','dsc',amountmontlyop[sessionStorage.getItem('lang')],"",first); 
    //Select Tipo de documentos en doble idioma
    var prefertypeop = {};
    prefertypeop.esp = [{"id":1,"dsc":"Cripto - Cripto (C-C)"},{"id":2,"dsc":"Cripto - Dinero Fiat (C-DF)"},
                        {"id":3,"dsc":"Dinero Fiat - Cripto (DF-C)"}];
    prefertypeop.eng = [{"id":1,"dsc":"Crypto - Crypto (C-C)"},{"id":2,"dsc":"Crypto - Fiat Money (C-FM)"},
                        {"id":3,"dsc":"Fiat Money - Crypto (FM-C)"}];
    var first = sessionStorage.getItem('lang') == 'esp' ? "Selecciona" : 'Select'
    drawSelectN(document.getElementById("prefertypeop"),'id','dsc',prefertypeop[sessionStorage.getItem('lang')],"",first); 
    //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();
        });
    }

    //Se cargan los uploads correspondientes
    getUploads();

    //Ciclo que se repite hasta que se completan todas las cargas dando prioridad a las que son previas al entry
    wait = setInterval(function(){
        if(upLoad){               
            clearInterval(wait);        
            getEntry();
        }
    },1000);   

    //Actualizar información y avanzar al siguiente nivel
    document.getElementById("next-button").addEventListener("click",function(){
        updateSave("kyc","regConfirm","");
    });
    //Guardar y Salir al dashboard
    document.getElementById("later-button").addEventListener("click",function(){
        document.getElementsByClassName('completeLater')[0].style.display = 'table';
    });
    // Ir a pagina anterior
    document.getElementById('previous-button').addEventListener("click", function(){ 
        gotoPage("kyc","jurMiddleLvl","");
    });
    //Evento al hacer change en select multiple
    document.getElementById("prefertypeop").addEventListener("change", function(){
        addSpan(null)
    });
}
//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:
                drawEntry(rsp);//Se arma la variable global entry con la respuesta y se cargan las llamadas adicionales
                entry = rsp.entry;
                if (entry.company.preferoptype.id == null || entry.company.preferoptype.id == 0){
                    document.getElementById('prefertypeop').value = "";
                }else{
                    addSpan(entry.company.preferoptype.id);
                }
                entry = undefined;
            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);
    }
}
//Se carga el listado de uploads y se pintan donde corresponda
function getUploads(){    
    //Cargar listado de uploads    
    var parms = {
        "type":2,
        "sessionid": sessionStorage.getItem('sessionid')
    }
    //Funcion si tiene exito el request
    var uplsRsp = function(status, rsp){        
        var rsp = JSON.parse(rsp);
        switch(status){
            case 200:
                uploadsDraw(rsp.records,3); //Nivel Avancado 4
                upLoad = true;
                break;
            case 204:
                break;
            case 400:
                // Parametros incorrectos
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                // Error
                break;
            default:
                break;
        }
    }  
    uploadsLoad(parms,uplsRsp);
}

function updateSave(id,sid){    
    //Files
    var files = ["qtymonthlyop","amountmontlyop","prefertypeop"];  
    //Parms name   
    var parmsList = ["qtymonthlyop","amomonthlyop","prefertypeop","economicrel"];
    //Se agregan los uploads a validar
    var uplsCnt = document.getElementsByClassName("upldsCnt");
    var recaudos = uplsCnt[0].getElementsByTagName("input");
    var fuploads = [];
    for(var i=0; i<recaudos.length; i++){
        fuploads.push(recaudos[i].getAttribute("id"));
    }  
    if(verifyData(files) && verifyData(fuploads)){   
        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 415:
                    
                    errFile(document.getElementById("file"+JSON.parse(rsp).invalid),JSON.parse(rsp).msg);
                break;
                case 500:
                    // Error
                    break;
                default:
                
                    break;
            }
        } 
        //Se agregan los campos que no requieren verificación antes de enviar los parametros
        files.push("economicrelation");

        var parms = new FormData();
        //Session
        parms.append("sessionid",sessionStorage.getItem('sessionid'));
        //Parametros generales definidos en arreglos
        for(var i=0;i<files.length;i++){
            if(document.getElementById(files[i]).getAttribute("type")=="checkbox"){
                var val = 0;
                if(document.getElementById(files[i]).checked)val = 1;
                parms.append(parmsList[i],val);
            }else{                
                parms.append(parmsList[i],document.getElementById(files[i]).value);
            }
        }
        //Caso especial se corrige el getoprtype
        parms.append("prefertypeop",getPrefertypeop());
        //Uploads
        var uplsCnt = document.getElementsByClassName("upldsCnt");
        var recaudos = uplsCnt[0].getElementsByTagName("input");
        var docids = idsloaded;
        for(var i=0; i<recaudos.length; i++){
            if(recaudos[i].getAttribute("loaded") == 1){
                docids  += recaudos[i].getAttribute("label")+"-"; 
            }
            if(recaudos[i].value !== ""){    
                parms.append(recaudos[i].getAttribute("label"), recaudos[i].files[0]);
            }
        }
        docids = docids.slice(0,-1); // Controla si estoy editando, guardando o eliminando algun archivo
        parms.append("uploadids",docids);
        //Paso actual
        parms.append("step",7);
        updateCompany(parms,success);
    }else{
        if(!erroractive){   
            erroractive = true;
            setTimeout(function(){
                clearErrors(); // Se blanquean todos los errores            
                erroractive = false;
            },6000);
        }
    }
}


