WS_waitscreen = true;
var requiredLevelData = [];

window.onload = function(){
    
    // Call Entry
    getCountries()
    // Go to back to Basic Data
    document.getElementById('previous-button').addEventListener("click", function(){
        gotoPage('register','regCompanyPartner',{ 'sessionid' : getParameterByName('sessionid') }) 
    });
    
    // 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 Profesional Information
    document.getElementById('next-button').addEventListener("click", function(){
        //gotoPage('register','regPersonInf',{ 'sessionid' : getParameterByName('sessionid') })
        verifyData()
    });

    
    // Change values where
    document.getElementById('country').addEventListener("change", function(){
        if (idCountry != document.getElementById('country').value){
            idCountry = document.getElementById('country').value
            getRegions('','')
            removeOptions('city')
            var selector = document.getElementsByName('city')[0];
            var firstOopcion = document.createElement("option");
            firstOopcion.disabled = true;
            firstOopcion.text = lang == "esp" ? 'Selecciona' : 'Select'
            firstOopcion.value =''
            firstOopcion.selected = true
            selector.add(firstOopcion)
        }
    });
    document.getElementById('state').addEventListener("change", function(){
        console.log('cambio')
        if (idState != document.getElementById('state').value){
            idState = document.getElementById('country').value
            getCities('','')
        }
    });
    
    // Remove red errors 
    document.getElementsByTagName('body')[0].addEventListener("click", function(){
        if (document.getElementById('country').value !== ''){
            noError('country','ecountry')
            document.getElementById('ecountry').style.display = 'none'
        }
        if (document.getElementById('state').value !== ''){
            noError('state','estate')
            document.getElementById('estate').style.display = 'none'
        }
        if (document.getElementById('city').value !== ''){
            noError('city','ecity')
            document.getElementById('ecity').style.display = 'none'
        }
        if (document.getElementById('street').value !== ''){
            noError('street','estreet')
            document.getElementById('estreet').style.display = 'none'
        }
        if (document.getElementById('branch').value !== ''){
            noError('branch','ebranch')
            document.getElementById('ebranch').style.display = 'none'
        }
        if (document.getElementById('house').value !== ''){
            noError('house','ehouse')
            document.getElementById('ehouse').style.display = 'none'
        }
    }); 
    
    // Session Update
    document.getElementById('expSessionButton').addEventListener("click",function(){
        var req = {
            'sessionid': getParameterByName('sessionid')
        }
        sessionUpdate(req)
    })
    
    //Mostrar HTML cargado
    esconderHTML(false);
}

var idCountry = '';
var idState = '';
var idCity = '';
var firstLoad = true;

function addOptions(domElement, array,bool) {
    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);
        }
    }
    console.log(firstLoad)
    
    setTimeout(function(){ 
        
        if(firstLoad){
         console.log('entro')
        setTimeout(function(){ 
        
            if(entrydata.company.document.country.id == 0 || entrydata.company.document.country.id == null){
                setTimeout(function(){ firstOopcion.selected = true }, 500);
            }else{
                //document.getElementById('country').value = entrydata.company.country.id
            }
            if(entrydata.company.document.region.id == 0 || entrydata.company.document.region.id == null){
                setTimeout(function(){ firstOopcion.selected = true }, 1000);
            }else{
                //document.getElementById('state').value = entrydata.company.region.id
            }
      
        }, 1500);   
        firstLoad = false;
        if (bool == true && domElement == 'country'){
            setLang()
        }
     }    
        

    }, 500);

}

function getCountries(){
    var req = {
        "sessionid": getParameterByName('sessionid')
    }
        
    callWS("GET", "demographics/countries", req, response);
        
    function response(status, rsp){
        switch(status){
            case 200:
                countries = JSON.parse(rsp);
                console.log('getcountry')
                addOptions("country", countries,true)
                break;
            case 204:
                break;
            case 400:
                // Parametros incorrectos
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                // Error
                break;
            default:
                break;
        }
    }    
}

function getRegions(selR,selC){
    removeOptions('state')
    var req = {
        "sessionid": getParameterByName('sessionid'),
        "countryid": document.getElementsByName('country')[0].value
    }
     if ( req.countryid != ''){
        callWS("GET", "demographics/regions", req, response);
        function response(status, rsp){
            switch(status){
                case 200:
                    states = JSON.parse(rsp);
                    addOptions("state", states,false);
                    if(selR!=''){
                        setTimeout(function(){ document.getElementById('state').value = selR}, 500);
                        if(selC!=''){
                            setTimeout(function(){ getCities(selR,selC)}, 500);
                        }
                    }
                    break;
                case 204:
                    break;
                case 400:
                    // Parametros incorrectos
                    break;
                case 401:
                    expiredSession();
                    break;
                case 500:
                    // Error
                    break;
                default:
                    break;
            }
        }     
    }
        
}

function removeOptions(selectElement) {
    x = document.getElementById(selectElement)
    var i, L = x.options.length - 1;
    for(i = L; i >= 0; i--) {
       x.remove(i);
    }
}

function getCities(selR,selC){
    removeOptions('city')
    var req = {
        "sessionid": getParameterByName('sessionid'),
        "regionid": document.getElementsByName('state')[0].value
    }
     if ( req.regionid != ''){
        callWS("GET", "demographics/cities", req, response);
        function response(status, rsp){
            switch(status){
                case 200:
                    cities = JSON.parse(rsp);
                    addOptions("city", cities,false)
                    if(selC!=''){
                        setTimeout(function(){ document.getElementById('city').value = selC}, 500);
                    }
                    break;
                case 204:
                    break;
                case 400:
                    // Parametros incorrectos
                    break;
                case 401:
                    expiredSession();
                    break;
                case 500:
                    // Error
                    break;
                default:
                    break;
            }
        }     
    }
        
}




function verifyData(){
    var countryid = document.getElementById('country');
    var stateid = document.getElementById('state');
    var cityid = document.getElementById('city');
    var street = document.getElementById('street');
    var domicile = document.getElementById('house');
    var branchoffices = document.getElementById('branch');
    var req = {
        "sessionid" : getParameterByName('sessionid'),
        "countryid" : countryid.value,
        "stateid": stateid.value,
        "cityid" : cityid. value,
        "street": capitalize(street.value),
        "domicile" : capitalize(domicile.value),
        "branchoffices" : branchoffices.value,
        "step" : 3
    }


    if( (countryid.value=='' && requiredLevelData.includes(countryid.getAttribute('dataname'))) ||
        (stateid.value=='' && requiredLevelData.includes(stateid.getAttribute('dataname'))) ||
        (cityid.value=='' && requiredLevelData.includes(cityid.getAttribute('dataname'))) ||
        (street.value=='' && requiredLevelData.includes(street.getAttribute('dataname'))) ||
        (branchoffices.value=='' && requiredLevelData.includes(branchoffices.getAttribute('dataname'))) ||
        (domicile.value=='' && requiredLevelData.includes(domicile.getAttribute('dataname')))
    ){
         console.log('asdadsadasdasd')
        if (countryid.value=='' && requiredLevelData.includes(countryid.getAttribute('dataname'))){
            error('country','ecountry',getLangById("usersUpdatecompany1")[lang]);
            document.getElementById('ecountry').style.display = 'block'
        }
        if (stateid.value=='' && requiredLevelData.includes(stateid.getAttribute('dataname'))){
            error('state','estate',getLangById("usersUpdatecompany2")[lang]);
            document.getElementById('estate').style.display = 'block'
        }
        if (cityid.value=='' && requiredLevelData.includes(cityid.getAttribute('dataname'))){
            error('city','ecity',getLangById("usersUpdatecompany3")[lang]);
            document.getElementById('ecity').style.display = 'block'
        }
        if (street.value=='' && requiredLevelData.includes(street.getAttribute('dataname'))){
            error('street','estreet',getLangById("usersUpdatecompany4")[lang]);
            document.getElementById('estreet').style.display = 'block'
        }
        if (branchoffices.value=='' && requiredLevelData.includes(branchoffices.getAttribute('dataname'))){
            error('branch','ebranch',getLangById("usersUpdatecompany5")[lang]);
            document.getElementById('ebranch').style.display = 'block'
        }
        if (domicile.value=='' && requiredLevelData.includes(domicile.getAttribute('dataname'))){
            error('house','ehouse',getLangById("usersUpdatecompany6")[lang]);
            document.getElementById('ehouse').style.display = 'block'
        }
        
        return;
        
    }else{
        updateCompany(req)    
    }


}

function updateCompany(req){
    callWS("POST", "users/updatecompany", req, response);
    console.log(req)
    function response(status, rsp){
        console.log(status)
        console.log(rsp)
        switch(status){
            case 200:
                // Ok
                console.log('ok')
                console.log(req)
                gotoPage('register','regCompanyInf',{ 'sessionid' : getParameterByName('sessionid') })
                break;
            case 204:
                break;
            case 400:
                // Parametros incorrectos
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                // Error
                break;
            default:
                break;
        }
    }  
}

var entrydata;
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))
                entrydata = JSON.parse(rsp).entry
                requiredLevelData = JSON.parse(rsp).requiredLevel ? (JSON.parse(rsp).requiredLevel).split(',') : []
                levels = JSON.parse(rsp).entry.levels
                console.log(requiredLevelData)
                
                document.getElementById('country').value = JSON.parse(rsp).entry.company.country.id;
                setStatus('countryIcon',JSON.parse(rsp).entry.company.country,'country')
                
                document.getElementById('state').value = JSON.parse(rsp).entry.company.region.id
                setStatus('stateIcon',JSON.parse(rsp).entry.company.region,'state')
                
                document.getElementById('city').value = JSON.parse(rsp).entry.company.city.id
                setStatus('cityIcon',JSON.parse(rsp).entry.company.city,'city')
                
                document.getElementById('street').value = JSON.parse(rsp).entry.company.street.value
                setStatus('streetIcon',JSON.parse(rsp).entry.company.street,'street')
                
                document.getElementById('house').value = JSON.parse(rsp).entry.company.home.value
                setStatus('houseIcon',JSON.parse(rsp).entry.company.home,'house')
                
                if( JSON.parse(rsp).entry.company.branchoffices.value == null){
                    document.getElementById('branch').value = ""
                }else{
                    document.getElementById('branch').value = JSON.parse(rsp).entry.company.branchoffices.value
                }
                setStatus('branchIcon',JSON.parse(rsp).entry.company.branchoffices,'branch')
                
                if (entrydata.company.step != 2){
                    firstLoad = false;
                    if(JSON.parse(rsp).entry.company.region.id!='' ){
                        getRegions(JSON.parse(rsp).entry.company.region.id,JSON.parse(rsp).entry.company.city.id)
                    }   
                }
                
                if (entrydata.company.step == 2){
                    document.getElementById('country').value = JSON.parse(rsp).entry.company.document.country.id;
                    document.getElementById('state').value = JSON.parse(rsp).entry.company.document.region.id
                    document.getElementById('city').value = JSON.parse(rsp).entry.company.document.city.id
                    if(JSON.parse(rsp).entry.company.document.region.id!='' ){
                        getRegions(JSON.parse(rsp).entry.company.document.region.id,JSON.parse(rsp).entry.company.document.city.id)
                    }
                }
                
                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'
        }
    }
    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','regcompany3');
    setWordLanginnerHTML('countryOfResidenceLabel','countryOfResidence');
    setWordLanginnerHTML('stateLabel','state');
    setWordLanginnerHTML('cityLabel','city');
    setWordLanginnerHTML('addressLabel','address');
    setWordLanginnerHTML('houseLabel','house');
    setWordLanginnerHTML('branchLabel','branchOffices');
    setWordLanginnerHTML('branchSelectSel','select');
    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('street','addressEx');
    setWordLangPlaceHolder('house','house');
    
    getEntry(getParameterByName('sessionid'));

}

