WS_waitscreen = true;
curInf = '';
feesInf = '';

window.onload = function(){
    
    // Go back
    document.getElementById('previous-button').addEventListener("click", function(){
        gotoPage('step','transferCrypto',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go step 4
    document.getElementById('next-button').addEventListener("click", function(){
        verifyNextButton()
    });
    
    // Go back R
    document.getElementById('previous-buttonR').addEventListener("click", function(){
        gotoPage('step','transferCrypto',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go step 4 R
    document.getElementById('next-buttonR').addEventListener("click", function(){
        verifyNextButton()
    });
    
    // Step
    document.getElementById('floatButton').addEventListener("click",function(){
        var popup = document.getElementById("floatButton").children[0].children[0];
        if(popup.classList.contains('show')){
            gotoPage('dashboard','home',{ 'sessionid' : getParameterByName('sessionid') })
        }else{
            popup.classList.toggle("show");
        }
    })

    document.getElementById('floatClose').addEventListener("click",function(event){
        var popup = document.getElementById("floatButton").children[0].children[0];
        popup.classList.remove("show")
        event.stopPropagation()
    })
    
    // Session Update
    document.getElementById('expSessionButton').addEventListener("click",function(){
        var req = {
            'sessionid': getParameterByName('sessionid')
        }
        sessionUpdate(req)
    })
    
    // withdraw
    document.getElementById('withdrawAmount').addEventListener("keyup",function(e){
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency(decimCoin,this.value);
        if(noVal!=="")this.value = noVal;
        document.getElementById('withdrawAmount').setAttribute("dataNumber",parseFloat(document.getElementById('withdrawAmount').value).noExponents());
        document.getElementById('error').style.display = 'none'
    })
    
    
    document.getElementById('all').addEventListener("click",function(){
        document.getElementById('withdrawAmount').setAttribute('dataNumber',parseFloat(document.getElementById('avail').getAttribute('number')).noExponents())
        document.getElementById('withdrawAmount').value = number_format(parseFloat(document.getElementById('avail').getAttribute('number')).noExponents(),decimCoin);
        document.getElementById('withdrawAmount').disabled = true
        if(feesInf.entry.xfer.nmalfee){
            document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + (feesInf.entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ',');
            
            document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + ((feesInf.entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ','));
            document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + ((feesInf.entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ','));
                var noVal = formatCurrency(decimCoin,this.value);
                if(noVal!=="")this.value = noVal;
                if(document.getElementById('withdrawAmount').value == ""){
                    document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
                    document.getElementById('withdrawTotalFinal').style.color="#262624"
                }else{
                    if(((((parseFloat((document.getElementById('withdrawAmount').value).replace(',','.')) - feesInf.entry.xfer.nmalfee.number).toFixed(decimCoin)).replace('.', ','))).startsWith('-')){
                        document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
                        document.getElementById('withdrawTotalFinal').style.color="#D0021B"
                    }else{
                        document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber')).noExponents() - parseFloat(feesInf.entry.xfer.nmalfee.number).noExponents()).noExponents(),decimCoin)
                        //((((parseFloat((document.getElementById('withdrawAmount').value).replace(',','.')) - fees.entry.xfer.nmalfee.number).toFixed(decimCoin)).replace('.', ',')));
                        document.getElementById('withdrawTotalFinal').style.color="#262624"
                    }
                    
                }
        }else if(feesInf.entry.xfer.pctfee){
            document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
            document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
                var noVal = formatCurrency(decimCoin,this.value);
                if(noVal!=="")this.value = noVal;
                document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + number_format((parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber')).noExponents() * parseFloat(feesInf.entry.xfer.pctfee.number)).noExponents() / 100 ,decimCoin)
                document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber')).noExponents() *(1 - feesInf.entry.xfer.pctfee.number / 100) ,decimCoin)
        }else{
            console.log('N/A')
        }
        
        
    })
    document.getElementById('notAll').addEventListener("click",function(){
        document.getElementById('withdrawAmount').disabled = false
    })
    
    var fieldAmo = ["withdrawAmount"];
    formatAmount(fieldAmo);
    
    // Go to preferences
    document.getElementById('preferences').addEventListener("click", function(){
        gotoPage('preferences','main',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to preferences
    document.getElementById('preferencesR').addEventListener("click", function(){
        gotoPage('preferences','main',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to balance
    document.getElementById('balance').addEventListener("click", function(){
        gotoPage('balance','balance',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to balance
    document.getElementById('balanceR').addEventListener("click", function(){
        gotoPage('balance','balance',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    document.getElementById('example-element-toggle2').checked = false;
    
    // Bar
    document.getElementById('togglebar').addEventListener("click", function(){
        var el = document.getElementById('addView2')
        document.getElementById('addView2').style.display = 'block'
        setTimeout(function(){ 
            document.getElementById('example-element-toggle2').checked = !document.getElementById('example-element-toggle2').checked;
        }, 15);   
        
    });
    
    // Logout
    document.getElementById('logouticon').addEventListener("click", function(){
        logout();
    });
    
    // Logout
    document.getElementById('logouticon2').addEventListener("click", function(){
        logout();
    });
    
    
    init()
    
    //Mostrar HTML cargado
    esconderHTML(false);
    
    var waitScreen = document.getElementById("waitScreen");
    document.body.removeChild(waitScreen);
    WS_waitscreen = false;
    document.getElementsByClassName('pageCnt')[0].style.visibility="visible"
}

function verifyNextButton(){
    if(parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber'))){
        if(parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber'))>parseFloat(document.getElementById('avail').getAttribute('number'))){
            document.getElementById('error').innerHTML = 'Saldo insuficiente.'
            document.getElementById('error').style.display = 'block'
        }
        else if((document.getElementById('withdrawAmount').value == number_format(0,document.getElementById('withdrawAmount').getAttribute("icDecim")).replace(".",",")) || document.getElementById('withdrawAmount').value == ""){
            document.getElementById('error').innerHTML = 'Cantidad inválida.'
            document.getElementById('error').style.display = 'block'
        }
        else if(document.getElementById('withdrawTotalFinal').style.color == '#D0021B' || document.getElementById('withdrawTotalFinal').style.color == 'rgb(208, 2, 27)'){
            document.getElementById('error').innerHTML = 'Cantidad inválida.'
            document.getElementById('error').style.display = 'block'
        }
        else if(document.getElementById('withdrawAmount').getAttribute('datanumber') > feesInf.entry.xfer.max.number){
            document.getElementById('error').innerHTML = 'Monto máximo mensual autorizado '+  feesInf.entry.xfer.max.formatted + ' ' + curInf.currency.symbol
            document.getElementById('error').style.display = 'block'
        }
        else if(document.getElementById('withdrawAmount').getAttribute('datanumber') < feesInf.entry.xfer.min.number){
            document.getElementById('error').innerHTML = 'Monto mínimo autorizado '+  feesInf.entry.xfer.min.formatted + ' ' + curInf.currency.symbol
            document.getElementById('error').style.display = 'block'
        }
        else{
            document.getElementById('error').style.display = 'none';
            gotoPage('step','transferCryptoAc',{ 'sessionid' : getParameterByName('sessionid'), 'cid' : getParameterByName('cid'),
                    'q': number_format(parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber')).noExponents(), document.getElementById('withdrawAmount').getAttribute('icdecim')).replace(".","").replace(",",".")})                

        }
    }else{
        document.getElementById('error').innerHTML = 'Cantidad inválida.'
        document.getElementById('error').style.display = 'block'   
    }
}

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";
                init()
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

function init(){
    setLang()
}

function getEntry(sessionid){
    callWS("GET", "users/entry", { 'sessionid' : sessionid}, response);
        
    function response(status, rsp){
        switch(status){
            case 200:
                entrydata = (JSON.parse(rsp).entry)
                putName(entrydata);
                var req = {
                    'sessionid': getParameterByName('sessionid'),
                    'action': 3, /*1 INtercambio, 2 Deposito, 3 Retiro, 4 Transferencia
                    'currencyid': getParameterByName('cid)*/
                }
                accountsPortfolio(req)
                break;
            case 204:
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }    
}

function putName(entrydata){
    var name;
    if(entrydata.company){
        if(entrydata.company.name.value=="" || entrydata.company.name.value== null){
            name = entrydata.usr
        }else{
            name = entrydata.company.name.value
        }
    }
    else if(entrydata.person){
        if(entrydata.person.firstname.value=="" || entrydata.person.firstname.value==null){
            name = entrydata.usr
        }else{
            name = entrydata.person.firstname.value + ' '+ entrydata.person.firstlastname.value
        }
    }
    document.getElementById('name').innerHTML = name
    document.getElementById('name2').innerHTML = name
}

function logout(){
    var sessionid = getParameterByName('sessionid')
    var req ={
        'sessionid': sessionid,
    }
    callWS('GET', 'login/logout', req, response);

    function response(status, rsp){
        console.log(JSON.parse(rsp));
        console.log(status)
        switch(status){
            case 200:
                gotoPage('login','main','')
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}


function accountsPortfolio(req){
    callWS('GET', 'accounts/portfolio', req, response);
    function response(status, rsp){
        console.log('accounts/portfolio')
        console.log(JSON.parse(rsp));
        console.log(status) 
        switch(status){
            case 200:
                curInf = null;
                JSON.parse(rsp).records.forEach(currency => {
                    if(currency.currency.id == getParameterByName('cid')){
                        curInf = currency;
                    }   
                });
                req = {
                    'sessionid': getParameterByName('sessionid'),
                    'currencyid': getParameterByName('cid')
                }
                feesEntry(req,curInf)
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

// fees/entry
function feesEntry(req,accPor){
    callWS('GET', 'fees/entry', req, response);
    function response(status, rsp){
        console.log('fees/entry')
        console.log(JSON.parse(rsp));
        console.log(status) 
        switch(status){
            case 200:
                loadData(accPor,JSON.parse(rsp))
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

function loadData(currency,fees){
    console.log(currency)
    console.log(fees)
    feesInf = fees
    document.getElementById('withdrawAmount').setAttribute("icDecim",currency.currency.decimals);
    document.getElementById('titP').children[0].innerHTML = currency.currency.dsc
    document.getElementById('avail').innerHTML = currency.currency.symbol + ' ' + currency.avaliable.formatted
    document.getElementById('avail').setAttribute("number",parseFloat(currency.avaliable.number));
    decimCoin = document.getElementById('withdrawAmount').getAttribute("icDecim")
    document.getElementById('next-button').setAttribute('interface',currency.currency.interface)

        if(fees.entry.xfer.nmalfee){
            document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + (fees.entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ',');
            
            document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + ((fees.entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ','));
            document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + ((fees.entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ','));
            document.getElementById('withdrawAmount').addEventListener("keyup", function(){
                var noVal = formatCurrency(decimCoin,this.value);
                if(noVal!=="")this.value = noVal;
                if(document.getElementById('withdrawAmount').value == ""){
                    document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
                    document.getElementById('withdrawTotalFinal').style.color="#262624"
                }else{
                    if(((((parseFloat((document.getElementById('withdrawAmount').value).replace(',','.')) - fees.entry.xfer.nmalfee.number).toFixed(decimCoin)).replace('.', ','))).startsWith('-')){
                        document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
                        document.getElementById('withdrawTotalFinal').style.color="#D0021B"
                    }else{
                        document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber')).noExponents() - parseFloat(fees.entry.xfer.nmalfee.number)).noExponents(),decimCoin)
                        //((((parseFloat((document.getElementById('withdrawAmount').value).replace(',','.')) - fees.entry.xfer.nmalfee.number).toFixed(decimCoin)).replace('.', ',')));
                        document.getElementById('withdrawTotalFinal').style.color="#262624"
                    }
                    
                }
            }); 
        }else if(fees.entry.xfer.pctfee){
            document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
            document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
            document.getElementById('withdrawAmount').addEventListener("keyup", function(){
                var noVal = formatCurrency(decimCoin,this.value);
                if(noVal!=="")this.value = noVal;
                document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(parseFloat(parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber')).noExponents() * parseFloat(fees.entry.xfer.pctfee.number)).noExponents() / 100).noExponents() ,decimCoin)
                document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber')).noExponents() * parseFloat(1 - fees.entry.xfer.pctfee.number / 100).noExponents()).noExponents() ,decimCoin)
            }); 
        }else{
            console.log('N/A')
        }
}
function setLang(){
    
    lang = localStorage.getItem('lang');
    
    /* inner HTML */
    setWordLanginnerHTML('home','home');
    setWordLanginnerHTML('balance','balance');
    setWordLanginnerHTML('preferences','preferences');
    setWordLanginnerHTML('homeR','home');
    setWordLanginnerHTML('balanceR','balance');
    setWordLanginnerHTML('preferencesR','preferences');
    setWordLanginnerHTML('langIcon','langIcon');
    
    
    setWordLanginnerHTML('titlePage','titlePage');
    setWordLanginnerHTML('step1','step1');
    setWordLanginnerHTML('step2','step2');
    setWordLanginnerHTML('step3','step3');
    setWordLanginnerHTML('step4','step4');
    setWordLanginnerHTML('step5','step5');
    setWordLanginnerHTML('titP','t1');
    
    setWordLanginnerHTML('t2','t2');
    setWordLanginnerHTML('avLabel','AVAILABLE');
    setWordLanginnerHTML('amountTransLabel','QuantityToTransfer');
    setWordLanginnerHTML('allAm','allAm');
    setWordLanginnerHTML('anotAm','anotAm');
    setWordLanginnerHTML('feesLabel','FEES');
    setWordLanginnerHTML('feesLabel','FEES');
    
    setWordLanginnerHTML('previous-button','RETURN');
    setWordLanginnerHTML('next-button','continue');
    setWordLanginnerHTML('previous-buttonR','RETURN');
    setWordLanginnerHTML('next-buttonR','continue');
    
    
    setWordLanginnerHTML('buttonAdv','ADVANCEDMODE');
    setWordLanginnerHTML('question','question');
    setWordLanginnerHTML('expired1','expired1');
    setWordLanginnerHTML('expired2','expired2');
    setWordLanginnerHTML('expSessionButton','continue');
    setWordLanginnerHTML('ts','ts');

    
    document.getElementById('floatClose').addEventListener("click",function(event){
        var popup = document.getElementById("floatButton").children[0].children[0];
        popup.classList.remove("show")
        event.stopPropagation()
    })
    
    document.getElementById('all').addEventListener("click",function(){
        document.getElementById('withdrawAmount').setAttribute('dataNumber',parseFloat(document.getElementById('avail').getAttribute('number')).noExponents())
        document.getElementById('withdrawAmount').value = number_format(parseFloat(document.getElementById('avail').getAttribute('number')).noExponents(),decimCoin);
        document.getElementById('withdrawAmount').disabled = true
        if(feesInf.entry.xfer.nmalfee){
            document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + (feesInf.entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ',');
            
            document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + ((feesInf.entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ','));
            document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + ((feesInf.entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ','));
                var noVal = formatCurrency(decimCoin,this.value);
                if(noVal!=="")this.value = noVal;
                if(document.getElementById('withdrawAmount').value == ""){
                    document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
                    document.getElementById('withdrawTotalFinal').style.color="#262624"
                }else{
                    if(((((parseFloat((document.getElementById('withdrawAmount').value).replace(',','.')) - feesInf.entry.xfer.nmalfee.number).toFixed(decimCoin)).replace('.', ','))).startsWith('-')){
                        document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
                        document.getElementById('withdrawTotalFinal').style.color="#D0021B"
                    }else{
                        document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber')).noExponents() - parseFloat(feesInf.entry.xfer.nmalfee.number).noExponents()).noExponents(),decimCoin)
                        //((((parseFloat((document.getElementById('withdrawAmount').value).replace(',','.')) - fees.entry.xfer.nmalfee.number).toFixed(decimCoin)).replace('.', ',')));
                        document.getElementById('withdrawTotalFinal').style.color="#262624"
                    }
                    
                }
        }else if(feesInf.entry.xfer.pctfee){
            document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
            document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(0,decimCoin);
                var noVal = formatCurrency(decimCoin,this.value);
                if(noVal!=="")this.value = noVal;
                document.getElementById('withdrawBTCFee').innerHTML = curInf.currency.symbol + ' ' + number_format((parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber')).noExponents() * parseFloat(feesInf.entry.xfer.pctfee.number)).noExponents() / 100 ,decimCoin)
                document.getElementById('withdrawTotalFinal').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(document.getElementById('withdrawAmount').getAttribute('datanumber')).noExponents() *(1 - feesInf.entry.xfer.pctfee.number / 100) ,decimCoin)
        }else{
            console.log('N/A')
        }
        
        
    })
    document.getElementById('notAll').addEventListener("click",function(){
        document.getElementById('withdrawAmount').disabled = false
    })
    
    getEntry(getParameterByName('sessionid'));

}
