WS_waitscreen = true;
var requiredLevelData = [];

window.onload = function(){
    
    // Call Entry
    getEntry(getParameterByName('sessionid'))
    
    // Go to Register Images
    document.getElementById('previous-button').addEventListener("click", function(){
        gotoPage('register','regPersonImg',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to Register Statement
    document.getElementById('next-button').addEventListener("click", function(){
        //gotoPage('register','regPersonStatement',{ 'sessionid' : getParameterByName('sessionid') })
        verifyData();
    });
    
    // 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'
    });
    
    //Funcion en el main para dar formato a campos
    var fields = ["amount","average"];
    var format = ["amount","amount"];
    formatFields2(fields,format);
    
    //Mostrar HTML cargado
    esconderHTML(false);
    
    // Session Update
    document.getElementById('expSessionButton').addEventListener("click",function(){
        var req = {
            'sessionid': getParameterByName('sessionid')
        }
        sessionUpdate(req)
    })
    
    // Remove red errors 
    document.getElementsByTagName('body')[0].addEventListener("click", function(){
        if (document.getElementById('average').value != 0){
            console.log('clean red error')
            noError('average','eaverage')
            document.getElementById('eaverage').style.display = 'none'
        }
        if (document.getElementById('amount').value != 0){
            noError('amount','eamount')
            document.getElementById('eamount').style.display = 'none'
        }
        if (document.getElementById('type').value != 0){
            noError('type','etype')
            document.getElementById('etype').style.display = 'none'
        }
        if (document.getElementById('relationship').value !== ''){
            noError('relationship','erelationship')
            document.getElementById('erelationship').style.display = 'none'
        }
    });
    
    
    
    document.getElementById("type").addEventListener("change", function(){
        addSpan(null)
    });
    
    
    
    
}

function addSpan(string){
    var curren = document.getElementById("type");
    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("type");
    curren.value = idSpan;
    var idx = curren.selectedIndex;
    console.log(idx)
    curren.options[idx].disabled = false;
    var parent = document.getElementById("selectGruop");
    var spanParent = document.getElementById(idSpan);
    parent.removeChild(spanParent);
    curren.value = "";
}


function verifyData(){
    var qtymonthlyop = document.getElementById('average');
    var prefertypeop = getPrefertypeop();
    var amomonthlyop = document.getElementById('amount');
    var economicrelation = document.getElementById('relationship');

        var req = {
            "sessionid" : getParameterByName('sessionid'),
            "qtymonthlyop" : qtymonthlyop.value,
            //"qtymonthlyop" : '0',
            "prefertypeop": prefertypeop,
            "amomonthlyop" : amomonthlyop.value,
            //"amomonthlyop" : '0',
            "economicrel": economicrelation.value,
            "step" : 5
        }
    console.log(req)
    
    if( (qtymonthlyop.value=='0' && requiredLevelData.includes(qtymonthlyop.getAttribute('dataname'))) || 
        (prefertypeop=='' && requiredLevelData.includes(document.getElementById('type').getAttribute('dataname'))) || 
        (amomonthlyop.value=='0' && requiredLevelData.includes(amomonthlyop.getAttribute('dataname'))) ||
        (economicrelation.value=='' && requiredLevelData.includes(economicrelation.getAttribute('dataname')))
      ){
        if (qtymonthlyop.value=='0' && requiredLevelData.includes(qtymonthlyop.getAttribute('dataname'))){
            error('average','eaverage','Seleccione una opción.');
            document.getElementById('eaverage').style.display = 'block'
        }
        if (prefertypeop=='' && requiredLevelData.includes(document.getElementById('type').getAttribute('dataname'))){
            error('type','etype','Seleccione una opción.');
            document.getElementById('etype').style.display = 'block'
        }
        if (amomonthlyop.value=='0' && requiredLevelData.includes(amomonthlyop.getAttribute('dataname'))){
            error('amount','eamount','Seleccione una opción.');
            document.getElementById('eamount').style.display = 'block'
        }
        if (economicrelation.value=='' && requiredLevelData.includes(economicrelation.getAttribute('dataname'))){
            error('relationship','erelationship','Seleccione una opción.');
            document.getElementById('erelationship').style.display = 'block'
        }
        return;
     }else{
         updatePerson(req) 
     }

}

function getPrefertypeop(){
    var selectGruop = document.getElementById('selectGruop')
    var array = [];
    for(var i = 0; i < selectGruop.children.length; i ++){
        console.log(selectGruop.children[i].id)
        array.push(selectGruop.children[i].id)
    }
    return array.join('-')
}

function updatePerson(req){
    console.log(req)
    callWS("POST", "users/updateperson", req, response);
    console.log(status)
    function response(status, rsp){
        switch(status){
            case 200:
                // Ok
                gotoPage('register','regPersonStatement',{ '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).entry)
                requiredLevelData = JSON.parse(rsp).requiredLevel ? (JSON.parse(rsp).requiredLevel).split(',') : []
                levels = JSON.parse(rsp).entry.levels
                //var val = (Math.round((JSON.parse(rsp).entry.person.qtyoperationsmothly)*100)/100).toFixed(2);
                //console.log(val)
                //document.getElementById('average').value = val;//JSON.parse(rsp).entry.company.amooperationsmonthly.number
                //document.getElementById('average').dispatchEvent(new Event("keyup"));
                document.getElementById('average').value = (JSON.parse(rsp).entry.person.qtyoperationsmothly.value == null) ? "" : JSON.parse(rsp).entry.person.qtyoperationsmothly.value
                setStatus('averageIcon',JSON.parse(rsp).entry.person.qtyoperationsmothly,'average')
                document.getElementById('average').setAttribute('dataname',JSON.parse(rsp).entry.person.qtyoperationsmothly.update)
                /*
                if(JSON.parse(rsp).entry.person.qtyoperationsmothly == 0){
                    document.getElementById('average').value = JSON.parse(rsp).entry.person.qtyoperationsmothly
                }
                else if(JSON.parse(rsp).entry.person.qtyoperationsmothly == 1){
                    document.getElementById('average').value = "1 a 10"
                }
                else if(JSON.parse(rsp).entry.person.qtyoperationsmothly == 10){
                    document.getElementById('average').value = "10 a 100"
                }
                else if(JSON.parse(rsp).entry.person.qtyoperationsmothly == 100){
                    document.getElementById('average').value = "100 a 1000"
                }
                else if(JSON.parse(rsp).entry.person.qtyoperationsmothly == 'Mas de 1000'){
                    document.getElementById('average').value = "Mas de 1000"
                }*/
                
                //var val = (Math.round((JSON.parse(rsp).entry.person.amooperationsmonthly.number)*100)/100).toFixed(2);
                //document.getElementById('amount').value = val;//JSON.parse(rsp).entry.company.amooperationsmonthly.number
                //document.getElementById('amount').dispatchEvent(new Event("keyup"));
                
                
                
                document.getElementById("type").value = 0;
                console.log(document.getElementById("type").selectedIndex)
                
                
                document.getElementById('amount').value = (JSON.parse(rsp).entry.person.amooperationsmonthly.number == null) ? "" : JSON.parse(rsp).entry.person.amooperationsmonthly.number
                
                setStatus('amountIcon',JSON.parse(rsp).entry.person.amooperationsmonthly,'amount')
                document.getElementById('amount').setAttribute('dataname',JSON.parse(rsp).entry.person.amooperationsmonthly.update)
                
                //document.getElementById('type').value = JSON.parse(rsp).entry.person.preferoptype.id;   
                if (JSON.parse(rsp).entry.person.preferoptype.id == null || JSON.parse(rsp).entry.person.preferoptype.id == 0){
                    document.getElementById('type').value = 0
                }else{
                    addSpan(JSON.parse(rsp).entry.person.preferoptype.id)  
                }
                setStatus('typeIcon',JSON.parse(rsp).entry.person.preferoptype,'type')
                document.getElementById('type').setAttribute('dataname',JSON.parse(rsp).entry.person.preferoptype.update)
                
                if (JSON.parse(rsp).entry.person.economicrelation.value == null){
                    document.getElementById('relationship').value = ''
                }else{
                    document.getElementById('relationship').value = JSON.parse(rsp).entry.person.economicrelation.value;   
                }
                setStatus('relationshipIcon',JSON.parse(rsp).entry.person.economicrelation,'relationship')
                document.getElementById('relationship').setAttribute('dataname',JSON.parse(rsp).entry.person.economicrelation.update)
                
                document.getElementsByClassName('pageCnt')[0].style.visibility="visible"
                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;
        }
    }    
}

// name A: classIcon
// name B : BD
// nameC: nameInput
function setStatus(nameA,nameB,nameC){
    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){
        console.log('entro',nameC)
        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'
        }
        if(nameA == 'typeIcon'){
            var selectGruop = document.getElementById('selectGruop')
            for(var i = 0; i < selectGruop.children.length; i ++){
                dad = selectGruop.children[i]
                children = selectGruop.children[i].children[0]
                dad.removeChild(children);
                if(i != selectGruop.children.length -1){
                    dad.innerHTML += ', '
                }
            }
        }
    }
    
    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 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].getAttribute('dataname')!='prefertypeop'){
                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>'
                }
            }   
        }
    }
}

    
