WS_waitscreen = true;
var decimCoinCurrency = 0; 
var decimCoinRefCurrency = 0; 
var secondCurrency = ''
var firstCurrencyR = ''
var firstCurrency = ''
var details = ''

window.onload = function(){
    
    // Go back
    document.getElementById('previous-button').addEventListener("click", function(){
        gotoPage('step','sellCrypto',{ 'sessionid' : getParameterByName('sessionid'), 'cid' : getParameterByName('cid') })
    });
    
    // Go step 4
    document.getElementById('next-button').addEventListener("click", function(){
        verifyNextButton()
    });
    
    // Go back R
    document.getElementById('previous-buttonR').addEventListener("click", function(){
        gotoPage('step','sellCrypto',{ 'sessionid' : getParameterByName('sessionid'), 'cid' : getParameterByName('cid') })
    });
    
    // 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)
    })
    
    // Monto    
    document.getElementById('amount').addEventListener("keyup",function(e){
        console.log('in amount')
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency(decimCoin,this.value);
        if(noVal!=="")this.value = noVal;
        document.getElementById('amount').setAttribute("dataNumber",parseFloat(document.getElementById('amount').value).noExponents());
        document.getElementById('quantity').setAttribute("dataNumber",parseFloat(document.getElementById('amount').value / document.getElementById('infText').children[0].getAttribute('datanumber')).noExponents());
        document.getElementById('quantity').setAttribute("type","text");
        document.getElementById('quantity').value = number_format(document.getElementById('quantity').getAttribute("dataNumber"),document.getElementById('quantity').getAttribute("icDecim"))
        
        document.getElementById('error').style.display = 'none'
        
        e.stopPropagation()
    })
    
    document.getElementById('amount').addEventListener("click",function(){
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency(decimCoin,this.value);
        if(noVal!=="")this.value = noVal;
        document.getElementById('amount').setAttribute("dataNumber",parseFloat(document.getElementById('amount').value).noExponents());
    })
    
    document.getElementById('quantity').addEventListener("click",function(){
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency(decimCoin,this.value);
        if(noVal!=="")this.value = noVal;
        document.getElementById('quantity').setAttribute("dataNumber",parseFloat(document.getElementById('quantity').value).noExponents());
    })
    
    // Cantidad
    document.getElementById('quantity').addEventListener("keyup",function(e){
        console.log( 'in quantity' )
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency(decimCoin,this.value);
        if(noVal!=="")this.value = noVal;
        document.getElementById('quantity').setAttribute("dataNumber",parseFloat(document.getElementById('quantity').value).noExponents());
        
        document.getElementById('amount').setAttribute("dataNumber",parseFloat(document.getElementById('quantity').value * document.getElementById('infText').children[0].getAttribute('datanumber')).noExponents());
        document.getElementById('amount').setAttribute("type","text");
        document.getElementById('amount').value = number_format(document.getElementById('amount').getAttribute("dataNumber"),document.getElementById('amount').getAttribute("icDecim"))
        
        document.getElementById('error').style.display = 'none'
        
        e.stopPropagation()
    })
    
    document.getElementById('maxSell').addEventListener("click",function(e){
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency(decimCoin,this.value);
        if(noVal!=="")this.value = noVal;
        document.getElementById('quantity').value = document.getElementById('balanceTotal').getAttribute('datanumber')
        document.getElementById('quantity').setAttribute("dataNumber",parseFloat(document.getElementById('quantity').value).noExponents());
        
        document.getElementById('quantity').value = number_format(document.getElementById('quantity').getAttribute("dataNumber"),document.getElementById('quantity').getAttribute("icDecim"))
        document.getElementById('amount').setAttribute("dataNumber",
                                            parseFloat(parseFloat(document.getElementById('balanceTotal').getAttribute('datanumber')) * (document.getElementById('infText').children[0].getAttribute('datanumber'))).noExponents());
        document.getElementById('amount').setAttribute("type","text");
        document.getElementById('amount').value = number_format(document.getElementById('amount').getAttribute("dataNumber"),document.getElementById('amount').getAttribute("icDecim"))
        e.stopPropagation()
    })
    
    document.getElementById('increaseAmount').addEventListener("click",function(e){
        gotoPage('step','depositFunds',{ 'sessionid' : getParameterByName('sessionid')})  
        
    })
    
    document.getElementById('maxSell').addEventListener("click",function(e){
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency(decimCoin,this.value);
        if(noVal!=="")this.value = noVal;
        document.getElementById('quantity').value = document.getElementById('balanceTotal').getAttribute('datanumber')
        document.getElementById('quantity').setAttribute("dataNumber",parseFloat(document.getElementById('quantity').value).noExponents());
        
        document.getElementById('quantity').value = number_format(document.getElementById('quantity').getAttribute("dataNumber"),document.getElementById('quantity').getAttribute("icDecim"))
        document.getElementById('amount').setAttribute("dataNumber",
                                            parseFloat(parseFloat(document.getElementById('balanceTotal').getAttribute('datanumber')) * (document.getElementById('infText').children[0].getAttribute('datanumber'))).noExponents());
        document.getElementById('amount').setAttribute("type","text");
        document.getElementById('amount').value = number_format(document.getElementById('amount').getAttribute("dataNumber"),document.getElementById('amount').getAttribute("icDecim"))
        e.stopPropagation()
    })
    
    // 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()
    
    var fieldAmo = ["quantity","amount"];
    formatAmount(fieldAmo);
    
    //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('quantity').getAttribute('datanumber'))){
        if(parseFloat(document.getElementById('quantity').getAttribute('datanumber'))>parseFloat(document.getElementById('balanceTotal').getAttribute('datanumber'))){
            document.getElementById('error').innerHTML = 'No existe suficiente liquidez.'
            document.getElementById('error').style.display = 'block'
        }
        else if(document.getElementById('quantity').value == number_format(0,document.getElementById('quantity').getAttribute("icDecim")).replace(".",",")){
            document.getElementById('error').innerHTML = 'Cantidad inválida.'
            document.getElementById('error').style.display = 'block'
        }
        else if(parseFloat(document.getElementById('quantity').getAttribute('datanumber'))>parseFloat(document.getElementById('balanceCur').getAttribute('datanumber'))){
            document.getElementById('error').innerHTML = 'Saldo insuficiente.'
            document.getElementById('error').style.display = 'block'
        }
        else if(document.getElementById('quantity').getAttribute('datanumber') > details.max.number){
            document.getElementById('error').innerHTML = 'No existe suficiente liquidez.'
            document.getElementById('error').style.display = 'block'
        }
        else if(document.getElementById('amount').getAttribute('datanumber') < details.min.number){
            document.getElementById('error').innerHTML = 'Monto mínimo autorizado '+ details.min.formatted + ' ' + secondCurrency.currency.symbol
            document.getElementById('error').style.display = 'block'
        }
        else{
            document.getElementById('error').style.display = 'none';
            gotoPage('step','sellCryptoCo',{ 'sessionid' : getParameterByName('sessionid'), 'cid' : getParameterByName('cid'), 'crid' : getParameterByName('crid'), 
                                            'q': number_format(parseFloat(document.getElementById('quantity').getAttribute('datanumber')).noExponents(), document.getElementById('quantity').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 ordersDetails(req){
    console.log(req)
    callWS('GET', 'orders/details', req, response);
    function response(status, rsp){
        console.log('orders/details')
        console.log(status) 
        switch(status){
            case 200:
                console.log(JSON.parse(rsp));
                reqAccounts = {
                    'sessionid' : getParameterByName('sessionid'),
                    'action' : 1,
                    'currencyid' : getParameterByName('cid')
                }
                accountsPortfolio(reqAccounts,JSON.parse(rsp).entry)
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

function ordersDetailsRefresh(req){
    console.log(req)
    callWSWithoutWS('GET', 'orders/details', req, response);
    function response(status, rsp){
        console.log('orders/details')
        console.log(status) 
        switch(status){
            case 200:
                console.log(JSON.parse(rsp));
                document.getElementById('balanceTotal').innerHTML = firstCurrency.symbol + ' ' + JSON.parse(rsp).entry.max.formatted
                if(JSON.parse(rsp).entry.max.number == 0){
                    document.getElementById('error').innerHTML = 'No hay liquidez en este momento para satisfacer su orden, favor intentar luego.'
                    document.getElementById('error').style.display = 'block'
                }
                document.getElementById('balanceTotal').setAttribute('datanumber', JSON.parse(rsp).entry.max.number)
                
                document.getElementById('infText').children[0].innerHTML = secondCurrency.currency.symbol + ' ' + JSON.parse(rsp).entry.bid.formatted + ' por 1 ' + firstCurrency.symbol
                document.getElementById('infText').children[0].setAttribute('datanumber',JSON.parse(rsp).entry.bid.number)
                setTimeout(function(){ 
                    var req = {
                        'sessionid': getParameterByName('sessionid'),
                        'currencyid': getParameterByName('cid'),
                        'refcurrencyid': getParameterByName('crid'),
                        'action' : 1
                    }
                    ordersDetailsRefresh(req)
                }, 5000);
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}
function accountsPortfolio(req,detailsOrder){
    console.log(req)
    callWS('GET', 'accounts/portfolio', req, response);
    function response(status, rsp){
        console.log('accounts/portfolio')
        console.log(status) 
        switch(status){
            case 200:
                console.log(JSON.parse(rsp));
                loadDetails(detailsOrder,JSON.parse(rsp))
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

function balanceAccounts(){
    var req = {
        'sessionid': getParameterByName('sessionid'),
        'currencyid': getParameterByName('cid')
    }
    callWS('GET', 'balance/accounts', req, response);
    function response(status, rsp){
        console.log('balance/accounts')
        console.log(JSON.parse(rsp));
        console.log(status) 
        switch(status){
            case 200:
                JSON.parse(rsp).record.forEach(record => {
                    if(record.currency.id == getParameterByName('cid')){
                        document.getElementById('balanceCur').innerHTML = record.currency.symbol + ' ' + record.total.formatted;
                        document.getElementById('balanceCur').setAttribute('datanumber',record.total.number)
                        console.log(document.getElementById('balanceCur').innerHTML)
                    }
                });
                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'),
                    'currencyid': getParameterByName('cid'),
                    'refcurrencyid': getParameterByName('crid'),
                    'action' : 1
                }
                ordersDetails(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 loadDetails(detailsOrder,accounts){
    console.log(detailsOrder)
    console.log(accounts)
    details = detailsOrder
    document.getElementById('titleText').children[0].innerHTML = detailsOrder.currency.id == getParameterByName('cid') ? detailsOrder.currency.dsc : detailsOrder.refcurrency.dsc;
    document.getElementById('subTitleText').children[0].innerHTML = detailsOrder.currency.id == getParameterByName('cid') ? detailsOrder.currency.dsc : detailsOrder.refcurrency.dsc;
    
    secondCurrency = accounts.records.find(element => element.currency.id == getParameterByName('crid'))
    
    firstCurrencyR = (secondCurrency.currency.id == detailsOrder.currency.id) ? detailsOrder.refcurrency : detailsOrder.currency
    console.log(firstCurrencyR)
    
    firstCurrency = detailsOrder.currency.id == secondCurrency.currency.id ? detailsOrder.refcurrency : detailsOrder.currency
    
    //firstCurrency = accounts.records.find(element => element.currency.id == getParameterByName('cid'))
    console.log(secondCurrency);
    balanceAccounts()
    document.getElementById('balanceTotal').innerHTML = firstCurrency.symbol + ' ' + secondCurrency.maxbuy.formatted
    document.getElementById('balanceTotal').setAttribute('datanumber',secondCurrency.maxbuy.number)
    
    if(secondCurrency.maxbuy.number == 0){
        document.getElementById('error').innerHTML = 'No hay liquidez en este momento para satisfacer su orden, favor intentar luego.'
        document.getElementById('error').style.display = 'block'
    }
    
    document.getElementById('infText').children[0].innerHTML = secondCurrency.currency.symbol + ' ' + detailsOrder.bid.formatted + ' por 1 ' + firstCurrency.symbol
    document.getElementById('infText').children[0].setAttribute('datanumber',detailsOrder.bid.number)
    
    document.getElementById('amount').setAttribute("icDecim",secondCurrency.currency.decimals);
    document.getElementById('quantity').setAttribute("icDecim",firstCurrencyR.decimals);
    
    var req = {
        'sessionid': getParameterByName('sessionid'),
        'currencyid': getParameterByName('cid'),
        'refcurrencyid': getParameterByName('crid'),
        'action' : 1
    }
    ordersDetailsRefresh(req)
    
}

function callWSWithoutWS(type, service, params, response){
    var url = globalurl + "/api/"+service+".php";
    var spin = document.createElement("div");
    spin.classList.add("spinChar");
    spin.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i>';
    
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
            var rsp = "";
            if(this.responseText !== ""){
                rsp = JSON.parse(this.responseText);
                response(this.status, this.responseText);
            }else{
                response(this.status, this.responseText);
            }
        }
    }
    switch (type){
        case "GET":
            var parsedPars = Object.keys(params).map(function(k) {
                return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
            }).join('&');
            xhttp.open(type.toUpperCase(), url + "?" + parsedPars, true);
            xhttp.send();
        break;
        case"POST":
            xhttp.open("POST", url, true);
            var formdata = new FormData();
            for(var key in params){
                formdata.append(key, params[key]);
            }
            xhttp.send(formdata);
        break;
    }
}

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('titleText','t1');
    
    setWordLanginnerHTML('subTitleText','t2');
    setWordLanginnerHTML('balanceM','balanceM');
    setWordLanginnerHTML('maxBuyL','PURCHASEMAX');
    setWordLanginnerHTML('QuantityToSell','QuantityToSell');
    setWordLanginnerHTML('amountLabel','amount');
    setWordLanginnerHTML('infText','infText');
    setWordLanginnerHTML('increaseAmount','increaseAmount');
    setWordLanginnerHTML('maxSell','maxSell');
    
    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()
    })
    
    getEntry(getParameterByName('sessionid'));

}
