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

function start() {

    // Go back
    document.getElementById('previous-button').addEventListener("click", function () {
        gotoPage('step', 'buyCryptoCur', { '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', 'buyCryptoCur', { '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', "")
        } 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


    // Monto    
    document.getElementById('amount').addEventListener("keyup", function (e) {
        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());

        /*if(document.getElementById('BuyAndSellPrice').getAttribute("dataNumber")!='' && document.getElementById('BuyAndSellAmount').getAttribute("dataNumber")!=''){
            document.getElementById('BuyAndSellTotal').value = document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") * document.getElementById('BuyAndSellAmount').getAttribute("dataNumber")
        }else{
            document.getElementById('BuyAndSellTotal').value = 0
        }
        ;*/

        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) {
        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());

        // Si el precio o el monto existen
        /*if(document.getElementById('BuyAndSellPrice').getAttribute("dataNumber")!='' && document.getElementById('BuyAndSellAmount').getAttribute("dataNumber")!=''){
            // El total es el precio por el monto
            document.getElementById('BuyAndSellTotal').value = document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") * document.getElementById('BuyAndSellAmount').getAttribute("dataNumber")
        
        // Si no
        }else{
            document.getElementById('BuyAndSellTotal').value = 0   
        }
        document.getElementById('BuyAndSellTotal').setAttribute("dataNumber",document.getElementById('BuyAndSellTotal').value);
        document.getElementById('BuyAndSellTotal').setAttribute("type","text");
        document.getElementById('BuyAndSellTotal').value = number_format(document.getElementById('BuyAndSellTotal').getAttribute("dataNumber"),document.getElementById('BuyAndSellTotal').getAttribute("icDecim"));*/

        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('maxBuy').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', "")

    })

    document.getElementById('maxBuy').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()
    })

    init()

    var fieldAmo = ["quantity", "amount"];
    formatAmount(fieldAmo);

    //Mostrar HTML cargado
    esconderHTML(false);

}

function verifyNextButton() {
    if (parseFloat(document.getElementById('quantity').getAttribute('datanumber'))) {
        var amobien = document.getElementById('amount').getAttribute('datanumber');
        var curr = secondCurrency.currency.symbol;
        if (details.orden.type == 1) {
            amobien = document.getElementById('quantity').getAttribute('datanumber');
            curr = firstCurrency.symbol;
        }
        if (parseFloat(document.getElementById('quantity').getAttribute('datanumber')) > parseFloat(document.getElementById('balanceTotal').getAttribute('datanumber'))) {
            document.getElementById('error').innerHTML = getLangById("var1")[lang]
            document.getElementById('error').style.display = 'block'
        }
        else if ((document.getElementById('quantity').value == number_format(0, document.getElementById('quantity').getAttribute("icDecim")).replace(".", ",")) || document.getElementById('quantity').value == "") {
            document.getElementById('error').innerHTML = getLangById("var2")[lang]
            document.getElementById('error').style.display = 'block'
        }
        else if (parseFloat(document.getElementById('amount').getAttribute('datanumber')) > parseFloat(document.getElementById('balanceCur').getAttribute('datanumber'))) {
            document.getElementById('error').innerHTML = getLangById("var3")[lang]
            document.getElementById('error').style.display = 'block'
        }
        else if (document.getElementById('quantity').getAttribute('datanumber') > details.max.number) {
            document.getElementById('error').innerHTML = getLangById("var1")[lang]
            document.getElementById('error').style.display = 'block'
        }
        else if (amobien < details.min.number) {
            document.getElementById('error').innerHTML = getLangById("var4")[lang] + details.min.formatted + ' ' + curr;
            document.getElementById('error').style.display = 'block'
        }
        else {
            document.getElementById('error').style.display = 'none';
            //sessionStorage.getItem('qty')
            //sessionStorage.setItem('qty', parseFloat(document.getElementById('quantity').getAttribute('datanumber')));
            var qty = 0;
            //if(details.orden.type == 2){
            qty = number_format(parseFloat(document.getElementById('quantity').getAttribute('datanumber')).noExponents(), document.getElementById('quantity').getAttribute('icdecim')).replace(".", "").replace(",", ".")
            /*}else{
                //CAMBIAR POR TOTAL 
                qty = number_format(parseFloat(document.getElementById('amount').getAttribute('datanumber')).noExponents(), document.getElementById('amount').getAttribute('icdecim')).replace(".","").replace(",",".")
            }*/

            gotoPage('step', 'buyCryptoCo', { 'cid': getParameterByName('cid'), 'crid': getParameterByName('crid'), 'q': qty })
        }
    } else {
        document.getElementById('error').innerHTML = getLangById("var2")[lang]
        document.getElementById('error').style.display = 'block'
    }
}



function sessionUpdate(req) {
    callWS('GET', 'session/update', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                document.getElementsByClassName('expired')[0].style.display = "none";
                init()
                break;
            case 400:
                break;
            case 401:
                gotoPage('login', 'main', '');
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

function ordersDetails(req) {
    callWS('GET', 'orders/details', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:

                reqAccounts = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'action': 2,
                    '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) {
    callWSWithoutWS('GET', 'orders/details', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:

                document.getElementById('balanceTotal').innerHTML = firstCurrency.symbol + ' ' + JSON.parse(rsp).entry.max.formatted
                document.getElementById('balanceTotal').setAttribute('datanumber', JSON.parse(rsp).entry.max.number)
                var price = JSON.parse(rsp).entry.ask;
                if (JSON.parse(rsp).entry.orden.type == 1) {
                    price = JSON.parse(rsp).entry.bid;
                }
                document.getElementById('infText').children[0].innerHTML = secondCurrency.currency.symbol + ' ' + price.formatted + getLangById("var5")[lang] + firstCurrency.symbol
                document.getElementById('infText').children[0].setAttribute('datanumber', price.number)
                setTimeout(function () {
                    var req = {
                        'sessionid': sessionStorage.getItem('sessionid'),
                        'currencyid': getParameterByName('cid'),
                        'refcurrencyid': getParameterByName('crid'),
                        'action': 2
                    }
                    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) {
    callWS('GET', 'accounts/portfolio', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:

                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 init() {
    setLang()
}

function getEntry(sessionid) {
    callWS("GET", "users/entry", { 'sessionid': sessionid }, response);

    function response(status, rsp) {
        switch (status) {
            case 200:
                if (JSON.parse(rsp).notifications > 0) {
                    document.getElementById('messageNotification').style.display = "table"
                    document.getElementById('messageNotification').children[0].innerHTML = JSON.parse(rsp).notifications
                } else {
                    document.getElementById('messageNotification').style.display = "none"
                    document.getElementById('messageNotification').children[0].innerHTML = ""
                }
                entrydata = (JSON.parse(rsp).entry)
                putName(entrydata);
                var req = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'currencyid': getParameterByName('cid'),
                    'refcurrencyid': getParameterByName('crid'),
                    'action': 2
                }
                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('headname').innerHTML = name
    document.getElementById('name2').innerHTML = name
}

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

    function response(status, rsp) {
        switch (status) {
            case 200:
                sessionStorage.removeItem('sessionid')
                gotoPage('login', 'main', '')
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

function loadDetails(detailsOrder, 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
    firstCurrency = detailsOrder.currency.id == secondCurrency.currency.id ? detailsOrder.refcurrency : detailsOrder.currency

    //firstCurrency = accounts.records.find(element => element.currency.id == getParameterByName('cid'))
    document.getElementById('balanceCur').innerHTML = secondCurrency.currency.symbol + ' ' + secondCurrency.avaliable.formatted
    document.getElementById('balanceCur').setAttribute('datanumber', secondCurrency.avaliable.number)

    /*
    document.getElementById('balanceTotal').innerHTML = firstCurrency.symbol + ' ' + secondCurrency.maxbuy.formatted
    document.getElementById('balanceTotal').setAttribute('datanumber',secondCurrency.maxbuy.number)
    */
    var price = detailsOrder.ask;
    if (detailsOrder.orden.type == 1) {
        price = detailsOrder.bid;
    }

    document.getElementById('infText').children[0].innerHTML = secondCurrency.currency.symbol + ' ' + price.formatted + getLangById("var5")[lang] + firstCurrency.symbol
    document.getElementById('infText').children[0].setAttribute('datanumber', price.number)

    document.getElementById('amount').setAttribute("icDecim", secondCurrency.currency.decimals);
    document.getElementById('quantity').setAttribute("icDecim", firstCurrencyR.decimals);

    var req = {
        'sessionid': sessionStorage.getItem('sessionid'),
        'currencyid': getParameterByName('cid'),
        'refcurrencyid': getParameterByName('crid'),
        'action': 2
    }
    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() {

    addFooter()

    lang = sessionStorage.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('saldo', 'balanceM');
    setWordLanginnerHTML('maxBuyL', 'PURCHASEMAX');
    setWordLanginnerHTML('QuantityToBuy', 'QuantityToBuy');
    setWordLanginnerHTML('amountLabel', 'amount');
    setWordLanginnerHTML('infText', 'infText');
    setWordLanginnerHTML('increaseAmount', 'increaseAmount');
    setWordLanginnerHTML('maxBuy', 'maxBuy');

    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(sessionStorage.getItem('sessionid'));

}
