WS_waitscreen = true;
var requiredLevelData = [];

window.onload = function(){
    
    // Go to Register Images
    document.getElementById('previous-button').addEventListener("click", function(){
        gotoPage('register','regCompanyImg',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to Register Statement
    document.getElementById('next-button').addEventListener("click", function(){
        //gotoPage('register','regPersonStatement',{ 'sessionid' : getParameterByName('sessionid') })
        verifyData();
    });
    
    //Funcion en el main para dar formato a campos
    var fields = ["amount","average"];
    var format = ["amount","amount"];
    formatFields2(fields,format);
    
    // 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'
    });
    
    // 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){
            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 != 'null'){
            noError('relationship','erelationship')
            document.getElementById('erelationship').style.display = 'none'
        }
    });
    
    //Mostrar HTML cargado
    esconderHTML(false);
    
    document.getElementById("type").addEventListener("change", function(){
        addSpan(null)
    });
    
    setLang()
    
}

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 economicrel = document.getElementById('relationship');
    var req = {
        "sessionid" : getParameterByName('sessionid'),
        "qtymonthlyop" : qtymonthlyop.value,
        "prefertypeop": prefertypeop,
        "amomonthlyop" : amomonthlyop.value,
        "economicrel": economicrel.value,
        "step" : 6
    }
    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'))) ||
        (economicrel.value=='' && requiredLevelData.includes(economicrel.getAttribute('dataname')))
      ){
        if (qtymonthlyop.value=='0' && requiredLevelData.includes(qtymonthlyop.getAttribute('dataname'))){
            error('average','eaverage',getLangById('usersUpdateperson1')[lang]);
            document.getElementById('eaverage').style.display = 'block'
        }
        if (prefertypeop=='' && requiredLevelData.includes(document.getElementById('type').getAttribute('dataname'))){
            error('amount','eamount',getLangById('usersUpdateperson1')[lang]);
            document.getElementById('eamount').style.display = 'block'
        }
        if (amomonthlyop.value=='0' && requiredLevelData.includes(amomonthlyop.getAttribute('dataname'))){
            error('type','etype',getLangById('usersUpdateperson1')[lang]);
            document.getElementById('etype').style.display = 'block'
        }
        if (economicrel.value=='null' && requiredLevelData.includes(economicrel.getAttribute('dataname'))){
            error('relationship','erelationship',getLangById('usersUpdateperson1')[lang]);
            document.getElementById('erelationship').style.display = 'block'
        }
        return;
     }else{
         updateCompany(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 updateCompany(req){
    console.log(req)
    callWS("POST", "users/updatecompany", req, response);
    
    console.log(status)
    console.log(req)
    function response(status, rsp){
        switch(status){
            case 200:
                console.log(req)
                gotoPage('register','regCompanyStatement',{ '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){
        console.log(JSON.parse(rsp).entry)
        switch(status){
            case 200:
                requiredLevelData = JSON.parse(rsp).requiredLevel ? (JSON.parse(rsp).requiredLevel).split(',') : []
                levels = JSON.parse(rsp).entry.levels
                //var val = (Math.round((JSON.parse(rsp).entry.company.qtyoperationsmothly)*100)/100).toFixed(2);
                document.getElementById('average').value = (JSON.parse(rsp).entry.company.qtyoperationsmothly.value==null) ? "" : JSON.parse(rsp).entry.company.qtyoperationsmothly.value  //JSON.parse(rsp).entry.company.amooperationsmonthly.number
                setStatus('averageIcon',JSON.parse(rsp).entry.company.qtyoperationsmothly,'average')
                document.getElementById('average').setAttribute('dataname',JSON.parse(rsp).entry.company.qtyoperationsmothly.update)
                console.log(document.getElementById('average').value)
                //document.getElementById('average').dispatchEvent(new Event("keyup"));
                //var val = (Math.round((JSON.parse(rsp).entry.company.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('amount').value = (JSON.parse(rsp).entry.company.amooperationsmonthly.number == null) ? "" : JSON.parse(rsp).entry.company.amooperationsmonthly.number
                setStatus('amountIcon',JSON.parse(rsp).entry.company.amooperationsmonthly,'amount')
                document.getElementById('amount').setAttribute('dataname',JSON.parse(rsp).entry.company.amooperationsmonthly.update)
                
                document.getElementById('averageIcon').parentNode.style.top = document.getElementById('amountpa').clientHeight + 7 + 'px'
                
                document.getElementById("type").value = 0;
                 
                if (JSON.parse(rsp).entry.company.preferoptype.id == null || JSON.parse(rsp).entry.company.preferoptype.id == 0){
                    document.getElementById('type').value = 0
                }else{
                    addSpan(JSON.parse(rsp).entry.company.preferoptype.id)  
                }
                setStatus('typeIcon',JSON.parse(rsp).entry.company.preferoptype,'type')
                document.getElementById('type').setAttribute('dataname',JSON.parse(rsp).entry.company.preferoptype.update)
    
                if(JSON.parse(rsp).entry.company.economicrelation.udpated){
                    document.getElementById('relationship').value = JSON.parse(rsp).entry.company.economicrelation.value
                    setStatus('relationshipIcon',JSON.parse(rsp).entry.company.economicrelation,'relationship')
                    document.getElementById('relationship').setAttribute('dataname',JSON.parse(rsp).entry.company.economicrelation.udpated)   
                }else{
                    document.getElementById('relationship').value = JSON.parse(rsp).entry.company.economicrelation.value
                    setStatus('relationshipIcon',JSON.parse(rsp).entry.company.economicrelation,'relationship')
                    document.getElementById('relationship').setAttribute('dataname',JSON.parse(rsp).entry.company.economicrelation.update)   
                }
                
                setLevels(levels)
                
                document.getElementsByClassName('pageCnt')[0].style.visibility="visible"
                // 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'
        }
        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 += ', '
                }
            }
        }
    }
    if(nameC != 'type'){
        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].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','regcompany6');
    setWordLanginnerHTML('amountpa','averageLabel');
    setWordLanginnerHTML('amountLabel','amountLabel');
    setWordLanginnerHTML('typeLabel','typeLabel');
    setWordLanginnerHTML('relationshipLabel','relationshipLabel');
    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');
    
    /* Select */
    setWordLanginnerHTML('averageSelect','select');
    setWordLanginnerHTML('average1','average1');
    setWordLanginnerHTML('average2','average2');
    setWordLanginnerHTML('average3','average3');
    setWordLanginnerHTML('average4','average4');
    setWordLanginnerHTML('amountSelect','select');
    setWordLanginnerHTML('amount1','amount1');
    setWordLanginnerHTML('amount2','amount2');
    setWordLanginnerHTML('amount3','amount3');
    setWordLanginnerHTML('amount4','amount4');
    setWordLanginnerHTML('typeSelect','select');
    setWordLanginnerHTML('type1','type1');
    setWordLanginnerHTML('type2','type2');
    setWordLanginnerHTML('type3','type3');
    setWordLanginnerHTML('relationshipSelect','select');
    setWordLanginnerHTML('yes','yes');
    setWordLanginnerHTML('no','no');
    
    getEntry(getParameterByName('sessionid'));

}

    

