WS_waitscreen = true;
var requiredLevelData = [];

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

    
    // 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 = 'Selecciona'
            firstOopcion.value =''
            firstOopcion.selected = true
            selector.add(firstOopcion)
        }
    });
    document.getElementById('state').addEventListener("change", function(){
        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('postalCode').value !== ''){
            noError('postalCode','epostalCode')
            document.getElementById('epostalCode').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 = ''

function addOptions(domElement, array, bool) {
    var selector = document.getElementsByName(domElement)[0];
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = 'Selecciona'
    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
    if(bool == true && domElement == "country"){
        getEntry(getParameterByName('sessionid'))
    }
}

function getCountries(bool){
    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,bool)
                //getEntry(getParameterByName('sessionid'))
                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);
                        }
                    }
                    //Timeout 500
                    //sel esta es la seleccionada setear
                    //getEntry(getParameterByName('sessionid'))
                    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 postalcode = document.getElementById('postalCode');
    var req = {
        "sessionid" : getParameterByName('sessionid'),
        "step" : 2
    }
    if(countryid.value){
        req.countryid = countryid.value
    }
    if(stateid.value){
        req.stateid = stateid.value
    }
    if(cityid.value){
        req.cityid = cityid.value
    }
    if(street.value){
        req.street = street.value
    }
    if(domicile.value){
        req.domicile = domicile.value
    }
    if(postalcode.value){
        req.postalcode = postalcode.value
    }
    
     /*"countryid" : countryid.value,
        "stateid": stateid.value,
        "cityid" : cityid. value,
        "street": capitalize(street.value),
        "domicile" : capitalize(domicile. value),
        "postalcode": postalcode.value,
        "step" : 2*/

    
    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'))) || 
        (postalcode.value=='' && requiredLevelData.includes(postalcode.getAttribute('dataname'))) || 
        (domicile.value=='' && requiredLevelData.includes(domicile.getAttribute('dataname')))) {
         
        if (countryid.value=='' && requiredLevelData.includes(countryid.getAttribute('dataname'))){
            error('country','ecountry','Seleccione un pais.');
            document.getElementById('ecountry').style.display = 'block'
        }
        if (stateid.value=='' && requiredLevelData.includes(stateid.getAttribute('dataname'))){
            error('state','estate','Seleccione un estado.');
            document.getElementById('estate').style.display = 'block'
        }
        if (cityid.value=='' && requiredLevelData.includes(cityid.getAttribute('dataname'))){
            error('city','ecity','Seleccione una ciudad.');
            document.getElementById('ecity').style.display = 'block'
        }
        if (street.value=='' && requiredLevelData.includes(street.getAttribute('dataname'))){
            error('street','estreet','Introduzca una dirección.');
            document.getElementById('estreet').style.display = 'block'
        }
        if (postalcode.value=='' && requiredLevelData.includes(postalcode.getAttribute('dataname'))){
            error('postalCode','epostalCode','Introduzca un código postal.');
            document.getElementById('epostalCode').style.display = 'block'
        }
        if (domicile.value=='' && requiredLevelData.includes(domicile.getAttribute('dataname'))){
            error('house','ehouse','Introduzca una Casa / Apt Nro.');
            document.getElementById('ehouse').style.display = 'block'
        }
        
        return;
        
    }else{
        updatePerson(req)    
    }


}

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

function getEntry(sessionid){
    console.log('entry')
    callWS("GET", "users/entry", { 'sessionid' : sessionid}, response);
        
    function response(status, rsp){
        switch(status){
            case 200:
                requiredLevelData = JSON.parse(rsp).requiredLevel ? (JSON.parse(rsp).requiredLevel).split(',') : []
                levels = JSON.parse(rsp).entry.levels
                
                console.log(requiredLevelData)
                
                if(  JSON.parse(rsp).entry.person.country.id == null){
                    document.getElementById('country').value = ''
                }else{
                    document.getElementById('country').value = JSON.parse(rsp).entry.person.country.id;
                }
                setStatus('countryIcon',JSON.parse(rsp).entry.person.country,'country')
                document.getElementById('country').setAttribute('dataname',JSON.parse(rsp).entry.person.country.update)
                
                if(JSON.parse(rsp).entry.person.region.id == null){
                    document.getElementById('state').value = ''
                }else{
                    document.getElementById('state').value = JSON.parse(rsp).entry.person.region.id
                }
                setStatus('stateIcon',JSON.parse(rsp).entry.person.region,'state')
                document.getElementById('state').setAttribute('dataname',JSON.parse(rsp).entry.person.region.update)
                
                if(JSON.parse(rsp).entry.person.city.id == null){
                    document.getElementById('city').value = ''
                }else{
                    document.getElementById('city').value = JSON.parse(rsp).entry.person.city.id
                }
                setStatus('cityIcon',JSON.parse(rsp).entry.person.city,'city')
                document.getElementById('city').setAttribute('dataname',JSON.parse(rsp).entry.person.city.update)
                
                document.getElementById('street').value = JSON.parse(rsp).entry.person.street.value
                setStatus('streetIcon',JSON.parse(rsp).entry.person.street,'street')
                document.getElementById('street').setAttribute('dataname',JSON.parse(rsp).entry.person.street.update)
                
                document.getElementById('house').value = JSON.parse(rsp).entry.person.home.value
                setStatus('houseIcon',JSON.parse(rsp).entry.person.home,'house')
                document.getElementById('house').setAttribute('dataname',JSON.parse(rsp).entry.person.home.update)
                
                document.getElementById('postalCode').value = JSON.parse(rsp).entry.person.postalcode.value
                setStatus('postalCodeIcon',JSON.parse(rsp).entry.person.postalcode,'postalCode')
                document.getElementById('postalCode').setAttribute('dataname',JSON.parse(rsp).entry.person.postalcode.update)
                
                
                if(JSON.parse(rsp).entry.person.region.id!='' && JSON.parse(rsp).entry.person.region.id!=null ){
                    getRegions(JSON.parse(rsp).entry.person.region.id,JSON.parse(rsp).entry.person.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)
    }    
}



/* function drawSelect(select, read, rsp, selected, first = ""){
    //rsp - (array) Registros
    //select - donde se insertan las opciones
    //first - si no es vacoi crea un opcion sin value
    //selected - selecciona una opcin 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].id);
        opt.innerHTML = rsp[i][read];
        if(selected !== null && selected !== "" && selected !== undefined){
            if(rsp[i].id == selected)
                opt.setAttribute("selected", "");
        }
        select.appendChild(opt);
    }
}*/


// name A: classIcon
// name B : BD
// nameC: nameInput
function setStatus(nameA,nameB,nameC){
    console.log(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'
        }
    }
    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)
    console.log(document.getElementsByClassName('inputElement'))
    console.log(document.getElementsByClassName('inputElement').length)
    for(var i = 0; i < document.getElementsByClassName('inputElement').length ; i++){
        if(levels[1].basicRequired.includes(document.getElementsByClassName('inputElement')[i].getAttribute('dataname'))){
            if(!document.getElementsByClassName('inputElement')[i].previousElementSibling.children[0]){
                if(levels[1].toString().indexOf(document.getElementsByClassName('inputElement')[i].getAttribute('dataname'))==-1){
                    if(levels[2].basicRequired.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{
                    document.getElementsByClassName('inputElement')[i].previousElementSibling.innerHTML += '<span style="font-size: 90%; color: #7D8B9E;" class="roboto-bold"> (1) </span>'       
                }
            }
        }
        else if(levels[2].basicRequired.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(levels[3].basicRequired.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>'
            }
        }
    }
}
