WS_waitscreen = true;
var requiredLevelData = [];
var decimCoin = 2;
window.onload = function(){
    
    getEconomicActs()
    
    // Later
    document.getElementById('later-button').addEventListener("click", function(){
        document.getElementsByClassName('completeLater')[0].style.display = 'table'
    });
    
    document.getElementById('completeLaterAccept').addEventListener("click", function(){
        gotoPage('dashboard','home', { 'sessionid' : getParameterByName('sessionid') })
    });
    
    document.getElementById('completeLaterCancel').addEventListener("click", function(){
        document.getElementsByClassName('completeLater')[0].style.display = 'none'
    });
    
    // Go to Register Residence Data
    document.getElementById('previous-button').addEventListener("click", function(){
        gotoPage('register','regCompanyRes',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to Register Images
    document.getElementById('next-button').addEventListener("click", function(){
        //gotoPage('register','regPersonImg','');
        verifyData()
    });
    
    // Remove red errors 
    document.getElementsByTagName('body')[0].addEventListener("click", function(){
        if (document.getElementById('economic').value !== ''){
            noError('economic','eeconomic')
            document.getElementById('eeconomic').style.display = 'none'
        }
        if (document.getElementById('politician').value !== ''){
            noError('politician','epolitician')
            document.getElementById('epolitician').style.display = 'none'
        }
        if (document.getElementById('heritage').value !== '0.00'){
            noError('heritage','eheritage')
            document.getElementById('eheritage').style.display = 'none'
        }
        if (document.getElementById('income').value !== '0.00'){
            noError('income','eincome')
            document.getElementById('eincome').style.display = 'none'
        }
    }); 
    
    // Session Update
    document.getElementById('expSessionButton').addEventListener("click",function(){
        var req = {
            'sessionid': getParameterByName('sessionid')
        }
        sessionUpdate(req)
    })
    
    //Funcion en el main para dar formato a campos
    var fields = ["income", "heritage"];
    formatAmount(fields);
    /*
    var format = ["amount", "amount"];
    formatFields2(fields,format);*/
    
    
    //Mostrar HTML cargado
    esconderHTML(false);
}


function verifyData(){
    var economicact = document.getElementById('economic');
    var anualincome = document.getElementById('income');
    var patrimony = document.getElementById('heritage');
    var politicalexp = document.getElementById('politician');
    var req = {
        "sessionid" : getParameterByName('sessionid'),
        "economicact": economicact.value,
        "anualincome": anualincome.getAttribute("dataNumber"),
        "patrimony" : patrimony.getAttribute("dataNumber"),
        'politicalexp' : politicalexp.value,
        "step" : 4
    }
    if( (economicact.value=='' && requiredLevelData.includes(economicact.getAttribute('dataname'))) || (politicalexp.value=='' && requiredLevelData.includes(politicalexp.getAttribute('dataname'))) ||
        ((anualincome.value=='' || anualincome.value=='0.00') && requiredLevelData.includes(anualincome.getAttribute('dataname'))) || ((patrimony.value=='' || patrimony.value=='0.00') && requiredLevelData.includes(patrimony.getAttribute('dataname')))
    
    ){
        console.log(patrimony.value)
        console.log(requiredLevelData.includes(patrimony.getAttribute('dataname')))
        console.log(requiredLevelData)
        console.log(patrimony.getAttribute('dataname'))
        if (economicact.value=='' && requiredLevelData.includes(economicact.getAttribute('dataname'))){
            error('economic','eeconomic',getLangById("usersUpdatecompany1")[lang]);
            document.getElementById('eeconomic').style.display = 'block'
        }
        if (politicalexp.value=='' && requiredLevelData.includes(politicalexp.getAttribute('dataname'))){
            error('politician','epolitician',getLangById("usersUpdatecompany2")[lang]);
            document.getElementById('epolitician').style.display = 'block'
        }
        if ((patrimony.value=='' || patrimony.value=='0.00') && requiredLevelData.includes(patrimony.getAttribute('dataname'))){
            error('heritage','eheritage',getLangById("usersUpdatecompany3")[lang]);
            document.getElementById('eheritage').style.display = 'block'
        }
        if ((anualincome.value=='' || anualincome.value=='0.00') && requiredLevelData.includes(anualincome.getAttribute('dataname'))){
            error('income','eincome',getLangById("usersUpdatecompany3")[lang]);
            document.getElementById('eincome').style.display = 'block'
        }
        return;
    }else{
        updateCompany(req)
    }

    console.log(req)


}

function addOptions(domElement, array) {
    var selector = document.getElementsByName(domElement)[0];
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = lang == "esp" ? "Selecciona " : "Select"
    firstOopcion.value =''
    firstOopcion.selected = true
    selector.add(firstOopcion)
    for (countrie in array.records) {
        if (array.records[countrie].id > 0){
            var opcion = document.createElement("option");
            opcion.text = array.records[countrie].dsc;
            opcion.value = array.records[countrie].id
            selector.add(opcion);
        }
    }
    // First Time
    //getEntry(getParameterByName('sessionid'))
}

function updateCompany(req){
    callWS("POST", "users/updatecompany", req, response);
    console.log(req)
    console.log(status)
    function response(status, rsp){
        switch(status){
            case 200:
                // Ok
                gotoPage('register','regCompanyImg',{ 'sessionid' : getParameterByName('sessionid') })
                break;
            case 204:
                break;
            case 400:
                // Parametros incorrectos
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                // Error
                break;
            default:
                break;
        }
        console.log(status)
        console.log(rsp)
    }  
}
    
function getEntry(sessionid){
    console.log('entry')
    callWS("GET", "users/entry", { 'sessionid' : sessionid}, response);
        
    function response(status, rsp){
        switch(status){
            case 200:
                console.log(JSON.parse(rsp))
                requiredLevelData = JSON.parse(rsp).requiredLevel ? (JSON.parse(rsp).requiredLevel).split(',') : []
                levels = JSON.parse(rsp).entry.levels
                console.log(requiredLevelData)
                
                document.getElementById('economic').value = JSON.parse(rsp).entry.company.economicalactivity.value
                setStatus('economicIcon',JSON.parse(rsp).entry.company.economicalactivity,'economic')
                
                if(JSON.parse(rsp).entry.company.anualincome.number != 0){
                    var val = (Math.round((JSON.parse(rsp).entry.company.anualincome.number)*100)/100).toFixed(2)
                }else{
                    var val = ''
                }
                document.getElementById('income').value = val;//JSON.parse(rsp).entry.company.amooperationsmonthly.number
                document.getElementById('income').dispatchEvent(new Event("focusout"));
                if(document.getElementById('income').value == '0'){
                    document.getElementById('income').value = ''
                }
                setStatus('incomeIcon',JSON.parse(rsp).entry.company.anualincome,'income')
                
                if(JSON.parse(rsp).entry.company.patrimony.number != 0){
                    var val = (Math.round((JSON.parse(rsp).entry.company.patrimony.number)*100)/100).toFixed(2)
                }else{
                    var val = ''
                }
                document.getElementById('heritage').value = val;
                document.getElementById('heritage').dispatchEvent(new Event("focusout"));
                if(document.getElementById('heritage').value == '0'){
                    document.getElementById('heritage').value = ''
                }
                setStatus('heritageIcon',JSON.parse(rsp).entry.company.patrimony,'heritage')
                
                document.getElementsByClassName('pageCnt')[0].style.visibility="visible"
                if (JSON.parse(rsp).entry.company.politicalexposed.value == null){
                    document.getElementById('politician').value = ''
                }else{
                    document.getElementById('politician').value = JSON.parse(rsp).entry.company.politicalexposed.value;   
                }
                setStatus('politicianIcon',JSON.parse(rsp).entry.company.politicalexposed,'politician')
                
                setLevels(levels)
                
                // Window Load
                var waitScreen = document.getElementById("waitScreen");
                document.body.removeChild(waitScreen);
                WS_waitscreen = false;
                break;
            case 204:
                break;
            case 400:
                // Parametros incorrectos
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                // Error
                break;
            default:
                break;
        }
        //console.log(status)
        //console.log(rsp)
    }    
}

// name A: classIcon
// name B : BD
// nameC: nameInput
function setStatus(nameA,nameB,nameC){
    
    document.getElementById(nameC).setAttribute('dataname',nameB.update)
                
    if(nameB.valid == -1){
        document.getElementById(nameA).classList.add("iconRed")
        document.getElementById(nameA).classList.add("fas")
        document.getElementById(nameA).classList.add("fa-times-circle")
    }
    else if (nameB.valid == 0){
        document.getElementById(nameA).classList.add("iconYellow")
        document.getElementById(nameA).classList.add("fas")
        document.getElementById(nameA).classList.add("fa-pause-circle")
    }
    else if (nameB.valid == 1){
        document.getElementById(nameA).classList.add("iconGreen")
        document.getElementById(nameA).classList.add("fas")
        document.getElementById(nameA).classList.add("fa-check-circle")
        document.getElementById(nameC).disabled = true;
        document.getElementById(nameC).style.cursor = 'default'
        if(document.getElementById(nameC).tagName != 'SELECT'){
            document.getElementById(nameC).style.backgroundColor = 'white'
        }
    }
    document.getElementById(nameC).classList.add("inputElement")
}

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

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

function getEconomicActs(){
    
    var req = {
        "sessionid": getParameterByName('sessionid')
    }
        
    callWS("GET", "additional/economicacts", req, response);
        
    function response(status, rsp){
        switch(status){
            case 200:
                economic = JSON.parse(rsp);
                addOptions("economic", economic)
                setLang()
                break;
            case 204:
                break;
            case 400:
                // Parametros incorrectos
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                // Error
                break;
            default:
                break;
        }
    }    
}


function setLevels(levels){
    console.log(levels)
    levels1 = levels[1].basicRequired.split(',')
    levels2 = levels[2].basicRequired.split(',')
    levels3 = levels[3].basicRequired.split(',')
    console.log(document.getElementsByClassName('inputElement'))
    console.log(document.getElementsByClassName('inputElement').length)
    for(var i = 0; i < document.getElementsByClassName('inputElement').length ; i++){
        if(levels1.includes(document.getElementsByClassName('inputElement')[i].getAttribute('dataname'))){
            if(!document.getElementsByClassName('inputElement')[i].previousElementSibling.children[0]){
                document.getElementsByClassName('inputElement')[i].previousElementSibling.innerHTML += '<span style="font-size: 90%; color: #7D8B9E;" class="roboto-bold"> (1) </span>'   
            }
        }
        else if(levels2.includes(document.getElementsByClassName('inputElement')[i].getAttribute('dataname'))){
            if(!document.getElementsByClassName('inputElement')[i].previousElementSibling.children[0]){
                document.getElementsByClassName('inputElement')[i].previousElementSibling.innerHTML += '<span style="font-size: 90%; color: #4287CE;" class="roboto-bold"> (2) </span>'   
            }
        }
        else if(levels3.includes(document.getElementsByClassName('inputElement')[i].getAttribute('dataname'))){
            if(!document.getElementsByClassName('inputElement')[i].previousElementSibling.children[0]){
                document.getElementsByClassName('inputElement')[i].previousElementSibling.innerHTML += '<span style="font-size: 90%; color: rgb(1, 42, 63);" class="roboto-bold"> (3) </span>'
            }
        }
    }
}
function setLang(){
    
    lang = localStorage.getItem('lang');
    
    /* inner HTML */
    setWordLanginnerHTML('regcompany1','regcompany1');
    setWordLanginnerHTML('regcompany2','regcompany2');
    setWordLanginnerHTML('regcompany3','regcompany3');
    setWordLanginnerHTML('regcompany4','regcompany4');
    setWordLanginnerHTML('regcompany5','regcompany5');
    setWordLanginnerHTML('regcompany6','regcompany6');
    setWordLanginnerHTML('regcompany7','regcompany7');
    setWordLanginnerHTML('regTitle','regcompany4');
    setWordLanginnerHTML('economicActivityLabel','economicActivity');
    setWordLanginnerHTML('politicianLabel','politicallyExposedPerson');
    setWordLanginnerHTML('politicianSelectSel','select');
    setWordLanginnerHTML('yes','yes');
    setWordLanginnerHTML('no','no');
    setWordLanginnerHTML('incomeLabel','annualIncome');
    setWordLanginnerHTML('herigateLabel','heritage');
    setWordLanginnerHTML('requiredLevel1','requiredLevel1');
    setWordLanginnerHTML('requiredLevel2','requiredLevel2');
    setWordLanginnerHTML('requiredLevel3','requiredLevel3');
    setWordLanginnerHTML('previous-button','goBack');
    setWordLanginnerHTML('later-button','completeThen');
    setWordLanginnerHTML('next-button','continue');
    setWordLanginnerHTML('ts','ts');
    setWordLanginnerHTML('completeLater','completeLater');
    setWordLanginnerHTML('completeLaterAccept','completeThen');
    setWordLanginnerHTML('completeLaterCancel','cancel');
    setWordLanginnerHTML('expired1','expired1');
    setWordLanginnerHTML('expired2','expired2');
    setWordLanginnerHTML('expSessionButton','continue');
    
    /*Placeholder*/
    /*setWordLangPlaceHolder('numberIdAlt','numberId');
    setWordLangPlaceHolder('socialReason','businessName');
    setWordLangPlaceHolder('comercialNameAlt','comercialName');
    setWordLangPlaceHolder('postalCode','postalCode');
    setWordLangPlaceHolder('phone','exmpleNumber');
    setWordLangPlaceHolder('web','websiteEx');*/
    
    /* Select */
    /*setWordLanginnerHTML('selectVenezuelan','select');
    setWordLanginnerHTML('selectVenezuelanYes','yes');
    setWordLanginnerHTML('selectVenezuelanNo','no');
    setWordLanginnerHTML('selectType','select');
    setWordLanginnerHTML('selectType1','selectType1');
    setWordLanginnerHTML('selectType2','selectType2');
    setWordLanginnerHTML('selectType3','selectType3');*/
    
    getEntry(getParameterByName('sessionid'));

}
