
portfolio = [];
var markersListArray = {};
var depositsAccountsArray = {}
var depositsAccountsArrayPM = {}
var WAccountsArrayPM = {}
var entrydata;
var decimCoinCurrency = 0;
var decimCoinRefCurrency = 0;
var dashboardUpdate;
var feesOrders;
var pairDetailsVar;
var canvas;
var ctx;
var isBPInterface = true;
var isBPWorks = true;
//loadTutorial(); drawTutorial(); endTutorial(); - Global funciones para el tutorial file:js/main.js


function closeAllPop() {
    document.getElementsByClassName('addressBTCInf')[0].style.display = "none"
    document.getElementsByClassName('withdrawBTC')[0].style.display = "none"
    //document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
    document.getElementsByClassName('success')[0].style.display = "none"
    document.getElementsByClassName('transferBTC')[0].style.display = "none"
    //document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
    document.getElementsByClassName('movBTC')[0].style.display = "none"
    document.getElementsByClassName('withdrawFiat')[0].style.display = "none"
    //document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
    document.getElementsByClassName('depFiatInf')[0].style.display = "none"
    document.getElementsByClassName('movVES')[0].style.display = "none"
    document.getElementsByClassName('movDetailFiat')[0].style.display = "none"

    // W Fiat remove red errors
    noError('withdrawFiatAmount', 'ewithdrawFiatAmount')
    document.getElementById('ewithdrawFiatAmount').style.display = 'none'

    noError('withdrawFiatAmount2', 'ewithdrawFiatAmount2')
    document.getElementById('ewithdrawFiatAmount2').style.display = 'none'

    //noError('depFiattPhonePM22','edepFiattPhonePM22')
    document.getElementById('edepFiattPhonePM22').style.display = 'none'

    noError('withdrawFiatAccount', 'ewithdrawFiatAccount')
    document.getElementById('ewithdrawFiatAccount').style.display = 'none'
    noError('withdrawFiatAccount2', 'ewithdrawFiatAccount2')
    document.getElementById('ewithdrawFiatAccount2').style.display = 'none'
    noError('withdrawFiatConfirmCode', 'ewithdrawFiatConfirmCode')
    document.getElementById('ewithdrawFiatConfirmCode').style.display = 'none'
    noError('withdrawFiatConfirmCode2', 'ewithdrawFiatConfirmCode2')
    document.getElementById('ewithdrawFiatConfirmCode2').style.display = 'none'
    document.getElementById("withdrawFiatAccount").classList.remove("selectwdFiatBank");
    document.getElementById("withdrawFiatAccount").classList.add("selectwdFiat");
    document.getElementById("withdrawFiatAccount2").classList.remove("selectwdFiatBank");
    document.getElementById("withdrawFiatAccount2").classList.add("selectwdFiat");

    // W BTC remove red erros
    noError('withdrawBTCAmount', 'ewithdrawBTCAmount')
    document.getElementById('ewithdrawBTCAmount').style.display = 'none'
    noError('withdrawBTCWallet', 'ewithdrawBTCWallet')
    document.getElementById('ewithdrawBTCWallet').style.display = 'none'
    noError('withdrawBTCConfirmCode', 'ewithdrawBTCConfirmCode')
    document.getElementById('ewithdrawBTCConfirmCode').style.display = 'none'

    // Dep Fiat remove red error
    noError('depFiatInfAmount', 'edepFiatInfAmount')
    noError('depFiatInfAmountPM', 'edepFiatInfAmountPM')
    document.getElementById('edepFiatInfAmount').style.display = 'none'
    document.getElementById('edepFiatInfAmountPM').style.display = 'none'
    document.getElementById('depFiatInfDestinationBank1').style.border = "1px solid #D5DCE5 !important";
    document.getElementById('depFiatInfDestinationBank2').style.border = "1px solid #D5DCE5 !important";

    document.getElementById("depFiatInfDestinationBank1").classList.remove("selectwdFiatBank");
    document.getElementById("depFiatInfDestinationBank2").classList.remove("selectwdFiatBank");

    document.getElementById("depFiatInfDestinationBank1").classList.add("selectwdFiat");
    document.getElementById("depFiatInfDestinationBank2").classList.add("selectwdFiat");

    document.getElementById('edepFiatInfDestinationBank1').innerHTML = '';
    document.getElementById('edepFiatInfDestinationBank2').innerHTML = '';

    document.getElementById('edepFiatInfDestinationBank1').style.display = 'none'
    document.getElementById('edepFiatInfDestinationBank2').style.display = 'none'
    noError('depFiatInfDate', 'edepFiatInfDate')
    document.getElementById('edepFiatInfDate').style.display = 'none'
    noError('depFiatInfRef', 'edepFiatInfRef')
    document.getElementById('edepFiatInfRef').style.display = 'none'
    noError('depFiatInfRec', 'edepFiatInfRec')
    document.getElementById('edepFiatInfRec').style.display = 'none'

    noError('depFiatInfPhonePM', 'edepFiatInfPhonePM')
    document.getElementById('edepFiatInfPhonePM').style.display = 'none'

    noError('codePM', 'ecodePM')
    document.getElementById('ecodePM').style.display = 'none'

    noError('depFiatInfCIPM', 'edepFiatInfCIPM')
    document.getElementById('edepFiatInfCIPM').style.display = 'none'

    noError('depFiatInfAmountPM22', 'edepFiatInfAmountPM22')
    document.getElementById('edepFiatInfAmountPM22').style.display = 'none'


    // Transf BTC remove red errors
    noError('transferBTCAmount', 'etransferBTCAmount')
    document.getElementById('etransferBTCAmount').style.display = 'none'
    noError('transferBTCEmail', 'etransferBTCEmail');
    document.getElementById('etransferBTCEmail').style.display = 'none'

    // Body scroll
    document.getElementsByTagName('body')[0].classList.remove('hidden')
}

function start() {

    lang = sessionStorage.getItem('lang');

    document.getElementById('logouticon2').addEventListener("click", function () {
        myLogout();;
    });
    //--

    //Lbl general de saltar popup
    document.getElementById("lblEndTut").innerHTML = getLangById('lblEndTut')[lang];
    //Evento "next" popup de tutoriales incial
    document.getElementById("nextStepTut").addEventListener("click", function () {
        loadTutorial(this.getAttribute("nextStep"));
    });
    //Evento "saltar" popup de tutoriales incial    
    document.getElementById("endTutorial").innerHTML = getLangById('endTutorial')[lang];
    document.getElementById("endTutorial").addEventListener("click", function () {
        endTutorial();
    });

    //Agregado javier 
    document.getElementById("cardBuyAndSellBuy").addEventListener("click", function () {
        if (document.getElementById('BuyAndSellSelect').value == 1) {
            var number = this.getAttribute("number");
            document.getElementById('BuyAndSellPrice').value = number;
            document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", number);

            document.getElementById('BuyAndSellPrice').setAttribute("type", "text");
            document.getElementById('BuyAndSellPrice').value = number_format(document.getElementById('BuyAndSellPrice').getAttribute("dataNumber"), document.getElementById('BuyAndSellPrice').getAttribute("icDecim"));
        }

    });
    document.getElementById("cardBuyAndSellSell").addEventListener("click", function () {
        if (document.getElementById('BuyAndSellSelect').value == 1) {
            var number = this.getAttribute("number");
            document.getElementById('BuyAndSellPrice').value = number;
            document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", number);

            document.getElementById('BuyAndSellPrice').setAttribute("type", "text");
            document.getElementById('BuyAndSellPrice').value = number_format(document.getElementById('BuyAndSellPrice').getAttribute("dataNumber"), document.getElementById('BuyAndSellPrice').getAttribute("icDecim"));
        }

    });

    if (screen.width <= 700) {
        changeDivs()
    } else {
        // Refresh
        document.getElementById('refreshButton').addEventListener("click", function () {
            var reqDashboardEntry = {
                'sessionid': sessionStorage.getItem('sessionid'),
                'ordernumofrec': 25,
                'exchangenumofrec': 25,
                'pairid': document.getElementById('pairName').getAttribute('pairId')
            }
            dashboardEntry(reqDashboardEntry, '', 0)

        });

        // Minimize card 2
        document.getElementById('iconRightCard2').addEventListener("click", function () {
            var card = document.getElementById('card2')
            var isCollapsed = card.getAttribute('data-collapsed') === 'true';
            if (isCollapsed) {
                expandSection(card, 392, 'iconRightCard2')
                card.setAttribute('data-collapsed', 'false')
            } else {
                collapseSection(card, 'iconRightCard2')
            }
        });

        // Minimize card 3
        document.getElementById('iconRightCard3').addEventListener("click", function () {
            var card = document.getElementById('card3')
            var isCollapsed = card.getAttribute('data-collapsed') === 'true';

            if (isCollapsed) {
                expandSection(card, 392, 'iconRightCard3')
                card.setAttribute('data-collapsed', 'false')
            } else {
                collapseSection(card, 'iconRightCard3')
            }
        });

        // Minimize card 4
        document.getElementById('iconRightCard4').addEventListener("click", function () {
            var card = document.getElementById('card4')
            var isCollapsed = card.getAttribute('data-collapsed') === 'true';

            if (isCollapsed) {
                expandSection(card, 236, 'iconRightCard4')
                card.setAttribute('data-collapsed', 'false')
            } else {
                collapseSection(card, 'iconRightCard4')
            }
        });

        // Minimize card 5
        document.getElementById('iconRightCard5').addEventListener("click", function () {
            var card = document.getElementById('card5')
            var isCollapsed = card.getAttribute('data-collapsed') === 'true';

            if (isCollapsed) {
                expandSection(card, 352, 'iconRightCard5')
                card.setAttribute('data-collapsed', 'false')
            } else {
                collapseSection(card, 'iconRightCard5')
            }
        });

        // Minimize card 6
        document.getElementById('iconRightCard6').addEventListener("click", function () {
            var card = document.getElementById('card6')
            var isCollapsed = card.getAttribute('data-collapsed') === 'true';

            if (isCollapsed) {
                expandSection(card, 400, 'iconRightCard6')
                card.setAttribute('data-collapsed', 'false')
            } else {
                collapseSection(card, 'iconRightCard6')
            }
        });

        // Minimize card 7
        document.getElementById('iconRightCard7').addEventListener("click", function () {
            var card = document.getElementById('card7')
            var isCollapsed = card.getAttribute('data-collapsed') === 'true';

            if (isCollapsed) {
                expandSection(card, 392, 'iconRightCard7')
                card.setAttribute('data-collapsed', 'false')
            } else {
                collapseSection(card, 'iconRightCard7')
            }
        });
    }


    document.getElementById('depFiatInfIdButton').addEventListener("click", function () {
        document.getElementById("depFiatInfId").dispatchEvent(new MouseEvent('click'));
    });


    // Retirar Fiat
    document.getElementById('withdrawFiat').addEventListener("click", function () {
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {

            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        } else {
            document.getElementById('withdrawFiatAmount').value = '';
            document.getElementById('withdrawFiatAmount').setAttribute("dataNumber", "");
            document.getElementById('withdrawFiatAmount2').value = '';
            document.getElementById('withdrawFiatAmount2').setAttribute("dataNumber", "");
            document.getElementById('withdrawFiatAccount').value = '';
            document.getElementById('withdrawFiatAccount2').value = '';
            document.getElementById('withdrawFiatFee').innerHTML = 0;
            document.getElementById('withdrawFiatTotal').innerHTML = 0;
            document.getElementById('depFiatInfPhonePM2').value = "";
            document.getElementById('phoneNumberPM').value = "";
            document.getElementById('withdrawFiatTotal').setAttribute("dataNumber", 0);
            document.getElementById('withdrawFiatFee2').innerHTML = 0;
            document.getElementById('withdrawFiatTotal2').innerHTML = 0;
            document.getElementById('withdrawFiatTotal2').setAttribute("dataNumber", 0);
            if (document.getElementById('FiatPortfolio').getAttribute('accidReal') == 0) {
                //accountsGenerate(document.getElementById('FiatPortfolio').getAttribute('icCur'), 'Fiat', 'Ret')
            }
            else {
                withdrawFiatButton()
            }
        }
    });

    //Confirm Fiat Retiro
    document.getElementById('wdFiatbutton').addEventListener("click", function () {
        verifywdFiatbutton()
    });

    //Confirm Fiat Retiro
    document.getElementById('wdFiatbutton2').addEventListener("click", function () {
        //verifywdFiatbutton2()
    });

    // Anular Fiat
    document.getElementById('wdFiatbuttonA').addEventListener("click", function () {
        var req = {
            'id': document.getElementsByClassName('withdrawFiatConfirm')[0].getAttribute('tridWI'),
            'sessionid': sessionStorage.getItem('sessionid')
        }
        transactionsCancel(req)
    });

    // Anular Fiat p2p
    document.getElementById('wdFiatbuttonA2').addEventListener("click", function () {
        var req = {
            'id': document.getElementsByClassName('withdrawFiatConfirm2')[0].getAttribute('tridWI'),
            'sessionid': sessionStorage.getItem('sessionid')
        }
        transactionsCancel(req)
    });

    // Validar Fiat
    document.getElementById('wdFiatbuttonV').addEventListener("click", function () {
        verifywdFiatbuttonV()
    });

    // Validar Fiat
    document.getElementById('wdFiatbuttonV2').addEventListener("click", function () {
        verifywdFiatbuttonV2()
    });


    // Retirar BTC
    document.getElementById('withdrawBTC').addEventListener("click", function () {
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {

            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        } else {
            document.getElementById('withdrawBTCAmount').value = ''
            document.getElementById('withdrawBTCAmount').setAttribute("dataNumber", "");
            document.getElementById('withdrawBTCWallet').value = ''
            document.getElementById('withdrawBTCFee').innerHTML = '0'
            document.getElementById('withdrawBTCTotal').innerHTML = '0'
            document.getElementById('withdrawBTCTotal').style.color = "#262624"
            accountsEntry(document.getElementById('BTCPortfolio').getAttribute('accidreal'), 'withdrawBTC')
        }
    });

    //Confirm BTC Retiro
    document.getElementById('wdBTCbutton').addEventListener("click", function () {
        verifywdBTCbutton();
    });

    // Anular BTC
    document.getElementById('wdBTCbuttonA').addEventListener("click", function () {
        document.getElementsByTagName('body')[0].classList.remove('hidden')
        var req = {
            'id': document.getElementsByClassName('withdrawBTCConfirm')[0].getAttribute('tridWI'),
            'sessionid': sessionStorage.getItem('sessionid')
        }
        transactionsCancel(req)
    });

    // Validar BTC
    document.getElementById('wdBTCbuttonV').addEventListener("click", function () {
        verifywdBTCbuttonV();
    });

    // Salir de inf Movimiento Fiat
    document.getElementById('detailFiatButton').addEventListener("click", function () {
        document.getElementsByClassName('movDetailFiat')[0].style.display = "none"
        document.getElementsByClassName('movVES')[0].style.display = "table"
    });


    // Transferir BTC
    document.getElementById('transferBTC').addEventListener("click", function () {
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {

            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        } else {
            document.getElementById('transferBTCAmount').value = '';
            document.getElementById('transferBTCAmount').setAttribute("dataNumber", "");
            document.getElementById('transferBTCEmail').value = '';
            document.getElementById('transferBTCFee').innerHTML = '0';
            document.getElementById('transferBTCTotal').innerHTML = '0';
            accountsEntry(document.getElementById('BTCPortfolio').getAttribute('accidreal'), 'transferBTC');
        }
    });
    // Transferir BTC
    document.getElementById('transferFiat').addEventListener("click", function () {
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {

            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        } else {
            document.getElementById('transferBTCAmount').value = '';
            document.getElementById('transferBTCAmount').setAttribute("dataNumber", "");
            document.getElementById('transferBTCEmail').value = '';
            document.getElementById('transferBTCFee').innerHTML = '0';
            document.getElementById('transferBTCTotal').innerHTML = '0';
            accountsEntry(document.getElementById('FiatPortfolio').getAttribute('accidreal'), 'transferFiat');
        }
    });

    //Confirm BTC Transferencia
    document.getElementById('trBTCbutton').addEventListener("click", function () {
        xferBTC()
    });

    // Anular BTC
    document.getElementById('trBTCbuttonA').addEventListener("click", function () {
        var req = {
            'id': document.getElementsByClassName('transferBTCConfirm')[0].getAttribute('tridWI'),
            'sessionid': sessionStorage.getItem('sessionid')
        }
        transactionsCancel(req)
    });

    // Validar BTC
    document.getElementById('trBTCbuttonV').addEventListener("click", function () {
        verifytrBTCbuttonV()
    });

    // Movimientos BTC 
    document.getElementById('movButtonBTC').addEventListener("click", function () {
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {
            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        } else {
            seeMovements(document.getElementById("BTCPortfolio").getAttribute("accidReal"), 'BTC')
        }
    });

    // Movimientos BTC Back
    document.getElementById('movBTCBack').addEventListener("click", function () {
        document.getElementsByClassName('movBTC')[0].style.display = "none"
        document.getElementsByTagName('body')[0].classList.remove('hidden')
    });

    // Movimientos VES 
    document.getElementById('movButtonVES').addEventListener("click", function () {
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {
            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        } else {
            if (document.getElementById('FiatPortfolio').getAttribute('accidReal') == 0) {
                //accountsGenerate(document.getElementById('FiatPortfolio').getAttribute('icCur'), 'Fiat', 'Mov')
            }
            else {
                seeMovements(document.getElementById("FiatPortfolio").getAttribute("accidReal"), 'FIAT')
            }
        }
    });

    // Disabled VES
    document.getElementById('movButtonDisabled').addEventListener("click", function () {
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {
            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        } else {
            var interf = document.getElementById("disabledPortfolio").getAttribute("interface");
            var accid = document.getElementById("disabledPortfolio").getAttribute("accidReal");
            if (accid != 0 && accid !== null && accid !== undefined) {
                if (interf == 4 || interf == 5 || interf == 7 || interf == 6) {
                    seeMovements(document.getElementById("disabledPortfolio").getAttribute("accidReal"), 'BTC')
                } else if (interf == 1 || interf == 2) {
                    seeMovements(document.getElementById("disabledPortfolio").getAttribute("accidReal"), 'FIAT')
                }
            }
        }
    });

    // Movimientos VES Back
    document.getElementById('movVESBack').addEventListener("click", function () {
        document.getElementsByClassName('movVES')[0].style.display = "none"
        document.getElementsByTagName('body')[0].classList.remove('hidden')
    });

    // Finalizar success
    document.getElementById('wdFiatbuttonF').addEventListener("click", function () {
        document.getElementsByClassName('success')[0].style.display = "none"
        document.getElementsByTagName('body')[0].classList.remove('hidden')
    });

    // Finalizar success yellow
    document.getElementById('wdFiatbuttonFYellow').addEventListener("click", function () {
        document.getElementsByClassName('success')[1].style.display = "none"
        document.getElementsByTagName('body')[0].classList.remove('hidden')
    });

    // Finalizar fail
    document.getElementById('wdFiatbuttonI').addEventListener("click", function () {
        document.getElementsByClassName('failure')[0].style.display = "none"
        document.getElementsByTagName('body')[0].classList.remove('hidden')
        document.getElementById('failureMsg').innerHTML = ''
        document.getElementById('failureTitle').innerHTML = getLangById('FailedTransaction')[lang]
        document.getElementById('wdFiatbuttonI').innerHTML = getLangById('TRYAGAIN')[lang]
    });

    // Abrir address AFX - BTC
    document.getElementById('addressBTC').addEventListener("click", function () {
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {
            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        } else {
            if (document.getElementById('BTCPortfolio').getAttribute('accidReal') == 0) {
                //accountsGenerate(document.getElementById('BTCPortfolio').getAttribute('icCur'), 'BTC')
            }
            else {
                putInformationWalletBTC(document.getElementById('BTCPortfolio').getAttribute('accidReal'))

            }
            //AGREGADO NUEVO
            req = {
                'sessionid': sessionStorage.getItem('sessionid'),
                'currencyid': document.getElementById('BTCPortfolio').getAttribute('icCur'),
            }
            feesEntry(req, 'depositBTC');
        }
    });

    // Cerrar address AFX - BTC
    document.getElementById('addressBTCInfBack').addEventListener("click", function () {
        document.getElementsByClassName('addressBTCInf')[0].style.display = "none"
        document.getElementsByTagName('body')[0].classList.remove('hidden')
    });
    // Valor inicial

    // copyBtc
    document.getElementById('copyIconBtc').addEventListener("click", function () {
        document.getElementById('copyDepBTC').select();
        document.execCommand('copy');
    });

    // copyFiat
    document.getElementById('copyIconFiat').addEventListener("click", function () {
        document.getElementById('copyDepFiat').select();
        document.execCommand('copy');
    });


    // Cerrar Depositar Fiat
    document.getElementById('depFiatAccept').addEventListener("click", function () {
        depositFiat()
    });

    document.getElementById('depFiatDep').addEventListener("click", function () {
        depositFiatPM()
        //document.getElementsByClassName('depFiatInf')[0].style.display = "none"
        //document.getElementsByTagName('body')[0].classList.remove('hidden')
    });

    document.getElementById('wdFiatbutton2').addEventListener("click", function () {
        wFiatPM()
        //document.getElementsByClassName('depFiatInf')[0].style.display = "none"
        //document.getElementsByTagName('body')[0].classList.remove('hidden')
    });

    // Tab 1 Retiro Fiat
    document.getElementById('reportDTFiat').addEventListener("click", function () {
        openTabFiat('reportDTFiat', 'depTr')
    });

    // Tab 2 Retiro Fiat
    document.getElementById('p2cfiat').addEventListener("click", function (e) {
        if (isBPWorks) {
            //DESHABILITADO PRD
            openTabFiat('p2cfiat', 'p2c');
            e.preventDefault();
            return false;
        } else {
            e.preventDefault();
            return false;
        }
    });

    // Tab 1 Retiro Fiat
    document.getElementById('reportDTFiat2').addEventListener("click", function () {
        openTabFiat('reportDTFiat2', 'depTr2')
    });

    // Tab 2 Retiro Fiat
    document.getElementById('p2cfiat2').addEventListener("click", function (e) {
        if (isBPWorks && isBPInterface) {
            //DESHABILITADO PRD
            openTabFiat('p2cfiat2', 'p2c2');
            e.preventDefault();
            return false;
        } else {
            e.preventDefault();
            return false;
        }

    });

    // Abrir Depositar Fiat
    document.getElementById('depFiat').addEventListener("click", function () {
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {
            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        } else {
            depositsAccounts(document.getElementById('FiatPortfolio').getAttribute('icCur'))
        }
    });

    // Add file
    document.addEventListener('change', function (evt) {
        if (evt.target.className === 'file') {
            var valid = validarFile(evt.target)
            if (valid) {
                document.getElementById('edepFiatInfRec').style.display = 'none';
                if (evt.target.files[0].name !== getLangById('var27')[lang] || evt.target.files[0].name !== 'Seleccione') {

                    // Asignar el nombre y color
                    evt.target.offsetParent.previousElementSibling.children[0].textContent = evt.target.files[0].name
                    evt.target.offsetParent.previousElementSibling.children[0].style.color = "#262624"
                }
            }

        }
    });

    document.addEventListener('click', function (evt) {
        if (evt.target.className === 'clickClose') {
            closeAllPop();
        }
    });

    document.getElementById('depFiatInfDestinationBank1').addEventListener("change", function () {
        if (document.getElementById('depFiatInfDestinationBank1').value != '') {
            putDepositDataFiat(document.getElementById('depFiatInfDestinationBank1').value);
        }
    });

    document.getElementById('withdrawFiatAccount').addEventListener("change", function () {
        if (document.getElementById('withdrawFiatAccount').value != '') {
            document.getElementById("withdrawFiatAccount").classList.remove("selectwdFiatBank");
            document.getElementById("withdrawFiatAccount").classList.add("selectwdFiat");
        }
    });

    document.getElementById('withdrawFiatAccount2').addEventListener("change", function () {
        if (document.getElementById('withdrawFiatAccount2').value != '') {
            document.getElementById("withdrawFiatAccount2").classList.remove("selectwdFiatBank");
            document.getElementById("withdrawFiatAccount2").classList.add("selectwdFiat");
        }
    });

    // Remove red errors in Deposit Fiat
    now = new Date();
    nowDate = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate()
    document.getElementsByTagName('body')[0].addEventListener("click", function () {
        if (document.getElementById('depFiatInfAmount').value !== '') {
            noError('depFiatInfAmount', 'edepFiatInfAmount')
            document.getElementById('edepFiatInfAmount').style.display = 'none'
        }

        if (document.getElementById('depFiatInfAmountPM').value !== '') {
            noError('depFiatInfAmountPM', 'edepFiatInfAmountPM')
            document.getElementById('edepFiatInfAmountPM').style.display = 'none'
        }

        if (document.getElementById('depFiatInfDestinationBank1').value !== '') {
            document.getElementById('depFiatInfDestinationBank1').style.border = "1px solid #D5DCE5 !important";
            document.getElementById("depFiatInfDestinationBank1").classList.remove("selectwdFiatBank");
            document.getElementById("depFiatInfDestinationBank1").classList.add("selectwdFiat");
            document.getElementById('edepFiatInfDestinationBank1').innerHTML = '';
            document.getElementById('edepFiatInfDestinationBank1').style.display = 'none'
        }

        if (document.getElementById('depFiatInfDestinationBank2').value !== '') {
            document.getElementById('depFiatInfDestinationBank2').style.border = "1px solid #D5DCE5 !important";
            document.getElementById("depFiatInfDestinationBank2").classList.remove("selectwdFiatBank");
            document.getElementById("depFiatInfDestinationBank2").classList.add("selectwdFiat");
            document.getElementById('edepFiatInfDestinationBank2').innerHTML = '';
            document.getElementById('edepFiatInfDestinationBank2').style.display = 'none'
        }

        if (document.getElementById('depFiatInfDate').value !== '' && now.getTime() >= new Date(document.getElementById('depFiatInfDate').value).getTime()) {
            noError('depFiatInfDate', 'edepFiatInfDate')
            document.getElementById('edepFiatInfDate').style.display = 'none'
        }
        if (document.getElementById('depFiatInfRef').value !== '') {
            noError('depFiatInfRef', 'edepFiatInfRef')
            document.getElementById('edepFiatInfRef').style.display = 'none'
        }
        if (document.getElementById('depFiatInfId').value !== '') {
            noError('depFiatInfRec', 'edepFiatInfRec')
            document.getElementById('edepFiatInfRec').style.display = 'none'
        }

        if (document.getElementById('depFiatInfCIPM').value !== '') {
            noError('depFiatInfCIPM', 'edepFiatInfCIPM')
            document.getElementById('edepFiatInfCIPM').style.display = 'none'
        }

        if (document.getElementById('depFiatInfAmountPM22').value !== '') {
            noError('depFiatInfAmountPM22', 'edepFiatInfAmountPM22')
            document.getElementById('edepFiatInfAmountPM22').style.display = 'none'
        }

        if (document.getElementById('depFiatInfPhonePM').value !== '') {
            noError('depFiatInfPhonePM', 'edepFiatInfPhonePM')
            document.getElementById('edepFiatInfPhonePM').style.display = 'none'
        }
        if (document.getElementById('codePM').value !== '') {
            noError('codePM', 'ecodePM')
            document.getElementById('ecodePM').style.display = 'none'
        }
    });

    // Remove red errors in Withd BTC
    document.getElementsByTagName('body')[0].addEventListener("click", function () {
        if (document.getElementById('withdrawBTCAmount').value !== '' && parseFloat(document.getElementById('withdrawBTCAmount').getAttribute("dataNumber")) <= parseFloat(document.getElementById('withdrawBTCBalance').getAttribute('numberAmount'))
            && document.getElementById('withdrawBTCFee').innerHTML <= document.getElementById('withdrawBTCAmount').value) {
            noError('withdrawBTCAmount', 'ewithdrawBTCAmount')
            document.getElementById('ewithdrawBTCAmount').style.display = 'none'
        }
        if ((document.getElementById('withdrawBTCWallet').value !== '') && onlyAlphanumeric(document.getElementById('withdrawBTCWallet'))) {
            noError('withdrawBTCWallet', 'ewithdrawBTCWallet')
            document.getElementById('ewithdrawBTCWallet').style.display = 'none'
        }

        if (document.getElementById('withdrawBTCConfirmCode').value != '') {
            noError('withdrawBTCConfirmCode', 'ewithdrawBTCConfirmCode')
            document.getElementById('ewithdrawBTCConfirmCode').style.display = 'none'
        }
    });

    // Remove red errors in Withd Fiat
    document.getElementsByTagName('body')[0].addEventListener("click", function () {
        if (document.getElementById('withdrawFiatAmount').value !== '' && parseFloat(document.getElementById('withdrawFiatAmount').getAttribute("dataNumber")) <= parseFloat(document.getElementById('withdrawFiatBalance').getAttribute('numberAmount'))) {
            noError('withdrawFiatAmount', 'ewithdrawFiatAmount')
            document.getElementById('ewithdrawFiatAmount').style.display = 'none'
        }
        if (document.getElementById('withdrawFiatAccount').value !== '') {
            noError('withdrawFiatAccount', 'ewithdrawFiatAccount')
            document.getElementById('ewithdrawFiatAccount').style.display = 'none'
        }
        if (document.getElementById('withdrawFiatAccount2').value !== '') {
            noError('withdrawFiatAccount2', 'ewithdrawFiatAccount2')
            document.getElementById('ewithdrawFiatAccount2').style.display = 'none'
        }
        if (document.getElementById('withdrawFiatConfirmCode').value != '') {
            noError('withdrawFiatConfirmCode', 'ewithdrawFiatConfirmCode')
            document.getElementById('ewithdrawFiatConfirmCode').style.display = 'none'
        }

        if (document.getElementById('withdrawFiatConfirmCode2').value != '') {
            noError('withdrawFiatConfirmCode2', 'ewithdrawFiatConfirmCode2')
            document.getElementById('ewithdrawFiatConfirmCode2').style.display = 'none'
        }

        if (document.getElementById('withdrawFiatAmount2').value != '') {
            noError('withdrawFiatAmount2', 'ewithdrawFiatAmount2')
            document.getElementById('ewithdrawFiatAmount2').style.display = 'none'
        }

        if (document.getElementById('depFiatInfPhonePM2').value != '' && document.getElementById('phoneNumberPM').value != '') {
            //noError('depFiattPhonePM22','edepFiattPhonePM22')
            document.getElementById('edepFiattPhonePM22').style.display = 'none'
        }

    });

    // Remove red errors in Xfer BTC
    document.getElementsByTagName('body')[0].addEventListener("click", function () {
        if (document.getElementById('transferBTCAmount').getAttribute("dataNumber") !== '' && parseFloat(document.getElementById('transferBTCAmount').getAttribute("dataNumber")) <= parseFloat(document.getElementById('transferBTCBalance').getAttribute('numberAmount'))) {
            noError('transferBTCAmount', 'etransferBTCAmount')
            document.getElementById('etransferBTCAmount').style.display = 'none'
        }
        if (document.getElementById('transferBTCEmail').value != '' && document.getElementById('transferBTCEmail').validity.valid) {
            noError('transferBTCEmail', 'etransferBTCEmail');
            document.getElementById('etransferBTCEmail').style.display = 'none'
        }
    });

    document.getElementById('movDetailFiatSeeComprobant').addEventListener("click", function () {
        if (document.getElementById("movDetailFiatSeeComprobant").getAttribute("comp") != 'undefined')
            window.open(document.getElementById('movDetailFiatSeeComprobant').getAttribute('comp'), '_blank');
    });

    document.getElementById('withdrawBTCConfirmResend').addEventListener("click", function () {
        var req = {
            'id': document.getElementsByClassName('withdrawBTCConfirm')[0].getAttribute('tridwi'),
            'sessionid': sessionStorage.getItem('sessionid')
        }

        transactionsValidation(req)
    });

    document.getElementById('withdrawFiatConfirmResend').addEventListener("click", function () {
        var req = {
            'id': document.getElementsByClassName('withdrawFiatConfirm')[0].getAttribute('tridwi'),
            'sessionid': sessionStorage.getItem('sessionid')
        }

        transactionsValidation(req)
    });

    document.getElementById('withdrawFiatConfirmResend2').addEventListener("click", function () {
        var req = {
            'id': document.getElementsByClassName('withdrawFiatConfirm2')[0].getAttribute('tridwi'),
            'sessionid': sessionStorage.getItem('sessionid')
        }

        transactionsValidation(req)
    });


    if (getBrowserInfo().startsWith('Chrome')) {
        document.getElementById('canBTC').style.marginRight = '20px'
        //document.getElementById('datBTC').parentNode.style.width = '27%'
        document.getElementById('amountVES').style.marginRight = '22px'
    }

    document.getElementById('transferBTCConfirmResend').addEventListener("click", function () {
        var req = {
            'id': document.getElementsByClassName('transferBTCConfirm')[0].getAttribute('tridwi'),
            'sessionid': sessionStorage.getItem('sessionid')
        }

        transactionsValidation(req)
    });

    document.getElementById("resend").addEventListener("click", function () {
        if (document.getElementById("movDetailFiatSeeComprobant").getAttribute("comp") != 'undefined')
            document.getElementById("movDetailFiatSeeComprobant").dispatchEvent(new Event("click"));
    });

    if (document.getElementById('BuyAndSellSelect').value == '2' || document.getElementById('BuyAndSellSelect').value == '3') {

        if (document.getElementById('BuyAndSellSelect').value == '2') {

            document.getElementById('orderSell').classList.remove('redButton');
            document.getElementById('orderSell').classList.add('grayButton');
            document.getElementById('orderSell').disabled = true;
            document.getElementById('orderBuy').classList.remove('grayButton');
            document.getElementById('orderBuy').classList.add('greenButton');
            document.getElementById('orderBuy').disabled = false;

        } else if (document.getElementById('BuyAndSellSelect').value == '3') {

            document.getElementById('orderBuy').classList.remove('greenButton');
            document.getElementById('orderBuy').classList.add('grayButton');
            document.getElementById('orderBuy').disabled = true;
            document.getElementById('orderSell').classList.remove('grayButton');
            document.getElementById('orderSell').classList.add('redButton');
            document.getElementById('orderSell').disabled = false;

        }

        document.getElementById('BuyAndSellPrice').disabled = true;
        //document.getElementById('BuyAndSellPrice').style.color = '#5C5D60 !important'
        document.getElementById('BuyAndSellPrice').classList.add('BuyAndSellDivInputSp')
        document.getElementById('BuyAndSellPrice').classList.remove('BuyAndSellDivInput')
        document.getElementById('BuyAndSellTextLeftPrice').innerHTML = getLangById('var4')[lang]
        document.getElementById('tooltip').addEventListener("click", function () {
            var popup = document.getElementById("tooltip").children[0];
            popup.classList.toggle("show");
        });

    }
    else {
        document.getElementById('BuyAndSellPrice').disabled = false;
        document.getElementById('BuyAndSellPrice').classList.remove('BuyAndSellDivInputSp')
        document.getElementById('BuyAndSellPrice').classList.add('BuyAndSellDivInput')
        document.getElementById('BuyAndSellTextLeftPrice').innerHTML = '<p class="poppins-medium">' + getLangById('price')[lang] + '</p>'

        document.getElementById('orderBuy').classList.remove('grayButton');
        document.getElementById('orderBuy').classList.add('greenButton');
        document.getElementById('orderBuy').disabled = false;
        document.getElementById('orderSell').classList.remove('grayButton');
        document.getElementById('orderSell').classList.add('redButton');
        document.getElementById('orderSell').disabled = false;

    }

    document.getElementById('BuyAndSellSelect').addEventListener("change", function () {
        if (document.getElementById('BuyAndSellSelect').value == '2' || document.getElementById('BuyAndSellSelect').value == '3') {

            if (document.getElementById('BuyAndSellSelect').value == '2') {

                document.getElementById('orderSell').classList.remove('redButton');
                document.getElementById('orderSell').classList.add('grayButton');
                document.getElementById('orderSell').disabled = true;
                document.getElementById('orderBuy').classList.remove('grayButton');
                document.getElementById('orderBuy').classList.add('greenButton');
                document.getElementById('orderBuy').disabled = false;

                document.getElementById('BuyAndSellPrice').value = (parseFloat(document.getElementById('cardBuyAndSellSell').getAttribute('number')))


            } else if (document.getElementById('BuyAndSellSelect').value == '3') {

                document.getElementById('orderBuy').classList.remove('greenButton');
                document.getElementById('orderBuy').classList.add('grayButton');
                document.getElementById('orderBuy').disabled = true;
                document.getElementById('orderSell').classList.remove('grayButton');
                document.getElementById('orderSell').classList.add('redButton');
                document.getElementById('orderSell').disabled = false;

                document.getElementById('BuyAndSellPrice').value = (parseFloat(document.getElementById('cardBuyAndSellBuy').getAttribute('number')))

            }

            document.getElementById('BuyAndSellPrice').classList.add('BuyAndSellDivInputSp')
            document.getElementById('BuyAndSellPrice').classList.remove('BuyAndSellDivInput')
            document.getElementById('BuyAndSellTextLeftPrice').innerHTML = getLangById('var4')[lang]
            document.getElementById('tooltip').addEventListener("click", function () {
                var popup = document.getElementById("tooltip").children[0];
                popup.classList.toggle("show");
            });


            //document.getElementById('BuyAndSellPrice').value = (parseFloat(document.getElementById('cardBuyAndSellBuy').getAttribute('number')) + parseFloat(document.getElementById('cardBuyAndSellSell').getAttribute('number')))/2

            document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", document.getElementById('BuyAndSellPrice').value);

            document.getElementById('BuyAndSellPrice').setAttribute("type", "text");
            document.getElementById('BuyAndSellPrice').value = number_format(document.getElementById('BuyAndSellPrice').getAttribute("dataNumber"), document.getElementById('BuyAndSellPrice').getAttribute("icDecim"));

            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('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('BuyAndSellNote').innerHTML = getLangById('var8')[lang] + document.getElementById('BuyAndSellPrice').value
            //document.getElementById('BuyAndSellNote').innerHTML = 'Comisión: ' + document.getElementById('BuyAndSellPrice').value
            document.getElementById('BuyAndSellPrice').disabled = true;
        }
        else {
            //document.getElementById('BuyAndSellNote').innerHTML = 'Nota'
            document.getElementById('BuyAndSellPrice').disabled = false;
            document.getElementById('BuyAndSellPrice').classList.remove('BuyAndSellDivInputSp')
            document.getElementById('BuyAndSellPrice').classList.add('BuyAndSellDivInput')
            document.getElementById('BuyAndSellTextLeftPrice').innerHTML = '<p class="poppins-medium">Precio</p>'

            document.getElementById('orderBuy').classList.remove('grayButton');
            document.getElementById('orderBuy').classList.add('greenButton');
            document.getElementById('orderBuy').disabled = false;
            document.getElementById('orderSell').classList.remove('grayButton');
            document.getElementById('orderSell').classList.add('redButton');
            document.getElementById('orderSell').disabled = false;
        }
        document.getElementById('BuyAndSellNote').innerHTML = setFeesOrders(document.getElementById('BuyAndSellSelect').value)
    })

    // Buy and Sell Input // Click in pairdetails
    document.getElementById('BuyAndSellPrice').setAttribute("icDecim", decimCoinCurrency);
    document.getElementById('BuyAndSellTotal').setAttribute("icDecim", decimCoinCurrency);
    document.getElementById('BuyAndSellAmount').setAttribute("icDecim", decimCoinRefCurrency);

    document.getElementById('BuyAndSellTotal').setAttribute("dataNumber", '');
    document.getElementById('BuyAndSellAmount').setAttribute("dataNumber", '');
    document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", '');

    document.getElementById('BuyAndSellTotal').value = number_format('', document.getElementById('BuyAndSellTotal').getAttribute("icDecim"));
    document.getElementById('BuyAndSellAmount').value = number_format('', document.getElementById('BuyAndSellAmount').getAttribute("icDecim"));
    document.getElementById('BuyAndSellPrice').value = number_format('', document.getElementById('BuyAndSellPrice').getAttribute("icDecim"));

    document.getElementById('BuyAndSellPrice').addEventListener("focus", function () {
        moveCursorToEnd(document.getElementById('BuyAndSellPrice'))
        //document.getElementById('BuyAndSellPrice').dispatchEvent(new Event(""))
    });

    document.getElementById('BuyAndSellPrice').addEventListener("focusin", function () {
        decimCoin = this.getAttribute("icDecim");
        if (document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") == 'NaN') {
            document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", '')
        }
    });

    document.getElementById('BuyAndSellTotal').addEventListener("focusin", function () {
        decimCoin = this.getAttribute("icDecim");
        if (document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") == 'NaN') {
            document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", '')
        }
    });

    document.getElementById('BuyAndSellAmount').addEventListener("focusin", function () {
        decimCoin = this.getAttribute("icDecim");
        if (document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") == 'NaN') {
            document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", '')
        }
    });

    // Price
    document.getElementById('BuyAndSellPrice').addEventListener("change", function () {
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency2(decimCoin, this.value);
        if (noVal !== "") this.value = noVal;
        //vars
        var qty, tot, price;
        qty = document.getElementById('BuyAndSellAmount');
        price = document.getElementById('BuyAndSellPrice');
        tot = document.getElementById('BuyAndSellTotal');
        price.setAttribute("dataNumber", price.value);
        var val, formatval;
        if (price.getAttribute("dataNumber") != '') {
            //Si los 3 están llenos en caso de precio se actualiza la cantidad.
            // O Si la cantidad está vacía y el total lleno, se actualiza la cantidad
            if ((tot.getAttribute("dataNumber") != '' && qty.getAttribute("dataNumber") != '') || (qty.getAttribute("dataNumber") == '' && tot.getAttribute("dataNumber") != '')) {
                val = (tot.getAttribute("dataNumber") / price.getAttribute("dataNumber"));
                formatval = formatCurrency2(qty.getAttribute("icDecim"), val.toString());
                qty.setAttribute("dataNumber", formatval);
                textval = number_format(formatval, qty.getAttribute("icDecim"));
                qty.setAttribute("type", "text");
                qty.value = textval;

            } else if (qty.getAttribute("dataNumber") !== '') {
                //Si la cantidad está llena y el total vacío se actualiza el total
                val = (qty.getAttribute("dataNumber") * price.getAttribute("dataNumber"));
                formatval = formatCurrency2(tot.getAttribute("icDecim"), val.toString());
                tot.setAttribute("dataNumber", formatval);
                textval = number_format(formatval, tot.getAttribute("icDecim"));
                tot.setAttribute("type", "text");
                tot.value = textval;
            }
        }
        if (document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") == 'NaN') {
            document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", '')
        }
    })
    // Total
    document.getElementById('BuyAndSellTotal').addEventListener("change", function () {
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency2(decimCoin, this.value);
        if (noVal !== "") this.value = noVal;
        //vars
        var qty, tot, price;
        qty = document.getElementById('BuyAndSellAmount');
        price = document.getElementById('BuyAndSellPrice');
        tot = document.getElementById('BuyAndSellTotal');
        tot.setAttribute("dataNumber", tot.value);
        var val, formatval;
        if (tot.getAttribute("dataNumber") != '') {
            //Si los 3 están llenos en caso de total se actualiza la cantidad.
            // O Si la cantidad está vacía y el precio está lleno, se actualiza la cantidad
            if ((price.getAttribute("dataNumber") != '' && qty.getAttribute("dataNumber") != '') || (qty.getAttribute("dataNumber") == '' && price.getAttribute("dataNumber") != '')) {
                val = (tot.getAttribute("dataNumber") / price.getAttribute("dataNumber"));
                formatval = formatCurrency2(qty.getAttribute("icDecim"), (val.noExponents()).toString())
                qty.setAttribute("dataNumber", formatval);
                //qty.dispatchEvent(new Event("focusin"));qty.dispatchEvent(new Event("focusout"));
                textval = number_format(formatval, qty.getAttribute("icDecim"));
                qty.setAttribute("type", "text");
                qty.value = textval;
            } else if (qty.getAttribute("dataNumber") !== '') {
                //Si la cantidad está llena y el precio vacío se actualiza el precio
                val = (tot.getAttribute("dataNumber") / qty.getAttribute("dataNumber"));
                formatval = formatCurrency2(price.getAttribute("icDecim"), val.toString());
                price.setAttribute("dataNumber", formatval);
                //price.dispatchEvent(new Event("focusin"));price.dispatchEvent(new Event("focusout"));
                textval = number_format(formatval, price.getAttribute("icDecim"));
                price.setAttribute("type", "text");
                price.value = textval;
            }
        }
        if (document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") == 'NaN') {
            document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", '')
        }
    })
    // Cantidad
    document.getElementById('BuyAndSellAmount').addEventListener("change", function () {
        if (document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") == 'NaN') {
            document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", '')
        }
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency2(decimCoin, this.value);
        if (noVal !== "") this.value = noVal;
        //vars
        var qty, tot, price;
        qty = document.getElementById('BuyAndSellAmount');
        price = document.getElementById('BuyAndSellPrice');
        tot = document.getElementById('BuyAndSellTotal');
        qty.setAttribute("dataNumber", qty.value);
        var val, formatval;
        if (qty.getAttribute("dataNumber") != '') {
            //Si los 3 están llenos en caso de precio se actualiza la cantidad.
            // O Si la cantidad está vacía y el total lleno, se actualiza la cantidad
            if ((tot.getAttribute("dataNumber") != '' && price.getAttribute("dataNumber") != '') || (tot.getAttribute("dataNumber") == '' && price.getAttribute("dataNumber") != '')) {
                val = (parseFloat(price.getAttribute("dataNumber")) * parseFloat(qty.getAttribute("dataNumber")));
                // Magui 
                //val = parseFloat(Math.round(parseFloat(val) * 100) / 100)
                val = parseFloat(val).toFixed(document.getElementById('BuyAndSellTotal').getAttribute('icdecim'));
                formatval = formatCurrency2(tot.getAttribute("icDecim"), val.toString());
                tot.setAttribute("dataNumber", formatval);
                textval = number_format(formatval, tot.getAttribute("icDecim"));
                tot.setAttribute("type", "text");
                tot.value = textval;
            } else if (tot.getAttribute("dataNumber") !== '') {
                //Si la cantidad está llena y el total vacío se actualiza el total
                val = (tot.getAttribute("dataNumber") / qty.getAttribute("dataNumber"));
                formatval = formatCurrency2(price.getAttribute("icDecim"), val.toString());
                price.setAttribute("dataNumber", formatval);
                //price.dispatchEvent(new Event("focusin"));price.dispatchEvent(new Event("focusout"));
                textval = number_format(formatval, price.getAttribute("icDecim"));
                price.setAttribute("type", "text");
                price.value = textval;
            }
        }
    })

    // See All Buy and Sell
    document.getElementById('markersSeeAll').addEventListener("click", function () {
        document.getElementById('markersSeeAll').classList.add('tablinksActive')
        document.getElementById('markersSeeMine').classList.remove('tablinksActive')
        var reqDashboardEntry = {
            'sessionid': sessionStorage.getItem('sessionid'),
            'ordernumofrec': 25,
            'exchangenumofrec': 25,
            'pairid': document.getElementById('pairName').getAttribute('pairId')
        }
        dashboardEntry(reqDashboardEntry, 'orders', 0)
    })

    document.addEventListener('click', function (evt) {
        if (evt.target.tagName != 'INPUT') {
            document.getElementById('BuyAndSellTotal').value = number_format(document.getElementById('BuyAndSellTotal').getAttribute("dataNumber"), document.getElementById('BuyAndSellTotal').getAttribute("icDecim"));
            document.getElementById('BuyAndSellAmount').value = number_format(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute("dataNumber")).noExponents(), document.getElementById('BuyAndSellAmount').getAttribute("icDecim"));
            document.getElementById('BuyAndSellPrice').value = number_format(document.getElementById('BuyAndSellPrice').getAttribute("dataNumber"), document.getElementById('BuyAndSellPrice').getAttribute("icDecim"));
        }
    })
    document.getElementById('markersSeeMine').addEventListener("click", function () {
        document.getElementById('markersSeeMine').classList.add('tablinksActive')
        document.getElementById('markersSeeAll').classList.remove('tablinksActive')
        var reqDashboardEntry = {
            'sessionid': sessionStorage.getItem('sessionid'),
            'ordernumofrec': 25,
            'exchangenumofrec': 25,
            'pairid': document.getElementById('pairName').getAttribute('pairId'),
            'ownorders': 1
        }
        dashboardEntry(reqDashboardEntry, 'orders', 1)

    })

    document.getElementById('chartSeeOne').addEventListener("click", function () {
        document.getElementById('chartSeeOne').classList.add('tablinksActive')
        document.getElementById('chartSeeTwo').classList.remove('tablinksActive')
        document.getElementById('chartSeeThree').classList.remove('tablinksActive')
        var reqDashboardEntry = {
            'sessionid': sessionStorage.getItem('sessionid'),
            'ordernumofrec': 25,
            'exchangenumofrec': 25,
            'pairid': document.getElementById('pairName').getAttribute('pairId'),
            'charttime': 1
        }
        dashboardEntry(reqDashboardEntry, 'chart', 1)

    });

    document.getElementById('chartSeeTwo').addEventListener("click", function () {
        document.getElementById('chartSeeOne').classList.remove('tablinksActive')
        document.getElementById('chartSeeTwo').classList.add('tablinksActive')
        document.getElementById('chartSeeThree').classList.remove('tablinksActive')
        var reqDashboardEntry = {
            'sessionid': sessionStorage.getItem('sessionid'),
            'ordernumofrec': 25,
            'exchangenumofrec': 25,
            'pairid': document.getElementById('pairName').getAttribute('pairId'),
            'charttime': 2
        }
        dashboardEntry(reqDashboardEntry, 'chart', 1)

    })

    document.getElementById('chartSeeThree').addEventListener("click", function () {
        document.getElementById('chartSeeOne').classList.remove('tablinksActive')
        document.getElementById('chartSeeTwo').classList.remove('tablinksActive')
        document.getElementById('chartSeeThree').classList.add('tablinksActive')
        var reqDashboardEntry = {
            'sessionid': sessionStorage.getItem('sessionid'),
            'ordernumofrec': 25,
            'exchangenumofrec': 25,
            'pairid': document.getElementById('pairName').getAttribute('pairId'),
            'charttime': 3
        }
        dashboardEntry(reqDashboardEntry, 'chart', 1)

    })


    // See All Exchange
    document.getElementById('exchangeSeeAll').addEventListener("click", function () {
        document.getElementById('exchangeSeeAll').classList.add('tablinksActive')
        document.getElementById('exchangeSeeMine').classList.remove('tablinksActive')
        var reqDashboardEntry = {
            'sessionid': sessionStorage.getItem('sessionid'),
            'ordernumofrec': 25,
            'exchangenumofrec': 25,
            'pairid': document.getElementById('pairName').getAttribute('pairId')
        }
        dashboardEntry(reqDashboardEntry, 'exchanges', 0)
    })

    // See Mine Exchange
    document.getElementById('exchangeSeeMine').addEventListener("click", function () {
        document.getElementById('exchangeSeeMine').classList.add('tablinksActive')
        document.getElementById('exchangeSeeAll').classList.remove('tablinksActive')
        var reqDashboardEntry = {
            'sessionid': sessionStorage.getItem('sessionid'),
            'ordernumofrec': 25,
            'exchangenumofrec': 25,
            'pairid': document.getElementById('pairName').getAttribute('pairId'),
            'ownexchange': 1
        }
        dashboardEntry(reqDashboardEntry, 'exchanges', 1)
    })

    // First dashboardEntry

    var reqDashboardEntry = {
        'sessionid': sessionStorage.getItem('sessionid'),
        'ordernumofrec': 25,
        'exchangenumofrec': 25
    }

    /*if(sessionStorage.getItem('pairid')){
        reqDashboardEntry.pairid = sessionStorage.getItem('pairid')
    }*/
    //dashboardEntry(reqDashboardEntry,'initial',0);

    // Order
    document.getElementById('orderBuy').addEventListener("click", function () {
        var hasAc = true;
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {

            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        } else {
            if (dashboardUpdate.dashboard.portfolio.accounts == null) {
                document.getElementById('failureMsg').innerHTML = getLangById('var5')[lang]
                document.getElementById('failureTitle').innerHTML = "Error"
                document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
                document.getElementsByClassName('failure')[0].style.display = "table"
            } else {
                for (var i = 0; i < dashboardUpdate.dashboard.portfolio.accounts.length; i++) {
                    if (dashboardUpdate.dashboard.portfolio.accounts[i].currency.id == document.getElementById('BuyAndSellTotal').getAttribute('currencyId')) {
                        if (dashboardUpdate.dashboard.portfolio.accounts[i].id == 0) {
                            hasAc = false;
                            document.getElementById('failureMsg').innerHTML = getLangById('var6')[lang] + document.getElementById('cardBuyAndSellPriceText').innerHTML + getLangById('var7')[lang]
                            document.getElementById('failureTitle').innerHTML = "Error"
                            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
                            document.getElementsByClassName('failure')[0].style.display = "table"
                        }
                        else {
                            if (dashboardUpdate.dashboard.portfolio.accounts[i].balance.number < parseFloat(document.getElementById('BuyAndSellTotal').getAttribute('dataNumber'))) {
                                document.getElementById('failureMsg').innerHTML = getLangById('var9')[lang]
                                document.getElementById('failureTitle').innerHTML = "Error"
                                document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
                                document.getElementsByClassName('failure')[0].style.display = "table"
                            }
                        }
                    }
                }
                if (document.getElementById('failureMsg').innerHTML != getLangById('var9')[lang]) {
                    if (document.getElementById('BuyAndSellSelect').value == 1) {
                        if (parseFloat(document.getElementById('BuyAndSellPrice').getAttribute('datanumber')) >= parseFloat(document.getElementById('cardBuyAndSellSell').getAttribute('number'))) {
                            if (document.getElementById('cardBuyAndSellSell').getAttribute('number') == 0 || document.getElementsByClassName('infOrderSell')[0].style.display == 'none') {
                                openConfirmOrder('bid')
                            } else {
                                document.getElementById('amountValidationText').children[0].innerHTML = getLangById('var10')[lang]
                                document.getElementById('amountValidationText').children[1].innerHTML = getLangById('var11')[lang]
                                document.getElementsByClassName('orderAttention')[0].style.display = "table"
                            }
                        } else {
                            if (hasAc) {
                                openConfirmOrder('bid')
                            }
                        }
                    } else {
                        if (hasAc) {
                            openConfirmOrder('bid')
                        }
                    }
                }
            }
        }
    });
    document.getElementById('orderSell').addEventListener("click", function () {
        var hasAc = true;
        var lvlno = 0;
        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
        if (parseFloat(lvlno) < 0.5) {

            document.getElementById('failureMsg').innerHTML = getLangById('var1')[lang]
            document.getElementById('failureTitle').innerHTML = getLangById('Attention')[lang]
            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
            document.getElementsByClassName('failure')[0].style.display = "table"
        }
        else {
            if (dashboardUpdate.dashboard.portfolio.accounts == null) {
                document.getElementById('failureMsg').innerHTML = getLangById('var5')[lang]
                document.getElementById('failureTitle').innerHTML = "Error"
                document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
                document.getElementsByClassName('failure')[0].style.display = "table"
            } else {
                for (var i = 0; i < dashboardUpdate.dashboard.portfolio.accounts.length; i++) {
                    if (dashboardUpdate.dashboard.portfolio.accounts[i].currency.id == document.getElementById('BuyAndSellAmount').getAttribute('currencyId')) {
                        if (dashboardUpdate.dashboard.portfolio.accounts[i].id == 0) {
                            hasAc = false;
                            document.getElementById('failureMsg').innerHTML = getLangById('var6')[lang] + document.getElementById('cardBuyAndSellAmountText').innerHTML + getLangById('var7')[lang]
                            document.getElementById('failureTitle').innerHTML = "Error"
                            document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
                            document.getElementsByClassName('failure')[0].style.display = "table"
                        } else {
                            if (dashboardUpdate.dashboard.portfolio.accounts[i].balance.number < parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('dataNumber'))) {
                                document.getElementById('failureMsg').innerHTML = getLangById('var9')[lang]
                                document.getElementById('failureTitle').innerHTML = "Error"
                                document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
                                document.getElementsByClassName('failure')[0].style.display = "table"
                            }
                        }
                    }
                }
                if (document.getElementById('failureMsg').innerHTML != getLangById('var9')[lang]) {
                    if (document.getElementById('BuyAndSellSelect').value == 1) {
                        if (parseFloat(document.getElementById('BuyAndSellPrice').getAttribute('datanumber')) <= parseFloat(document.getElementById('cardBuyAndSellBuy').getAttribute('number'))) {
                            document.getElementById('amountValidationText').children[0].innerHTML = getLangById('var12')[lang]
                            document.getElementById('amountValidationText').children[1].innerHTML = getLangById('var13')[lang]
                            document.getElementsByClassName('orderAttention')[0].style.display = "table"
                        } else {
                            if (hasAc) {
                                openConfirmOrder('ask')
                            }
                        }
                    } else {
                        if (hasAc) {
                            openConfirmOrder('ask')
                        }
                    }
                }
            }
        }
    });

    document.getElementById('confirmOrderContinue').addEventListener("click", function () {
        makeOrder()
    });

    document.getElementById('confirmOrderCancel').addEventListener("click", function () {
        document.getElementById('messageInfCountdown').innerHTML = getLangById('var14')[lang]
        document.getElementsByClassName('confirmOrder')[0].style.display = "none"
        document.getElementsByTagName('body')[0].classList.remove('hidden')
    });

    document.getElementById('orderAttentionContinue').addEventListener("click", function () {
        document.getElementsByClassName('orderAttention')[0].style.display = "none"
        openConfirmOrderToMarket(document.getElementById('amountValidationText').children[0].innerHTML == 'venta' ? 'ask' : 'bid')
    });

    document.getElementById('orderAttentionCancel').addEventListener("click", function () {
        document.getElementsByClassName('orderAttention')[0].style.display = "none"
    });


    document.getElementById('totalPortfolioSel').addEventListener("change", function () {
        document.getElementById("totalPortfolioAmountTotal").innerText = this.options[this.selectedIndex].getAttribute("total");

        /*
        var reqDashboardEntry = {
            'sessionid': sessionStorage.getItem('sessionid'),
            'ordernumofrec': 25,
            'exchangenumofrec': 25,
            'pairid' : document.getElementById('pairName').getAttribute('pairId')
        }
        dashboardEntry(reqDashboardEntry,'portfolioTotal',0)*/

    })

    // Session Update


    // Step
    document.getElementById('floatButton').addEventListener("click", function () {
        var popup = document.getElementById("floatButton").children[0].children[0];
        if (popup.classList.contains('show')) {
            gotoPage('step', 'main', "")
            sessionValidUpdate(1)
            view = 1
        } else {
            popup.classList.toggle("show");
        }
    })

    //Mostrar HTML cargado
    esconderHTML(false);

    init()

    var fieldAmo = ["withdrawBTCAmount", "transferBTCAmount", "depFiatInfAmount", "depFiatInfAmountPM", "withdrawFiatAmount", "BuyAndSellPrice", "BuyAndSellAmount", "BuyAndSellTotal", "withdrawFiatAmount2"];
    //var fieldAmo = ["withdrawBTCAmount","transferBTCAmount","depFiatInfAmount","withdrawFiatAmount"];
    formatAmount(fieldAmo);

    //Funcion en el main para dar formato a campos
    //var fields = ["withdrawBTCAmount"];
    //var format = ["amountBTC"];
    //formatFields2(fields,format);

    //#NEW EVENTOS BOTONES DEL BANER
    document.getElementById("completeNow").addEventListener("click", function () {
        if (entrydata.type.id == 1) {
            goToRegisterPerson(entrydata.person.step)
        } else {
            goToRegisterCompany(entrydata.company.step);
        }
    });
    document.getElementById("completeThen").addEventListener("click", function () {
        var regBanner = document.getElementById("regBanner");
        var height = document.getElementsByTagName("header")[0].offsetHeight;
        var pg = document.getElementsByClassName("pageCnt")[0];
        regBanner.style.top = "";
        pg.style.marginTop = "";
        setTimeout(function () {
            pg.classList.remove("regBannerPag");
            regBanner.classList.remove("regBannerActv");
        }, 500);
    });


}
function goToRegisterPerson(numberStep) {
    switch (numberStep) {
        case 0:
            gotoPage('kyc', 'regC', "");
            break;
        case 1:
            gotoPage('kyc', 'natInitialLvl', "");
            break;
        case 2:
            gotoPage('kyc', 'natBasicLvl', "");
            break;
        case 3:
            gotoPage('kyc', 'natMiddleLvl', "");
            break;
        case 4:
            gotoPage('kyc', 'natAdvancedLvl', "");
            break;
    }
}

function goToRegisterCompany(numberStep) {
    switch (numberStep) {
        case 0:
            gotoPage('kyc', 'regC', "");
            break;
        case 1:
            gotoPage('kyc', 'jurInitBasic', "");
            break;
        case 2:
            gotoPage('kyc', 'jurInitReg', "");
            break;
        case 3:
            gotoPage('kyc', 'jurInitPrtnrs', "");
            break;
        case 4:
            gotoPage('kyc', 'jurInitEconom', "");
            break;
        case 5:
            gotoPage('kyc', 'jurInitImgs', "");
            break;
        case 6:
            gotoPage('kyc', 'jurMiddleLvl', "");
            break;
        case 7:
            gotoPage('kyc', 'jurAdvancedLvl', "");
            break;
    }
}

function drawCanvas() {

    /* CANVA */
    canvas = document.getElementById('canvasId');
    canvas.width = document.getElementById('divCanva').clientWidth;
    canvas.height = document.getElementById('divCanva').clientHeight;
    ctx = document.getElementById('canvasId').getContext('2d');
    canvas.addEventListener('mousemove', function (evt) {

        let ySize = parseFloat(canvas.width / 12);
        let xSize = parseFloat(canvas.height / 11);

        var mousePos = getMousePos(canvas, evt);

        if (((parseFloat(mousePos.x) >= ySize) && (parseFloat(mousePos.x) <= canvas.width - ySize)) && ((parseFloat(mousePos.y) >= xSize) && (parseFloat(mousePos.y) <= canvas.height - xSize))) {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            canvas.style.cursor = 'crosshair'
            ctx.setLineDash([0, 0]);
            if (dashboardUpdate) {
                chargeChart(dashboardUpdate.dashboard.chart)
            }

            ctx.setLineDash([2, 4]);
            ctx.lineWidth = 2;
            ctx.strokeStyle = '#D5DCE5'
            ctx.fillStyle = '#D5DCE5';
            ctx.beginPath();

            // Horizontal
            ctx.moveTo(mousePos.x, xSize)
            ctx.lineTo(mousePos.x, xSize * 10)

            // Vertical
            ctx.moveTo(ySize, mousePos.y)
            ctx.lineTo(ySize * 11, mousePos.y)

            ctx.stroke();

            // x y width height

            // Cuadros de informacion

            // Left
            ctx.setLineDash([0, 0]);
            ctx.moveTo(canvas.width - xSize, mousePos.y)
            ctx.beginPath();
            ctx.lineWidth = "4";
            ctx.strokeStyle = "#4F555B";
            ctx.fillStyle = '#4F555B'
            ctx.fillRect(canvas.width - ySize * 12, mousePos.y - xSize / 3, ySize, xSize / 1.5); // sin el *12
            ctx.stroke();

            // Right
            ctx.setLineDash([0, 0]);
            ctx.moveTo(canvas.width - xSize, mousePos.y)
            ctx.beginPath();
            ctx.lineWidth = "4";
            ctx.strokeStyle = "#4F555B";
            ctx.fillStyle = '#4F555B'
            ctx.fillRect(canvas.width - ySize, mousePos.y - xSize / 3, ySize, xSize / 1.5);
            ctx.stroke();

            let arrayDates = getArrayLegendCalculateDate(dashboardUpdate.dashboard.chart.bars.records, dashboardUpdate.dashboard.chart.timeframe)
            let miniBLock = ySize / 6 // LO que de este numero coloco la fecha

            // Bottom
            if (blocksDate(arrayDates, miniBLock, mousePos.x - ySize) != '') {
                ctx.moveTo(mousePos.x, canvas.height - ySize)
                ctx.beginPath();
                ctx.lineWidth = "4";
                ctx.strokeStyle = "#4F555B";
                ctx.fillStyle = '#4F555B'
                ctx.fillRect(mousePos.x - ySize, canvas.height - xSize, ySize * 2, xSize + xSize / 4);
                ctx.stroke();
            }

            yPlot = 9.15
            xPlot = 10

            let arrayBars = getArrayLegendCalculateBars(dashboardUpdate.dashboard.chart.bars.max * 2)
            // text x y
            ctx.font = 'normal 10px Roboto';
            ctx.textAlign = 'right';
            ctx.fillStyle = 'white';
            ctx.fillText(arrayBars[parseInt(mousePos.y)], blocks(0.9, 'X'), mousePos.y + xSize / 6);
            ctx.stroke();

            let arrayLines = getArrayLegendCalculateLines(dashboardUpdate.dashboard.chart.lines.max * 1.05)
            ctx.font = 'normal 10px Roboto';
            ctx.textAlign = 'left';
            ctx.fillStyle = 'white';
            ctx.fillText(arrayLines[parseInt(mousePos.y)], blocks(11.1, 'X'), mousePos.y + xSize / 6);
            ctx.stroke();

            ctx.font = 'normal 12px Roboto';
            ctx.textAlign = 'center';
            ctx.fillStyle = 'white';
            ctx.fillText(blocksDate(arrayDates, miniBLock, mousePos.x - ySize), mousePos.x, blocks(10.8, 'Y'));
            ctx.stroke();

        } else {
            document.getElementById('canvasId').style.cursor = 'initial'
            ctx.clearRect(0, 0, canvas.width, canvas.height);

            ctx.setLineDash([0, 0]);
            if (dashboardUpdate) {
                chargeChart(dashboardUpdate.dashboard.chart)
            }
        }
    }, false);
}

function init() {
    // Call Entry 
    setLang()
}




function collapseSection(element, iconid) {

    document.getElementById(iconid).classList.remove('fa-minus-circle')
    document.getElementById(iconid).classList.add('fa-plus-circle')

    var sectionHeight = element.scrollHeight;

    var elementTransition = element.style.transition;
    element.style.transition = '';

    requestAnimationFrame(function () {
        element.style.height = sectionHeight + 'px';
        element.style.transition = elementTransition;

        requestAnimationFrame(function () {
            element.style.height = 50 + 'px';
        });
    });

    element.setAttribute('data-collapsed', 'true');
}

function expandSection(element, height, iconid) {

    document.getElementById(iconid).classList.remove('fa-plus-circle')
    document.getElementById(iconid).classList.add('fa-minus-circle')

    var sectionHeight = element.scrollHeight;
    element.style.height = height + 'px';

    element.addEventListener('transitionend', function (e) {
        element.removeEventListener('transitionend', arguments.callee);
    });
    element.setAttribute('data-collapsed', 'false');
}


function openTabFiat(name, nametab) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabDepFiatContent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    tablinks = document.getElementsByClassName("tablinksDepFiat");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    document.getElementById(nametab).style.display = "block";
    document.getElementById(name).className += " active";

}

function changeDivs() {

    var card2 = document.getElementById('divCard2')
    var card7 = document.getElementById('divCard7')
    var card4 = document.getElementById('divCard4')
    var card6 = document.getElementById('divCard6')

    var clone2 = card2.cloneNode(true)
    var clone7 = card7.cloneNode(true)
    var clone4 = card4.cloneNode(true)
    var clone6 = card6.cloneNode(true)

    // Cambiar
    card2.innerHTML = clone4.innerHTML
    card7.innerHTML = clone6.innerHTML
    card4.innerHTML = clone7.innerHTML
    card6.innerHTML = clone2.innerHTML

    //card4.innerHTML = clone2.innerHTML

    var tableOrderSell = document.getElementById('tableOrderSell')
    var clontableOrderSell = tableOrderSell.cloneNode(true)
    document.getElementById('tableOrderBuy').style.display = 'table'
    document.getElementById('tableOrderBuy').style.width = '100%'
    document.getElementById('tableOrderBuy').style.borderRight = 'none'
    document.getElementById('tableOrderSell').style.display = 'table'
    document.getElementById('tableOrderSell').style.width = '100%'
    document.getElementById('tableOrderSell').style.direction = 'rtl'

    // Minimize card 3 - Portfolio
    document.getElementById('iconRightCard3').addEventListener("click", function () {
        var card = document.getElementById('card3')
        var isCollapsed = card.getAttribute('data-collapsed') === 'true';

        if (isCollapsed) {
            expandSectionR(card, 'iconRightCard3', 3)
            card.setAttribute('data-collapsed', 'false')
        } else {
            collapseSectionR(card, 'iconRightCard3', 3)
        }
    });

    // Minimize card 4 - Sell and Buy
    document.getElementById('iconRightCard4').addEventListener("click", function () {
        var card = document.getElementById('card4')
        var isCollapsed = card.getAttribute('data-collapsed') === 'true';

        if (isCollapsed) {
            expandSectionR(card, 'iconRightCard4', 4)
            card.setAttribute('data-collapsed', 'false')
        } else {
            collapseSectionR(card, 'iconRightCard4', 4)
        }
    });

    document.getElementById('tableOrderBuy').children[1].style.marginLeft = 'auto'
    document.getElementById('tableOrderBuy').children[1].style.marginRight = 'auto'

    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[0].classList.add('w30')
    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[1].classList.add('w30')
    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[2].classList.add('w30')
    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[3].classList.add('w7')
    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[4].classList.add('w3')

    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[3].classList.remove('pr2')

    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[0].classList.remove('w18')
    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[1].classList.remove('w33')
    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[2].classList.remove('w33')
    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[3].classList.remove('w13')
    document.getElementById('tableOrderSell').children[1].children[0].children[0].children[4].classList.remove('w3')


    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[0].classList.add('w30')
    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[1].classList.add('w30')
    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[2].classList.add('w30')
    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[3].classList.add('w7')
    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[4].classList.add('w3')

    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[3].classList.remove('pr2')

    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[0].classList.remove('w18')
    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[1].classList.remove('w33')
    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[2].classList.remove('w33')
    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[3].classList.remove('w13')
    document.getElementById('tableOrderSell').children[1].children[1].children[0].children[4].classList.remove('w3')

    // Minimize card 6 - Orders Book
    document.getElementById('iconRightCard6').addEventListener("click", function () {
        var card = document.getElementById('card6')
        var isCollapsed = card.getAttribute('data-collapsed') === 'true';

        if (isCollapsed) {
            expandSectionR(card, 'iconRightCard6', 6)
            card.setAttribute('data-collapsed', 'false')
        } else {
            collapseSectionR(card, 'iconRightCard6', 6)
        }
    });

    document.getElementById('tableExchange').children[0].children[1].children[0].children[0].classList.remove('w10')
    document.getElementById('tableExchange').children[0].children[1].children[0].children[1].classList.remove('w30')
    document.getElementById('tableExchange').children[0].children[1].children[0].children[2].classList.remove('w30')
    document.getElementById('tableExchange').children[0].children[1].children[0].children[3].classList.remove('w30')


    document.getElementById('tableExchange').children[0].children[1].children[0].children[0].classList.add('w4')
    document.getElementById('tableExchange').children[0].children[1].children[0].children[1].classList.add('w34')
    document.getElementById('tableExchange').children[0].children[1].children[0].children[2].classList.add('w31')
    document.getElementById('tableExchange').children[0].children[1].children[0].children[3].classList.add('w31')

    // Minimize card 7 - Exchange
    document.getElementById('iconRightCard7').addEventListener("click", function () {
        var card = document.getElementById('card7')
        var isCollapsed = card.getAttribute('data-collapsed') === 'true';

        if (isCollapsed) {
            expandSectionR(card, 'iconRightCard7', 7)
            card.setAttribute('data-collapsed', 'false')
        } else {
            collapseSectionR(card, 'iconRightCard7', 7)
        }
    });



    // Minimize card 2
    document.getElementById('iconRightCard2').addEventListener("click", function () {
        var card = document.getElementById('card2')
        var isCollapsed = card.getAttribute('data-collapsed') === 'true';
        if (isCollapsed) {
            expandSectionR(card, 'iconRightCard2', 2)
            card.setAttribute('data-collapsed', 'false')
        } else {
            collapseSectionR(card, 'iconRightCard2', 2)
        }
    });

    // Minimize card 5
    document.getElementById('iconRightCard5').addEventListener("click", function () {
        var card = document.getElementById('card5')
        var isCollapsed = card.getAttribute('data-collapsed') === 'true';

        if (isCollapsed) {
            expandSection(card, 352, 'iconRightCard5')
            card.setAttribute('data-collapsed', 'false')
        } else {
            collapseSection(card, 'iconRightCard5')
        }
    });


}

function collapseSectionR(element, iconid, number) {

    document.getElementById(iconid).classList.remove('fa-minus-circle')
    document.getElementById(iconid).classList.add('fa-plus-circle')

    var sectionHeight = element.scrollHeight;

    var elementTransition = element.style.transition;
    element.style.transition = '';

    requestAnimationFrame(function () {
        element.style.height = sectionHeight + 'px';
        element.style.transition = elementTransition;

        requestAnimationFrame(function () {
            element.style.height = 50 + 'px';
        });

    });

    element.setAttribute('data-collapsed', 'true');
}

function expandSectionR(element, iconid, number) {
    document.getElementById(iconid).classList.remove('fa-plus-circle')
    document.getElementById(iconid).classList.add('fa-minus-circle')

    var sectionHeight = element.scrollHeight;
    element.classList.remove('minimizeHeightR')
    element.style.height = null

    element.addEventListener('transitionend', function (e) {
        element.removeEventListener('transitionend', arguments.callee);
    });
    element.setAttribute('data-collapsed', 'false');
}

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 = ""
                }
                sessionValidUpdate(0)
                entrydata = (JSON.parse(rsp).entry);
                //#NEW Se agregó que si se valida que el nivel del usuario es 0 o 0.5 se muestre el banner de invitación al registro
                var regBanner = document.getElementById("regBanner");
                var height = document.getElementsByTagName("header")[0].offsetHeight;
                var pg = document.getElementsByClassName("pageCnt")[0];
                document.getElementById('bannerInfo').innerHTML = getLangById('bannerInfo')[lang];
                document.getElementById('completeNow').innerHTML = getLangById('completeNow')[lang];
                document.getElementById('completeThen').innerHTML = getLangById('completeThen')[lang];
                var validStep = false;
                if (entrydata.type.id == 1) {
                    if (entrydata.person.step < 5) validStep = true;
                } else {
                    if (entrydata.company.step < 8) validStep = true;
                }
                if ((entrydata.level.id < '0.5' && validStep) || (entrydata.level.id == 0 && validStep)) {
                    if (entrydata.declaration !== "" && entrydata.declaration !== null) {
                        document.getElementById('bannerInfo').innerHTML = getLangById('bannerInfo2')[lang];
                        document.getElementById('completeNow').innerHTML = getLangById('completeNow2')[lang];
                        document.getElementById('completeThen').innerHTML = getLangById('completeThen2')[lang];
                    }
                    regBanner.classList.add("regBannerActv");
                    pg.classList.add("regBannerPag");
                    setTimeout(function () {
                        pg.style.marginTop = ((regBanner.offsetHeight) + height) + "px";
                        regBanner.style.top = height + "px";
                    }, 200);
                } else {
                    regBanner.style.top = "";
                    pg.style.marginTop = "";
                    setTimeout(function () {
                        pg.classList.remove("regBannerPag");
                        regBanner.classList.remove("regBannerActv");
                    }, 500);
                }


                putName(entrydata);
                document.getElementsByClassName('pageCnt')[0].style.visibility = "visible"

                var reqDashboardEntry = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'ordernumofrec': 25,
                    'exchangenumofrec': 25
                }
                dashboardEntry(reqDashboardEntry, 'initial', 0);
                break;
            case 204:
                break;
            case 400:
                break;
            case 401:
                document.getElementsByClassName('pageCnt')[0].style.visibility = "visible"
                // Window Load
                var waitScreen = document.getElementById("waitScreen");
                document.body.removeChild(waitScreen);
                WS_waitscreen = false;
                expiredSession();
                break;
            case 500:
                // Error
                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 listDraw(rsp, changeName) {
    var tbl;
    var node;
    if (changeName === 'markers') {
        tbl = document.getElementsByClassName("card2")[0];
        var node = tbl.lastElementChild.cloneNode(true);
        //tbl.children[3].innerHTML = "";
    }

    if (changeName === 'exchange') {
        tbl = document.getElementById("tableExchange");
        var node = tbl.children[0].children[0].children[1].cloneNode(true);
        var header = tbl.children[0].children[0].children[0].cloneNode(true);
        tbl.children[0].children[0].innerHTML = "";
        tbl.children[0].children[0].appendChild(header);
    }
    if (changeName === 'data') {
        if (screen.width > 700) {
            tbl = document.getElementById("imovBTC").children[0];
            var node = tbl.children[0].cloneNode(true);
            tbl.children[0].innerHTML = "";
        } else {
            document.getElementById("imovBTC").style.display = 'none'
            document.getElementById("imovBTCR").style.display = 'block'
            tbl = document.getElementById("imovBTCR").children[0];
            var node = tbl.children[0].cloneNode(true);
            tbl.children[0].innerHTML = "";
        }
    }
    if (changeName === 'dataFiat') {
        if (screen.width > 700) {
            tbl = document.getElementById("imovVES").children[0];
            var node = tbl.children[0].cloneNode(true);
            tbl.children[0].innerHTML = "";
        } else {
            document.getElementById("imovVES").style.display = 'none'
            document.getElementById("imovVESR").style.display = 'block'
            tbl = document.getElementById("imovVESR").children[0];
            var node = tbl.children[0].cloneNode(true);
            tbl.children[0].innerHTML = "";
        }
    }
    if (changeName === 'portfolio') {
        tbl = document.getElementsByClassName("card3")[0];
        var node = tbl.children[3].cloneNode(true);

        var portBox = node.cloneNode(true);
        portBox.innerHTML = "";
    }
    var tmp = null; tmp = node.cloneNode(true);
    //tbl.children[2].innerHTML = "";
    if (changeName === 'markers') {
        //tbl.removeChild(document.getElementById('tableMarks'))   
    }
    if (changeName === 'portfolio') {
        //tbl.children[3].removeChild(document.getElementById('tablePortfolio'))           
    }
    if (changeName === 'data') {
        //tbl.removeChild(document.getElementById('movBTCid'))   
        tbl.innerHTML = ''
    }
    if (changeName === 'dataFiat') {
        //tbl.removeChild(document.getElementById('movVESid'))   
        tbl.innerHTML = ''
    }
    if (!(rsp.length > 0)) {
        var ele = null;
        ele = tmp.cloneNode(true);
        ele.style.display = "none";
        tbl.appendChild(ele);
    } else {
        for (var i = 0; i < rsp.length; i++) {
            var ele = null;
            ele = tmp.cloneNode(true);
            ele.style.display = "table";
            if (rsp[i].name !== "") {
                if (changeName === 'markers') {
                    /*
                    ele.children[0].children[0].setAttribute("src",rsp[i].src);
                    ele.children[1].children[0].textContent = rsp[i].name
                    ele.children[2].children[0].textContent = rsp[i].ult
                    ele.children[3].children[0].textContent = rsp[i].day
                    ele.setAttribute('name',rsp[i].name)
                    ele.setAttribute('currencyId',rsp[i].id)
                    if(rsp[i].color === 'green'){
                        ele.children[3].children[0].style.color="#85BB4F"
                    }else{
                        ele.children[3].children[0].style.color="#C04F5D"
                    }
                    ele.children[4].children[0].textContent = rsp[i].vol   
                    ele.children[1].children[0].addEventListener("click",function(e){
                        if(e.srcElement.parentNode.parentNode.getAttribute('name')=='BTC'){
                            //markersListArray = {};
                            var currency;
                            var refCurrency;
                            for (var i = 0; i < markersListArray.numofrecords ; i++){
                                if (markersListArray.records[i].currency.symbol == 'BTC'){
                                    currency = markersListArray.records[i].refcurrency
                                }
                                else if (markersListArray.records[i].refcurrency.symbol == 'BTC'){
                                    refCurrency = markersListArray.records[i].currency
                                }
                            }
                            accountsPortfolio(5,currency,refCurrency)

                            // Pinta 
                        }
                        if(e.srcElement.parentNode.parentNode.getAttribute('name')=='PTR'){
                            //markersListArray = {};
                            var currency;
                            var refCurrency;
                            for (var i = 0; i < markersListArray.numofrecords ; i++){
                               //console.log(markersListArray)
                                if (markersListArray.records[i].currency.symbol == 'PTR'){
                                    currency = markersListArray.records[i].refcurrency
                                    refcurrency = markersListArray.records[i].currency
                                }
                                else if (markersListArray.records[i].refcurrency.symbol == 'PTR'){
                                    refCurrency = markersListArray.records[i].currency
                                    currency = markersListArray.records[i].refcurrency
                                }
                            }
                            accountsPortfolio(6,currency,refCurrency)

                            // Pinta 
                        }
                        
                    })
                    ele.children[2].children[0].addEventListener("click",function(e){
                       //console.log(e.srcElement.parentNode.parentNode.getAttribute('name'))
                    })
                    ele.children[3].children[0].addEventListener("click",function(e){
                       //console.log(e.srcElement.parentNode.parentNode.getAttribute('name'))
                    })
                    tbl.appendChild(ele);*/
                }
                if (changeName === 'portfolio') {
                    //ele.children[0].children[0].children[0].setAttribute("src",rsp[i].src);
                    ele.children[0].children[1].children[0].textContent = rsp[i].name
                    ele.children[0].children[2].children[0].textContent = (rsp[i].amount == 0 ? number_format(rsp[i].amount, rsp[i].decimals) : rsp[i].amount)
                    ele.children[0].children[3].children[0].textContent = rsp[i].ptc
                    var findIcon = false;
                    ele.children[0].children[0].children[0].style.backgroundImage = "";
                    for (var j = 0; j < icons.length; j++) {
                        if (icons[j].name == rsp[i].icon) {
                            ele.children[0].children[0].children[0].style.backgroundImage = 'url(' + icons[j].url + ')';
                            findIcon = true;
                        }
                    }
                    if (findIcon == false) {
                        ele.children[0].children[0].children[0].removeAttribute('style')
                    }
                    ele.children[0].children[0].children[0].style.cursor = 'pointer'
                    ele.children[0].children[1].children[0].style.cursor = 'pointer'
                    ele.children[0].children[2].children[0].style.cursor = 'pointer'
                    ele.children[0].children[3].children[0].style.cursor = 'pointer'
                    ele.children[0].setAttribute("accidPosition", i);
                    ele.children[0].setAttribute("accidReal", rsp[i].id);
                    ele.children[0].setAttribute("icCur", rsp[i].currencyid);
                    ele.children[0].setAttribute("icDecim", rsp[i].decimals);
                    ele.children[0].setAttribute("icSym", rsp[i].name);
                    ele.children[0].setAttribute("interface", rsp[i].interface);
                    ele.children[0].setAttribute("status", rsp[i].status);
                    ele.children[0].setAttribute("xfer", rsp[i].xfer);
                    ele.children[0].addEventListener("click", function (e) {
                        decimCoin = this.getAttribute("icDecim");//Visualización de decimales

                        //AGREGADA AQUÍ LA VALIDACIÓN CON MONEDAS CORREGIDO DESPUES DE CAMBIOS SIDNEY
                        if (this.getAttribute("interface") == 4 || this.getAttribute("interface") == 5
                            || this.getAttribute("interface") == 6 || this.getAttribute("interface") == 7
                        ) {
                            //VEO QUE MAGI HACE 2 PORTAFOLIOS DISTINTOS (3 SI CONSIDERAMOS EL DESACTIVADO) 
                            //AGREGO EL MANEJO SEGÚN CORRESPONDE
                            if (this.getAttribute("xfer") == 1) {
                                //Siempre se usa la pantalla transfer BTC
                                document.getElementById("transferBTC").getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                                document.getElementById("transferBTC").style.display = "";
                            } else {
                                document.getElementById("transferBTC").parentElement.parentElement.style.display = "none";
                            }

                            //Se pinta la moneda que corresponde en los botones
                            document.getElementById("addressBTC").getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                            document.getElementById("withdrawBTC").getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                            document.getElementById("movButtonBTC").getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                            document.getElementById("movButtonDisabled").getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");

                            //PINTAR LOS TITULOS DE LAS PANTALLAS CON LA CRIPTO SELECCIONADA
                            var criptoTit = document.getElementsByClassName("titCripto");
                            if (criptoTit.length > 0) {
                                for (var i = 0; i < criptoTit.length; i++) {
                                    criptoTit[i].getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                                }
                            }

                            //PINTAR LOS SUBTITULOS DE LAS PANTALLAS SI ES USDT
                            var criptoSubTit = document.getElementsByClassName("subtitUSDT");
                            if (criptoSubTit.length > 0) {
                                for (var i = 0; i < criptoSubTit.length; i++) {
                                    if (this.getAttribute("interface") == 6) {
                                        criptoSubTit[i].innerHTML = getLangById('subUSDT')[lang];
                                    } else {
                                        criptoSubTit[i].innerHTML = "";
                                    }
                                }
                            }

                            if (this.getAttribute("status") == 1) {
                                var ele = e.srcElement;
                                if (!ele.classList.contains("tablePortfolio")) ele = e.srcElement.parentNode.parentNode;

                                document.getElementById("BTCPortfolio").setAttribute("accidReal", ele.getAttribute('accidReal'));
                                document.getElementById("BTCPortfolio").setAttribute("icCur", ele.getAttribute('icCur'));
                                document.getElementById("BTCPortfolio").setAttribute("icDecim", ele.getAttribute('icDecim'));
                                document.getElementById("BTCPortfolio").setAttribute("interface", ele.getAttribute('interface'));

                                document.getElementById('BTCPortfolio').style.display = 'table'
                                document.getElementById('PortfolioName').style.display = 'none'
                                document.getElementById('PortfolioScroll').style.display = 'none'
                                document.getElementById('totalPortfolio').style.display = 'none'
                                document.getElementById('BTCPortfolio').children[0].children[0].children[0].addEventListener("click", function (e) {
                                    document.getElementById('BTCPortfolio').style.display = 'none'
                                    document.getElementById('PortfolioName').style.display = 'table'
                                    document.getElementById('PortfolioScroll').style.display = 'table'
                                    document.getElementById('totalPortfolio').style.display = 'table'
                                });

                            } else {

                                document.getElementById("disabledPortfolio").setAttribute("accidReal", e.srcElement.parentNode.parentNode.getAttribute('accidReal'));
                                document.getElementById("disabledPortfolio").setAttribute("icCur", e.srcElement.parentNode.parentNode.getAttribute('icCur'));
                                document.getElementById("disabledPortfolio").setAttribute("icDecim", e.srcElement.parentNode.parentNode.getAttribute('icDecim'));
                                document.getElementById("disabledPortfolio").setAttribute("interface", e.srcElement.parentNode.parentNode.getAttribute('interface'));

                                document.getElementById('disabledPortfolio').style.display = 'table'
                                document.getElementById('PortfolioName').style.display = 'none'
                                document.getElementById('PortfolioScroll').style.display = 'none'
                                document.getElementById('totalPortfolio').style.display = 'none'
                                document.getElementById('disabledPortfolio').children[0].children[0].children[0].addEventListener("click", function (e) {
                                    document.getElementById('disabledPortfolio').style.display = 'none'
                                    document.getElementById('PortfolioName').style.display = 'table'
                                    document.getElementById('PortfolioScroll').style.display = 'table'
                                    document.getElementById('totalPortfolio').style.display = 'table'
                                })
                            }
                        }
                        else if (this.getAttribute("interface") == 1 || this.getAttribute("interface") == 2) {
                            if (this.getAttribute("xfer") == 1) {
                                //PINTAR LOS TITULOS DE LAS PANTALLAS CON LA CRIPTO SELECCIONADA SE PINTAN LOS DE CRIPTO PARA USAR EL MODAL DE TRANSFERENCIAS
                                var criptoTit = document.getElementsByClassName("titCripto");
                                if (criptoTit.length > 0) {
                                    for (var i = 0; i < criptoTit.length; i++) {
                                        criptoTit[i].getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                                    }
                                }
                                //Siempre se usa la pantalla transfer BTC
                                document.getElementById("transferFiat").getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                                document.getElementById("transferFiat").style.display = "";
                            } else {
                                document.getElementById("transferFiat").parentElement.parentElement.style.display = "none";
                            }


                            var fiatTit = document.getElementsByClassName("titFiat");
                            if (fiatTit.length > 0) {
                                for (var i = 0; i < fiatTit.length; i++) {
                                    fiatTit[i].getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                                }
                            }
                            document.getElementById("depFiat").getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                            document.getElementById("withdrawFiat").getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                            document.getElementById("movButtonVES").getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");
                            document.getElementById("movButtonDisabled").getElementsByTagName("span")[0].innerHTML = this.getAttribute("icSym");

                            if (e.srcElement.parentNode.parentNode.getAttribute('accidReal') == 0) {
                                //accountsGenerate(e.srcElement.parentNode.parentNode.getAttribute('icCur'))
                            }

                            if (this.getAttribute("status") == 1) {
                                var ele = e.srcElement;
                                if (!ele.classList.contains("tablePortfolio")) ele = e.srcElement.parentNode.parentNode;
                                document.getElementById("FiatPortfolio").setAttribute("accidReal", ele.getAttribute('accidReal'));
                                document.getElementById("FiatPortfolio").setAttribute("icCur", ele.getAttribute('icCur'));
                                document.getElementById("FiatPortfolio").setAttribute("icDecim", ele.getAttribute('icDecim'));
                                document.getElementById("FiatPortfolio").setAttribute("interface", ele.getAttribute('interface'));

                                document.getElementById('FiatPortfolio').style.display = 'table'
                                document.getElementById('PortfolioName').style.display = 'none'
                                document.getElementById('PortfolioScroll').style.display = 'none'
                                document.getElementById('totalPortfolio').style.display = 'none'
                                document.getElementById('FiatPortfolio').children[0].children[0].children[0].addEventListener("click", function (e) {
                                    document.getElementById('FiatPortfolio').style.display = 'none'
                                    document.getElementById('PortfolioName').style.display = 'table'
                                    document.getElementById('PortfolioScroll').style.display = 'table'
                                    document.getElementById('totalPortfolio').style.display = 'table'
                                });

                            } else {

                                document.getElementById("disabledPortfolio").setAttribute("accidReal", e.srcElement.parentNode.parentNode.getAttribute('accidReal'));
                                document.getElementById("disabledPortfolio").setAttribute("icCur", e.srcElement.parentNode.parentNode.getAttribute('icCur'));
                                document.getElementById("disabledPortfolio").setAttribute("icDecim", e.srcElement.parentNode.parentNode.getAttribute('icDecim'));
                                document.getElementById("disabledPortfolio").setAttribute("interface", e.srcElement.parentNode.parentNode.getAttribute('interface'));

                                document.getElementById('disabledPortfolio').style.display = 'table'
                                document.getElementById('PortfolioName').style.display = 'none'
                                document.getElementById('PortfolioScroll').style.display = 'none'
                                document.getElementById('totalPortfolio').style.display = 'none'
                                document.getElementById('disabledPortfolio').children[0].children[0].children[0].addEventListener("click", function (e) {
                                    document.getElementById('disabledPortfolio').style.display = 'none'
                                    document.getElementById('PortfolioName').style.display = 'table'
                                    document.getElementById('PortfolioScroll').style.display = 'table'
                                    document.getElementById('totalPortfolio').style.display = 'table'
                                })
                            }
                        }
                    });
                    portBox.appendChild(ele.children[0]);
                }
                if (changeName === 'exchange') {
                    ele.style.display = "";
                    if (rsp[i].color === 'red') {
                        ele.children[0].innerHTML = '<i class="fas fa-caret-down" style="color: #C04F5D"></i>'
                    }
                    else if (rsp[i].color === 'green') {
                        ele.children[0].innerHTML = '<i class="fas fa-caret-up" style="color: #85BB4F"></i>'
                    }
                    else if (rsp[i].color === 'none') {
                        ele.children[0].innerHTML = '<i class="fas fa-caret-up" style="color: #2F3236"></i>'
                    }
                    ele.children[1].textContent = rsp[i].date
                    ele.children[2].textContent = rsp[i].total
                    ele.children[3].textContent = rsp[i].price
                    tbl.children[0].children[0].appendChild(ele);
                }
                if (changeName === 'data') {
                    if (rsp[i].status == 'green') {
                        ele.children[0].children[0].innerHTML = '<i class="fas fa-check-circle" style="font-size: 55%; top: -4px; position: relative; color: #85BB4F"></i>'
                    }
                    else if (rsp[i].status == 'red') {
                        ele.children[0].children[0].innerHTML = '<i class="fas fa-times-circle" style="font-size: 55%; top: -4px; position: relative; color: #C04F5D"></i>'
                    }
                    else if (rsp[i].status == 'yellow') {
                        ele.children[0].children[0].innerHTML = '<i class="fas fa-pause-circle" style="font-size: 55%; top: -4px; position: relative; color: #f2c542"></i>'
                    }

                    if (screen.width > 700) {
                        ele.children[0].children[1].children[0].innerHTML = rsp[i].date
                        ele.children[0].children[2].children[0].innerHTML = rsp[i].id
                        ele.children[0].children[3].children[0].innerHTML = rsp[i].description
                        ele.children[0].children[4].children[0].innerHTML = fixDecimals(rsp[i].total)

                        // rsp[i].type == 3 -> Transferencia
                        if (rsp[i].type != 3 && rsp[i].optype != 'FEE') {
                            ele.children[0].children[5].innerHTML = '<i class="fas fa-external-link-alt" style="font-size: 50%; top: -4px; position: relative; color: #4287CE; cursor: pointer"></i>'
                            ele.children[0].children[5].children[0].setAttribute("id", rsp[i].id);
                            ele.children[0].children[5].children[0].setAttribute("txid", rsp[i].txid);
                            ele.children[0].children[5].children[0].addEventListener("click", function (e) {
                                openBlockChainPag(e.srcElement.getAttribute('txid'), document.getElementById('BTCPortfolio').getAttribute('interface'))
                            });
                        } else {
                            ele.children[0].children[5].innerHTML = ''
                        }

                        if (i % 2 != 0) {
                            ele.children[0].style.backgroundColor = 'rgba(245, 246, 248, 0.800000011920929)'
                        }
                        tbl.appendChild(ele);
                        if (getBrowserInfo().startsWith('Firefox')) {
                            if (rsp.length >= 10) {
                                document.getElementById('canBTC').style.marginRight = '18px'
                                document.getElementById('imovBTC').style.paddingRight = '10px'
                            }
                        }
                    } else {
                        ele.children[0].children[1].children[0].innerHTML = rsp[i].date + '<br>' + rsp[i].description
                        ele.children[0].children[2].children[0].innerHTML = 'TXID ' + rsp[i].id + '<br>' + fixDecimals(rsp[i].total)
                        if (rsp[i].type != 3 && rsp[i].optype != 'FEE') {
                            ele.children[0].children[3].innerHTML = '<i class="fas fa-external-link-alt" style="font-size: 50%; top: -4px; position: relative; color: #4287CE; cursor: pointer"></i>'
                            ele.children[0].children[3].children[0].setAttribute("id", rsp[i].id);
                            ele.children[0].children[3].children[0].setAttribute("txid", rsp[i].txid);
                            ele.children[0].children[3].children[0].addEventListener("click", function (e) {
                                openBlockChainPag(e.srcElement.getAttribute('txid'), document.getElementById('BTCPortfolio').getAttribute('interface'))
                            });
                        } else {
                            ele.children[0].children[3].innerHTML = ''
                        }


                        if (i % 2 != 0) {
                            ele.children[0].style.backgroundColor = 'rgba(245, 246, 248, 0.800000011920929)'
                        }
                        tbl.appendChild(ele);
                    }
                }
                if (changeName === 'dataFiat') {
                    ele.children[0].children[0].innerHTML = "";
                    if (rsp[i].status == 'green') {
                        ele.children[0].children[0].innerHTML = '<i class="fas fa-check-circle" style="font-size: 55%; top: -4px; position: relative; color: #85BB4F"></i>'
                    }
                    else if (rsp[i].status == 'red') {
                        ele.children[0].children[0].innerHTML = '<i class="fas fa-times-circle" style="font-size: 55%; top: -4px; position: relative; color: #C04F5D"></i>'
                    }
                    else if (rsp[i].status == 'yellow') {
                        ele.children[0].children[0].innerHTML = '<i class="fas fa-pause-circle" style="font-size: 55%; top: -4px; position: relative; color: #f2c542"></i>'
                    }
                    //SE AGREGÓ EXCLUSIÓN DE OJITO A MOVIMIENTOS DE COMISIÓN - JR
                    if (screen.width > 700) {
                        ele.children[0].children[1].children[0].innerHTML = rsp[i].date
                        ele.children[0].children[1].children[0].setAttribute("date", rsp[i].date);
                        ele.children[0].children[2].children[0].innerHTML = rsp[i].description
                        ele.children[0].children[3].children[0].innerHTML = fixDecimals(rsp[i].total)
                        ele.children[0].children[3].children[0].setAttribute("total", rsp[i].date);
                        /*if ((rsp[i].description == "Retiro" ||
                            rsp[i].description == "Comisión de Retiro" ||
                            rsp[i].description == "Depósito inicial de pruebas" ||
                            rsp[i].description == "Comisión de Depósito inicial de pruebas" ||
                            rsp[i].description == "Depósito" ||
                            rsp[i].description == "Comisión de Depósito") && !((rsp[i].description).indexOf("Comisión") >= 0)) {*/
                        if ((rsp[i].optype == 'DEP' || rsp[i].optype == "WITH") && rsp[i].imageview) {
                            ele.children[0].children[4].innerHTML = '<i class="fas fa-eye tableMovEye"></i>'
                            ele.children[0].children[4].children[0].setAttribute("id", rsp[i].id);
                            ele.children[0].children[4].children[0].addEventListener("click", function (e) {
                                openMovDetailFiat(e.srcElement.id)
                            });

                        } else {
                            ele.children[0].children[4].innerHTML = ''
                        }

                        if (i % 2 != 0) {
                            ele.children[0].style.backgroundColor = 'rgba(245, 246, 248, 0.800000011920929)'
                        }

                        tbl.appendChild(ele);
                        if (getBrowserInfo().startsWith('Firefox')) {
                            if (rsp.length >= 10) {
                                document.getElementById('amountVES').style.marginRight = '18px'
                                document.getElementById('imovVES').style.paddingRight = '15px'
                                document.getElementById('datVES').parentNode.style.width = '29%'
                            }
                        }

                        if (getBrowserInfo().startsWith('Chrome')) {
                            document.getElementById('datVES').parentNode.style.width = "29%"
                            if (rsp.length >= 10) {
                                document.getElementById('amountVES').style.marginRight = '22px'
                                document.getElementById('imovVES').style.paddingRight = '10px'
                            }
                        }
                    } else {
                        ele.children[0].children[1].children[0].innerHTML = rsp[i].date + '<br>' + rsp[i].description;
                        ele.children[0].children[2].children[0].innerHTML = fixDecimals(rsp[i].total);
                        /*if ((rsp[i].description == "Retiro" ||
                            rsp[i].description == "Comisión de Retiro" ||
                            rsp[i].description == "Depósito inicial de pruebas" ||
                            rsp[i].description == "Comisión de Depósito inicial de pruebas" ||
                            rsp[i].description == "Depósito" ||
                            rsp[i].description == "Comisión de Depósito") && !((rsp[i].description).indexOf("Comisión") >= 0)) {*/
                        if ((rsp[i].optype == 'DEP' || rsp[i].optype == "WITH") && rsp[i].imageview) {

                            ele.children[0].children[3].innerHTML = '<i class="fas fa-eye tableMovEye"></i>'
                            ele.children[0].children[3].children[0].setAttribute("id", rsp[i].id);
                            ele.children[0].children[3].children[0].addEventListener("click", function (e) {
                                openMovDetailFiat(e.srcElement.id)
                            });

                        } else {
                            ele.children[0].children[3].innerHTML = ''
                        }

                        if (i % 2 != 0) {
                            ele.children[0].style.backgroundColor = 'rgba(245, 246, 248, 0.800000011920929)'
                        }
                        tbl.appendChild(ele);
                    }

                }

            }

        }
        if (changeName === 'portfolio') {
            tbl.insertBefore(portBox, tbl.children[3]);
            tbl.removeChild(tbl.children[4]);
        }
    }
}

// Service markers/list
function markersList() {

    var sessionid = sessionStorage.getItem('sessionid')
    var order = 1 // Puede ser 1, 2, 3 o 4.
    var time; // Opcional
    var numofrec = 10; // Puede ser cualquiera

    var req = {
        'sessionid': sessionid,
        'order': order,
        'numofrec': numofrec
    }

    callWS('GET', 'markers/list', req, response);

    function response(status, rsp) {
        switch (status) {
            case 200:
                markersListArray = JSON.parse(rsp);
                drawMarkersList(markersListArray.records);
                // Dummy data. Solo funciona el 5
                //accountsPortfolio(5)
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

/**FUNCION AGREGADA LOS MARCADORES SE PINTAN DEL SERVICIO***/
function drawMarkersList(rsp, reason) {
    var tbl = document.getElementById("tableMarksCnt");
    var node = tbl.firstElementChild.cloneNode(true);
    var tmp = null; tmp = node.cloneNode(true);
    tbl.innerHTML = "";
    if (!(rsp.length > 0)) {
        var ele = null;
        ele = tmp.cloneNode(true);
        ele.style.display = "none";
        tbl.appendChild(ele);
    } else {
        for (var i = 0; i < rsp.length; i++) {
            var ele = null;
            ele = tmp.cloneNode(true);
            ele.style.display = "table";
            ele.setAttribute("parid", rsp[i].id);
            ele.setAttribute("currency", rsp[i].currency.symbol);
            ele.setAttribute("currencyid", rsp[i].currency.id);
            ele.setAttribute("currencydecim", rsp[i].currency.decimals);
            ele.setAttribute("refcurrency", rsp[i].refcurrency.symbol);
            ele.setAttribute("refcurrencyid", rsp[i].refcurrency.id);
            ele.setAttribute("refcurrencydecim", rsp[i].refcurrency.decimals);
            ele.classList.remove("parSelected");
            if (sessionStorage.getItem('pairid')) {
                if (sessionStorage.getItem('pairid') == rsp[i].id) {
                    ele.classList.add("parSelected");
                }
                /*
                ele.addEventListener("click",function(){
                    var prev = document.getElementsByClassName("parSelected");
                    if(prev.length>0)prev[0].classList.remove("parSelected");
                    ;
                    this.classList.add("parSelected");
                    var currency={};
                    currency.id = this.getAttribute("currencyid");
                    currency.symbol = this.getAttribute("currency");
                    currency.decimals = this.getAttribute("currencydecim");
                    var refcurrency={};
                    refcurrency.id = this.getAttribute("refcurrencyid");
                    refcurrency.symbol = this.getAttribute("refcurrency");
                    refcurrency.decimals = this.getAttribute("refcurrencydecim");
                    /**DEPENDIENDO DEL PAR SE LLAMA EL PORTAFOLIO **
                    //accountsPortfolio(this.getAttribute("parid"),currency,refcurrency);
                    
                    var reqDashboardEntry = {
                        'sessionid': sessionStorage.getItem('sessionid'),
                        'ordernumofrec': 25,
                        'exchangenumofrec': 25,
                        'pairid' : this.getAttribute("parid")
                    }
                    dashboardEntry(reqDashboardEntry,'portfolio',0);   
                });
            }else{
                ele.addEventListener("click",function(){
                    var prev = document.getElementsByClassName("parSelected");
                    if(prev.length>0)prev[0].classList.remove("parSelected");
                    this.classList.add("parSelected");
                    var currency={};
                    currency.id = this.getAttribute("currencyid");
                    currency.symbol = this.getAttribute("currency");
                    currency.decimals = this.getAttribute("currencydecim");
                    var refcurrency={};
                    refcurrency.id = this.getAttribute("refcurrencyid");
                    refcurrency.symbol = this.getAttribute("refcurrency");
                    refcurrency.decimals = this.getAttribute("refcurrencydecim");
                    //accountsPortfolio(this.getAttribute("parid"),currency,refcurrency);
                    
                    var reqDashboardEntry = {
                        'sessionid': sessionStorage.getItem('sessionid'),
                        'ordernumofrec': 25,
                        'exchangenumofrec': 25,
                        'pairid' : this.getAttribute("parid")
                    }
                    dashboardEntry(reqDashboardEntry,'portfolio',0);
                }); 
            }*
            ele.addEventListener("click",function(){
                var prev = document.getElementsByClassName("parSelected");
                if(prev.length>0)prev[0].classList.remove("parSelected");
                this.classList.add("parSelected");
                var currency={};
                currency.id = this.getAttribute("currencyid");
                currency.symbol = this.getAttribute("currency");
                currency.decimals = this.getAttribute("currencydecim");
                var refcurrency={};
                refcurrency.id = this.getAttribute("refcurrencyid");
                refcurrency.symbol = this.getAttribute("refcurrency");
                refcurrency.decimals = this.getAttribute("refcurrencydecim");
                //accountsPortfolio(this.getAttribute("parid"),currency,refcurrency);
                
                var reqDashboardEntry = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'ordernumofrec': 25,
                    'exchangenumofrec': 25,
                    'pairid' : this.getAttribute("parid")
                }
                dashboardEntry(reqDashboardEntry,'portfolio',0);
            }); 
        }else{
            ele.addEventListener("click",function(){
                var prev = document.getElementsByClassName("parSelected");
                if(prev.length>0)prev[0].classList.remove("parSelected");
                ;
                this.classList.add("parSelected");
                var currency={};
                currency.id = this.getAttribute("currencyid");
                currency.symbol = this.getAttribute("currency");
                currency.decimals = this.getAttribute("currencydecim");
                var refcurrency={};
                refcurrency.id = this.getAttribute("refcurrencyid");
                refcurrency.symbol = this.getAttribute("refcurrency");
                refcurrency.decimals = this.getAttribute("refcurrencydecim");
                /**DEPENDIENDO DEL PAR SE LLAMA EL PORTAFOLIO **
                //accountsPortfolio(this.getAttribute("parid"),currency,refcurrency);
                
                var reqDashboardEntry = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'ordernumofrec': 25,
                    'exchangenumofrec': 25,
                    'pairid' : this.getAttribute("parid")
                }
                dashboardEntry(reqDashboardEntry,'portfolio',0);
            });   
        }*/
            }
            ele.addEventListener("click", function () {
                var prev = document.getElementsByClassName("parSelected");
                if (prev.length > 0) prev[0].classList.remove("parSelected");
                this.classList.add("parSelected");
                var currency = {};
                currency.id = this.getAttribute("currencyid");
                currency.symbol = this.getAttribute("currency");
                currency.decimals = this.getAttribute("currencydecim");
                var refcurrency = {};
                refcurrency.id = this.getAttribute("refcurrencyid");
                refcurrency.symbol = this.getAttribute("refcurrency");
                refcurrency.decimals = this.getAttribute("refcurrencydecim");

                var reqDashboardEntry = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'ordernumofrec': 25,
                    'exchangenumofrec': 25,
                    'pairid': this.getAttribute("parid")
                }
                dashboardEntry(reqDashboardEntry, 'portfolio', 0);
            });

            //Bg del reglon
            /*ele.classList.remove("rowBg2");
            if(i%2!==0)ele.classList.add("rowBg2");
             */
            var colx, col1, col2, col3, col4;

            //Var col img
            //col0 = ele.children[0]; var img=col.children[0];
            //img.setAttribute("src","./img/05 Rounded BW/SVG/"+rsp[i].currency.name+".svg")

            //Var Columna 1 Nombre
            var col1 = ele.children[0]; var name = col1.children[0];
            name.innerHTML = rsp[i].refcurrency.symbol + '/' + rsp[i].currency.symbol;

            //Var Columna 2 Ultimo precio
            var col2 = ele.children[1]; var last = col2.children[0];
            last.innerHTML = rsp[i].last.formatted + " " + rsp[i].currency.symbol;

            //Var Columna 3 Porcentaje de cambio
            var col3 = ele.children[2]; var change = col3.children[0];
            change.innerHTML = rsp[i].change.formatted;

            if (rsp[i].change.number < 0) {
                change.classList.remove('pairPos')
                change.classList.add('pairNeg')
            } else {
                change.classList.remove('pairNeg')
                change.classList.add('pairPos')
            }

            //Var Columna 4 Volumen
            var col4 = ele.children[3]; var volumen = col4.children[0];
            volumen.innerHTML = rsp[i].volume.formatted + ' ' + rsp[i].refcurrency.symbol;

            tbl.appendChild(ele);
        }
        if (sessionStorage.getItem('pairid')) {
            for (var i = 0; i < rsp.length; i++) {
                if (rsp[i].id == sessionStorage.getItem('pairid')) {
                    tbl.children[i].dispatchEvent(new Event("click"));
                }
            }
        } else {
            tbl.children[0].dispatchEvent(new Event("click"));
        }
    }
}

function updateMarkersList(rsp) {
    var tbl = document.getElementById("tableMarksCnt");
    var node = tbl.firstElementChild.cloneNode(true);
    var tmp = null; tmp = node.cloneNode(true);
    if (!(rsp.length > 0)) {
        var ele = null;
        ele = tmp.cloneNode(true);
        ele.style.display = "none";
        tbl.appendChild(ele);
    } else {
        for (var i = 0; i < tbl.children.length; i++) {

            //Var Columna 1 Nombre
            tbl.children[i].children[0].children[0].innerHTML = rsp[i].refcurrency.symbol + '/' + rsp[i].currency.symbol;

            //Var Columna 2 Ultimo precio
            tbl.children[i].children[1].children[0].innerHTML = rsp[i].last.formatted + " " + rsp[i].currency.symbol;

            //Var Columna 3 Porcentaje de cambio
            tbl.children[i].children[2].children[0].innerHTML = rsp[i].change.formatted;

            if (rsp[i].change.number < 0) {
                tbl.children[i].children[2].children[0].classList.remove('pairPos')
                tbl.children[i].children[2].children[0].classList.add('pairNeg')
            } else {
                tbl.children[i].children[2].children[0].classList.remove('pairNeg')
                tbl.children[i].children[2].children[0].classList.add('pairPos')
            }

            //Var Columna 4 Volumen
            tbl.children[i].children[3].children[0].innerHTML = rsp[i].volume.formatted + ' ' + rsp[i].refcurrency.symbol;

        }
    }
}


// Service markers/entry
function markersEntry() {

    var sessionid = sessionStorage.getItem('sessionid')
    var id = 1 // Valor que se consulta. Varia.
    var time;

    var req = {
        'sessionid': sessionid,
        'id': id,
    }

    callWS('GET', 'markers/entry', req, response);

    function response(status, rsp) {
        switch (status) {
            case 200:
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

// Service markers/chart
function markersChart() {

    var sessionid = sessionStorage.getItem('sessionid')
    var id = 1 // Valor que se consulta. Varia.
    var time;

    var req = {
        'sessionid': sessionid,
        'id': id
    }

    callWS('GET', 'markers/chart', req, response);

    function response(status, rsp) {
        switch (status) {
            case 200:
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

// Service accounts/portfolio
//FUERA DE USO
function accountsPortfolio(parid, currency, refCurrency) {

    var sessionid = sessionStorage.getItem('sessionid')

    var req = {
        'sessionid': sessionid,
        'parid': parid
    }
    callWS('GET', 'accounts/portfolio', req, response);


    function response(status, rsp) {
        var ifCurrency = false;
        var ifRefCurrency = false;
        switch (status) {
            case 200:
                var portfolio = []
                for (var i = 0; i < JSON.parse(rsp).numofrecords; i++) {
                    portfolio.push({
                        'src': "",//"./img/05 Rounded BW/SVG/"+JSON.parse(rsp).records[i].currency.icon+".svg",
                        'name': JSON.parse(rsp).records[i].currency.symbol,
                        'amount': fixDecimals(JSON.parse(rsp).records[i].balance.formatted),
                        'ptc': '0,00%',
                        'id': JSON.parse(rsp).records[i].id,
                        'currencyid': JSON.parse(rsp).records[i].currency.id,
                        'decimals': JSON.parse(rsp).records[i].currency.decimals,
                        'dsc': JSON.parse(rsp).records[i].currency.dsc,
                        'icon': JSON.parse(rsp).records[i].currency.icon
                    })

                    //VALIDA SI LAS MONEDAS EXISTENTES POR SYMBOL VIENE EN EL SERVICIO SI NO GENERA PARA PERMITIR LA CREACIÓN
                    if (currency.symbol == JSON.parse(rsp).records[i].currency.symbol) {
                        ifCurrency = true
                    }
                    if (refCurrency.symbol == JSON.parse(rsp).records[i].currency.symbol) {
                        ifRefCurrency = true
                    }
                }
                if (!ifCurrency) {
                    portfolio.push({
                        'src': '',
                        'name': currency.symbol,
                        'amount': 0,
                        'ptc': '0,00%',
                        'id': 0,
                        'currencyid': currency.id,
                        'decimals': currency.decimals,
                        'dsc': currency.dsc,
                        'icon': currency.icon
                    })
                }
                if (!ifRefCurrency) {
                    if (ifCurrency) {
                        portfolio.push({
                            'src': '',
                            'name': refCurrency.symbol,
                            'amount': 0,
                            'ptc': '0,00%',
                            'id': 0,
                            'currencyid': refCurrency.id,
                            'decimals': refCurrency.decimals,
                            'dsc': refCurrency.dsc,
                            'icon': refCurrency.icon
                        })
                    } else {
                        portfolio.push({
                            'src': '',
                            'name': refCurrency.symbol,
                            'amount': 0,
                            'ptc': '0,00%',
                            'id': 0,
                            'currencyid': refCurrency.id,
                            'decimals': refCurrency.decimals,
                            'dsc': refCurrency.dsc,
                            'icon': refCurrency.icon
                        })
                    }
                }
                listDraw(portfolio, 'portfolio');
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

// Service transactions/list
function transactionsList() {

    var sessionid = sessionStorage.getItem('sessionid')
    var parid = 1 // Valor que se opera. Varia.
    var order; // ??
    var numofrec = 10 // Numero de registros que devuelve
    var offset = 0; // Registro desde el que se mostrará la información

    var req = {
        'sessionid': sessionid,
        'parid': parid,
        'order': order,
        'numofrec': numofrec,
        'offset': offset
    }

    callWS('GET', 'transactions/list', req, response);

    function response(status, rsp) {
        switch (status) {
            case 200:
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

function chargeData(chargeData) {

    var data = chargeData

    var status = new Array(10);
    var date = new Array(10);
    var description = new Array(10);
    var total = new Array(10);

    /*
    for (var i = 0; i < chargeData.numofrecords ; i++ ){
        
        if(chargeData.records[i].valid.id == 1){
            status[i] = 'green'
        }
        else if(chargeData.records[i].valid.id == -1){
            status[i] = 'red'
        }
        else if(chargeData.records[i].valid.id == 0){
            status[i] = 'yellow'
        }
        
        qr[i] = 'qr'
        currency[i] = chargeData.records[i].currency.symbol;
        bank[i] = chargeData.records[i].paymentmethod.dsc;
        number[i] = chargeData.records[i].details1;
        id[i] = chargeData.records[i].id;
        countryid[i] = chargeData.records[i].country.id;
        if(chargeData.records[i].status === 1){
            toggle[i] = 'true'
        }else{
            toggle[i] = 'false'
        }
        
        trash[i] = 'trash'
        
        data.push({
            'status' : status[i],
            'qr' : 'qr',
            'currency' : currency[i],
            'bank' : bank[i],
            'number' : number[i],
            'toggle' : toggle[i],
            'trash' : 'trash',
            'id': id[i],
            'countryid': countryid[i]
        })
    }*/
    listDraw(data, 'data')
}

// Service accounts/generate
function accountsGenerate(currencyid, type, button) {
    var sessionid = sessionStorage.getItem('sessionid');
    var req = {
        'sessionid': sessionid,
        'currencyid': currencyid
    }
    callWS('GET', 'accounts/generate', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:

                if (type == 'BTC') {
                    document.getElementById('BTCPortfolio').setAttribute('accidReal', JSON.parse(rsp).id)
                    putInformationWalletBTC(JSON.parse(rsp).id)
                } else {
                    document.getElementById('FiatPortfolio').setAttribute('accidReal', JSON.parse(rsp).id)
                    if (button == 'Dep') {
                        accountsEntry(JSON.parse(rsp).id, 'depFiatInfButton')
                    }
                    else if (button == 'Ret') {
                        withdrawFiatButton()
                    }
                    else if (button == 'Mov') {
                        seeMovements(document.getElementById("FiatPortfolio").getAttribute("accidReal"), 'FIAT')
                    }
                }
                if (document.getElementsByClassName("parSelected").length > 0)
                    document.getElementsByClassName("parSelected")[0].dispatchEvent(new Event("click"));
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 502:
                if (document.getElementsByClassName("parSelected").length > 0)
                    document.getElementsByClassName("parSelected")[0].dispatchEvent(new Event("click"));

                document.getElementById('failureMsg').innerHTML = getLangById('connecerr')[lang];
                document.getElementById('failureTitle').innerHTML = rsp.msg;
                document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

// Service accounts/generate
function accountsGenerateN(currencies) {
    var sessionid = sessionStorage.getItem('sessionid');
    var req = {
        'sessionid': sessionid,
        'currencies': currencies
    }
    callWS('GET', 'accounts/generate', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                var reqDashboardEntry = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'ordernumofrec': 25,
                    'exchangenumofrec': 25,
                    'pairid': document.getElementById('pairName').getAttribute('pairId')
                }
                dashboardEntry(reqDashboardEntry, '', 0);
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 502:
                var reqDashboardEntry = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'ordernumofrec': 25,
                    'exchangenumofrec': 25,
                    'pairid': document.getElementById('pairName').getAttribute('pairId')
                }
                dashboardEntry(reqDashboardEntry, '', 0);

                if (document.getElementsByClassName("parSelected").length > 0)
                    document.getElementsByClassName("parSelected")[0].dispatchEvent(new Event("click"));

                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg;
                document.getElementById('failureTitle').innerHTML = getLangById('conerrtit')[lang];
                document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

// Service accounts/entry
function accountsEntry(id, action) {

    var sessionid = sessionStorage.getItem('sessionid')
    var id = id

    var req = {
        'sessionid': sessionid,
        'id': id
    }
    callWS('GET', 'accounts/entry', req, response);

    function response(status, rsp) {
        switch (status) {
            case 200:
                if (action == 'putInformationWalletBTC') {
                    document.getElementById('addressBTCInfBalance').innerHTML = fixDecimals(JSON.parse(rsp).entry.balance.formatted);
                    document.getElementById('copyInfAFX').innerHTML = JSON.parse(rsp).entry.wallet.dsc;
                    document.getElementById('addressBTCInfDate').innerHTML = JSON.parse(rsp).entry.wallet.expiry.formatted;
                    document.getElementById("qrcode").innerHTML = ''
                    var qrcode = new QRCode(document.getElementById("qrcode"), {
                        text: document.getElementById('copyInfAFX').innerHTML,
                        width: 110,
                        height: 110,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: QRCode.CorrectLevel.H
                    });
                    if (JSON.parse(rsp).entry.currency.interface == 6) {
                        document.getElementById('USDTInfo').innerHTML = getLangById('usdtInfoDep')[lang]
                    } else {
                        document.getElementById('USDTInfo').innerHTML = ""
                    }
                    document.getElementsByClassName('addressBTCInf')[0].style.display = "table"
                    document.getElementsByTagName('body')[0].classList.add('hidden')
                    document.getElementById('copyDepBTC').value = document.getElementById('copyInfAFX').innerHTML
                }
                else if (action == 'withdrawBTC') {
                    document.getElementById('withdrawBTCBalance').setAttribute('numberAmount', JSON.parse(rsp).entry.balance.number)
                    document.getElementById('withdrawBTCBalance').innerHTML = fixDecimals(JSON.parse(rsp).entry.balance.formatted)

                    req = {
                        'sessionid': sessionStorage.getItem('sessionid'),
                        'currencyid': document.getElementById('BTCPortfolio').getAttribute('icCur')
                    }
                    setWordLanginnerHTML('walletDest', 'destinationWallet');
                    if (document.getElementById('BTCPortfolio').getAttribute('interface') == 6) {
                        document.getElementById('walletDest').innerHTML += getLangById('usdtInfoW')[lang];
                        document.getElementById('USDTInfoRet').innerHTML = getLangById('USDTInfoRet')[lang];
                    } else {
                        document.getElementById('USDTInfoRet').innerHTML = "";
                    }
                    feesEntry(req, 'withdrawBTC')
                }
                else if (action == 'withdrawFiat') {
                    document.getElementById('withdrawFiatBalance').setAttribute('numberAmount', JSON.parse(rsp).entry.balance.number)
                    document.getElementById('withdrawFiatBalance').innerHTML = fixDecimals(JSON.parse(rsp).entry.balance.formatted)
                    document.getElementById('reportDTFiat2').dispatchEvent(new Event("click"));
                    accountsList(JSON.parse(rsp).entry.currency.id)
                    if (JSON.parse(rsp).entry.currency.interface != 1) {
                        isBPInterface = false;
                    } else {
                        isBPInterface = true;
                    }
                }
                else if (action == 'verifywdFiatbutton') {
                    document.getElementById('withdrawFiatConfirmAccount').innerHTML = transformAccountString(JSON.parse(rsp).entry.paymentmethod.dsc, JSON.parse(rsp).entry.details1.value)
                    document.getElementById('withdrawFiatConfirmAmount').innerHTML = number_format(document.getElementById('withdrawFiatAmount').getAttribute("dataNumber"), decimCoin);
                    document.getElementById('withdrawFiatConfirmFee').innerHTML = document.getElementById('withdrawFiatFee').innerHTML
                    document.getElementById('withdrawFiatConfirmTotalN').innerHTML = document.getElementById('withdrawFiatTotal').innerHTML
                    document.getElementById('withdrawFiatConfirmEmail').innerHTML = getLangById('var15')[lang] + entrydata.usr
                    document.getElementById('withdrawFiatConfirmCode').value = ''
                    //document.getElementsByClassName('withdrawFiat')[0].style.display = "none"
                    //document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "table"
                }
                else if (action == 'transferBTC') {
                    document.getElementById('transferBTCBalance').setAttribute('numberAmount', JSON.parse(rsp).entry.balance.number)
                    document.getElementById('transferBTCBalance').innerHTML = fixDecimals(JSON.parse(rsp).entry.balance.formatted)
                    req = {
                        'sessionid': sessionStorage.getItem('sessionid'),
                        'currencyid': document.getElementById('BTCPortfolio').getAttribute('icCur')
                    }
                    feesEntry(req, 'transferBTC')
                } else if (action == 'transferFiat') {
                    document.getElementById('transferBTCBalance').setAttribute('numberAmount', JSON.parse(rsp).entry.balance.number)
                    document.getElementById('transferBTCBalance').innerHTML = fixDecimals(JSON.parse(rsp).entry.balance.formatted)
                    req = {
                        'sessionid': sessionStorage.getItem('sessionid'),
                        'currencyid': document.getElementById('FiatPortfolio').getAttribute('icCur')
                    }
                    feesEntry(req, 'transferBTC')
                }
                else if (action == 'verifytrBTCbutton') {
                    document.getElementById('transferBTCConfirmEmail').innerHTML = document.getElementById('transferBTCEmail').value
                    document.getElementById('transferBTCConfirmAmount').innerHTML = document.getElementById('transferBTCAmount').value;//fixDecimals((parseFloat((document.getElementById('transferBTCAmount').value).replace(/\,/g, '.')).toFixed(decimCoin)).replace(/\./g, ','));
                    document.getElementById('transferBTCConfirmFee').innerHTML = document.getElementById('transferBTCFee').innerHTML
                    document.getElementById('transferBTCConfirmTotalN').innerHTML = document.getElementById('transferBTCTotal').innerHTML
                    document.getElementById('transferBTCConfirmEmailConfirm').innerHTML = getLangById('var15')[lang] + entrydata.usr
                    document.getElementById('transferBTCConfirmCode').value = ''
                }
                else if (action == 'depFiatInfButton') {
                    document.getElementById('depFiatInfBalance').innerHTML = fixDecimals(JSON.parse(rsp).entry.balance.formatted)
                    document.getElementById('reportDTFiat').dispatchEvent(new Event("click"));
                    req = {
                        'sessionid': sessionStorage.getItem('sessionid'),
                        'currencyid': document.getElementById('FiatPortfolio').getAttribute('icCur')
                    }
                    feesEntry(req, 'depFiatInfButton')

                    //document.getElementsByClassName('depFiatInf')[0].style.display = "table" 
                }
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

// Service accounts/list
function accountsList(idCurrency) {

    var sessionid = sessionStorage.getItem('sessionid')

    var req = {
        'sessionid': sessionid,
        'paym': 1,
    }

    callWS('GET', 'accounts/list', req, response);

    function response(status, rsp) {
        switch (status) {
            case 200:
                arrayAccounts = { 'records': [] }
                for (var i = 0; i < JSON.parse(rsp).numofrecords; i++) {
                    if (idCurrency == JSON.parse(rsp).records[i].currency.id && JSON.parse(rsp).records[i].paymentmethod.id != -1) {
                        arrayAccounts.records.push(JSON.parse(rsp).records[i])
                    }
                }
                if (arrayAccounts.records.length > 0) {
                    addOptions('withdrawFiatAccount', arrayAccounts)
                    addOptions('withdrawFiatAccount2', arrayAccounts)
                } else {
                    addOptions('withdrawFiatAccount', arrayAccounts)
                    addOptions('withdrawFiatAccount2', arrayAccounts)
                    error('withdrawFiatAccount', 'ewithdrawFiatAccount', getLangById('var16')[lang]);
                    //error('withdrawFiatAccount2','ewithdrawFiatAccount2',getLangById('var16')[lang]);
                    document.getElementById("withdrawFiatAccount").classList.remove("selectwdFiat");
                    document.getElementById("withdrawFiatAccount").classList.add("selectwdFiatBank");
                    document.getElementById('ewithdrawFiatAccount').style.display = 'block'
                    document.getElementById('ewithdrawFiatAccount').style.marginLeft = '20px'
                    //document.getElementById("withdrawFiatAccount2").classList.remove("selectwdFiat");
                    //document.getElementById("withdrawFiatAccount2").classList.add("selectwdFiatBank");
                    //document.getElementById('ewithdrawFiatAccount2').style.display = 'block'
                    //document.getElementById('ewithdrawFiatAccount2').style.marginLeft = '20px'
                }
                req = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'currencyid': document.getElementById('FiatPortfolio').getAttribute('icCur')
                }
                feesEntry(req, 'withdrawFiat')
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

function putInformationWalletBTC(id) {
    document.getElementById('copyDepBTC').value = ''
    accountsEntry(id, 'putInformationWalletBTC')
}

// deposits/insert

function depositsInsert(req) {
    callWS('POST', 'deposits/insert', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                document.getElementsByClassName('depFiatInf')[0].style.display = "none";
                document.getElementsByClassName('success')[0].style.display = "table";
                if (document.getElementsByClassName("parSelected").length > 0)
                    document.getElementsByClassName("parSelected")[0].dispatchEvent(new Event("click"));
                break;
            case 400:
                document.getElementsByClassName('depFiatInf')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 403:
                error('depFiatInfAmount', 'edepFiatInfAmount', JSON.parse(rsp).msg);
                document.getElementById('edepFiatInfAmount').style.display = 'block'
                document.getElementById('edepFiatInfAmount').style.marginLeft = '20px'
                break;
            case 500:
                document.getElementsByClassName('depFiatInf')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementsByClassName('depFiatInf')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

// c2p/insert

function depositsInsertPM(req) {
    callWS('POST', 'c2p/insert', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                document.getElementsByClassName('depFiatInf')[0].style.display = "none";
                document.getElementsByClassName('success')[0].style.display = "table";
                if (document.getElementsByClassName("parSelected").length > 0)
                    document.getElementsByClassName("parSelected")[0].dispatchEvent(new Event("click"));
                break;
            case 400:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                //error('depFiatInfAmount','edepFiatInfAmount',JSON.parse(rsp).msg);
                document.getElementsByClassName('depFiatInf')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 403:
                error('depFiatInfAmountPM', 'edepFiatInfAmountPM', JSON.parse(rsp).msg);
                document.getElementById('edepFiatInfAmountPM').style.display = 'block'
                document.getElementById('edepFiatInfAmountPM').style.marginLeft = '20px'
                break;
            case 500:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('depFiatInf')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('depFiatInf')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

function wInsertPM(req) {
    callWS('POST', 'p2p/insert', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                document.getElementById('withdrawFiatConfirmCode2').value = ''
                document.getElementsByClassName('withdrawFiat')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "table"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].setAttribute('idWI', JSON.parse(rsp).id)
                document.getElementsByClassName('withdrawFiatConfirm2')[0].setAttribute('tridWI', JSON.parse(rsp).id)
                document.getElementById('withdrawFiatConfirmAmount2').innerHTML = number_format(document.getElementById('withdrawFiatAmount2').getAttribute("dataNumber"), decimCoin);
                document.getElementById('withdrawFiatConfirmFee2').innerHTML = document.getElementById('withdrawFiatFee2').innerHTML
                document.getElementById('withdrawFiatConfirmTotalN2').innerHTML = document.getElementById('withdrawFiatTotal2').innerHTML
                document.getElementById('withdrawFiatConfirmId').innerHTML = document.getElementById('depFiatInfAmountPM22').value
                document.getElementById('withdrawFiatConfirmPhone').innerHTML = document.getElementById("phoneNumberPM").value + document.getElementById("depFiatInfPhonePM2").value
                var sel = document.getElementById("withdrawFiatAccount2");
                var text = sel.options[sel.selectedIndex].text;
                document.getElementById('withdrawFiatConfirmAccount2').innerHTML = text
                document.getElementById('withdrawFiatConfirmEmail2').innerHTML = getLangById('var15')[lang] + entrydata.usr
                break;
            case 400:
                document.getElementsByClassName('withdrawBTC')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiat')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 403:
                error('withdrawFiatAmount2', 'ewithdrawFiatAmount2', JSON.parse(rsp).msg);
                document.getElementById('ewithdrawFiatAmount2').style.display = 'block'
                document.getElementById('ewithdrawFiatAmount2').style.marginLeft = '20px'
                break;
            case 500:
                document.getElementsByClassName('withdrawBTC')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiat')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementsByClassName('withdrawBTC')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiat')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

function depositFiat() {


    var req = {
        'sessionid': sessionStorage.getItem('sessionid'),
        'accountid': document.getElementById("FiatPortfolio").getAttribute("accidReal"),
        'paymentdate': document.getElementById("depFiatInfDate").value,
        'amount': document.getElementById("depFiatInfAmount").getAttribute("dataNumber"),
        'paymentaccountid': document.getElementById("depFiatInfDestinationBank1").value,
        'paymentref': document.getElementById("depFiatInfRef").value,
        'paymentfile': document.getElementById("depFiatInfId").files[0]
    }

    document.getElementById("FiatPortfolio").getAttribute("accidReal")

    verifyDepositsInsert(req)
}

function depositFiatPM() {

    var req = {
        'sessionid': sessionStorage.getItem('sessionid'),
        'bankid': document.getElementById("depFiatInfDestinationBank2").value,
        'phone': document.getElementById("depFiatInfPhonePM").value,
        'amount': document.getElementById("depFiatInfAmountPM").getAttribute("dataNumber"),
        'token': document.getElementById("codePM").value,
        'currencyid': document.getElementById("FiatPortfolio").getAttribute("iccur")
    }

    //document.getElementById("FiatPortfolio").getAttribute("accidReal")

    verifyDepositsInsertPM(req)
}


function wFiatPM() {


    var req = {
        'sessionid': sessionStorage.getItem('sessionid'),
        'bankid': document.getElementById("withdrawFiatAccount2").value,
        'phone': document.getElementById("phoneNumberPM").value + document.getElementById("depFiatInfPhonePM2").value,
        'amount': document.getElementById("withdrawFiatAmount2").getAttribute("dataNumber"),
        'currencyid': document.getElementById("FiatPortfolio").getAttribute("iccur")
    }


    verifywdFiatbutton2(req)
}

function verifyDepositsInsert(req) {

    now = new Date();
    nowDate = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate()

    if (document.getElementById('depFiatInfAmount').value == '' || document.getElementById('depFiatInfDestinationBank1').value == '' || document.getElementById('depFiatInfDate').value == '' ||
        document.getElementById('depFiatInfRef').value == '' || document.getElementById('depFiatInfId').value == '' || now.getTime() < new Date(document.getElementById('depFiatInfDate').value).getTime()) {

        if (document.getElementById('depFiatInfAmount').value == '') {
            //error('depFiatInfAmount','edepFiatInfAmount','Seleccione un pais.');
            document.getElementById('depFiatInfAmount').style.border = "2px solid #D0021B";
            document.getElementById('edepFiatInfAmount').innerHTML = getLangById('var17')[lang];
            document.getElementById('edepFiatInfAmount').style.display = 'block'
        }
        if (document.getElementById('depFiatInfDestinationBank1').value == '') {
            document.getElementById('depFiatInfDestinationBank1').style.border = "";
            document.getElementById("depFiatInfDestinationBank1").classList.remove("selectwdFiat");
            document.getElementById("depFiatInfDestinationBank1").classList.add("selectwdFiatBank");
            document.getElementById('edepFiatInfDestinationBank1').innerHTML = getLangById('var18')[lang];
            document.getElementById('edepFiatInfDestinationBank1').style.display = 'block'
        }
        if (document.getElementById('depFiatInfDate').value == '') {
            error('depFiatInfDate', 'edepFiatInfDate', getLangById('var19')[lang]);
            document.getElementById('edepFiatInfDate').style.display = 'block'
        }
        if (document.getElementById('depFiatInfRef').value == '') {
            error('depFiatInfRef', 'edepFiatInfRef', getLangById('var20')[lang]);
            document.getElementById('edepFiatInfRef').style.display = 'block'
        }
        if (document.getElementById('depFiatInfId').value == '' || document.getElementById('depFiatInfId').value == undefined) {
            document.getElementById('edepFiatInfRec').innerHTML = getLangById('var21')[lang];
            document.getElementById('edepFiatInfRec').style.display = 'block'
        }
        if (now.getTime() < new Date(document.getElementById('depFiatInfDate').value).getTime()) {
            error('depFiatInfDate', 'edepFiatInfDate', getLangById('var22')[lang]);
            document.getElementById('edepFiatInfDate').style.display = 'block'
        }

        return;

    } else {
        depositsInsert(req)
    }
}

function verifyDepositsInsertPM(req) {

    if (document.getElementById('depFiatInfAmountPM').value == '' || document.getElementById('depFiatInfDestinationBank2').value == '' || document.getElementById('depFiatInfCIPM').value == '' ||
        document.getElementById('depFiatInfPhonePM').value == '' || document.getElementById('codePM').value == '') {

        if (document.getElementById('depFiatInfAmountPM').value == '') {
            //error('depFiatInfAmount','edepFiatInfAmount','Seleccione un pais.');
            document.getElementById('depFiatInfAmountPM').style.border = "2px solid #D0021B";
            document.getElementById('edepFiatInfAmountPM').innerHTML = getLangById('var17')[lang];
            document.getElementById('edepFiatInfAmountPM').style.display = 'block'
        }
        if (document.getElementById('depFiatInfDestinationBank2').value == '') {
            document.getElementById('depFiatInfDestinationBank2').style.border = "";
            document.getElementById("depFiatInfDestinationBank2").classList.remove("selectwdFiat");
            document.getElementById("depFiatInfDestinationBank2").classList.add("selectwdFiatBank");
            document.getElementById('edepFiatInfDestinationBank2').innerHTML = getLangById('var18')[lang];
            document.getElementById('edepFiatInfDestinationBank2').style.display = 'block'
        }
        if (document.getElementById('depFiatInfCIPM').value == '') {
            error('depFiatInfCIPM', 'edepFiatInfCIPM', getLangById('var50')[lang]);
            document.getElementById('edepFiatInfCIPM').style.display = 'block'
        }
        if (document.getElementById('depFiatInfPhonePM').value == '') {
            error('depFiatInfPhonePM', 'edepFiatInfPhonePM', getLangById('var51')[lang]);
            document.getElementById('edepFiatInfPhonePM').style.display = 'block'
        }
        if (document.getElementById('codePM').value == '') {
            error('codePM', 'ecodePM', getLangById('var52')[lang]);
            document.getElementById('ecodePM').style.display = 'block'
        }

        return;

    } else {
        depositsInsertPM(req)
    }
}

// transactions/movements

function transactionsMovements(req, type) {
    callWS('GET', 'transactions/movements', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                if (type == 'BTC') {
                    if (JSON.parse(rsp).numofrecords == 0) {
                        document.getElementById('movBTCDeferred').innerHTML = number_format(0, document.getElementById('BTCPortfolio').getAttribute('icDecim'));
                        document.getElementById('movBTCBalance').innerHTML = number_format(0, document.getElementById('BTCPortfolio').getAttribute('icDecim'));
                        document.getElementById('movBTCCommitted').innerHTML = number_format(0, document.getElementById('BTCPortfolio').getAttribute('icDecim'));
                        document.getElementById('movBTCTotal').innerHTML = number_format(0, document.getElementById('BTCPortfolio').getAttribute('icDecim'));
                    } else {
                        document.getElementById('movBTCDeferred').innerHTML = JSON.parse(rsp).account.deferred.formatted
                        document.getElementById('movBTCBalance').innerHTML = JSON.parse(rsp).account.balance.formatted
                        document.getElementById('movBTCCommitted').innerHTML = JSON.parse(rsp).account.committed.formatted
                        document.getElementById('movBTCTotal').innerHTML = number_format(JSON.parse(rsp).account.deferred.number + JSON.parse(rsp).account.balance.number + JSON.parse(rsp).account.committed.number,
                            document.getElementById('BTCPortfolio').getAttribute('icDecim'));
                    }
                    transformTransactionsMovementsBTC(JSON.parse(rsp))
                } else {
                    if (JSON.parse(rsp).numofrecords == 0) {
                        document.getElementById('movVESDeferred').innerHTML = number_format(0, document.getElementById('FiatPortfolio').getAttribute('icDecim'));
                        document.getElementById('movVESBalance').innerHTML = number_format(0, document.getElementById('FiatPortfolio').getAttribute('icDecim'));
                        document.getElementById('movVESCommitted').innerHTML = number_format(0, document.getElementById('FiatPortfolio').getAttribute('icDecim'));
                        document.getElementById('movVESTotal').innerHTML = number_format(0, document.getElementById('FiatPortfolio').getAttribute('icDecim'));
                    } else {
                        document.getElementById('movVESDeferred').innerHTML = JSON.parse(rsp).account.deferred.formatted
                        document.getElementById('movVESBalance').innerHTML = JSON.parse(rsp).account.balance.formatted
                        document.getElementById('movVESCommitted').innerHTML = JSON.parse(rsp).account.committed.formatted
                        document.getElementById('movVESTotal').innerHTML = number_format(JSON.parse(rsp).account.deferred.number + JSON.parse(rsp).account.balance.number + JSON.parse(rsp).account.committed.number,
                            document.getElementById('FiatPortfolio').getAttribute('icDecim'));
                    }
                    transformTransactionsMovementsVES(JSON.parse(rsp))
                }
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

function seeMovements(id, type) {

    var req = {
        'sessionid': sessionStorage.getItem('sessionid'),
        'accountid': id,
        'time': 0,
    }

    transactionsMovements(req, type)
}

function transformTransactionsMovementsVES(data) {
    dataArray = []
    for (var i = 0; i < data.numofrecords; i++) {
        if (data.records[i].status == 0) {
            data.records[i].status = 'yellow'
            ////0 Pendiente, -1 Rechazado, 1 Aprobado
        }
        if (data.records[i].status == -1) {
            data.records[i].status = 'red'
        }
        if (data.records[i].status == 1) {
            data.records[i].status = 'green'
        }
        dataArray.push({
            'status': data.records[i].status,
            'date': data.records[i].date.formatted,
            'description': data.records[i].dsc,
            'total': data.records[i].amount.formatted,
            'id': data.records[i].id,
            'optype': data.records[i].optype,
            'imageview': data.records[i].imageview
        })
    }
    listDraw(dataArray, 'dataFiat')
    document.getElementsByClassName('movVES')[0].style.display = "table"
    document.getElementsByTagName('body')[0].classList.add('hidden')
}

function transformTransactionsMovementsBTC(data) {
    dataArray = []
    for (var i = 0; i < data.numofrecords; i++) {
        if (data.records[i].status == 0) {
            data.records[i].status = 'yellow'
            ////0 Pendiente, -1 Rechazado, 1 Aprobado
        }
        if (data.records[i].status == -1) {
            data.records[i].status = 'red'
        }
        if (data.records[i].status == 1) {
            data.records[i].status = 'green'
        }
        dataArray.push({
            'status': data.records[i].status,
            'date': data.records[i].date.formatted,
            'description': data.records[i].dsc,
            'total': data.records[i].amount.formatted,
            'id': data.records[i].id,
            'type': data.records[i].type,
            'txid': data.records[i].txid,
            'optype': data.records[i].optype
        })
    }
    //listDraw(dataArray, 'dataFiat')
    listDraw(dataArray, 'data')
    document.getElementsByClassName('movBTC')[0].style.display = "table"
    document.getElementsByTagName('body')[0].classList.add('hidden')
}

// transacionts/entry

function transactionsEntry(req) {
    callWS('GET', 'transactions/entry', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                /*MODIFICADO*/
                var trans = JSON.parse(rsp).entry;
                var amount = trans.amount.formatted;
                var total = trans.total.formatted;
                var fee = trans.fee.formatted;
                if (trans.origin) {
                    document.getElementById('movDetailFiatAddress').style.display = 'table';
                    document.getElementById('movDetailFiatAddressHr').style.display = 'block';
                    document.getElementById('movDetailFiatAddress').style.display = 'table';
                    document.getElementById('movDetailFiatAddressHr').style.display = 'block';
                    document.getElementById('movDetailFiatAddress').style.display = 'table';
                    document.getElementById('movDetailFiatAddressHr').style.display = 'block';
                    if (JSON.parse(rsp).entry.destination != null && JSON.parse(rsp).entry.destination != undefined)
                        document.getElementById('movDetailFiatAccount').innerHTML = this.transformAccountString(JSON.parse(rsp).entry.destination.account.paymentmethod.dsc, JSON.parse(rsp).entry.destination.account.details1)
                    else
                        document.getElementById('movDetailFiatAccount').innerHTML = "";

                    document.getElementById("movDetailTit").innerHTML = getLangById('var26')[lang] + trans.origin.account.currency.symbol;
                    /*
                    if(valid !== null)document.getElementById("resend").style.display = "";
                    else document.getElementById("resend").style.display = "none";*/
                    document.getElementById("resend").parentElement.parentElement.style.display = "none";

                    /*if(JSON.parse(rsp).entry.destination.account.details1){
                        
                    }else{
                        document.getElementById('movDetailFiatAddress').style.display = 'none';
                        document.getElementById('movDetailFiatAddressHr').style.display = 'none';
                        document.getElementById('movDetailFiatAccount').innerHTML = '';
                        document.getElementById("movDetailTit").innerHTML = "Retiro "+ trans.destination.account.currency.symbol; 
                        document.getElementById("resend").parentElement.parentElement.style.display = "none";

                    }     */
                    document.getElementById('movDetailFiatAmount').innerHTML = total;
                    document.getElementById('movDetailFiatAmountRet').innerHTML = amount;
                    document.getElementById('comisionFiatDetails').innerHTML = fee;
                    document.getElementById('movDetailFiatDate').innerHTML = JSON.parse(rsp).entry.datecreated.formatted;
                    document.getElementById('movDetailFiatSeeComprobant').setAttribute("comp", JSON.parse(rsp).entry.payment.url);
                    document.getElementsByClassName('movDetailFiat')[0].style.display = "table";
                    document.getElementsByClassName('movVES')[0].style.display = "none";
                    document.getElementById('movDetailLblAmount').innerHTML = getLangById('var23')[lang];

                } else if (trans.destination) {
                    document.getElementById("movDetailTit").innerHTML = getLangById('var24')[lang] + trans.destination.account.currency.symbol;

                    document.getElementById('movDetailFiatAddress').style.display = 'table';
                    document.getElementById('movDetailFiatAddressHr').style.display = 'block';
                    if (JSON.parse(rsp).entry.destination != null && JSON.parse(rsp).entry.destination != undefined)
                        document.getElementById('movDetailFiatAccount').innerHTML = this.transformAccountString(JSON.parse(rsp).entry.destination.account.paymentmethod.dsc, JSON.parse(rsp).entry.destination.account.details1)
                    else
                        document.getElementById('movDetailFiatAccount').innerHTML = "";

                    document.getElementById("resend").parentElement.parentElement.style.display = "table";
                    /*}else{
                        document.getElementById('movDetailFiatAddress').style.display = 'none';
                        document.getElementById('movDetailFiatAddressHr').style.display = 'none';
                        document.getElementById('movDetailFiatAccount').innerHTML = '';
                        document.getElementById("movDetailTit").innerHTML = "COMISIÓN DE DEPOSIO";
                        document.getElementById("resend").parentElement.parentElement.style.display = "none";
                    }*/
                    document.getElementById('movDetailLblAmount').innerHTML = getLangById('var25')[lang];
                    document.getElementById('movDetailFiatDate').innerHTML = JSON.parse(rsp).entry.datecreated.formatted;
                    document.getElementById('movDetailFiatAmount').innerHTML = total;
                    document.getElementById('movDetailFiatAmountRet').innerHTML = amount;
                    document.getElementById('comisionFiatDetails').innerHTML = fee;
                    document.getElementById('movDetailFiatSeeComprobant').setAttribute("comp", JSON.parse(rsp).entry.payment.url);
                    document.getElementsByClassName('movDetailFiat')[0].style.display = "table";
                    document.getElementsByClassName('movVES')[0].style.display = "none";

                }
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

function openMovDetailFiat(id) {
    var req = {
        'sessionid': sessionStorage.getItem('sessionid'),
        'id': id,
        'time': 0,
    }

    transactionsEntry(req)
}

function transformAccountString(paymentmethod, details1) {
    if (details1 !== null)
        return (paymentmethod + '(****' + details1.substr(-4) + ')')
    else {
        if (lang == "esp") return "Pago móvil";
        else if (lang == "eng") return "Mobile pay";
    }
}

function depositsAccounts(currencyid) {
    var req = {
        'sessionid': sessionStorage.getItem('sessionid'),
        'currencyid': currencyid,
    }
    callWS('GET', 'deposits/accounts', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                depositsAccountsArray = JSON.parse(rsp);
                addOptions('depFiatInfDestinationBank1', JSON.parse(rsp));
                //addOptions('depFiatInfDestinationBank2',JSON.parse(rsp))
                document.getElementById('depFiatInfAmount').value = '';
                document.getElementById('depFiatInfAmount').setAttribute("dataNumber", "");
                document.getElementById('depFiatInfAmountPM').value = '';
                document.getElementById('depFiatInfAmountPM').setAttribute("dataNumber", "");
                document.getElementById('depFiatInfDestinationBank1').value = '';
                document.getElementById('depFiatInfDestinationBank2').value = '';
                document.getElementById('depFiatInfDate').value = '';
                document.getElementById('depFiatInfRef').value = '';
                document.getElementById('depFiatInFee').innerHTML = '0';
                document.getElementById('depFiatInNeTotal').innerHTML = '0';
                document.getElementById('depFiatInFeePM').innerHTML = '0';
                document.getElementById('depFiatInNeTotalPM').innerHTML = '0';
                document.getElementById('depFiatInfDate').value = '';
                document.getElementById('depFiatInfCIPM').value = '';
                document.getElementById('depFiatInfPhonePM').value = '';
                document.getElementById('codePM').value = '';
                document.getElementById('depFiatInfRec').children[0].innerHTML = '';
                if (document.getElementById('FiatPortfolio').getAttribute('accidReal') == 0) {
                    //accountsGenerate(document.getElementById('FiatPortfolio').getAttribute('icCur'), 'Fiat', 'Dep')
                }
                else {
                    accountsEntry(document.getElementById('FiatPortfolio').getAttribute('accidReal'), 'depFiatInfButton')
                }
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

function addOptions(domElement, array) {
    removeOptions(domElement)
    var selector = document.getElementById(domElement);
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = getLangById('var27')[lang]
    firstOopcion.value = ''
    firstOopcion.selected = true
    selector.add(firstOopcion);
    for (var i = 0; i < array.records.length; i++) {
        var opcion = document.createElement("option");
        opcion.text = array.records[i].paymentmethod.dsc;
        if (domElement == 'withdrawFiatAccount') {
            opcion.text = transformAccountString(array.records[i].paymentmethod.dsc, array.records[i].details1)
        }
        opcion.value = array.records[i].id
        selector.add(opcion);
    }
    setTimeout(function () {
        firstOopcion.selected = true
    }, 1000);


}

function removeOptions(selectElement) {
    document.getElementById('depFiatInfDetailRsp1').innerHTML = ''
    document.getElementById('copyDepFiat').value = ''
    document.getElementById('depFiatInfDetail2').innerHTML = ''
    document.getElementById('depFiatInfDetailRsp2').innerHTML = ''
    document.getElementById('depFiatInfDetail3').innerHTML = ''
    document.getElementById('depFiatInfDetailRsp3').innerHTML = ''
    document.getElementById('depFiatInfDetail4').innerHTML = ''
    document.getElementById('depFiatInfDetailRsp4').innerHTML = ''
    x = document.getElementById(selectElement)
    var i, L = x.options.length - 1;
    for (i = L; i >= 0; i--) {
        x.remove(i);
    }
}

function putDepositDataFiat(id) {
    for (var i = 0; i < depositsAccountsArray.numofrecords; i++) {
        if (depositsAccountsArray.records[i].id == id) {
            document.getElementById('depFiatInfDetailRsp1').innerHTML = depositsAccountsArray.records[i].details1
            document.getElementById('copyDepFiat').value = depositsAccountsArray.records[i].details1
            document.getElementById('depFiatInfDetail2').innerHTML = depositsAccountsArray.records[i].paymentmethod.details2
            document.getElementById('depFiatInfDetailRsp2').innerHTML = depositsAccountsArray.records[i].details2
            document.getElementById('depFiatInfDetail3').innerHTML = depositsAccountsArray.records[i].paymentmethod.details3
            document.getElementById('depFiatInfDetailRsp3').innerHTML = depositsAccountsArray.records[i].details3
            document.getElementById('depFiatInfDetail4').innerHTML = depositsAccountsArray.records[i].paymentmethod.details4
            document.getElementById('depFiatInfDetailRsp4').innerHTML = depositsAccountsArray.records[i].details4
        }
    }
}

function verifywdBTCbutton() {
    if (document.getElementById('withdrawBTCAmount').value == '' || document.getElementById('withdrawBTCWallet').value == '') {
        if (document.getElementById('withdrawBTCAmount').value == '') {
            error('withdrawBTCAmount', 'ewithdrawBTCAmount', getLangById('var17')[lang]);
            document.getElementById('ewithdrawBTCAmount').style.display = 'block'
            document.getElementById('ewithdrawBTCAmount').style.marginLeft = '20px'
        }
        if (document.getElementById('withdrawBTCWallet').value == '') {
            if (document.getElementById('walletDest').innerHTML.includes('TRC20')) {
                error('withdrawBTCWallet', 'ewithdrawBTCWallet', getLangById('var28USDT')[lang]);
            } else {
                error('withdrawBTCWallet', 'ewithdrawBTCWallet', getLangById('var28')[lang]);
            }
            document.getElementById('ewithdrawBTCWallet').style.display = 'block'
            document.getElementById('ewithdrawBTCWallet').style.marginLeft = '20px'
        }
        return;
    }
    if (!onlyAlphanumeric(document.getElementById('withdrawBTCWallet'))) {
        error('withdrawBTCWallet', 'ewithdrawBTCWallet', getLangById('var29')[lang]);
        document.getElementById('ewithdrawBTCWallet').style.display = 'block'
        document.getElementById('ewithdrawBTCWallet').style.marginLeft = '20px'
        return;
    }
    if (document.getElementById('withdrawBTCAmount').getAttribute("dataNumber") <= 0) {
        error('withdrawBTCAmount', 'ewithdrawBTCAmount', getLangById('var30')[lang]);
        document.getElementById('ewithdrawBTCAmount').style.display = 'block'
        document.getElementById('ewithdrawBTCAmount').style.marginLeft = '20px'
        return;
    }
    if (parseFloat(document.getElementById('withdrawBTCAmount').getAttribute("dataNumber")) > parseFloat(document.getElementById('withdrawBTCBalance').getAttribute('numberAmount'))) {
        error('withdrawBTCAmount', 'ewithdrawBTCAmount', getLangById('var9')[lang]);
        document.getElementById('ewithdrawBTCAmount').style.display = 'block'
        document.getElementById('ewithdrawBTCAmount').style.marginLeft = '20px'
        return;
    }

    if (document.getElementById('withdrawBTCAmount').getAttribute("dataNumber") > parseFloat(document.getElementById('withdrawBTCBalance').getAttribute('numberAmount'))) {
        error('withdrawBTCAmount', 'ewithdrawBTCAmount', getLangById('var9')[lang]);
        document.getElementById('ewithdrawBTCAmount').style.display = 'block'
        document.getElementById('ewithdrawBTCAmount').style.marginLeft = '20px'
        return;
    }
    if (parseFloat(document.getElementById('withdrawBTCFee').innerHTML) > document.getElementById('withdrawBTCAmount').getAttribute("dataNumber")) {
        error('withdrawBTCAmount', 'ewithdrawBTCAmount', getLangById('var31')[lang]);
        document.getElementById('ewithdrawBTCAmount').style.display = 'block'
        document.getElementById('ewithdrawBTCAmount').style.marginLeft = '20px'
        return;
    }


    document.getElementById('withdrawBTCConfirmAmount').innerHTML = fixDecimals((parseFloat((document.getElementById('withdrawBTCAmount').value).replace('.', '').replace(',', '.')).toFixed(decimCoin)).replace('.', ','))
    document.getElementById('withdrawBTCConfirmFee').innerHTML = document.getElementById('withdrawBTCFee').innerHTML
    document.getElementById('withdrawBTCConfirmTotalN').innerHTML = document.getElementById('withdrawBTCTotal').innerHTML
    document.getElementById('withdrawBTCConfirmWallet').innerHTML = document.getElementById('withdrawBTCWallet').value
    document.getElementById('withdrawBTCConfirmEmail').innerHTML = getLangById('var15')[lang] + entrydata.usr
    document.getElementById('withdrawBTCConfirmCode').value = ''

    var req = {
        'accountid': document.getElementById('BTCPortfolio').getAttribute('accidreal'),
        'amount': document.getElementById('withdrawBTCAmount').getAttribute("dataNumber"),
        'paymentwallet': document.getElementById('withdrawBTCConfirmWallet').innerHTML,
        'sessionid': sessionStorage.getItem('sessionid')
    }

    withdrawalsInsert(req, 'BTC')
}


// withdrawals/insert

function withdrawalsInsert(req, type) {
    callWS('POST', 'withdrawals/insert', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                if (type == 'BTC') {
                    document.getElementsByClassName('withdrawBTC')[0].style.display = "none"
                    document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "table"
                    document.getElementsByClassName('withdrawBTCConfirm')[0].setAttribute('idWI', JSON.parse(rsp).id)
                    document.getElementsByClassName('withdrawBTCConfirm')[0].setAttribute('tridWI', JSON.parse(rsp).transacctionid)
                }
                else if (type == 'Fiat') {
                    document.getElementsByClassName('withdrawFiat')[0].style.display = "none"
                    document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "table"
                    document.getElementsByClassName('withdrawFiatConfirm')[0].setAttribute('idWI', JSON.parse(rsp).id)
                    document.getElementsByClassName('withdrawFiatConfirm')[0].setAttribute('tridWI', JSON.parse(rsp).id)
                }
                break;
            case 400:
                document.getElementsByClassName('withdrawBTC')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiat')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 403:
                if (type == 'BTC') {
                    error('withdrawBTCAmount', 'ewithdrawBTCAmount', JSON.parse(rsp).msg);
                    document.getElementById('ewithdrawBTCAmount').style.display = 'block'
                    document.getElementById('ewithdrawBTCAmount').style.marginLeft = '20px'
                }
                else if (type == 'Fiat') {
                    error('withdrawFiatAmount', 'ewithdrawFiatAmount', JSON.parse(rsp).msg);
                    document.getElementById('ewithdrawFiatAmount').style.display = 'block'
                    document.getElementById('ewithdrawFiatAmount').style.marginLeft = '20px'
                }
                break;
            case 500:
                document.getElementsByClassName('withdrawBTC')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiat')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementsByClassName('withdrawBTC')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiat')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

// transactions/accept

function TransactionsAccept(req, type) {
    callWS('GET', 'transactions/accept', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                if (type == 'BTC') {
                    document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                    document.getElementsByClassName('success')[0].style.display = "table"
                }
                if (type == 'Fiat') {
                    document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                    document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "none"
                    document.getElementsByClassName('success')[0].style.display = "table"
                }
                if (type == 'BTCxfer') {
                    document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                    document.getElementsByClassName('success')[0].style.display = "table"
                }
                if (document.getElementsByClassName("parSelected").length > 0)
                    document.getElementsByClassName("parSelected")[0].dispatchEvent(new Event("click"));
                break;
            case 400:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                if (type == 'BTC') {
                    error('withdrawBTCConfirmCode', 'ewithdrawBTCConfirmCode', getLangById('var32')[lang]);
                    document.getElementById('ewithdrawBTCConfirmCode').style.display = 'block';
                    document.getElementById('ewithdrawBTCConfirmCode').style.marginLeft = '20px';
                }
                if (type == 'Fiat') {
                    error('withdrawFiatConfirmCode', 'ewithdrawFiatConfirmCode', getLangById('var32')[lang]);
                    document.getElementById('ewithdrawFiatConfirmCode').style.display = 'block'
                    document.getElementById('ewithdrawFiatConfirmCode').style.marginLeft = '20px'

                    error('withdrawFiatConfirmCode2', 'ewithdrawFiatConfirmCode2', getLangById('var32')[lang]);
                    document.getElementById('ewithdrawFiatConfirmCode2').style.display = 'block'
                    document.getElementById('ewithdrawFiatConfirmCode2').style.marginLeft = '20px'
                }
                if (type == 'BTCxfer') {
                    error('transferBTCConfirmCode', 'etransferBTCConfirmCode', getLangById('var32')[lang]);
                    document.getElementById('etransferBTCConfirmCode').style.display = 'block'
                    document.getElementById('etransferBTCConfirmCode').style.marginLeft = '20px'
                }
                break;
            case 403:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                if (type == 'BTC') {
                    error('withdrawBTCConfirmCode', 'ewithdrawBTCConfirmCode', getLangById('var33')[lang]);
                    document.getElementById('ewithdrawBTCConfirmCode').style.display = 'block';
                    document.getElementById('ewithdrawBTCConfirmCode').style.marginLeft = '20px';
                }
                if (type == 'Fiat') {
                    error('withdrawFiatConfirmCode', 'ewithdrawFiatConfirmCode', getLangById('var33')[lang]);
                    document.getElementById('ewithdrawFiatConfirmCode').style.display = 'block'
                    document.getElementById('ewithdrawFiatConfirmCode').style.marginLeft = '20px'

                    error('withdrawFiatConfirmCode2', 'ewithdrawFiatConfirmCode2', getLangById('var33')[lang]);
                    document.getElementById('ewithdrawFiatConfirmCode2').style.display = 'block'
                    document.getElementById('ewithdrawFiatConfirmCode2').style.marginLeft = '20px'
                }
                if (type == 'BTCxfer') {
                    error('transferBTCConfirmCode', 'etransferBTCConfirmCode', getLangById('var33')[lang]);
                    document.getElementById('etransferBTCConfirmCode').style.display = 'block'
                    document.getElementById('etransferBTCConfirmCode').style.marginLeft = '20px'
                }
                break;
            case 500:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

function verifywdBTCbuttonV() {

    if (document.getElementById('withdrawBTCConfirmCode').value == '') {
        error('withdrawBTCConfirmCode', 'ewithdrawBTCConfirmCode', getLangById('var34')[lang]);
        document.getElementById('ewithdrawBTCConfirmCode').style.display = 'block'
        document.getElementById('ewithdrawBTCConfirmCode').style.marginLeft = '20px'
        return;

    }

    var req = {
        'id': document.getElementsByClassName('withdrawBTCConfirm')[0].getAttribute('tridWI'),
        'validator': document.getElementById('withdrawBTCConfirmCode').value,
        'sessionid': sessionStorage.getItem('sessionid')

    }

    TransactionsAccept(req, 'BTC')
}


function withdrawFiatButton() {
    document.getElementById('withdrawFiatAmount').value = '';
    document.getElementById('withdrawFiatAmount').setAttribute("dataNumber", "");
    document.getElementById('withdrawFiatAccount').value = '';
    document.getElementById('withdrawFiatAccount2').value = '';
    document.getElementById('withdrawFiatFee').innerHTML = 0;
    document.getElementById('withdrawFiatTotal').innerHTML = 0;
    document.getElementById('withdrawFiatTotal').setAttribute("dataNumber", 0);
    accountsEntry(document.getElementById('FiatPortfolio').getAttribute('accidreal'), 'withdrawFiat');
}

function verifywdFiatbutton() {
    if (document.getElementById('withdrawFiatAmount').value == '' || document.getElementById('withdrawFiatAccount').value == '') {
        if (document.getElementById('withdrawFiatAmount').value == '') {
            error('withdrawFiatAmount', 'ewithdrawFiatAmount', getLangById('var17')[lang]);
            document.getElementById('ewithdrawFiatAmount').style.display = 'block'
            document.getElementById('ewithdrawFiatAmount').style.marginLeft = '20px'
        }
        if (document.getElementById('withdrawFiatAccount').value == '') {
            error('withdrawFiatAccount', 'ewithdrawFiatAccount', getLangById('var35')[lang]);
            document.getElementById("withdrawFiatAccount").classList.remove("selectwdFiat");
            document.getElementById("withdrawFiatAccount").classList.add("selectwdFiatBank");
            document.getElementById('ewithdrawFiatAccount').style.display = 'block'
            document.getElementById('ewithdrawFiatAccount').style.marginLeft = '20px'
        }
        return;
    }
    if (parseFloat(document.getElementById('withdrawFiatAmount').getAttribute("dataNumber")) > parseFloat(document.getElementById('withdrawFiatBalance').getAttribute('numberAmount'))) {
        error('withdrawFiatAmount', 'ewithdrawFiatAmount', getLangById('var9')[lang]);
        document.getElementById('ewithdrawFiatAmount').style.display = 'block';
        document.getElementById('ewithdrawFiatAmount').style.marginLeft = '20px';
        return;
    }

    accountsEntry(document.getElementById('withdrawFiatAccount').value, 'verifywdFiatbutton')

    var req = {
        'accountid': document.getElementById('FiatPortfolio').getAttribute('accidreal'),
        'amount': document.getElementById('withdrawFiatAmount').getAttribute("dataNumber"),
        'paymentaccountid': document.getElementById('withdrawFiatAccount').value,
        'sessionid': sessionStorage.getItem('sessionid')
    }
    withdrawalsInsert(req, 'Fiat')
}

function verifywdFiatbutton2(req) {
    if (document.getElementById('withdrawFiatAmount2').value == '' || document.getElementById('withdrawFiatAccount2').value == '' || document.getElementById('phoneNumberPM').value == '' || document.getElementById('depFiatInfPhonePM2').value == '') {
        if (document.getElementById('withdrawFiatAmount2').value == '') {
            error('withdrawFiatAmount2', 'ewithdrawFiatAmount2', getLangById('var17')[lang]);
            document.getElementById('ewithdrawFiatAmount2').style.display = 'block'
            document.getElementById('ewithdrawFiatAmount2').style.marginLeft = '20px'
        }
        if (document.getElementById('withdrawFiatAccount2').value == '') {
            error('withdrawFiatAccount2', 'ewithdrawFiatAccount2', getLangById('var35')[lang]);
            document.getElementById("withdrawFiatAccount2").classList.remove("selectwdFiat");
            document.getElementById("withdrawFiatAccount2").classList.add("selectwdFiatBank");
            document.getElementById('ewithdrawFiatAccount2').style.display = 'block'
            document.getElementById('ewithdrawFiatAccount2').style.marginLeft = '20px'
        }
        if (document.getElementById('phoneNumberPM').value == '' || document.getElementById('depFiatInfPhonePM2').value == '') {
            error('withdrawFiatAmount2', 'edepFiattPhonePM22', getLangById('var211')[lang]);
            document.getElementById('edepFiattPhonePM22').style.display = 'block'
            document.getElementById('edepFiattPhonePM22').style.marginLeft = '20px'
        }
        return;
    }
    if (parseFloat(document.getElementById('withdrawFiatAmount').getAttribute("dataNumber")) > parseFloat(document.getElementById('withdrawFiatBalance').getAttribute('numberAmount'))) {
        error('withdrawFiatAmount', 'ewithdrawFiatAmount', getLangById('var9')[lang]);
        document.getElementById('ewithdrawFiatAmount').style.display = 'block';
        document.getElementById('ewithdrawFiatAmount').style.marginLeft = '20px';
        return;
    }

    wInsertPM(req)

    //accountsEntry(document.getElementById('withdrawFiatAccount2').value,'verifywdFiatbutton')

    /*var req = {
        'accountid': document.getElementById('FiatPortfolio').getAttribute('accidreal'),
        'amount': document.getElementById('withdrawFiatAmount').getAttribute("dataNumber"),
        'paymentaccountid': document.getElementById('withdrawFiatAccount2').value,
        'sessionid': sessionStorage.getItem('sessionid')
    }
    */
}

function verifywdFiatbuttonV() {

    if (document.getElementById('withdrawFiatConfirmCode').value == '') {
        error('withdrawFiatConfirmCode', 'ewithdrawFiatConfirmCode', getLangById('var34')[lang]);
        document.getElementById('ewithdrawFiatConfirmCode').style.display = 'block'
        document.getElementById('ewithdrawFiatConfirmCode').style.marginLeft = '20px'
        return;

    }

    var req = {
        'id': document.getElementsByClassName('withdrawFiatConfirm')[0].getAttribute('tridWI'),
        'validator': document.getElementById('withdrawFiatConfirmCode').value,
        'sessionid': sessionStorage.getItem('sessionid')
    }
    //document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
    // document.getElementsByClassName('success')[0].style.display = "table"

    TransactionsAccept(req, 'Fiat')
}

function verifywdFiatbuttonV2() {

    if (document.getElementById('withdrawFiatConfirmCode2').value == '') {
        error('withdrawFiatConfirmCode2', 'ewithdrawFiatConfirmCode2', getLangById('var34')[lang]);
        document.getElementById('ewithdrawFiatConfirmCode2').style.display = 'block'
        document.getElementById('ewithdrawFiatConfirmCode2').style.marginLeft = '20px'
        return;

    }

    var req = {
        'id': document.getElementsByClassName('withdrawFiatConfirm2')[0].getAttribute('tridWI'),
        'validator': document.getElementById('withdrawFiatConfirmCode2').value,
        'sessionid': sessionStorage.getItem('sessionid')
    }
    //document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
    // document.getElementsByClassName('success')[0].style.display = "table"
    TransactionsAccept(req, 'Fiat')
}


// xfer/make 
function xferMake(req) {
    callWS('GET', 'xfer/make', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                document.getElementsByClassName('transferBTCConfirm')[0].setAttribute('idWI', JSON.parse(rsp).transactionid)
                document.getElementsByClassName('transferBTCConfirm')[0].setAttribute('tridWI', JSON.parse(rsp).transactionid)
                document.getElementById('transferBTCConfirmNameDest').innerHTML = JSON.parse(rsp).destinationuser.name
                document.getElementById('transferBTCConfirmNameDest').setAttribute('idDestinationUser', JSON.parse(rsp).destinationuser.id)
                document.getElementsByClassName('transferBTC')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "table"
                break;
            case 400:
                document.getElementsByClassName('transferBTC')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 404:
                error('transferBTCEmail', 'etransferBTCEmail', getLangById('var36')[lang]);
                document.getElementById('etransferBTCEmail').style.display = 'block'
                document.getElementById('etransferBTCEmail').style.marginLeft = '20px'
                break;
            case 403:
                error('transferBTCAmount', 'etransferBTCAmount', JSON.parse(rsp).msg);
                document.getElementById('etransferBTCAmount').style.display = 'block'
                document.getElementById('etransferBTCAmount').style.marginLeft = '20px'
                break;
            case 500:
                document.getElementsByClassName('transferBTC')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementsByClassName('transferBTC')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

function xferBTC() {
    if (document.getElementById('transferBTCAmount').value == '' || document.getElementById('transferBTCEmail').value == '' || !document.getElementById('transferBTCEmail').validity.valid) {
        if (document.getElementById('transferBTCAmount').value == '') {
            error('transferBTCAmount', 'etransferBTCAmount', getLangById('var17')[lang]);
            document.getElementById('etransferBTCAmount').style.display = 'block'
            document.getElementById('etransferBTCAmount').style.marginLeft = '20px'
        }
        if (document.getElementById('transferBTCEmail').value == '') {
            error('transferBTCEmail', 'etransferBTCEmail', getLangById('var37')[lang]);
            document.getElementById('etransferBTCEmail').style.display = 'block'
            document.getElementById('etransferBTCEmail').style.marginLeft = '20px'
        }
        if (!document.getElementById('transferBTCEmail').validity.valid) {
            error('transferBTCEmail', 'etransferBTCEmail', getLangById('var38')[lang]);
            document.getElementById('etransferBTCEmail').style.display = 'block'
            document.getElementById('etransferBTCEmail').style.marginLeft = '20px'
        }
        return;
    }
    if (parseFloat(document.getElementById('transferBTCAmount').getAttribute('dataNumber')) > parseFloat(document.getElementById('transferBTCBalance').getAttribute('numberAmount'))) {
        error('transferBTCAmount', 'etransferBTCAmount', getLangById('var9')[lang]);
        document.getElementById('etransferBTCAmount').style.display = 'block'
        document.getElementById('etransferBTCAmount').style.marginLeft = '20px'
        return;
    }
    if (document.getElementById('BTCPortfolio').style.display !== "")
        accid = document.getElementById('BTCPortfolio').getAttribute('accidreal');
    else if (document.getElementById('FiatPortfolio').style.display !== "")
        accid = document.getElementById('FiatPortfolio').getAttribute('accidreal');


    accountsEntry(accid, 'verifytrBTCbutton');

    var req = {
        'originaccountid': accid,
        'amount': document.getElementById('transferBTCAmount').getAttribute("dataNumber"),
        'usr': document.getElementById('transferBTCEmail').value,
        'sessionid': sessionStorage.getItem('sessionid')
    }
    xferMake(req)

}

function verifytrBTCbuttonV() {
    if (document.getElementById('transferBTCConfirmCode').value == '') {
        error('transferBTCConfirmCode', 'etransferBTCConfirmCode', getLangById('var34')[lang]);
        document.getElementById('etransferBTCConfirmCode').style.display = 'block'
        document.getElementById('etransferBTCConfirmCode').style.marginLeft = '20px'
        return;
    }

    var req = {
        'id': document.getElementsByClassName('transferBTCConfirm')[0].getAttribute('tridWI'),
        'validator': document.getElementById('transferBTCConfirmCode').value,
        'sessionid': sessionStorage.getItem('sessionid')
    }

    TransactionsAccept(req, 'BTCxfer')
}

// xfer/make 
function transactionsCancel(req) {
    callWS('GET', 'transactions/cancel', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "none"
                document.getElementsByTagName('body')[0].classList.remove('hidden')
                break;
            case 400:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 403:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 500:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm2')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

// fees/entry
var decimCoin = 0;
var lastfee = {};
function feesEntry(req, type) {
    callWS('GET', 'fees/entry', req, response);
    function response(status, rsp) {
        lastfee = JSON.parse(rsp);

        //IMPLEMNTACIÓN ATRIBUTO FEE TYPE <-- Esta validación si ya se cargó un tipo de fee permite que la asignación de evento se realice de la manera correcta
        //Se mantiene la logica de asignación de ambos casos, pero se agrega validación paraa que solo se ejecute el activo
        if (document.getElementById('withdrawBTCAmount').getAttribute("feetype") == undefined) {
            //Hay que controlar que no se cargue varias veces así que Sacamos la asignación
            document.getElementById('withdrawBTCAmount').addEventListener("keyup", function () {
                if (this.getAttribute("feetype") == "nml") {
                    var noVal = formatCurrency(decimCoin, this.value);
                    if (noVal !== "") this.value = noVal;
                    if (document.getElementById('withdrawBTCAmount').value == "") {
                        document.getElementById('withdrawBTCTotal').innerHTML = '0';
                        document.getElementById('withdrawBTCTotal').style.color = "#262624"
                    } else {
                        if ((fixDecimals(((parseFloat((document.getElementById('withdrawBTCAmount').value).replace(',', '.')) - (lastfee.entry.withdrawals.nmalfee.number + lastfee.entry.blockchainfee.number)).toFixed(decimCoin)).replace('.', ','))).startsWith('-')) {
                            document.getElementById('withdrawBTCTotal').innerHTML = '0';
                            document.getElementById('withdrawBTCTotal').style.color = "#D0021B"
                        } else {
                            document.getElementById('withdrawBTCTotal').innerHTML = (fixDecimals(((parseFloat((document.getElementById('withdrawBTCAmount').value).replace(',', '.')) - (lastfee.entry.withdrawals.nmalfee.number + lastfee.entry.blockchainfee.number)).toFixed(decimCoin)).replace('.', ',')));
                            document.getElementById('withdrawBTCTotal').style.color = "#262624"
                        }

                    }
                }
            });
            document.getElementById('withdrawBTCAmount').addEventListener("keyup", function () {
                if (this.getAttribute("feetype") == "pct") {
                    var noVal = formatCurrency(decimCoin, this.value);
                    if (noVal !== "") this.value = noVal;
                    document.getElementById('withdrawBTCFee').innerHTML = fixDecimals(((((document.getElementById('withdrawBTCAmount').value).replace(',', '.') * lastfee.entry.withdrawals.pctfee.number / 100) + lastfee.entry.blockchainfee.number).toFixed(decimCoin)).replace('.', ','));
                    document.getElementById('withdrawBTCTotal').innerHTML = fixDecimals(((((document.getElementById('withdrawBTCAmount').value).replace(',', '.') * (1 - lastfee.entry.withdrawals.pctfee.number / 100)) - lastfee.entry.blockchainfee.number).toFixed(decimCoin)).replace('.', ','));
                }

            });
        }
        if (document.getElementById('depFiatInfAmount').getAttribute("feetype") == undefined) {
            document.getElementById('depFiatInfAmount').addEventListener("keyup", function () {
                if (this.getAttribute("feetype") == "nml") {
                    //CONTROLA decimales y numero signitificaivo máx
                    var noVal = formatCurrency(decimCoin, this.value);
                    if (noVal !== "") this.value = noVal;

                    if (document.getElementById('depFiatInfAmount').value == "") {
                        document.getElementById('depFiatInNeTotal').innerHTML = '0'
                    } else {
                        document.getElementById('depFiatInNeTotal').innerHTML = number_format(((((document.getElementById('depFiatInfAmount').value).replace(',', '.')) - lastfee.entry.deposits.nmalfee.number)), decimCoin);
                    }
                }
            });
            document.getElementById('depFiatInfAmount').addEventListener("keyup", function () {
                if (this.getAttribute("feetype") == "pct") {
                    //CONTROLA decimales y numero signitificaivo máx
                    var noVal = formatCurrency(decimCoin, this.value);
                    if (noVal !== "") this.value = noVal;

                    document.getElementById('depFiatInFee').innerHTML = number_format((((document.getElementById('depFiatInfAmount').value).replace(',', '.') * lastfee.entry.deposits.pctfee.number / 100)), decimCoin);
                    document.getElementById('depFiatInNeTotal').innerHTML = number_format(((document.getElementById('depFiatInfAmount').value).replace(',', '.') * (1 - lastfee.entry.deposits.pctfee.number / 100)), decimCoin);
                }

            });
        }
        if (document.getElementById('transferBTCAmount').getAttribute("feetype") == undefined) {
            document.getElementById('transferBTCAmount').addEventListener("keyup", function () {
                if (this.getAttribute("feetype") == "nml") {
                    //CONTROLA decimales y numero signitificaivo máx
                    var noVal = formatCurrency(decimCoin, this.value);
                    if (noVal !== "") this.value = noVal;

                    if (document.getElementById('transferBTCAmount').value == "" || document.getElementById('transferBTCAmount').value < 0) {
                        document.getElementById('transferBTCTotal').innerHTML = '0'
                    } else {
                        document.getElementById('transferBTCTotal').innerHTML = number_format(fixDecimals(((parseFloat((document.getElementById('transferBTCAmount').value).replace(/\,/g, '.')) - lastfee.entry.xfer.nmalfee.number).toFixed(decimCoin))), decimCoin);
                    }
                }
            });
            document.getElementById('transferBTCAmount').addEventListener("keyup", function () {
                if (this.getAttribute("feetype") == "pct") {
                    //CONTROLA decimales y numero signitificaivo máx
                    var noVal = formatCurrency(decimCoin, this.value);
                    if (noVal !== "") this.value = noVal;
                    var fee = number_format(fixDecimals((((document.getElementById('transferBTCAmount').value).replace(/\,/g, '.') * lastfee.entry.xfer.pctfee.number / 100)).noExponents()), decimCoin);
                    var tot = number_format(fixDecimals(((document.getElementById('transferBTCAmount').value).replace(/\,/g, '.') * (1 - lastfee.entry.xfer.pctfee.number / 100)).noExponents()), decimCoin);
                    document.getElementById('transferBTCFee').innerHTML = fee;
                    document.getElementById('transferBTCTotal').innerHTML = tot;
                }
            });
        }
        if (document.getElementById('withdrawFiatAmount').getAttribute("feetype") == undefined) {
            document.getElementById('withdrawFiatAmount').addEventListener("keyup", function () {
                if (this.getAttribute("feetype") == "nml") {
                    if (document.getElementById('withdrawFiatAmount').value == "") {
                        document.getElementById('withdrawFiatTotal').innerHTML = '0'
                        document.getElementById('withdrawFiatTotal').setAttribute("dataNumber", 0);
                    } else {
                        document.getElementById('withdrawFiatTotal').innerHTML = number_format(((parseFloat((document.getElementById('withdrawFiatAmount').value).replace(/\,/g, '.')) + parseFloat(lastfee.entry.withdrawals.nmalfee.number))), decimCoin);
                        document.getElementById('withdrawFiatTotal').setAttribute("dataNumber", ((((document.getElementById('withdrawFiatAmount').value).replace(/\,/g, '.')) + lastfee.entry.withdrawals.nmalfee.number)));
                    }
                }
                if (this.getAttribute("feetype") == "pct") {
                    //CONTROLA decimales y numero signitificaivo máx
                    var noVal = formatCurrency(decimCoin, this.value);
                    if (noVal !== "") this.value = noVal;

                    document.getElementById('withdrawFiatFee').innerHTML = number_format((((document.getElementById('withdrawFiatAmount').value).replace(/\,/g, '.') * lastfee.entry.withdrawals.pctfee.number / 100)), decimCoin);
                    document.getElementById('withdrawFiatTotal').innerHTML = number_format(parseFloat((document.getElementById('withdrawFiatAmount').value).replace(/\,/g, '.')) + parseFloat(document.getElementById('withdrawFiatFee').innerHTML.replace(/\,/g, '.')), decimCoin);
                    document.getElementById('withdrawFiatTotal').setAttribute("dataNumber", (parseFloat((document.getElementById('withdrawFiatAmount').value).replace(/\,/g, '.')) + parseFloat(document.getElementById('withdrawFiatFee').innerHTML.replace(/\,/g, '.'))));
                }
            });
        }
        switch (status) {
            case 200:
                /**SECCION MODIFICADA MANEJO DE DECIMAL EN MONTOS CON VARIABLE GLOBAL**/
                //OJO AQUÍ BUG DETECTADO DE @MAGI ESTA FUNCION SE LLAMA TANTAS VECES CÓMO SE DA CLICK EN LOS BOTONES DEL PORTAFOLIO
                //ESTO ESTA GENERANDO QUE SE AGREGEN EVENTOS DE MÁS Y REPETIDOS EN LOS ELEMENTOS
                /*
                if(type=='depositBTC'){
                    if(lastfee.entry.deposits.nmalfee){
                        document.getElementById("depositCriptoFee").innerHTML = (JSON.parse(rsp).entry.deposits.nmalfee.number).toFixed(decimCoin).replace('.',',');
                    }
                    else if(JSON.parse(rsp).entry.deposits.pctfee){
                        document.getElementById('depositCriptoFee').innerHTML = ((JSON.parse(rsp).entry.deposits.pctfee.number).toFixed(decimCoin)+"%").replace('.',',');
                    }
                    
                }
                if(type=='withdrawBTC'){
                    if(JSON.parse(rsp).entry.withdrawals.nmalfee){
                        document.getElementById('withdrawBTCFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang];
                        document.getElementById('withdrawBTCFee').innerHTML = fixDecimals((JSON.parse(rsp).entry.withdrawals.nmalfee.number+JSON.parse(rsp).entry.blockchainfee.number).toFixed(decimCoin).replace('.', ','));
                        //document.getElementById('withdrawBTCTotal').innerHTML = fixDecimals((((document.getElementById('withdrawBTCAmount').value).replace(',','.')) - (JSON.parse(rsp).entry.withdrawals.nmalfee.number+JSON.parse(rsp).entry.blockchainfee.number)).toFixed(decimCoin).replace('.', ','));
                        document.getElementById('withdrawBTCAmount').addEventListener("keyup", function(){
                            var noVal = formatCurrency(decimCoin,this.value);
                            if(noVal!=="")this.value = noVal;
                            if(document.getElementById('withdrawBTCAmount').value == ""){
                                document.getElementById('withdrawBTCTotal').innerHTML = '0';
                                document.getElementById('withdrawBTCTotal').style.color="#262624"
                            }else{
                                if((fixDecimals(((parseFloat((document.getElementById('withdrawBTCAmount').value).replace(',','.')) - (JSON.parse(rsp).entry.withdrawals.nmalfee.number+JSON.parse(rsp).entry.blockchainfee.number)).toFixed(decimCoin)).replace('.', ','))).startsWith('-')){
                                    document.getElementById('withdrawBTCTotal').innerHTML = '0';
                                    document.getElementById('withdrawBTCTotal').style.color="#D0021B"
                                }else{
                                    document.getElementById('withdrawBTCTotal').innerHTML = (fixDecimals(((parseFloat((document.getElementById('withdrawBTCAmount').value).replace(',','.')) - (JSON.parse(rsp).entry.withdrawals.nmalfee.number+JSON.parse(rsp).entry.blockchainfee.number)).toFixed(decimCoin)).replace('.', ',')));
                                    document.getElementById('withdrawBTCTotal').style.color="#262624"
                                }
                                
                           }
                        }); 
                        document.getElementById('withdrawBTCAmount').dispatchEvent(new Event("keyup"));
                    }
                    else if(JSON.parse(rsp).entry.withdrawals.pctfee){
                        document.getElementById('withdrawBTCFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang] + " ("+fixDecimals(((JSON.parse(rsp).entry.withdrawals.pctfee.number).toFixed(2)).replace('.', ','))+"%)";
                        document.getElementById('withdrawBTCAmount').addEventListener("keyup", function(){
                            var noVal = formatCurrency(decimCoin,this.value);
                            if(noVal!=="")this.value = noVal;

                            document.getElementById('withdrawBTCFee').innerHTML = fixDecimals(((  ((document.getElementById('withdrawBTCAmount').value).replace(',', '.')   * JSON.parse(rsp).entry.withdrawals.pctfee.number / 100)+JSON.parse(rsp).entry.blockchainfee.number).toFixed(decimCoin)).replace('.', ','));
                            document.getElementById('withdrawBTCTotal').innerHTML = fixDecimals((((  (document.getElementById('withdrawBTCAmount').value).replace(',', '.')   * (1 - JSON.parse(rsp).entry.withdrawals.pctfee.number / 100))-JSON.parse(rsp).entry.blockchainfee.number).toFixed(decimCoin)).replace('.', ','));
                        }); 
                    }
                    document.getElementsByTagName('body')[0].classList.add('hidden')
                    document.getElementsByClassName('withdrawBTC')[0].style.display = "table"
                }
                if(type=='transferBTC'){
                    if(JSON.parse(rsp).entry.xfer.nmalfee){
                        document.getElementById('transferBTCFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang];
                        document.getElementById('transferBTCFee').innerHTML = fixDecimals((JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin).replace(/\./g, ','));
                        document.getElementById('transferBTCTotal').innerHTML = fixDecimals((JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin).replace(/\./g, ','));
                        document.getElementById('transferBTCAmount').addEventListener("keyup", function(){
                            //CONTROLA decimales y numero signitificaivo máx
                            var noVal = formatCurrency(decimCoin,this.value);
                            if(noVal!=="")this.value = noVal;
                            if(document.getElementById('transferBTCAmount').value == "" || document.getElementById('transferBTCAmount').value < 0){
                                document.getElementById('transferBTCTotal').innerHTML = '0'
                            }else{
                                document.getElementById('transferBTCTotal').innerHTML =  fixDecimals(((parseFloat((document.getElementById('transferBTCAmount').value).replace(/\,/g,'.')) - JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin)).replace(/\./g, ','));
                            }
                        }); 
                    }
                    else if(JSON.parse(rsp).entry.xfer.pctfee){
                        document.getElementById('transferBTCFee').parentElement.previousElementSibling.children[0].innerHTML =  getLangById('FEES')[lang] + " ("+fixDecimals(((JSON.parse(rsp).entry.xfer.pctfee.number).toFixed(2)).replace('.', ','))+"%)";
                        document.getElementById('transferBTCAmount').addEventListener("keyup", function(){
                            //CONTROLA decimales y numero signitificaivo máx
                            var noVal = formatCurrency(decimCoin,this.value);
                            if(noVal!=="")this.value = noVal;
                            var fee = number_format(fixDecimals(((  (document.getElementById('transferBTCAmount').value).replace(/\,/g,'.')   * JSON.parse(rsp).entry.xfer.pctfee.number / 100).toFixed(decimCoin)).replace(/\./g,",")),decimCoin);
                            var tot = number_format(fixDecimals(((  (document.getElementById('transferBTCAmount').value).replace(/\,/g, '.')   * (1 - JSON.parse(rsp).entry.xfer.pctfee.number / 100)).toFixed(decimCoin)).replace(/\./g, ',')),decimCoin);
                            document.getElementById('transferBTCFee').innerHTML = fee;
                            document.getElementById('transferBTCTotal').innerHTML = tot;
                        }); 
                    }
                   document.getElementsByClassName('transferBTC')[0].style.display = "table"
                   document.getElementsByTagName('body')[0].classList.add('hidden')
                }
                if(type=='depFiatInfButton'){
                 //  //console.log(JSON.parse(rsp).entry)
                    if(JSON.parse(rsp).entry.deposits.nmalfee){
                        document.getElementById('depFiatInFee').parentElement.previousElementSibling.children[0].innerHTML =  getLangById('FEES')[lang]
                        document.getElementById('depFiatInFee').innerHTML = fixDecimals(((JSON.parse(rsp).entry.deposits.nmalfee.number).toFixed(decimCoin)).replace('.', ','));
                        document.getElementById('depFiatInNeTotal').innerHTML = fixDecimals(((JSON.parse(rsp).entry.deposits.nmalfee.number).toFixed(decimCoin)).replace('.', ','));
                        document.getElementById('depFiatInfAmount').addEventListener("keyup", function(){
                            //CONTROLA decimales y numero signitificaivo máx
                            var noVal = formatCurrency(decimCoin,this.value);
                            if(noVal!=="")this.value = noVal;

                            if(document.getElementById('depFiatInfAmount').value == ""){
                                document.getElementById('depFiatInNeTotal').innerHTML = '0'
                            }else{
                                document.getElementById('depFiatInNeTotal').innerHTML =  number_format(((((document.getElementById('depFiatInfAmount').value).replace(',','.')) - JSON.parse(rsp).entry.deposits.nmalfee.number)),decimCoin);
                            }
                        }); 
                    }
                    else if(JSON.parse(rsp).entry.deposits.pctfee){
                        document.getElementById('depFiatInFee').parentElement.previousElementSibling.children[0].innerHTML =  getLangById('FEES')[lang] + " ("+fixDecimals(((JSON.parse(rsp).entry.deposits.pctfee.number).toFixed(2)).replace('.', ','))+"%)";
                        document.getElementById('depFiatInfAmount').addEventListener("keyup", function(){
                            //CONTROLA decimales y numero signitificaivo máx
                            var noVal = formatCurrency(decimCoin,this.value);
                            if(noVal!=="")this.value = noVal;

                            document.getElementById('depFiatInFee').innerHTML = number_format(((  (document.getElementById('depFiatInfAmount').value).replace(',', '.')   * JSON.parse(rsp).entry.deposits.pctfee.number / 100)),decimCoin);
                            document.getElementById('depFiatInNeTotal').innerHTML = number_format(((document.getElementById('depFiatInfAmount').value).replace(',', '.')   * (1 - JSON.parse(rsp).entry.deposits.pctfee.number / 100)),decimCoin);
                        }); 
                    }else{
                        document.getElementById('depFiatInfAmount').addEventListener("keyup", function(){
                            //CONTROLA decimales y numero signitificaivo máx
                            var noVal = formatCurrency(decimCoin,this.value);
                            if(noVal!=="")this.value = noVal;

                            if(document.getElementById('depFiatInfAmount').value == ""){
                                document.getElementById('depFiatInNeTotal').innerHTML = '0'
                            }else{
                                document.getElementById('depFiatInNeTotal').innerHTML =  number_format(((((document.getElementById('depFiatInfAmount').value).replace(',','.')))),decimCoin);
                            }
                        });
                    }
                    
                    // Call Pago Movil DESHABILITADO PRD
                    callPM(JSON.parse(rsp))
                }
                if(type=='withdrawFiat'){
                    if(JSON.parse(rsp).entry.withdrawals.nmalfee){
                        //CONTROLA decimales y numero signitificaivo máx
                       //    //console.log(decimCoin)
                       //    //console.log(this.value)
                       //    //console.log(this)
                            //var noVal = formatCurrency(decimCoin,this.value);
                            //if(noVal!=="")this.value = noVal;
                        document.getElementById('withdrawFiatFee').parentElement.previousElementSibling.children[0].innerHTML =  getLangById('FEES')[lang];
                        document.getElementById('withdrawFiatFee').innerHTML = number_format((JSON.parse(rsp).entry.withdrawals.nmalfee.number),decimCoin);
                        document.getElementById('withdrawFiatTotal').innerHTML = number_format((JSON.parse(rsp).entry.withdrawals.nmalfee.number),decimCoin);
                        document.getElementById('withdrawFiatTotal').setAttribute("dataNumber",JSON.parse(rsp).entry.withdrawals.nmalfee.number);
                        
                        document.getElementById('withdrawFiatAmount').addEventListener("keyup", function(){
                            if(document.getElementById('withdrawFiatAmount').value == ""){
                                document.getElementById('withdrawFiatTotal').innerHTML = '0'
                                document.getElementById('withdrawFiatTotal').setAttribute("dataNumber",0);
                            }else{
                                document.getElementById('withdrawFiatTotal').innerHTML =  number_format(((parseFloat((document.getElementById('withdrawFiatAmount').value).replace(',','.')) + parseFloat(JSON.parse(rsp).entry.withdrawals.nmalfee.number))),decimCoin);
                                document.getElementById('withdrawFiatTotal').setAttribute("dataNumber",((((document.getElementById('withdrawFiatAmount').value).replace(',','.')) + JSON.parse(rsp).entry.withdrawals.nmalfee.number)));
                            }
                        }); 
                    }
                    else if(JSON.parse(rsp).entry.withdrawals.pctfee){
                        document.getElementById('withdrawFiatFee').parentElement.previousElementSibling.children[0].innerHTML =  getLangById('FEES')[lang] + " ("+fixDecimals(((JSON.parse(rsp).entry.withdrawals.pctfee.number).toFixed(2)).replace('.', ','))+"%)";
                        document.getElementById('withdrawFiatAmount').addEventListener("keyup", function(){
                            //CONTROLA decimales y numero signitificaivo máx
                            var noVal = formatCurrency(decimCoin,this.value);
                            if(noVal!=="")this.value = noVal;

                            document.getElementById('withdrawFiatFee').innerHTML = number_format((( (document.getElementById('withdrawFiatAmount').value).replace(',', '.')   * JSON.parse(rsp).entry.withdrawals.pctfee.number / 100)),decimCoin);
                            document.getElementById('withdrawFiatTotal').innerHTML = number_format(( (document.getElementById('withdrawFiatAmount').value).replace(',', '.')   * (1 + JSON.parse(rsp).entry.withdrawals.pctfee.number / 100)),decimCoin);
                            document.getElementById('withdrawFiatTotal').setAttribute("dataNumber",( (document.getElementById('withdrawFiatAmount').value).replace(',', '.')   * (1 + JSON.parse(rsp).entry.withdrawals.pctfee.number / 100)));
                            
                        }); 
                    }else{
                        document.getElementById('withdrawFiatAmount').addEventListener("keyup", function(){
                            if(document.getElementById('withdrawFiatAmount').value == ""){
                                document.getElementById('withdrawFiatTotal').innerHTML = '0'
                                document.getElementById('withdrawFiatTotal').setAttribute("dataNumber",0);
                            }else{
                                document.getElementById('withdrawFiatTotal').innerHTML =  number_format(((((document.getElementById('withdrawFiatAmount').value).replace(',','.')))),decimCoin);
                                document.getElementById('withdrawFiatTotal').setAttribute("dataNumber",((((document.getElementById('withdrawFiatAmount').value).replace(',','.')))));
                            }
                        }); 
                    }
                   // Call Pago Movil DESHABILITADO PRD
                    callPM2(JSON.parse(rsp))
                }
                */
                //--AJUSTADO JAVIER
                if (type == 'depositBTC') {
                    //No hay asignación de eventos
                    if (JSON.parse(rsp).entry.deposits.nmalfee) {
                        document.getElementById("depositCriptoFee").innerHTML = (JSON.parse(rsp).entry.deposits.nmalfee.number).toFixed(decimCoin).replace('.', ',');
                    }
                    else if (JSON.parse(rsp).entry.deposits.pctfee) {
                        document.getElementById('depositCriptoFee').innerHTML = ((JSON.parse(rsp).entry.deposits.pctfee.number).toFixed(decimCoin) + "%").replace('.', ',');
                    }
                }
                if (type == 'withdrawBTC') {
                    if (JSON.parse(rsp).entry.withdrawals.nmalfee) {
                        document.getElementById('withdrawBTCFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang];
                        document.getElementById('withdrawBTCFee').innerHTML = fixDecimals((JSON.parse(rsp).entry.withdrawals.nmalfee.number + JSON.parse(rsp).entry.blockchainfee.number).toFixed(decimCoin).replace('.', ','));
                        //document.getElementById('withdrawBTCTotal').innerHTML = fixDecimals((((document.getElementById('withdrawBTCAmount').value).replace(',','.')) - (JSON.parse(rsp).entry.withdrawals.nmalfee.number+JSON.parse(rsp).entry.blockchainfee.number)).toFixed(decimCoin).replace('.', ','));
                        document.getElementById('withdrawBTCAmount').setAttribute("feetype", "nml");
                        document.getElementById('withdrawBTCAmount').dispatchEvent(new Event("keyup"));
                    }
                    else if (JSON.parse(rsp).entry.withdrawals.pctfee) {
                        document.getElementById('withdrawBTCFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang] + " (" + fixDecimals(((JSON.parse(rsp).entry.withdrawals.pctfee.number).toFixed(2)).replace('.', ',')) + "%)";
                        document.getElementById('withdrawBTCAmount').setAttribute("feetype", "pct");
                        document.getElementById('withdrawBTCAmount').dispatchEvent(new Event("keyup"));
                    }
                    document.getElementsByTagName('body')[0].classList.add('hidden')
                    document.getElementsByClassName('withdrawBTC')[0].style.display = "table"
                }
                if (type == 'transferBTC') {
                    if (JSON.parse(rsp).entry.xfer.nmalfee) {
                        document.getElementById('transferBTCFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang];
                        document.getElementById('transferBTCFee').innerHTML = fixDecimals((JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin).replace(/\./g, ','));
                        document.getElementById('transferBTCTotal').innerHTML = fixDecimals((JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin).replace(/\./g, ','));
                        document.getElementById('transferBTCAmount').setAttribute("feetype", "nml");
                        document.getElementById('transferBTCAmount').dispatchEvent(new Event("keyup"));
                    }
                    else if (JSON.parse(rsp).entry.xfer.pctfee) {
                        document.getElementById('transferBTCFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang] + " (" + fixDecimals(((JSON.parse(rsp).entry.xfer.pctfee.number).toFixed(2)).replace('.', ',')) + "%)";
                        document.getElementById('transferBTCAmount').setAttribute("feetype", "pct");
                        document.getElementById('transferBTCAmount').dispatchEvent(new Event("keyup"));
                    }
                    document.getElementsByClassName('transferBTC')[0].style.display = "table"
                    document.getElementsByTagName('body')[0].classList.add('hidden')
                }
                if (type == 'depFiatInfButton') {
                    if (JSON.parse(rsp).entry.deposits.nmalfee) {
                        document.getElementById('depFiatInFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang];
                        document.getElementById('depFiatInFee').innerHTML = fixDecimals(((JSON.parse(rsp).entry.deposits.nmalfee.number).toFixed(decimCoin)).replace('.', ','));
                        document.getElementById('depFiatInNeTotal').innerHTML = fixDecimals(((JSON.parse(rsp).entry.deposits.nmalfee.number).toFixed(decimCoin)).replace('.', ','));
                        document.getElementById('depFiatInfAmount').setAttribute("feetype", "nml");
                        document.getElementById('depFiatInfAmount').dispatchEvent(new Event("keyup"));
                    }
                    else if (JSON.parse(rsp).entry.deposits.pctfee) {
                        document.getElementById('depFiatInFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang] + " (" + fixDecimals(((JSON.parse(rsp).entry.deposits.pctfee.number).toFixed(2)).replace('.', ',')) + "%)";
                        document.getElementById('depFiatInfAmount').setAttribute("feetype", "pct");
                        document.getElementById('depFiatInfAmount').dispatchEvent(new Event("keyup"));
                    } else {
                        //NO SE ESTE A QUE CASO COREESPONDE
                        document.getElementById('depFiatInfAmount').addEventListener("keyup", function () {
                            //CONTROLA decimales y numero signitificaivo máx
                            var noVal = formatCurrency(decimCoin, this.value);
                            if (noVal !== "") this.value = noVal;
                            if (document.getElementById('depFiatInfAmount').value == "") {
                                document.getElementById('depFiatInNeTotal').innerHTML = '0'
                            } else {
                                document.getElementById('depFiatInNeTotal').innerHTML = number_format(((((document.getElementById('depFiatInfAmount').value).replace(',', '.')))), decimCoin);
                            }
                        });
                    }
                    // Call Pago Movil DESHABILITADO PRD
                    callPM(JSON.parse(rsp))
                }
                if (type == 'withdrawFiat') {
                    if (JSON.parse(rsp).entry.withdrawals.nmalfee) {
                        //CONTROLA decimales y numero signitificaivo máx
                        //var noVal = formatCurrency(decimCoin,this.value);
                        //if(noVal!=="")this.value = noVal;
                        document.getElementById('withdrawFiatFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang];
                        document.getElementById('withdrawFiatFee').innerHTML = number_format((JSON.parse(rsp).entry.withdrawals.nmalfee.number), decimCoin);
                        document.getElementById('withdrawFiatTotal').innerHTML = number_format((JSON.parse(rsp).entry.withdrawals.nmalfee.number), decimCoin);
                        document.getElementById('withdrawFiatTotal').setAttribute("dataNumber", JSON.parse(rsp).entry.withdrawals.nmalfee.number);
                        document.getElementById('withdrawFiatAmount').setAttribute("feetype", "nml");
                        document.getElementById('withdrawFiatAmount').dispatchEvent(new Event("keyup"));

                    }
                    else if (JSON.parse(rsp).entry.withdrawals.pctfee) {
                        document.getElementById('withdrawFiatFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang] + " (" + fixDecimals(((JSON.parse(rsp).entry.withdrawals.pctfee.number).toFixed(2)).replace('.', ',')) + "%)";
                        document.getElementById('withdrawFiatAmount').setAttribute("feetype", "pct");
                        document.getElementById('withdrawFiatAmount').dispatchEvent(new Event("keyup"));
                    } else {
                        document.getElementById('withdrawFiatAmount').addEventListener("keyup", function () {
                            if (document.getElementById('withdrawFiatAmount').value == "") {
                                document.getElementById('withdrawFiatTotal').innerHTML = '0'
                                document.getElementById('withdrawFiatTotal').setAttribute("dataNumber", 0);
                            } else {
                                document.getElementById('withdrawFiatTotal').innerHTML = number_format(((((document.getElementById('withdrawFiatAmount').value).replace(',', '.')))), decimCoin);
                                document.getElementById('withdrawFiatTotal').setAttribute("dataNumber", ((((document.getElementById('withdrawFiatAmount').value).replace(',', '.')))));
                            }
                        });
                    }
                    // Call Pago Movil DESHABILITADO PRD
                    callPM2(JSON.parse(rsp))
                }
                break;
            case 400:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 403:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 502:
                document.getElementById('failureMsg').innerHTML = getLangById('connecerr')[lang];
                document.getElementById('failureTitle').innerHTML = getLangById('conerrtit')[lang];
                document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang]
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 500:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

function callPM(JSONe) {

    if (JSONe.entry.deposits.nmalfee) {
        document.getElementById('depFiatInFeePM').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang]
        document.getElementById('depFiatInFeePM').innerHTML = fixDecimals(((JSONe.entry.deposits.nmalfee.number).toFixed(decimCoin)).replace('.', ','));
        document.getElementById('depFiatInNeTotalPM').innerHTML = fixDecimals(((JSONe.entry.deposits.nmalfee.number).toFixed(decimCoin)).replace('.', ','));
        document.getElementById('depFiatInfAmountPM').addEventListener("keyup", function () {
            //CONTROLA decimales y numero signitificaivo máx
            var noVal = formatCurrency(decimCoin, this.value);
            if (noVal !== "") this.value = noVal;

            if (document.getElementById('depFiatInfAmountPM').value == "") {
                document.getElementById('depFiatInNeTotalPM').innerHTML = '0'
            } else {
                document.getElementById('depFiatInNeTotalPM').innerHTML = number_format(((((document.getElementById('depFiatInfAmountPM').value).replace(',', '.')) - JSONe.entry.deposits.nmalfee.number)), decimCoin);
            }
        });
    }
    else if (JSONe.entry.deposits.pctfee) {
        document.getElementById('depFiatInFeePM').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang] + " (" + fixDecimals(((JSONe.entry.deposits.pctfee.number).toFixed(2)).replace('.', ',')) + "%)";
        document.getElementById('depFiatInfAmountPM').addEventListener("keyup", function () {
            //CONTROLA decimales y numero signitificaivo máx
            var noVal = formatCurrency(decimCoin, this.value);
            if (noVal !== "") this.value = noVal;
            document.getElementById('depFiatInFeePM').innerHTML = number_format((((document.getElementById('depFiatInfAmountPM').value).replace(',', '.') * JSONe.entry.deposits.pctfee.number / 100)), decimCoin);
            document.getElementById('depFiatInNeTotalPM').innerHTML = number_format(((document.getElementById('depFiatInfAmountPM').value).replace(',', '.') * (1 - JSONe.entry.deposits.pctfee.number / 100)), decimCoin);
        });
    } else {
        document.getElementById('depFiatInfAmountPM').addEventListener("keyup", function () {
            //CONTROLA decimales y numero signitificaivo máx
            var noVal = formatCurrency(decimCoin, this.value);
            if (noVal !== "") this.value = noVal;
            if (document.getElementById('depFiatInfAmountPM').value == "") {
                document.getElementById('depFiatInNeTotalPM').innerHTML = '0'
            } else {
                document.getElementById('depFiatInNeTotalPM').innerHTML = number_format(((((document.getElementById('depFiatInfAmountPM').value).replace(',', '.')))), decimCoin);
            }
        });
    }

    req = {
        'sessionid': sessionStorage.getItem('sessionid')
    }

    getCp2Banks(req);

    document.getElementsByClassName('depFiatInf')[0].style.display = "table"
    document.getElementsByTagName('body')[0].classList.add('hidden')
}


function callPM2(JSONe) {

    if (JSONe.entry.withdrawals.nmalfee) {
        document.getElementById('withdrawFiatFee2').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang];
        document.getElementById('withdrawFiatFee2').innerHTML = number_format((JSONe.entry.withdrawals.nmalfee.number), decimCoin);
        document.getElementById('withdrawFiatTotal2').innerHTML = number_format((JSONe.entry.withdrawals.nmalfee.number), decimCoin);
        document.getElementById('withdrawFiatTotal2').setAttribute("dataNumber", JSONe.entry.withdrawals.nmalfee.number);

        document.getElementById('withdrawFiatAmount2').addEventListener("keyup", function () {
            if (document.getElementById('withdrawFiatAmount2').value == "") {
                document.getElementById('withdrawFiatTotal2').innerHTML = '0'
                document.getElementById('withdrawFiatTotal2').setAttribute("dataNumber", 0);
            } else {
                document.getElementById('withdrawFiatTotal2').innerHTML = number_format(((parseFloat((document.getElementById('withdrawFiatAmount2').value).replace(',', '.')) + parseFloat(JSONe.entry.withdrawals.nmalfee.number))), decimCoin);
                document.getElementById('withdrawFiatTotal2').setAttribute("dataNumber", ((((document.getElementById('withdrawFiatAmount2').value).replace(',', '.')) + JSONe.entry.withdrawals.nmalfee.number)));
            }
        });
    }
    else if (JSONe.entry.withdrawals.pctfee) {
        document.getElementById('withdrawFiatFee2').parentElement.previousElementSibling.children[0].innerHTML = getLangById('FEES')[lang] + " (" + fixDecimals(((JSONe.entry.withdrawals.pctfee.number).toFixed(2)).replace('.', ',')) + "%)";
        document.getElementById('withdrawFiatAmount2').addEventListener("keyup", function () {
            //CONTROLA decimales y numero signitificaivo máx
            var noVal = formatCurrency(decimCoin, this.value);
            if (noVal !== "") this.value = noVal;

            document.getElementById('withdrawFiatFee2').innerHTML = number_format((((document.getElementById('withdrawFiatAmount2').value).replace(',', '.') * JSONe.entry.withdrawals.pctfee.number / 100)), decimCoin);
            document.getElementById('withdrawFiatTotal2').innerHTML = number_format(((document.getElementById('withdrawFiatAmount2').value).replace(',', '.') * (1 + JSONe.entry.withdrawals.pctfee.number / 100)), decimCoin);
            document.getElementById('withdrawFiatTotal2').setAttribute("dataNumber", ((document.getElementById('withdrawFiatAmount2').value).replace(',', '.') * (1 + JSONe.entry.withdrawals.pctfee.number / 100)));

        });
    } else {
        document.getElementById('withdrawFiatAmount2').addEventListener("keyup", function () {
            if (document.getElementById('withdrawFiatAmount2').value == "") {
                document.getElementById('withdrawFiatTotal2').innerHTML = '0'
                document.getElementById('withdrawFiatTotal2').setAttribute("dataNumber", 0);
            } else {
                document.getElementById('withdrawFiatTotal2').innerHTML = number_format(((((document.getElementById('withdrawFiatAmount2').value).replace(',', '.')))), decimCoin);
                document.getElementById('withdrawFiatTotal2').setAttribute("dataNumber", ((((document.getElementById('withdrawFiatAmount2').value).replace(',', '.')))));
            }
        });
    }
    req = {
        'sessionid': sessionStorage.getItem('sessionid')
    }

    getp2pBanks(req);

    document.getElementsByClassName('withdrawFiat')[0].style.display = "table";
    document.getElementsByTagName('body')[0].classList.add('hidden');
}

function getCp2Banks(req) {
    callWS('GET', 'c2p/banks', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                isBPWorks = true;
                depositsAccountsArrayPM = JSON.parse(rsp)
                addOptionsPM('depFiatInfDestinationBank2', JSON.parse(rsp).bancos)
                addCP2InfL()
                break;
            case 204:
                isBPWorks = false;
                break;
            case 401:
                expiredSession();
                break;
            default:
                isBPWorks = false;
                break;
        }
    }
}

function getp2pBanks(req) {
    callWS('GET', 'p2p/banks', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                isBPWorks = true;
                WAccountsArrayPM = JSON.parse(rsp);
                addOptionsPM('withdrawFiatAccount2', JSON.parse(rsp).bancos);
                addCP2InfL2();
                break;
            case 204:
                isBPWorks = false;
                break;
            case 401:
                expiredSession();
                break;
            default:
                isBPWorks = false;
                document.getElementsByClassName('withdrawFiat')[0].style.display = "table";
                document.getElementsByTagName('body')[0].classList.add('hidden');
                break;
        }
    }
}

function addCP2InfL() {
    if (entrydata.person) {
        document.getElementById('depFiatInfCIPM').value = entrydata.person.document.dsc.value
        //document.getElementById('depFiatInfPhonePM').value = entrydata.person.phone.value
    } else {
        document.getElementById('depFiatInfCIPM').value = entrydata.company.document.dsc.value
        //document.getElementById('depFiatInfPhonePM').value = entrydata.company.phone.value
    }
}

function addCP2InfL2() {
    if (entrydata.person) {
        document.getElementById('depFiatInfAmountPM22').value = entrydata.person.document.dsc.value
        document.getElementById('selectPM2').value = entrydata.person.document.type.id
        //document.getElementById('depFiatInfPhonePM').value = entrydata.person.phone.value
    } else {
        document.getElementById('depFiatInfAmountPM22').value = entrydata.company.document.dsc.value
        document.getElementById('selectPM2').value = 4
        //document.getElementById('depFiatInfPhonePM').value = entrydata.company.phone.value
    }
}

function addOptionsPM(domElement, array) {
    removeOptions(domElement)
    var selector = document.getElementById(domElement);
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = getLangById('var27')[lang]
    firstOopcion.value = ''
    firstOopcion.selected = true
    selector.add(firstOopcion);
    for (var i = 0; i < array.length; i++) {
        var opcion = document.createElement("option");
        opcion.text = array[i].nombre;
        opcion.value = array[i].codigo;
        selector.add(opcion);
    }
    setTimeout(function () {
        firstOopcion.selected = true
    }, 1000);

}

function fixDecimals(number) {
    return number;
    /*
    number = number.split('').reverse().join('')
    for (var i = 0; i < number.length; i ++){
      if(number[i] == ','){
        return (number.slice(i+1)).split('').reverse().join('')
      }
      else if(number[i] != 0){
        return (number.slice(i)).split('').reverse().join('')
      }
    }*/
}

function transactionsValidation(req) {
    callWS('GET', 'transactions/validation', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                break;
            case 400:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 403:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 500:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementsByClassName('withdrawBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

function dashboardEntry(req, reason, num) {
    if (document.getElementById('markersSeeAll').classList.contains('tablinksActive')) {
        req.ownorders = 0
    } else {
        req.ownorders = 1
    }
    if (document.getElementById('exchangeSeeAll').classList.contains('tablinksActive')) {
        req.ownexchange = 0
    } else {
        req.ownexchange = 1
    }
    if (document.getElementById('chartSeeOne').classList.contains('tablinksActive')) {
        req.charttime = 1
    } else if (document.getElementById('chartSeeTwo').classList.contains('tablinksActive')) {
        req.charttime = 2
    } else {
        req.charttime = 3
    }
    if (document.getElementById('exchangeSeeAll').classList.contains('tablinksActive')) {
        req.ownexchange = 0
    } else {
        req.ownexchange = 1
    }
    req.totportfolio = document.getElementById('totalPortfolioSel').value;
    if (reason == 'initial') {
        if (sessionStorage.getItem('pairid')) {
            req.pairid = sessionStorage.getItem('pairid')
            document.getElementById('pairName').setAttribute('pairId', sessionStorage.getItem('pairid'))
        }
    }
    callWS('GET', 'dashboard/entryNew', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                dashboardUpdate = JSON.parse(rsp);
                switch (reason) {
                    case 'initial':

                        drawCanvas();
                        chargePairs(JSON.parse(rsp).dashboard.pairs, true)
                        chargeOrders(JSON.parse(rsp).dashboard.orders, req.ownorders)
                        chargeExchanges(JSON.parse(rsp).dashboard.exchanges)
                        chargePairDetails(JSON.parse(rsp).dashboard.pairdetails, true)
                        chargePortfolio(reason, JSON.parse(rsp).dashboard.portfolio, JSON.parse(rsp).dashboard.pairdetails.currency, JSON.parse(rsp).dashboard.pairdetails.refcurrency)
                        chargeChart(JSON.parse(rsp).dashboard.chart)
                        chargePortfolioSelectInitial(JSON.parse(rsp).dashboard.portfolio)
                        setTimeout(function () {
                            var req = {
                                'sessionid': sessionStorage.getItem('sessionid'),
                                'ordernumofrec': 25,
                                'exchangenumofrec': 25,
                                'pairid': document.getElementById('pairName').getAttribute('pairId'),
                            }
                            dashboardEntryRefresh(req)
                        }, 3000);
                        if (entrydata.level !== null) lvlno = entrydata.level.name.split(" ")[1];
                        if (parseFloat(lvlno) >= 0.5) {
                            setTimeout(function () {
                                if (getCookie('withtut') == 'with4') {
                                    loadTutorial('with5');
                                } else {
                                    validarStepTut();
                                }
                            }, 2000);
                        }
                        break;
                    case 'portfolio':
                        sessionStorage.setItem('pairid', JSON.parse(rsp).dashboard.pairdetails.id);
                        chargePairs(JSON.parse(rsp).dashboard.pairs, false)
                        chargePortfolio(reason, JSON.parse(rsp).dashboard.portfolio, JSON.parse(rsp).dashboard.pairdetails.currency, JSON.parse(rsp).dashboard.pairdetails.refcurrency)
                        chargePairDetails(JSON.parse(rsp).dashboard.pairdetails, true)
                        chargeOrders(JSON.parse(rsp).dashboard.orders, req.ownorders)
                        chargeExchanges(JSON.parse(rsp).dashboard.exchanges)
                        chargeChart(JSON.parse(rsp).dashboard.chart)
                        chargePortfolioSelect(JSON.parse(rsp).dashboard.portfolio)

                        // Pre Market
                        if (document.getElementById('BuyAndSellSelect').value == 2 || document.getElementById('BuyAndSellSelect').value == 3) {

                            if (document.getElementById('BuyAndSellSelect').value == '2') {

                                document.getElementById('orderSell').classList.remove('redButton');
                                document.getElementById('orderSell').classList.add('grayButton');
                                document.getElementById('orderSell').disabled = true;
                                document.getElementById('orderBuy').classList.remove('grayButton');
                                document.getElementById('orderBuy').classList.add('greenButton');
                                document.getElementById('orderBuy').disabled = false;

                                document.getElementById('BuyAndSellPrice').value = (parseFloat(document.getElementById('cardBuyAndSellSell').getAttribute('number')))


                            } else if (document.getElementById('BuyAndSellSelect').value == '3') {

                                document.getElementById('orderBuy').classList.remove('greenButton');
                                document.getElementById('orderBuy').classList.add('grayButton');
                                document.getElementById('orderBuy').disabled = true;
                                document.getElementById('orderSell').classList.remove('grayButton');
                                document.getElementById('orderSell').classList.add('redButton');
                                document.getElementById('orderSell').disabled = false;

                                document.getElementById('BuyAndSellPrice').value = (parseFloat(document.getElementById('cardBuyAndSellBuy').getAttribute('number')))

                            }
                            //document.getElementById('BuyAndSellPrice').value = (parseFloat(document.getElementById('cardBuyAndSellBuy').getAttribute('number')) + parseFloat(document.getElementById('cardBuyAndSellSell').getAttribute('number')))/2
                            document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", document.getElementById('BuyAndSellPrice').value);
                            document.getElementById('BuyAndSellPrice').setAttribute("type", "text");
                            document.getElementById('BuyAndSellPrice').value = number_format(document.getElementById('BuyAndSellPrice').getAttribute("dataNumber"), document.getElementById('BuyAndSellPrice').getAttribute("icDecim"));
                            document.getElementById('BuyAndSellTotal').value = document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") * document.getElementById('BuyAndSellAmount').getAttribute("dataNumber")
                            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('BuyAndSellPrice').disabled = true;
                        }

                        break;

                    case 'chart':
                        chargePairs(JSON.parse(rsp).dashboard.pairs, false)
                        chargePortfolio(reason, JSON.parse(rsp).dashboard.portfolio, JSON.parse(rsp).dashboard.pairdetails.currency, JSON.parse(rsp).dashboard.pairdetails.refcurrency)
                        chargePairDetails(JSON.parse(rsp).dashboard.pairdetails, true)
                        chargeOrders(JSON.parse(rsp).dashboard.orders, req.ownorders)
                        chargeExchanges(JSON.parse(rsp).dashboard.exchanges)
                        chargeChart(JSON.parse(rsp).dashboard.chart)
                        chargePortfolioSelect(JSON.parse(rsp).dashboard.portfolio)
                        break;
                    default:
                        chargePairs(JSON.parse(rsp).dashboard.pairs, false)
                        chargePortfolio(reason, JSON.parse(rsp).dashboard.portfolio, JSON.parse(rsp).dashboard.pairdetails.currency, JSON.parse(rsp).dashboard.pairdetails.refcurrency)
                        chargePairDetails(JSON.parse(rsp).dashboard.pairdetails, false)
                        chargeOrders(JSON.parse(rsp).dashboard.orders, req.ownorders)
                        chargeExchanges(JSON.parse(rsp).dashboard.exchanges)
                        chargeChart(JSON.parse(rsp).dashboard.chart)
                        chargePortfolioSelect(JSON.parse(rsp).dashboard.portfolio)

                        break;
                }
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

function dashboardEntryRefresh(req) {
    if (document.getElementById('markersSeeAll').classList.contains('tablinksActive')) {
        req.ownorders = 0
    } else {
        req.ownorders = 1
    }
    if (document.getElementById('exchangeSeeAll').classList.contains('tablinksActive')) {
        req.ownexchange = 0
    } else {
        req.ownexchange = 1
    }
    if (document.getElementById('chartSeeOne').classList.contains('tablinksActive')) {
        req.charttime = 1
    } else if (document.getElementById('chartSeeTwo').classList.contains('tablinksActive')) {
        req.charttime = 2
    } else {
        req.charttime = 3
    }
    //callWSWithoutWS('GET', 'dashboard/entry', req, response);
    callWSWithoutWS('GET', 'dashboard/entryNew', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                //sessionStorage.setItem('pairid', document.getElementById('pairName').getAttribute('pairId'));
                dashboardUpdate = JSON.parse(rsp)
                chargePairs(JSON.parse(rsp).dashboard.pairs, false)
                chargePairDetails(JSON.parse(rsp).dashboard.pairdetails, false)
                chargeOrders(JSON.parse(rsp).dashboard.orders, req.ownorders)
                chargeExchanges(JSON.parse(rsp).dashboard.exchanges)
                chargePortfolio('refresh', JSON.parse(rsp).dashboard.portfolio, JSON.parse(rsp).dashboard.pairdetails.currency, JSON.parse(rsp).dashboard.pairdetails.refcurrency)
                //chargeChart(JSON.parse(rsp).dashboard.chart)
                setTimeout(function () {
                    var req = {
                        'sessionid': sessionStorage.getItem('sessionid'),
                        'ordernumofrec': 25,
                        'exchangenumofrec': 25,
                        'pairid': document.getElementById('pairName').getAttribute('pairId'),
                    }
                    dashboardEntryRefresh(req)
                }, 15000);
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}


function chargePairs(pairs, first) {
    markersListArray = pairs;
    var maxheight = (document.getElementById("card2").offsetHeight - document.getElementById("card2").children[1].offsetHeight - document.getElementById("card2").children[2].offsetHeight);
    document.getElementById("card2").children[3].style.height = (maxheight - 20) + "px";
    //Si hay scroll le ajustamos el header
    if (document.getElementById("card2").children[3].scrollHeight > document.getElementById("card2").children[3].offsetHeight) {
        document.getElementById("card2").children[2].style.width = "calc(100% - 10px)";
    }
    if (first) {
        drawMarkersList(pairs);
    } else {
        updateMarkersList(pairs);
    }
}

function chargeOrders(orders, num) {
    chargeOrdersAsks(orders, num)
    chargeOrdersBids(orders, num)
}

function chargeOrdersBids(orders, num) {
    var bids = orders.asks
    var myown = orders.myown.split('-')
    var tbl;
    var node;
    tbl = document.getElementById('tableOrderBuy');
    //var node = tbl.children[1].children[0].children[1].cloneNode(true);
    //var header = tbl.children[1].children[0].children[0].cloneNode(true);
    //tbl.children[1].children[0].innerHTML = "";
    //tbl.children[1].children[0].appendChild(header);
    var node = tbl.children[1].children[1].children[0].cloneNode(true);
    var header = tbl.children[1].children[0].children[0].cloneNode(true);
    tbl.children[1].children[1].innerHTML = "";
    var tmp = null; tmp = node.cloneNode(true);

    //if(!(bids.length>0)){
    if (!(bids)) {
        var ele = null;
        ele = tmp.cloneNode(true);
        ele.style.display = "none";
        tbl.children[1].children[1].appendChild(ele);
    } else {
        for (var i = 0; i < bids.length; i++) {
            var ele = null;
            ele = tmp.cloneNode(true);
            ele.style.display = "";
            ele.children[0].setAttribute('orderId', bids[i].id)
            ele.children[1].textContent = bids[i].orders
            ele.children[2].textContent = bids[i].quantity.formatted
            ele.children[2].setAttribute('quantityNumber', bids[i].quantity.number)
            ele.children[3].textContent = bids[i].total.formatted
            ele.children[3].setAttribute('totalNumber', bids[i].total.number)
            ele.children[4].textContent = bids[i].price.formatted
            ele.children[4].setAttribute('priceNumber', bids[i].price.number)

            if (num === 1) {
                ele.children[0].innerHTML = '<i class="fas fa-trash-alt trashIcon"></i>'
                var arrayBids = bids[i].ids.split('-');
                var find = false;
                var findId;
                for (var j = 0; j < arrayBids.length; j++) {
                    if (myown.includes(arrayBids[j])) {
                        find = true;
                        findId = arrayBids[j]
                    }
                }
                ele.children[0].setAttribute('orderId', findId)
                ele.children[0].addEventListener("click", function (e) {
                    /*req = {
                        'id': ele.children[0].getAttribute('orderId'),
                        'sessionid': sessionStorage.getItem('sessionid')
                    }*/
                    req = {
                        'id': this.getAttribute('orderId'),
                        'sessionid': sessionStorage.getItem('sessionid')
                    }
                    ordersCancel(req)
                });
            } else {
                var arrayBids = bids[i].ids.split('-');
                var find = false;
                var findId;
                for (var j = 0; j < arrayBids.length; j++) {
                    if (myown.includes(arrayBids[j])) {
                        find = true;
                        findId = arrayBids[j]
                    }
                }
                if (find) {
                    ele.children[0].innerHTML = '<i class="fas fa-circle circleIcon"></i>'
                    ele.children[0].setAttribute('orderId', findId)
                } else {
                    ele.children[0].innerHTML = ''
                }
            }
            tbl.children[1].children[1].appendChild(ele);

        }
    }
}


function chargeOrdersAsks(orders, num) {
    var asks = orders.bids
    var myown = orders.myown.split('-')
    var tbl;
    var node;
    tbl = document.getElementById('tableOrderSell');
    //var node = tbl.children[1].children[0].children[1].cloneNode(true);
    var node = tbl.children[1].children[1].children[0].cloneNode(true);
    //var header = tbl.children[1].children[0].children[0].cloneNode(true);
    var header = tbl.children[1].children[0].children[0].cloneNode(true);
    //tbl.children[1].children[0].innerHTML = "";
    tbl.children[1].children[1].innerHTML = "";
    //tbl.children[1].children[0].appendChild(header);
    var tmp = null; tmp = node.cloneNode(true);

    //if(!(asks.length>0)){
    if (!(asks)) {
        var ele = null;
        ele = tmp.cloneNode(true);
        ele.style.display = "none";
        //tbl.children[1].children[0].appendChild(ele);
        tbl.children[1].children[1].appendChild(ele);
    } else {
        for (var i = 0; i < asks.length; i++) {
            var ele = null;
            ele = tmp.cloneNode(true);
            ele.style.display = "";
            ele.children[0].textContent = asks[i].price.formatted
            ele.children[0].setAttribute('priceNumber', asks[i].price.number)
            ele.children[1].textContent = asks[i].total.formatted
            ele.children[1].setAttribute('totalNumber', asks[i].total.number)
            ele.children[2].textContent = asks[i].quantity.formatted
            ele.children[2].setAttribute('quantityNumber', asks[i].quantity.number)
            ele.children[3].textContent = asks[i].orders
            ele.children[4].setAttribute('orderId', asks[i].id)
            if (num === 1) {
                ele.children[4].innerHTML = '<i class="fas fa-trash-alt trashIcon"></i>'

                var arrayAsks = asks[i].ids.split('-');
                var find = false;
                var findId;
                for (var j = 0; j < arrayAsks.length; j++) {
                    if (myown.includes(arrayAsks[j])) {
                        find = true;
                        findId = arrayAsks[j]
                    }
                }
                ele.children[4].children[0].setAttribute('orderId', findId)
                if (find) {
                    ele.children[4].innerHTML = '<i class="fas fa-trash-alt trashIcon"></i>'
                    ele.children[4].setAttribute('orderId', findId)
                }
                ele.children[4].addEventListener("click", function (e) {
                    /*req = {
                        'id': ele.children[4].getAttribute('orderId'),
                        'sessionid': sessionStorage.getItem('sessionid')
                    }*/
                    req = {
                        'id': this.getAttribute('orderId'),
                        'sessionid': sessionStorage.getItem('sessionid')
                    }
                    ordersCancel(req)
                });
            } else {
                var arrayAsks = asks[i].ids.split('-');
                //for(var i = 0 ; i < )
                var find = false;
                var findId;
                for (var j = 0; j < arrayAsks.length; j++) {
                    if (myown.includes(arrayAsks[j])) {
                        find = true;
                        findId = arrayAsks[j]
                    }
                }
                if (find) {
                    ele.children[4].innerHTML = '<i class="fas fa-circle circleIcon"></i>'
                    ele.children[4].setAttribute('orderId', findId)
                } else {
                    ele.children[4].innerHTML = ''
                }

            }
            //tbl.children[1].children[0].appendChild(ele);
            tbl.children[1].children[1].appendChild(ele);
        }
    }
}

function chargeExchanges(exchanges) {
    var tbl;
    var node;
    tbl = document.getElementById("tableExchange");
    //var node = tbl.children[0].children[0].children[1].cloneNode(true);
    var node = tbl.children[0].children[1].children[0].cloneNode(true);
    var header = tbl.children[0].children[0].children[0].cloneNode(true);
    tbl.children[0].children[1].innerHTML = "";
    //tbl.children[0].children[0].appendChild(header);
    var tmp = null; tmp = node.cloneNode(true);
    //if(!(exchanges.length>0)){
    if (!(exchanges)) {
        var ele = null;
        ele = tmp.cloneNode(true);
        ele.style.display = "none";
        tbl.children[0].children[1].appendChild(ele);
    } else {
        for (var i = 0; i < exchanges.length; i++) {
            var ele = null;
            ele = tmp.cloneNode(true);
            ele.style.display = "";
            if (exchanges[i].side.id === 1) {
                ele.children[0].innerHTML = '<i class="fas fa-caret-down" style="color: #C04F5D"></i>'
            }
            else if (exchanges[i].side.id === 2) {
                ele.children[0].innerHTML = '<i class="fas fa-caret-up" style="color: #85BB4F"></i>'
            }
            ele.children[1].textContent = exchanges[i].date.formatted
            ele.children[2].textContent = exchanges[i].quantity.formatted
            ele.children[3].textContent = exchanges[i].price.formatted
            tbl.children[0].children[1].appendChild(ele);
        }
    }
}

function chargePortfolio(reason, portfolio, currency, refCurrency) {
    var ifCurrency = false;
    var ifRefCurrency = false;
    var portfolioArray = []
    var newCurrencieArray = [];
    if (portfolio.accounts != null && portfolio.accounts != undefined && portfolio.accounts != '') {
        for (var i = 0; i < portfolio.accounts.length; i++) {
            portfolioArray.push({
                'src': "",//"./img/05 Rounded BW/SVG/"+JSON.parse(rsp).records[i].currency.icon+".svg",
                'name': portfolio.accounts[i].currency.symbol,
                'amount': (portfolio.accounts[i].balance ? fixDecimals(portfolio.accounts[i].balance.formatted) : 0),
                'ptc': portfolio.accounts[i].pct ? portfolio.accounts[i].pct.formatted : '0,00%',
                'id': portfolio.accounts[i].id,
                'currencyid': portfolio.accounts[i].currency.id,
                'decimals': portfolio.accounts[i].currency.decimals,
                'interface': portfolio.accounts[i].currency.interface,
                'status': portfolio.accounts[i].currency.status,
                'dsc': portfolio.accounts[i].currency.dsc,
                'icon': portfolio.accounts[i].currency.icon,
                'xfer': portfolio.accounts[i].currency.xfer
            })
            if (portfolio.accounts[i].id == 0) {
                newCurrencieArray.push(portfolio.accounts[i].currency.id)
            }

            //VALIDA SI LAS MONEDAS EXISTENTES POR SYMBOL VIENE EN EL SERVICIO SI NO GENERA PARA PERMITIR LA CREACIÓN
            if (currency.symbol == portfolio.accounts[i].currency.symbol) {
                ifCurrency = true
            }
            if (refCurrency.symbol == portfolio.accounts[i].currency.symbol) {
                ifRefCurrency = true
            }
        }
    }
    //accountsGenerateN
    if (newCurrencieArray.length > 0 && reason === 'initial') {
        accountsGenerateN(newCurrencieArray.join('-'), portfolioArray)
    } else {
        listDraw(portfolioArray, 'portfolio');
    }
}





function chargePairDetails(pairdetails, reset) {
    decimCoinCurrency = pairdetails.currency.decimals;
    decimCoinRefCurrency = pairdetails.refcurrency.decimals;

    document.getElementById('BuyAndSellPrice').setAttribute("icDecim", decimCoinCurrency);
    document.getElementById('BuyAndSellTotal').setAttribute("icDecim", decimCoinCurrency);
    document.getElementById('BuyAndSellAmount').setAttribute("icDecim", decimCoinRefCurrency);

    if (reset) {
        document.getElementById('BuyAndSellPrice').value = '';
        document.getElementById('BuyAndSellTotal').value = '';
        document.getElementById('BuyAndSellAmount').value = '';

        document.getElementById('BuyAndSellPrice').setAttribute("datanumber", '');
        document.getElementById('BuyAndSellTotal').setAttribute("datanumber", '');
        document.getElementById('BuyAndSellAmount').setAttribute("datanumber", '');

        document.getElementById('BuyAndSellTotal').value = number_format(document.getElementById('BuyAndSellPrice').getAttribute('dataNumber'), document.getElementById('BuyAndSellTotal').getAttribute("icDecim"));
        document.getElementById('BuyAndSellAmount').value = number_format(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('dataNumber')).noExponents(), document.getElementById('BuyAndSellAmount').getAttribute("icDecim"));
        document.getElementById('BuyAndSellPrice').value = number_format(document.getElementById('BuyAndSellPrice').getAttribute('dataNumber'), document.getElementById('BuyAndSellPrice').getAttribute("icDecim"));

        feesOrders = pairdetails.fees
        pairDetailsVar = pairdetails
        document.getElementById('BuyAndSellNote').innerHTML = setFeesOrders(document.getElementById('BuyAndSellSelect').value)
    }

    document.getElementById('pairName').innerHTML = pairdetails.refcurrency.symbol + '/' + pairdetails.currency.symbol
    document.getElementById('pairName').setAttribute("pairid", pairdetails.id);
    //sessionStorage.setItem('pairid', pairdetails.id);
    document.getElementById('pairAmount').innerHTML = pairdetails.last.formatted
    document.getElementById('pairVol').innerHTML = 'VOL <strong>' + pairdetails.volume.formatted + '</strong> ' + pairdetails.refcurrency.symbol
    if (pairdetails.change.number >= 0) {
        document.getElementById('pairPct').innerHTML = pairdetails.nmalchange.formatted + '<i class="fas fa-caret-up"></i> (' + pairdetails.change.formatted + ')'
        document.getElementById('pairPct').classList.remove('pairNeg')
        document.getElementById('pairPct').classList.add('pairPos')
    } else {
        document.getElementById('pairPct').innerHTML = pairdetails.nmalchange.formatted + '<i class="fas fa-caret-down"></i> (' + pairdetails.change.formatted + ')'
        document.getElementById('pairPct').classList.remove('pairPos')
        document.getElementById('pairPct').classList.add('pairNeg')
    }

    document.getElementById('pairLow').innerHTML = 'LOW <strong>' + pairdetails.low.formatted + '</strong>'
    document.getElementById('pairHigh').innerHTML = 'HIGH <strong>' + pairdetails.high.formatted + '</strong>'

    document.getElementById('cardBuyAndSellBuy').innerHTML = '<i class="fas fa-caret-up"></i> <strong> ' + pairdetails.bid.formatted + '</strong>'
    document.getElementById('cardBuyAndSellBuy').setAttribute('number', pairdetails.bid.number)
    document.getElementById('cardBuyAndSellBuy').setAttribute('formatted', pairdetails.bid.formatted)
    document.getElementById('cardBuyAndSellSell').innerHTML = '<i class="fas fa-caret-down"></i> <strong> ' + pairdetails.ask.formatted + '</strong>'
    document.getElementById('cardBuyAndSellSell').setAttribute('number', pairdetails.ask.number)
    document.getElementById('cardBuyAndSellSell').setAttribute('formatted', pairdetails.ask.formatted)

    document.getElementById('cardBuyAndSellPriceText').innerHTML = pairdetails.currency.symbol
    document.getElementById('cardBuyAndSellAmountText').innerHTML = pairdetails.refcurrency.symbol
    document.getElementById('cardBuyAndSellTotalText').innerHTML = pairdetails.currency.symbol

    for (var i = 0; i < icons.length; i++) {
        if (icons[i].name == pairdetails.refcurrency.icon) {
            //document.getElementById('detailIcon').setAttribute("src",icons[i].url);
            document.getElementById('detailIcon').style.backgroundImage = 'url(' + icons[i].url + ')';

            //document.getElementById('detailIcon').setAttribute("style","background-image:url('"+icons[i].url+"')");
        }
    }


    document.getElementById('BuyAndSellTotal').setAttribute('currencyId', pairdetails.currency.id)
    document.getElementById('BuyAndSellAmount').setAttribute('currencyId', pairdetails.refcurrency.id)

}

var getBrowserInfo = function () {
    var ua = navigator.userAgent, tem,
        M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE ' + (tem[1] || '');
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
        if (tem != null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
    return M.join(' ');
};

function ordersInsert(req) {
    callWS('POST', 'orders/insert', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                var reqDashboardEntry = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'ordernumofrec': 25,
                    'exchangenumofrec': 25,
                    'pairid': document.getElementById('pairName').getAttribute('pairId')
                }
                if (document.getElementById('markersSeeAll').classList.contains('tablinksActive')) {
                    dashboardEntry(reqDashboardEntry, 'orders', 0)
                } else {
                    reqDashboardEntry.ownorders = 1
                    dashboardEntry(reqDashboardEntry, 'orders', 1)
                }
                document.getElementById('BuyAndSellPrice').value = '';
                document.getElementById('BuyAndSellTotal').value = '';
                document.getElementById('BuyAndSellAmount').value = '';

                document.getElementById('BuyAndSellPrice').setAttribute("datanumber", '');
                document.getElementById('BuyAndSellTotal').setAttribute("datanumber", '');
                document.getElementById('BuyAndSellAmount').setAttribute("datanumber", '');

                document.getElementById('BuyAndSellTotal').value = number_format(document.getElementById('BuyAndSellTotal').getAttribute('dataNumber'), document.getElementById('BuyAndSellTotal').getAttribute("icDecim"));
                document.getElementById('BuyAndSellAmount').value = number_format(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('dataNumber')).noExponents(), document.getElementById('BuyAndSellAmount').getAttribute("icDecim"));
                document.getElementById('BuyAndSellPrice').value = number_format(document.getElementById('BuyAndSellPrice').getAttribute('dataNumber'), document.getElementById('BuyAndSellPrice').getAttribute("icDecim"));
                break;
            case 400:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                req.qty = JSON.parse(rsp).avaliable
                ordersInsertParcial(req)
                break;
            case 403:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 406:
                document.getElementById('failureMsg').innerHTML = getLangById('var39')[lang]
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 500:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

function ordersInsertParcial(req) {
    callWS('POST', 'orders/insert', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                if (req.side == 2) {
                    document.getElementById('failureMsgYellow').innerHTML = getLangById('var40')[lang] +
                        number_format(parseFloat(req.qty), document.getElementById('BuyAndSellAmount').getAttribute("icDecim"))
                        + ' ' + document.getElementById('cardBuyAndSellAmountText').innerHTML
                        + getLangById('var41')[lang] + number_format(JSON.parse(rsp).finalprice, document.getElementById('BuyAndSellPrice').getAttribute('icdecim'))
                        + ' ' + document.getElementById('cardBuyAndSellPriceText').innerHTML
                    // Venta
                } else if (req.side == 1) {
                    document.getElementById('failureMsgYellow').innerHTML = getLangById('var40')[lang] +
                        number_format(parseFloat(req.qty), document.getElementById('BuyAndSellAmount').getAttribute("icDecim"))
                        + ' ' + document.getElementById('cardBuyAndSellAmountText').innerHTML
                        + getLangById('var41')[lang] + number_format(JSON.parse(rsp).finalprice, document.getElementById('BuyAndSellPrice').getAttribute('icdecim'))
                        + ' ' + document.getElementById('cardBuyAndSellPriceText').innerHTML
                }
                document.getElementsByClassName('success')[1].style.display = "table"
                var reqDashboardEntry = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'ordernumofrec': 25,
                    'exchangenumofrec': 25,
                    'pairid': document.getElementById('pairName').getAttribute('pairId')
                }
                if (document.getElementById('markersSeeAll').classList.contains('tablinksActive')) {
                    dashboardEntry(reqDashboardEntry, 'orders', 0)
                } else {
                    reqDashboardEntry.ownorders = 1
                    dashboardEntry(reqDashboardEntry, 'orders', 1)
                }
                document.getElementById('BuyAndSellPrice').value = '';
                document.getElementById('BuyAndSellTotal').value = '';
                document.getElementById('BuyAndSellAmount').value = '';

                document.getElementById('BuyAndSellPrice').setAttribute("datanumber", '');
                document.getElementById('BuyAndSellTotal').setAttribute("datanumber", '');
                document.getElementById('BuyAndSellAmount').setAttribute("datanumber", '');

                document.getElementById('BuyAndSellTotal').value = number_format(document.getElementById('BuyAndSellTotal').getAttribute('dataNumber'), document.getElementById('BuyAndSellTotal').getAttribute("icDecim"));
                document.getElementById('BuyAndSellAmount').value = number_format(document.getElementById('BuyAndSellAmount').getAttribute('dataNumber'), document.getElementById('BuyAndSellAmount').getAttribute("icDecim"));
                document.getElementById('BuyAndSellPrice').value = number_format(document.getElementById('BuyAndSellPrice').getAttribute('dataNumber'), document.getElementById('BuyAndSellPrice').getAttribute("icDecim"));
                break;
            case 400:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 403:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 406:
                document.getElementById('failureMsg').innerHTML = getLangById('var39')[lang]
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 500:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

function ordersCancel(req) {
    callWS('GET', 'orders/cancel', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                var reqDashboardEntry = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'ordernumofrec': 25,
                    'exchangenumofrec': 25,
                    'pairid': document.getElementById('pairName').getAttribute('pairId'),
                    'ownorders': 1
                }
                dashboardEntry(reqDashboardEntry, 'orders', 1)
                break;
            case 400:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 403:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 500:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

String.prototype.replaceAll = function (strReplace, strWith) {
    // See http://stackoverflow.com/a/3561711/556609
    var esc = strReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    var reg = new RegExp(esc, 'ig');
    return this.replace(reg, strWith);
};

function makeOrder() {

    req = {
        'pairid': parseInt(document.getElementById('pairName').getAttribute("pairid")),
        'qty': parseFloat((number_format(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')).noExponents(), document.getElementById('BuyAndSellAmount').getAttribute("icDecim")).replaceAll('.', '').toString()).replaceAll(',', '.')).noExponents(),
        'type': document.getElementById('confirmOrderTypeOrder').innerHTML == 'Market' ? 1 : 2,
        'side': document.getElementById('confirmOrderTypeAction').innerHTML == 'Venta' ? 1 : 2,
        'sessionid': sessionStorage.getItem('sessionid')
    }
    /*req = {
        'pairid': parseInt(document.getElementById('pairName').getAttribute("pairid")),
        'qty': parseFloat(number_format(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')).noExponents(),document.getElementById('BuyAndSellAmount').getAttribute("icDecim")).replaceAll('.','').replaceAll(',','.')).noExponents(),
        'type': document.getElementById('confirmOrderTypeOrder').innerHTML == 'Market' ? 1 : 2,
        'side': document.getElementById('confirmOrderTypeAction').innerHTML == 'Venta' ? 1 : 2,
        'sessionid': sessionStorage.getItem('sessionid')
    }
    replace*/

    // Si es limit debo mandar el precio
    if (req.type == 2) {
        req.price = parseFloat(document.getElementById('BuyAndSellPrice').getAttribute('dataNumber'))
    }


    ordersInsert(req)

    document.getElementsByClassName('confirmOrder')[0].style.display = "none"
    document.getElementsByTagName('body')[0].classList.remove('hidden')
}

function openConfirmOrderToMarket(type) {

    document.getElementById('BuyAndSellSelect').value = (type == 'bid' ? 2 : 3)
    document.getElementById('BuyAndSellPrice').classList.add('BuyAndSellDivInputSp')
    //document.getElementById('BuyAndSellTextLeftPrice').innerHTML = '<p class="poppins-medium">Precio  <i class="fas fa-exclamation-circle tooltip"><span class="tooltiptext poppins-regular">Referencial. Calculado como el promedio entre el precio de compra y venta</span></i></p>'
    document.getElementById('BuyAndSellTextLeftPrice').innerHTML = getLangById('var4')[lang]

    document.getElementById('tooltip').addEventListener("click", function () {
        var popup = document.getElementById("tooltip").children[0];
        popup.classList.toggle("show");
    });

    if (document.getElementById('BuyAndSellSelect').value == '2') {

        document.getElementById('orderSell').classList.remove('redButton');
        document.getElementById('orderSell').classList.add('grayButton');
        document.getElementById('orderSell').disabled = true;
        document.getElementById('orderBuy').classList.remove('grayButton');
        document.getElementById('orderBuy').classList.add('greenButton');
        document.getElementById('orderBuy').disabled = false;

        document.getElementById('BuyAndSellPrice').value = (parseFloat(document.getElementById('cardBuyAndSellSell').getAttribute('number')))


    } else if (document.getElementById('BuyAndSellSelect').value == '3') {

        document.getElementById('orderBuy').classList.remove('greenButton');
        document.getElementById('orderBuy').classList.add('grayButton');
        document.getElementById('orderBuy').disabled = true;
        document.getElementById('orderSell').classList.remove('grayButton');
        document.getElementById('orderSell').classList.add('redButton');
        document.getElementById('orderSell').disabled = false;

        document.getElementById('BuyAndSellPrice').value = (parseFloat(document.getElementById('cardBuyAndSellBuy').getAttribute('number')))

    }

    document.getElementById('BuyAndSellPrice').classList.remove('BuyAndSellDivInput')
    //document.getElementById('BuyAndSellPrice').value = (parseFloat(document.getElementById('cardBuyAndSellBuy').getAttribute('number')) + parseFloat(document.getElementById('cardBuyAndSellSell').getAttribute('number')))/2
    document.getElementById('BuyAndSellPrice').setAttribute("dataNumber", document.getElementById('BuyAndSellPrice').value);
    document.getElementById('BuyAndSellPrice').setAttribute("type", "text");
    document.getElementById('BuyAndSellPrice').value = number_format(document.getElementById('BuyAndSellPrice').getAttribute("dataNumber"), document.getElementById('BuyAndSellPrice').getAttribute("icDecim"));
    document.getElementById('BuyAndSellTotal').value = document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") * document.getElementById('BuyAndSellAmount').getAttribute("dataNumber")
    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('BuyAndSellNote').innerHTML = getLangById('var8')[lang] + document.getElementById('BuyAndSellPrice').value
    document.getElementById('BuyAndSellPrice').disabled = true;

    openConfirmOrder(type)
}

function openConfirmOrder(type) {
    document.getElementById('confirmOrderPair').innerHTML = document.getElementById('pairName').innerHTML
    document.getElementById('confirmOrderTypeOrder').innerHTML = document.getElementById('BuyAndSellSelect').value == 1 ? 'Limit' : 'Market'
    document.getElementById('confirmOrderTypeAction').innerHTML = type == 'bid' ? 'Compra' : 'Venta'
    document.getElementById('confirmOrderAmount').innerHTML = document.getElementById('cardBuyAndSellAmountText').innerHTML + ' ' +
        number_format(document.getElementById('BuyAndSellAmount').getAttribute("dataNumber"), document.getElementById('BuyAndSellAmount').getAttribute("icDecim"));
    document.getElementById('confirmOrderFees').innerHTML = calculateFees(type, document.getElementById('BuyAndSellSelect').value);

    ////console.log(feesOrders.orders.limit) // document.getElementById('BuyAndSellSelect').value == 1
    ////console.log(feesOrders.orders.market) // document.getElementById('BuyAndSellSelect').value == 2

    /*document.getElementById('confirmOrderFinal').innerHTML = document.getElementById('cardBuyAndSellPriceText').innerHTML + ' ' + 
                                                             (document.getElementById('BuyAndSellSelect').value == 1 ?
                                                             // Limit
                                                             number_format(document.getElementById('BuyAndSellTotal').getAttribute("dataNumber"),
                                                                           document.getElementById('BuyAndSellTotal').getAttribute("icDecim")) :
                                                             // Market
                                                             number_format(calculateTotalM(type),
                                                                           document.getElementById('BuyAndSellTotal').getAttribute("icDecim")))*/

    document.getElementById('confirmOrderFinal').innerHTML = calculateTotalWithFees(document.getElementById('BuyAndSellSelect').value, type)

    //if(document.getElementById('confirmOrderFinal').innerHTML == 'false'){
    if (parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')).noExponents() < parseFloat(feesOrders.min.number)) {
        document.getElementById('failureMsg').innerHTML = getLangById('var42')[lang] + feesOrders.min.formatted + ' ' + document.getElementById('cardBuyAndSellAmountText').innerHTML;
        document.getElementById('failureTitle').innerHTML = "Error";
        document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang];
        document.getElementsByClassName('failure')[0].style.display = "table";
        return;
    }

    if (calculateMinimum(type)) {
        return;
    }

    document.getElementById('textInCardResumeDivTextPrice').innerHTML = document.getElementById('BuyAndSellSelect').value == 1 ? getLangById('price')[lang] : getLangById('var43')[lang]

    if (document.getElementById('BuyAndSellSelect').value == 1) {
        document.getElementById('textInCardResumeDivTextPrice').innerHTML = getLangById('price')[lang]
    } else {
        document.getElementById('textInCardResumeDivTextPrice').innerHTML = getLangById('var44')[lang]
        document.getElementById('tooltip2').addEventListener("click", function () {
            var popup2 = document.getElementById("tooltip2").children[0];
            popup2.classList.toggle("show");
        });
    }



    //document.getElementById('cardAmountRoundedTextLastText').innerHTML = document.getElementById('BuyAndSellSelect').value == 1 ? 'Precio Efectivo' : 'Total'

    if (document.getElementById('BuyAndSellSelect').value == 1) {
        document.getElementById('efectPriceHr').style.display = 'block'
        document.getElementById('efectPriceDiv').style.display = 'table'
        /*document.getElementById('totalNDHr').style.display = 'block'
        document.getElementById('totalNDiv').style.display = 'table'*/
    } else {
        document.getElementById('efectPriceHr').style.display = 'none'
        document.getElementById('efectPriceDiv').style.display = 'none'
        /*document.getElementById('totalNDHr').style.display = 'none'
        document.getElementById('totalNDiv').style.display = 'none'*/
    }


    document.getElementById('confirmOrderEstimatedPrice').innerHTML = document.getElementById('cardBuyAndSellPriceText').innerHTML + ' ' +
        (document.getElementById('BuyAndSellSelect').value == 1 ?
            number_format(document.getElementById('BuyAndSellTotal').getAttribute("dataNumber") / document.getElementById('BuyAndSellAmount').getAttribute('dataNumber'),
                document.getElementById('BuyAndSellTotal').getAttribute("icDecim")) :
            (type == 'ask' ? document.getElementById('cardBuyAndSellBuy').children[1].innerHTML : document.getElementById('cardBuyAndSellSell').children[1].innerHTML))
    //document.getElementById('confirmOrderContinue').style.display = 'block'
    //document.getElementById('confirmOrderContinueDisabled').style.display = 'none'
    document.getElementById('confirmOrderContinue').classList.add('blueButton');
    document.getElementById('confirmOrderContinue').classList.remove('grayButton');
    document.getElementById('confirmOrderContinue').disabled = false;

    document.getElementsByClassName('confirmOrder')[0].style.display = "table"
    document.getElementsByTagName('body')[0].classList.add('hidden')

    /*setTimeout(function(){ 
        
        document.getElementById('confirmOrderContinue').classList.remove('blueButton');
        document.getElementById('confirmOrderContinue').classList.add('grayButton');
        document.getElementById('confirmOrderContinue').disabled = true;
    }, 15000);*/

    // Compra: Cantidad x Precio / Total Neto a Obtener
    if (document.getElementById('BuyAndSellAmount').getAttribute('datanumber') != '' && document.getElementById('BuyAndSellPrice').getAttribute('datanumber') != ''
        && document.getElementById('BuyAndSellTotal').getAttribute("dataNumber") != '') {

        if (type == 'bid') {
            document.getElementById('efectPrice').innerHTML = document.getElementById('cardBuyAndSellPriceText').innerHTML + ' ' + number_format(estimatedPrice(type,
                document.getElementById('BuyAndSellAmount').getAttribute('datanumber'),
                document.getElementById('BuyAndSellPrice').getAttribute('datanumber'),
                calculateTotalWithFeesNumber(document.getElementById('BuyAndSellSelect').value, type)), document.getElementById('BuyAndSellTotal').getAttribute("icDecim"))


            // Venta: (Cantidad x Precio / Total Neto a Obtener) x Precio
        } else {
            document.getElementById('efectPrice').innerHTML = document.getElementById('cardBuyAndSellPriceText').innerHTML + ' ' + number_format(estimatedPrice(type,
                document.getElementById('BuyAndSellAmount').getAttribute('datanumber'),
                document.getElementById('BuyAndSellPrice').getAttribute('datanumber'),
                calculateTotalWithFeesNumber(document.getElementById('BuyAndSellSelect').value, type)), document.getElementById('BuyAndSellTotal').getAttribute("icDecim"))
        }
    } else {
        document.getElementById('efectPrice').innerHTML = document.getElementById('confirmOrderEstimatedPrice').innerHTML
    }

    //if(calculateMinimum(type) == false){
    if (document.getElementById('confirmOrderFinal').innerHTML == 'false') {
        document.getElementById('confirmOrderFinal').innerHTML = document.getElementById('confirmOrderTypeAction').innerHTML == 'Venta' ?
            number_format(0, document.getElementById('BuyAndSellTotal').getAttribute('icdecim')) :
            number_format(0, document.getElementById('BuyAndSellAmount').getAttribute('icdecim'))
        document.getElementById('messageInfCountdown').innerHTML = getLangById('var45')[lang]
        document.getElementById('confirmOrderContinue').classList.remove('blueButton');
        document.getElementById('confirmOrderContinue').classList.add('grayButton');
        document.getElementById('confirmOrderContinue').disabled = true;
    } else {
        var n = 15;
        var tm = setInterval(countDown, 1000);

        function countDown() {
            n--;
            if (n == 0) {
                document.getElementById('messageInfCountdown').innerHTML = getLangById('var46')[lang]
                document.getElementById('confirmOrderContinue').classList.remove('blueButton');
                document.getElementById('confirmOrderContinue').classList.add('grayButton');
                document.getElementById('confirmOrderContinue').disabled = true;
                clearInterval(tm);
            }
            if (document.getElementById('messageInfCountdown').children[0]) {
                document.getElementById('messageInfCountdown').children[0].innerHTML = n
            }
            if (document.getElementsByClassName('confirmOrder')[0].style.display == "none") {
                document.getElementById('messageInfCountdown').innerHTML = getLangById('var47')[lang]
                clearInterval(tm);
            }
        }
    }
}

function calculateMinimum(type) {
    //if(parseFloat(document.getElementById('BuyAndSellTotal').getAttribute('datanumber')) < parseFloat(feesOrders.min.number)){
    if (parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')) < parseFloat(feesOrders.min.number)) {
        document.getElementById('failureMsg').innerHTML = getLangById('var42')[lang] + feesOrders.min.formatted + ' ' + document.getElementById('cardBuyAndSellTotalText').innerHTML;
        document.getElementById('failureTitle').innerHTML = "Error";
        document.getElementById('wdFiatbuttonI').innerHTML = getLangById('var2')[lang];
        document.getElementsByClassName('failure')[0].style.display = "table";
        return true
    }
    return false;
}

function calculateTotalWithFees(typeSelect, typeButton) {
    // Limit
    if (typeSelect == 1) {
        // Compra - Limit
        if (typeButton == 'bid') {
            if (parseFloat(calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')), feesOrders.orders.limit)) < 0) {
                return false
            }
            return document.getElementById('cardBuyAndSellAmountText').innerHTML + ' ' +
                number_format(calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')), feesOrders.orders.limit),
                    document.getElementById('BuyAndSellAmount').getAttribute("icDecim"))
            // Venta - Limit
        } else {
            if (parseFloat(calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellTotal').getAttribute('datanumber')), feesOrders.orders.limit)) < 0) {
                return false
            }
            return document.getElementById('cardBuyAndSellTotalText').innerHTML + ' ' +
                number_format(calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellTotal').getAttribute('datanumber')), feesOrders.orders.limit),
                    document.getElementById('BuyAndSellTotal').getAttribute("icDecim"))
        }
        // Market    
    } else {
        // Compra - Market
        if (typeButton == 'bid') {
            if (parseFloat(calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')), feesOrders.orders.market)) < 0) {
                return false
            }
            return document.getElementById('cardBuyAndSellAmountText').innerHTML + ' ' +
                number_format(calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')), feesOrders.orders.market),
                    document.getElementById('BuyAndSellAmount').getAttribute("icDecim"))
            // Venta - Market
        } else {
            if (parseFloat(calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellTotal').getAttribute('datanumber')), feesOrders.orders.market)) < 0) {
                return false
            }
            return document.getElementById('cardBuyAndSellTotalText').innerHTML + ' ' +
                number_format(calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellTotal').getAttribute('datanumber')), feesOrders.orders.market),
                    document.getElementById('BuyAndSellTotal').getAttribute("icDecim"))
        }
    }
    return 0
}

function calculateTotalWithFeesNumber(typeSelect, typeButton) {
    // Limit
    if (typeSelect == 1) {
        // Compra - Limit
        if (typeButton == 'bid') {
            return calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')), feesOrders.orders.limit)
            // Venta - Limit
        } else {
            return calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellTotal').getAttribute('datanumber')), feesOrders.orders.limit)
        }
        // Market    
    } else {
        // Compra - Market
        if (typeButton == 'bid') {
            return calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')), feesOrders.orders.market)
            // Venta - Market
        } else {
            return calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellTotal').getAttribute('datanumber')), feesOrders.orders.market)
        }
    }
    return 0
}

function calculateFeesConfirmOrder(number, fee, type) {
    if (fee.pctfee) {
        return (parseFloat(number - number * (fee.pctfee.number / 100))).noExponents()
    } else if (fee.nmalfee) {
        return (parseFloat(number - fee.nmalfee.number)).noExponents()
    }
    else {
        return parseFloat(number).noExponents()
    }
}

function calculateTotal(type) {
    var amount = parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('dataNumber'))
    var amountCount = 0;
    var finalCount = 0;
    switch (type) {
        case 'ask':
            if (document.getElementsByClassName('infOrderBuy').length > 0) {
                // Itero sobre las ordenes
                for (var i = 0; document.getElementsByClassName('infOrderBuy').length > i; i++) {
                    // Si no he llegado al monto que quiero
                    if (amountCount + parseFloat(document.getElementsByClassName('infOrderBuy')[i].children[2].getAttribute('quantitynumber')) < amount) {
                        amountCount += parseFloat(document.getElementsByClassName('infOrderBuy')[i].children[2].getAttribute('quantitynumber'))
                        finalCount += parseFloat(document.getElementsByClassName('infOrderBuy')[i].children[3].getAttribute('totalNumber'))
                        // Si ya llegue al monto que quiero o me pase
                    } else {
                        finalCount += (amount - amountCount) * parseFloat(document.getElementsByClassName('infOrderBuy')[i].children[4].getAttribute('priceNumber'))
                        return finalCount
                    }
                }
                // Si no hay suficientes ordenes para completar la mia
                if (amountCount < amount) {
                    finalCount += (amount - amountCount) * parseFloat(document.getElementById('cardBuyAndSellBuy').getAttribute('number'));
                    return finalCount
                }
                // Si no hay ordenes que iterar, devuelvo ult precio * cantidad
            } else {
                return (parseFloat(document.getElementById('cardBuyAndSellBuy').getAttribute('number')) * amount, decimCoinCurrency)
            }
            break;
        case 'bid':
            if (document.getElementsByClassName('infOrderSell').length > 0) {
                for (var i = 0; document.getElementsByClassName('infOrderSell').length > i; i++) {
                    if (amountCount + parseFloat(document.getElementsByClassName('infOrderSell')[i].children[2].getAttribute('quantitynumber')) < amount) {
                        amountCount += parseFloat(document.getElementsByClassName('infOrderSell')[i].children[2].getAttribute('quantitynumber'))
                        finalCount += parseFloat(document.getElementsByClassName('infOrderSell')[i].children[1].getAttribute('totalNumber'))
                    } else {
                        finalCount += (amount - amountCount) * parseFloat(document.getElementsByClassName('infOrderSell')[i].children[0].getAttribute('priceNumber'))
                        return finalCount
                    }
                }
                if (amountCount < amount) {
                    finalCount += (amount - amountCount) * parseFloat(document.getElementById('cardBuyAndSellSell').getAttribute('number'));
                    return finalCount
                }
            } else {
                return (parseFloat(document.getElementById('cardBuyAndSellSell').getAttribute('number')) * amount, decimCoinCurrency)
            }
            break;
        default:
            return 0
            break;
    }
    return -1
}

function calculateTotalM(type) {
    switch (type) {
        case 'ask':
            //return document.getElementById('cardBuyAndSellBuy').children[1].innerHTML
            return parseFloat(document.getElementById('cardBuyAndSellSell').getAttribute('number')) * parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber'))
            break;
        case 'bid':
            //return document.getElementById('cardBuyAndSellSell').children[1].innerHTML
            return parseFloat(document.getElementById('cardBuyAndSellBuy').getAttribute('number')) * parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber'))
            break;
        default:
            return 0
            break;
    }
}

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;
    }
}

// Ref max 6 digitos numericos
function depFiatRefLength(e) {
    if (document.getElementById('depFiatInfRef').value.length > document.getElementById('depFiatInfRef').maxLength) {
        return false;
    }

    tecla = (document.all) ? e.keyCode : e.which;

    //Tecla de retroceso para borrar, siempre la permite
    if (tecla == 8) {
        return true;
    }

    // Patron de entrada, en este caso solo acepta numeros
    patron = /[0-9]/;
    tecla_final = String.fromCharCode(tecla);
    return patron.test(tecla_final);
}

// Solo numeros y letras
function noSpecialChar(e) {
    tecla = (document.all) ? e.keyCode : e.which;

    if (tecla == 8) {
        return true;
    }

    patron = /[a-zA-Z0-9]/;
    tecla_final = String.fromCharCode(tecla);
    return patron.test(tecla_final);
}

function onlyNumber(e) {
    tecla = (document.all) ? e.keyCode : e.which;

    if (tecla == 8) {
        return true;
    }

    patron = /[0-9]/;
    tecla_final = String.fromCharCode(tecla);
    return patron.test(tecla_final);
}

function onlyAlphanumeric(input) {
    var letters = /^[0-9a-zA-Z]+$/;
    return input.value.match(letters)
}

function openBlockChainPag(id, type) {
    if (type == 4) {
        window.open('https://www.blockchain.com/search?search=' + id, '_blank');
    } else if (type == 5) {
        window.open('https://explorador.petro.gob.ve/insight/transaction/' + id, '_blank');
    } else if (type == 6) {
        window.open('https://tronscan.org/#/transaction/' + id, '_blank');
    } else if (type == 7) {
        window.open('https://blockexplorer.one/dash/testnet/tx/' + id, '_blank');
        //window.open('https://blockexplorer.one/dash/tx/'+id, '_blank'); <-- Real blockchain
    }
}

function setFeesOrders(value) {
    if (value == 1) {
        if (feesOrders.orders.limit.nmalfee) {
            return getLangById('fees')[lang] + ': ' + pairDetailsVar.currency.nmalfee
        }
        else if (feesOrders.orders.limit.pctfee) {
            return getLangById('fees')[lang] + ': ' + feesOrders.orders.limit.pctfee.formatted + '%'
        }
        else {
            return getLangById('var48')[lang]
        }
    }
    else if (value == 2 || value == 3) {
        if (feesOrders.orders.market.nmalfee) {
            return getLangById('fees')[lang] + ': ' + pairDetailsVar.currency.nmalfee
        }
        else if (feesOrders.orders.market.pctfee) {
            return getLangById('fees')[lang] + ': ' + feesOrders.orders.market.pctfee.formatted + '%'
        }
        else {
            return getLangById('var48')[lang]
        }
    }
    else {
        return getLangById('var48')[lang]
    }
}

function calculateFees(typeOrder, typeLM) {
    // Limit
    if (typeLM == 1) {
        if (feesOrders.orders.limit.nmalfee) {
            return (typeOrder == 'ask' ? document.getElementById('cardBuyAndSellPriceText').innerHTML + ' ' + number_format(feesOrders.orders.limit.nmalfee.number, document.getElementById('BuyAndSellPrice').getAttribute('icdecim')) :
                document.getElementById('cardBuyAndSellAmountText').innerHTML + ' ' + number_format(feesOrders.orders.limit.nmalfee.number, document.getElementById('BuyAndSellAmount').getAttribute('icdecim')))
        }
        else if (feesOrders.orders.limit.pctfee) {
            return (typeOrder == 'ask' ? document.getElementById('cardBuyAndSellPriceText').innerHTML + ' ' + feesOrders.orders.limit.pctfee.formatted + '%' :
                document.getElementById('cardBuyAndSellAmountText').innerHTML + ' ' + feesOrders.orders.limit.pctfee.formatted + '%')
        }
        else {
            return 'N/A'
        }
    }
    // Market
    else if (typeLM == 2 || typeLM == 3) {
        if (feesOrders.orders.market.nmalfee) {
            return (typeOrder == 'ask' ? document.getElementById('cardBuyAndSellPriceText').innerHTML + ' ' + number_format(feesOrders.orders.market.nmalfee.number, document.getElementById('BuyAndSellPrice').getAttribute('icdecim')) :
                document.getElementById('cardBuyAndSellAmountText').innerHTML + ' ' + number_format(feesOrders.orders.market.nmalfee.number, document.getElementById('BuyAndSellAmount').getAttribute('icdecim')))
        }
        else if (feesOrders.orders.market.pctfee) {
            return (typeOrder == 'ask' ? document.getElementById('cardBuyAndSellPriceText').innerHTML + ' ' + feesOrders.orders.market.pctfee.formatted + '%' :
                document.getElementById('cardBuyAndSellAmountText').innerHTML + ' ' + feesOrders.orders.market.pctfee.formatted + '%')
        }
        else {
            return 'N/A'
        }
    }
    else {
        return 'N/A';
    }
}

Number.prototype.noExponents = function () {
    var data = String(this).split(/[eE]/);
    if (data.length == 1) return data[0];

    var z = '', sign = this < 0 ? '-' : '',
        str = data[0].replace('.', ''),
        mag = Number(data[1]) + 1;

    if (mag < 0) {
        z = sign + '0.';
        while (mag++) z += '0';
        return z + str.replace(/^\-/, '');
    }
    mag -= str.length;
    while (mag--) z += '0';
    return str + z;
}

/* Code Limitless */

// Obtiene un numero random entre min y max
function getRandomInt(min, max) {
    "use strict";
    if (max < min) {
        // Swap min and max
        [min, max] = [min, max];
    }

    // Generate random number n, where min <= n <= max
    let range = max - min + 1;
    return Math.floor(Math.random() * range) + min;
}


// Dibuja los cuadritos grises de fondo
function drawGrids() {

    let ySize = parseFloat(canvas.width / 12);
    let xSize = parseFloat(canvas.height / 11);

    let xGrid = parseFloat(canvas.height / 11);
    let yGrid = parseFloat(canvas.width / 12);

    ctx.beginPath();
    ctx.fillStyle = '#5C5D60'
    ctx.strokeStyle = '#5C5D60'
    ctx.lineWidth = 1;

    // Horizontal
    while (xGrid < canvas.height) {
        ctx.moveTo(ySize, xGrid)
        ctx.lineTo(canvas.width - ySize, xGrid)
        xGrid = xGrid + xSize
        ctx.strokeStyle = '#5C5D60'
        ctx.stroke();
    }

    // Vertical
    while (yGrid + ySize < canvas.width) {
        ctx.moveTo(yGrid, xSize)
        ctx.lineTo(yGrid, canvas.height - xSize)
        yGrid = yGrid + ySize
        ctx.strokeStyle = '#5C5D60'
        ctx.stroke();
    }

    ctx.strokeStyle = '#5C5D60'
    ctx.stroke();

    // Reinicia xGrid y yGrid
    yGrid = parseFloat(canvas.width / 12);
    xGrid = parseFloat(canvas.height / 11);

}

// Devuelve posicion en las unidades de bloque.
function blocks(count, axis) {
    let ySize = parseFloat(canvas.width / 12);
    let xSize = parseFloat(canvas.height / 11);
    return (axis == 'X' ? count * ySize : count * xSize);
}

// Devuelve la fecha correspondiente en unidades de bloque
function blocksDate(array, count, positionX) {
    return array[Math.ceil(positionX / count)]
}

function transformLegendLeft(lines) {
    let maxNum = (parseFloat(lines.max) * 1.05).noExponents()
    let minNum = 0
    let result = []
    for (var i = 9; i > 0; i--) {
        result.push(symbolNumber(i * (maxNum / 9)))
    }
    // result.push( symbolNumber ( number_format(i * (maxNum/9), document.getElementById('BuyAndSellPrice').getAttribute("icDecim")  ) ) )
    return result;
}

function transformLegendRight(bars) {
    let maxNum = (parseFloat(bars.max) * 2).noExponents()
    let minNum = 0
    let result = []
    for (var i = 9; i > 0; i--) {
        result.push(number_format(i * (maxNum / 9), document.getElementById('BuyAndSellAmount').getAttribute("icDecim")))
    }
    return result;
}

function transformLegendBottom(bars, timeframe) {
    let result = [];
    let lastLabel = 5;
    for (var i = 59; i >= 0; i--) {
        if (bars.records) {
            if (bars.records[i]) {
                if (bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '00:00' ||
                    bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '06:00' ||
                    bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '12:00' ||
                    bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '18:00') {
                    if (timeframe == 1) {
                        lastLabel = i
                    }
                } if (bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '00:00' ||
                    bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '04:00' ||
                    bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '08:00' ||
                    bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '12:00' ||
                    bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '16:00' ||
                    bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '20:00') {
                    if (timeframe == 2) {
                        if (bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '00:00') {
                            lastLabel = 0
                        } else if (bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '04:00') {
                            lastLabel = 1
                        } else if (bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '08:00') {
                            lastLabel = 2
                        } else if (bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '12:00') {
                            lastLabel = 3
                        } else if (bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '16:00') {
                            lastLabel = 4
                        } else if (bars.records[i].labeldetail.substr(bars.records[i].labeldetail.length - 5) == '20:00') {
                            lastLabel = 5
                        }
                    }
                }
            }
        }
    }

    for (var i = 9; i > 0; i--) {
        if (bars.records) {
            if (bars.records[i * 6 - 1 - (5 - lastLabel)]) {
                result.push(bars.records[i * 6 - 1 - (5 - lastLabel)].label)
            } else {
                result.push('')
            }
        } else {
            result.push('')
        }
    }
    return [result, lastLabel];

}

function getArrayLegendCalculateBars(maxNumBars) {
    let ySize = parseFloat(canvas.width / 12);
    let xSize = parseFloat(canvas.height / 11);
    pixelBlock = parseFloat(parseFloat(maxNumBars) / parseFloat(xSize * 9))
    let resultBars = [];
    for (var i = xSize * 10; i > 0; i--) {
        resultBars.push(number_format(parseFloat(i * pixelBlock), document.getElementById('BuyAndSellAmount').getAttribute("icDecim")))
    }
    return resultBars;
}


function getArrayLegendCalculateLines(maxNumBars) {
    let ySize = parseFloat(canvas.width / 12);
    let xSize = parseFloat(canvas.height / 11);
    pixelBlock = parseFloat(parseFloat(maxNumBars) / parseFloat(xSize * 9))
    let resultBars = [];
    for (var i = xSize * 10; i > 0; i--) {
        resultBars.push(symbolNumber(parseFloat(i * pixelBlock)))
    }
    return resultBars;
}

function getArrayLegendCalculateDate(records, timeframe) {


    let ySize = parseFloat(canvas.width / 12);
    let xSize = parseFloat(canvas.height / 11);
    pixelBlock = parseFloat(ySize / 6)
    let resultDates = [];
    for (var i = 60; i > 0; i--) {
        if (records) {
            if (records[i - 1]) {
                resultDates.push(records[i - 1].labeldetail)
            } else {
                resultDates.push('')
            }
        } else {
            resultDates.push('')
        }
    }
    resultDates.push('')

    let lastLabel = 5;

    for (var i = 59; i >= 0; i--) {
        if (records) {
            if (records[i]) {
                if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '00:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '06:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '12:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '18:00') {
                    if (timeframe == 1) {
                        lastLabel = i
                    }
                } if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '00:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '04:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '08:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '12:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '16:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '20:00') {
                    if (timeframe == 2) {
                        if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '00:00') {
                            lastLabel = 0
                        } else if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '04:00') {
                            lastLabel = 1
                        } else if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '08:00') {
                            lastLabel = 2
                        } else if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '12:00') {
                            lastLabel = 3
                        } else if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '16:00') {
                            lastLabel = 4
                        } else if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '20:00') {
                            lastLabel = 5
                        }
                    }
                }
            }
        }
    }

    let resultDatesTemp = resultDates

    // Si last label es 0, le quito 5

    for (var i = 0; i < resultDates.length; i++) {
        if (i < resultDates.length - (5 - lastLabel)) {
            resultDates[i] = resultDatesTemp[i + (5 - lastLabel)]
        } else {
            resultDates[i] = 0
        }
    }
    return resultDates;
}

function symbolNumber(num) {
    let numString = parseInt(num).toString()
    if (numString[0] != 0) {
        if (numString.length <= 3) {
            return numString
        } else if (numString.length <= 6) {
            if (numString.length == 4) {
                return numString.substring(0, numString.length - 3) + '.' + numString[1] + numString[2] + 'k'
            } else if (numString.length == 5) {
                return numString.substring(0, numString.length - 3) + '.' + numString[2] + 'k'
            } else {
                return numString.substring(0, numString.length - 3) + 'k'
            }
        } else if (numString.length <= 9) {
            if (numString.length == 7) {
                return numString.substring(0, numString.length - 6) + '.' + numString[1] + numString[2] + 'M'
            } else if (numString.length == 8) {
                return numString.substring(0, numString.length - 6) + '.' + numString[2] + 'M'
            } else {
                return numString.substring(0, numString.length - 6) + 'M'
            }
        } else if (numString.length <= 12) {
            if (numString.length == 10) {
                return numString.substring(0, numString.length - 9) + '.' + numString[1] + numString[2] + 'G'
            } else if (numString.length == 11) {
                return numString.substring(0, numString.length - 9) + '.' + numString[2] + 'G'
            } else {
                return numString.substring(0, numString.length - 9) + 'G'
            }
        } else if (numString.length <= 15) {
            if (numString.length == 13) {
                return numString.substring(0, numString.length - 12) + '.' + numString[1] + numString[2] + 'T'
            } else if (numString.length == 14) {
                return numString.substring(0, numString.length - 12) + '.' + numString[2] + 'T'
            } else {
                return numString.substring(0, numString.length - 12) + 'T'
            }
        } else if (numString.length <= 18) {
            if (numString.length == 16) {
                return numString.substring(0, numString.length - 15) + '.' + numString[1] + numString[2] + 'P'
            } else if (numString.length == 17) {
                return numString.substring(0, numString.length - 15) + '.' + numString[2] + 'P'
            } else {
                return numString.substring(0, numString.length - 15) + 'P'
            }
        } else if (numString.length <= 21) {
            if (numString.length == 19) {
                return numString.substring(0, numString.length - 18) + '.' + numString[1] + numString[2] + 'E'
            } else if (numString.length == 20) {
                return numString.substring(0, numString.length - 18) + '.' + numString[2] + 'E'
            } else {
                return numString.substring(0, numString.length - 18) + 'E'
            }
        } else if (numString.length <= 24) {
            if (numString.length == 22) {
                return numString.substring(0, numString.length - 21) + '.' + numString[1] + numString[2] + 'Z'
            } else if (numString.length == 23) {
                return numString.substring(0, numString.length - 21) + '.' + numString[2] + 'Z'
            } else {
                return numString.substring(0, numString.length - 21) + 'Z'
            }
        } else {
            return ''
        }
    } else {
        return number_format(parseFloat(num), document.getElementById('BuyAndSellPrice').getAttribute("icDecim"))
    }

    //result.push( symbolNumber ( number_format(i * (maxNum/9), document.getElementById('BuyAndSellPrice').getAttribute("icDecim")  ) ) )
}

function chargeChart(chart) {
    document.getElementById('charPair').innerHTML = chart.pair
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.setLineDash([0, 0]);
    drawGrids()

    let legendLeft = transformLegendLeft(chart.lines)
    let legendRight = transformLegendRight(chart.bars)
    let legendBottom = transformLegendBottom(chart.bars, chart.timeframe)
    let lastLabel = legendBottom[1]

    let legendBottomTemp = legendBottom[0]

    drawLegend(legendRight, legendLeft, legendBottom[0])
    drawLinesChart(chart.lines, chart.timeframe)
    drawBarsChart(chart.bars, chart.timeframe)
}

function calculateChartSixtyOne(array) {
    result = []
    return result;
}

// Dibuja leyenda
function drawLegend(legendLeft, legendRight, legendBottom) {
    let yPlot = 9.15;
    let pop = 0;
    ctx.beginPath();
    ctx.lineWidth = 1;
    ctx.strokeStyle = '#4287CE'
    ctx.fillStyle = '#4287CE';

    // Add left text
    ctx.moveTo(blocks(0, 'X'), blocks(10, 'Y'))
    for (let i = 8; i >= 0; i--) {
        ctx.font = 'normal 10px Roboto';
        ctx.textAlign = 'right';
        ctx.fillStyle = '#D5DCE5';
        ctx.fillText(legendLeft[i], blocks(0.9, 'X'), blocks(yPlot, 'Y'));
        yPlot = yPlot - 1
    }

    // Add right text
    yPlot = 9.15
    ctx.moveTo(blocks(0, 'X'), blocks(10, 'Y'))
    for (let i = 8; i >= 0; i--) {
        ctx.font = 'normal 10px Roboto';
        ctx.textAlign = 'left';
        ctx.fillStyle = '#D5DCE5';
        ctx.fillText(legendRight[i], blocks(11.1, 'X'), blocks(yPlot, 'Y'));
        yPlot = yPlot - 1
    }

    // Add bottom text
    xPlot = 10
    ctx.moveTo(blocks(5, 'X'), blocks(0, 'Y'))
    for (let i = 8; i >= 0; i--) {
        ctx.font = 'normal 12px Roboto';
        ctx.textAlign = 'center';
        ctx.fillStyle = '#D5DCE5';
        ctx.fillText(legendBottom[i], blocks(xPlot, 'X'), blocks(10.8, 'Y'));
        xPlot = xPlot - 1
    }

    ctx.stroke();
}

// Encuentra la pendiente de la recta ( m = (y2-y1)/(x2-x1) )
function findSlope(x1, y1, x2, y2) {
    return (y2 - y1) / (x2 - x1)
}

// Encuentra b (y = mx + b)
function findB(y, m, x) {
    return y - m * x
}

// Encuentra el valor de y en un determinado punto X
function findValueY(m, x, b) { // y = mx + b
    return m * x + b
}

function drawLinesChart(lines, timeframe) {
    let linesArray = getArrayForChart(lines.records, timeframe)
    let lastLabel = linesArray[1]
    let maxNum = lines.max
    let maxLine = maxNum * 1.05
    let difference = maxNum * 0.05
    let tamBloqueNumber = maxLine / 9
    ctx.setLineDash([0, 0]);
    drawLines(linesArray[0], difference, tamBloqueNumber, maxNum, lastLabel)
}

function drawBarsChart(bars, timeframe) {
    let barsArray = getArrayForChart(bars.records, timeframe)
    let lastLabel = barsArray[1]
    let maxNumB = parseFloat(bars.max) * 2;
    let tamBloqueNumberB = maxNumB / 9
    drawBars(barsArray[0], tamBloqueNumberB, maxNumB, lastLabel)
}

function getArrayForChart(records, timeframe) {
    let result = []
    let labeldetails = []
    let lastLabel = 5;
    for (var i = 59; i >= 0; i--) {
        if (records) {
            if (records[i]) {
                result.push(parseFloat(records[i].price.number).noExponents())
                labeldetails.push(records[i].labeldetail.substr(records[i].labeldetail.length - 5))
                if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '00:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '06:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '12:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '18:00') {
                    if (timeframe == 1) {
                        lastLabel = i
                    }
                } if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '00:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '04:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '08:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '12:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '16:00' ||
                    records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '20:00') {
                    if (timeframe == 2) {
                        if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '00:00') {
                            lastLabel = 0
                        } else if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '04:00') {
                            lastLabel = 1
                        } else if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '08:00') {
                            lastLabel = 2
                        } else if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '12:00') {
                            lastLabel = 3
                        } else if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '16:00') {
                            lastLabel = 4
                        } else if (records[i].labeldetail.substr(records[i].labeldetail.length - 5) == '20:00') {
                            lastLabel = 5
                        }
                    }
                }
            } else {
                result.push(0)
            }
        } else {
            result.push(0)
        }
    }
    return [result, lastLabel];
}


function drawLines(dummyArrayY, difference, tamBloqueNumber, maxNum, lastLabel) {
    for (var i = 0; i < dummyArrayY.length; i++) {
        dummyArrayY[i] = maxNum - dummyArrayY[i]
    }

    let dummyArrayYTemp = dummyArrayY

    // Si last label es 0, le quito 5

    for (var i = 0; i < dummyArrayY.length; i++) {
        if (i < dummyArrayY.length - (5 - lastLabel)) {
            dummyArrayY[i] = dummyArrayYTemp[i + (5 - lastLabel)]
        } else {
            dummyArrayY[i] = null
        }
    }

    // 59 y no 60
    /*for(var i = 0 ; i < dummyArrayY.length-1 ; i++){
        dummyArrayY[i] = dummyArrayY[i+1]
    }*/

    let ySize = parseFloat(canvas.width / 12);
    let xSize = parseFloat(canvas.height / 11);

    ctx.beginPath();
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#4287CE'
    ctx.fillStyle = '#4287CE';
    ctx.moveTo(blocks(1, 'X'), blocks((((dummyArrayY[0] + difference) / tamBloqueNumber) + 1), 'Y'))

    // Dibuja las lineas
    for (var eX = 1; eX < 11; eX++) {
        for (var eY = 0; eY < 6; eY++) {
            if (dummyArrayY[(eX - 1) * 6 + eY] !== null) {
                ctx.lineTo(blocks(eX + (eY / 6), 'X'), blocks(((dummyArrayY[(eX - 1) * 6 + eY] + difference) / tamBloqueNumber) + 1, 'Y'))
                ctx.stroke();
            }
        }
    }
    ctx.stroke();


    // Fill lines
    for (var i = 1; i < 10.4; i++) {
        for (var eY = 0; eY < 6; eY++) {
            if (dummyArrayY[(i - 1) * 6 + eY + 1] !== null) {
                m = findSlope(blocks(i + (eY / 6), 'X'), blocks((dummyArrayY[(i - 1) * 6 + eY] / tamBloqueNumber), 'Y'), blocks(i + ((eY + 1) / 6), 'X'), blocks((dummyArrayY[(i - 1) * 6 + eY + 1] / tamBloqueNumber), 'Y'))
                b = findB(blocks((dummyArrayY[(i - 1) * 6 + eY] / tamBloqueNumber), 'Y'), m, blocks(i + (eY / 6), 'X'))
                for (var j = blocks(i + (eY / 6), 'X'); j < blocks(i + ((eY + 1) / 6), 'X'); j++) {
                    // FILL 
                    drawThinBar(ctx, j, findValueY(m, j, b) + xSize + blocks(difference / tamBloqueNumber, 'Y'), j, blocks(10, 'Y'), '#4287CE2E')
                }
            }
        }
    }

    //drawDottedLines(dummyArrayY,difference,tamBloqueNumber)
}

// Dibuja una linea
function drawThinBar(ctx, startX, startY, endX, endY, color) {
    ctx.lineWidth = 1;
    ctx.save();
    ctx.strokeStyle = color;
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.stroke();
    ctx.restore();
}

// Dibuja todas las barras
function drawBars(dummyArrayYB, tamBloqueNumberB, maxNumB, lastLabel) {

    // 59 y no 60
    for (var i = 0; i < dummyArrayYB.length - 1; i++) {
        dummyArrayYB[i] = dummyArrayYB[i + 1]
    }

    dummyArrayYB[59] = 0

    let dummyArrayYBTemp = dummyArrayYB

    // Si last label es 0, le quito 5

    for (var i = 0; i < dummyArrayYB.length; i++) {
        if (i < dummyArrayYB.length - (5 - lastLabel)) {
            dummyArrayYB[i] = dummyArrayYBTemp[i + (5 - lastLabel)]
        } else {
            dummyArrayYB[i] = 0
        }
    }

    let ySize = parseFloat(canvas.width / 12);
    let xSize = parseFloat(canvas.height / 11);
    for (var i = 1; i < 10.4; i++) {
        for (var eY = 0; eY < 6; eY++) {
            if (i == 10 && eY == 5) {
                // nothing
                drawBar(ctx, blocks(i + (eY / 6), 'X'), blocks(10, 'Y') - blocks((dummyArrayYB[(i - 1) * 6 + eY] / tamBloqueNumberB), 'Y'), (ySize / 6), blocks(dummyArrayYB[(i - 1) * 6 + eY] / tamBloqueNumberB, 'Y'), '#D8D8D880')
            } else {
                drawBar(ctx, blocks(i + (eY / 6), 'X'), blocks(10, 'Y') - blocks((dummyArrayYB[(i - 1) * 6 + eY] / tamBloqueNumberB), 'Y'), (ySize / 6), blocks(dummyArrayYB[(i - 1) * 6 + eY] / tamBloqueNumberB, 'Y'), '#D8D8D880')
            }

        }
    }
}

// Dibuja una barra
function drawBar(ctx, upperLeftCornerX, upperLeftCornerY, width, height, color) {
    //ctx.save();
    ctx.fillStyle = color;
    ctx.fillRect(upperLeftCornerX, upperLeftCornerY, width, height);
    //ctx.restore();
}

// Dibuja lineas punteadas del final
function drawDottedLines(dummyArrayY, difference, tamBloqueNumber) {
    ctx.setLineDash([2, 4]);//dashes are 5px and spaces are 3px
    ctx.lineWidth = 1;
    ctx.strokeStyle = '#FFFFFF'
    ctx.fillStyle = '#FFFFFF';
    ctx.beginPath();

    let ySize = parseFloat(canvas.width / 12);
    let xSize = parseFloat(canvas.height / 11);

    // Horizontal
    ctx.moveTo(blocks(10 + (5 / 6), 'X'), xSize)
    ctx.lineTo(blocks(10 + (5 / 6), 'X'), xSize * 10)

    // Vertical
    ctx.moveTo(ySize, blocks(((dummyArrayY[59] + difference) / tamBloqueNumber) + 1, 'Y'))
    ctx.lineTo(ySize * 11, blocks(((dummyArrayY[59] + difference) / tamBloqueNumber + 1), 'Y'))

    ctx.stroke();
}


// Obtiene la posicion del mouse en canva
function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

function chargePortfolioSelectInitial(portfolio) {
    var selector = document.getElementById('totalPortfolioSel');
    for (var i = 0; i < portfolio.total.currencies.length; i++) {
        var opcion = document.createElement("option");
        if (i == 0) opcion.setAttribute("selected", "");
        opcion.setAttribute("total", portfolio.total.currencies[i].total.formatted);
        opcion.text = portfolio.total.currencies[i].dsc;
        opcion.value = portfolio.total.currencies[i].id;
        selector.add(opcion);
    }
    // //console.log(document.getElementById('totalPortfolioSel').value)
    document.getElementById('totalPortfolioAmountTotal').innerHTML = selector.options[selector.selectedIndex].getAttribute("total");
}

function chargePortfolioSelect(portfolio) {
    var selector = document.getElementById('totalPortfolioSel');
    document.getElementById('totalPortfolioAmountTotal').innerHTML = selector.options[selector.selectedIndex].getAttribute("total");
}

function estimatedPriceM(type, qty, price, totalN) {
    // Compra: Cantidad x Precio / Total Neto a Obtener
    if (type == 'bid') {
        return (qty * price) / totalN
        // Venta: (Cantidad x Precio / Total Neto a Obtener) x Precio
    } else {
        return ((qty * price) / totalN) * price
    }
}

// Precio a obtener tras comisiones.
function estimatedPrice(type, qty, price, totalN) {
    // PE=Total /(Cantidad-Comisión)
    if (type == 'bid') {
        return document.getElementById('BuyAndSellTotal').getAttribute('datanumber') / totalN
        // PE=(Total - Comisión)/Cantidad
    } else {
        return totalN / qty
    }
}


function validarFile(all) {
    //EXTENSIONES Y TAMANO PERMITIDO.
    //var extensiones_permitidas = [".png", ".bmp", ".jpg", ".jpeg", ".pdf", ".doc", ".docx", ".gif"];
    var extensiones_permitidas = [".jpg", ".png", ".jpeg"];
    var tamano = 10; // EXPRESADO EN MB.
    var rutayarchivo = all.value;
    var ultimo_punto = all.value.lastIndexOf(".");
    var extension = rutayarchivo.slice(ultimo_punto, rutayarchivo.length);
    if (extensiones_permitidas.indexOf(extension.toLowerCase()) == -1) {
        document.getElementById(all.id).value = "";
        document.getElementById('selDepFiat1').innerHTML = ""
        document.getElementById('edepFiatInfRec').innerHTML = getLangById('usersUpdateperson4')[lang];
        document.getElementById('edepFiatInfRec').style.display = 'block';
        return false; // Si la extension es no válida ya no chequeo lo de abajo.
    } else {
        if ((all.files[0].size / 1048576) > tamano) {
            document.getElementById(all.id).value = "";
            document.getElementById('selDepFiat1').innerHTML = ""
            document.getElementById('edepFiatInfRec').innerHTML = getLangById('usersUpdateperson5')[lang] + tamano + "MB.";
            document.getElementById('edepFiatInfRec').style.display = 'block'
            return false;
        } else {
            return true;
        }
    }
}

function setLang() {

    addFooter()

    lang = sessionStorage.getItem('lang');

    //new
    setWordLanginnerHTML('bannerTit', 'bannerTit');


    /* inner HTML */
    setWordLanginnerHTML('home', 'home');
    setWordLanginnerHTML('balance', 'balance');
    setWordLanginnerHTML('preferences', 'preferences');
    setWordLanginnerHTML('homeR', 'home');
    setWordLanginnerHTML('balanceR', 'balance');
    setWordLanginnerHTML('preferencesR', 'preferences');
    setWordLanginnerHTML('langIcon', 'langIcon');
    setWordLanginnerHTML('MARKERSTITLE', 'MARKERSTITLE');
    setWordLanginnerHTML('mark1', 'mark1');
    setWordLanginnerHTML('mark2', 'mark2');
    setWordLanginnerHTML('mark3', 'mark3');
    setWordLanginnerHTML('mark4', 'mark4');
    setWordLanginnerHTML('PORTFOLIO', 'PORTFOLIO');
    setWordLanginnerHTML('portfolio1', 'portfolio1');
    setWordLanginnerHTML('portfolio2', 'portfolio2');
    setWordLanginnerHTML('portfolio3', 'portfolio3');
    setWordLanginnerHTML('totalIn', 'totalIn');
    setWordLanginnerHTML('addressBTC', 'addressBTC');
    setWordLanginnerHTML('withdrawBTC', 'withdrawBTC');
    setWordLanginnerHTML('transferBTC', 'transferBTC');
    setWordLanginnerHTML('movButtonBTC', 'movButtonBTC');
    setWordLanginnerHTML('depFiat', 'addressBTC');
    setWordLanginnerHTML('withdrawFiat', 'withdrawBTC');
    setWordLanginnerHTML('movButtonVES', 'movButtonBTC');
    setWordLanginnerHTML('movButtonDisabled', 'movButtonBTC');
    setWordLanginnerHTML('EXCHANGESTitle', 'EXCHANGES');
    setWordLanginnerHTML('exchangeSeeAll', 'exchangeSeeAll');
    setWordLanginnerHTML('exchangeSeeMine', 'exchangeSeeMine');
    setWordLanginnerHTML('exD', 'date');
    setWordLanginnerHTML('exPr', 'price')
    setWordLanginnerHTML('CHARTtitle', 'CHART');
    setWordLanginnerHTML('card4TItle', 'BUYANDSELL');
    setWordLanginnerHTML('mc', 'mc');
    setWordLanginnerHTML('mv', 'mv');
    setWordLanginnerHTML('buyBidT', 'buyBidT');
    setWordLanginnerHTML('sellBidT', 'sellBidT');
    setWordLanginnerHTML('BuyAndSellNote', 'note');
    setWordLanginnerHTML('priceTableP', 'price');
    setWordLanginnerHTML('amountTableP', 'portfolio2');
    setWordLanginnerHTML('orderBuy', 'BUY');
    setWordLanginnerHTML('orderSell', 'SELL');
    setWordLanginnerHTML('car6TtitleF', 'ORDERBOOK');
    setWordLanginnerHTML('markersSeeAll', 'exchangeSeeAll');
    setWordLanginnerHTML('markersSeeMine', 'exchangeSeeMine');
    setWordLanginnerHTML('orderBuyT', 'PURCHASEORDERS');
    setWordLanginnerHTML('orderSellT', 'SALESORDERS');
    setWordLanginnerHTML('amount6', 'portfolio2');
    setWordLanginnerHTML('price6', 'price');
    setWordLanginnerHTML('price61', 'price');
    setWordLanginnerHTML('amoun61', 'portfolio2');
    setWordLanginnerHTML('floatCloseI', 'BASICMODE');
    setWordLanginnerHTML('depositWithSpan', 'depositWithSpan');
    setWordLanginnerHTML('depositMyBalance', 'YOURBALANCE');
    setWordLanginnerHTML('depBTCDir', 'address');
    setWordLanginnerHTML('depVen', 'expiration');
    setWordLanginnerHTML('depFesLab', 'FEES');
    setWordLanginnerHTML('addressBTCInfBack', 'BACK');
    setWordLanginnerHTML('withdrawTitLab', 'withdrawWithSPan');
    setWordLanginnerHTML('withdrawBtcAm', 'YOURBALANCE');
    setWordLanginnerHTML('amountWithBTC', 'AmountToWithdraw');
    setWordLanginnerHTML('walletDest', 'destinationWallet');
    setWordLanginnerHTML('withBTCFees', 'FEES');
    setWordLanginnerHTML('netTotalWithd', 'NETTOTAL');
    setWordLanginnerHTML('wdBTCbutton', 'withdrawMay');
    setWordLanginnerHTML('withdrawLabel2', 'withdrawWithSPan');
    setWordLanginnerHTML('amountWithdraw2', 'AMOUNTTOWITHDRAW');
    setWordLanginnerHTML('withdrawBTC2LabelFee', 'fees');
    setWordLanginnerHTML('withdrawBTC2LabelNetTotal', 'nettotal');
    setWordLanginnerHTML('withdrawBTC2LabelNetAd', 'address');
    setWordLanginnerHTML('withdrawBTCConfirmResend', 'resendCode');
    setWordLanginnerHTML('wdBTCbuttonV', 'VALIDATE');
    setWordLanginnerHTML('wdBTCbuttonA', 'CANCEL');
    setWordLanginnerHTML('TransactionSuccessful', 'TransactionSuccessful');
    setWordLanginnerHTML('wdFiatbuttonF', 'FINALIZE');
    setWordLanginnerHTML('PartiallyCompletedTransaction', 'PartiallyCompletedTransaction');
    setWordLanginnerHTML('wdFiatbuttonFYellow', 'FINALIZE');
    setWordLanginnerHTML('failureTitle', 'FailedTransaction');
    setWordLanginnerHTML('wdFiatbuttonI', 'TRYAGAIN');
    setWordLanginnerHTML('transferBTCLabelTit', 'transferWithSpan');
    setWordLanginnerHTML('yourBalanceTransfer', 'YOURBALANCE');
    setWordLanginnerHTML('AmountToTransfer', 'AmountToTransfer');
    setWordLanginnerHTML('emailToTransfer', 'DestinationUserEmail');
    setWordLanginnerHTML('feesTransfer1', 'FEES');
    setWordLanginnerHTML('netTotalTransfer1', 'NETTOTAL');
    setWordLanginnerHTML('trBTCbutton', 'TRANSFERL');
    setWordLanginnerHTML('transferTitle2', 'transferWithSpan');
    setWordLanginnerHTML('transferAm2', 'AmountToTransfer');
    setWordLanginnerHTML('transferBTCFees2', 'fees');
    setWordLanginnerHTML('transferTNBTC2', 'nettotal');
    setWordLanginnerHTML('userTransfer2', 'user');
    setWordLanginnerHTML('destTransfer2BTC', 'Addressee');
    setWordLanginnerHTML('transferBTCConfirmResend', 'resendCode');
    setWordLanginnerHTML('trBTCbuttonV', 'VALIDATE');
    setWordLanginnerHTML('trBTCbuttonA', 'CANCEL');
    setWordLanginnerHTML('movTitleBTC1', 'movementsMinWithoutSpan');
    setWordLanginnerHTML('movStatusBTC', 'status');
    setWordLanginnerHTML('datBTC', 'date');
    setWordLanginnerHTML('desBTC', 'Description');
    setWordLanginnerHTML('canBTC', 'portfolio2');
    setWordLanginnerHTML('R1BTC', 'AVAILABLE');
    setWordLanginnerHTML('R2BTC', 'DEFERRED');
    setWordLanginnerHTML('R3BTC', 'COMMITTED');
    setWordLanginnerHTML('movBTCBack', 'BACK');
    setWordLanginnerHTML('fiatWithdraw1', 'withdrawWithSPan');
    setWordLanginnerHTML('yourAmountFiat', 'YOURBALANCE');
    setWordLanginnerHTML('amountWithFiat1', 'AmountToWithdraw');
    setWordLanginnerHTML('acDestWithdraw1', 'DestinationAccount');
    setWordLanginnerHTML('fiatWithdrawFees', 'FEES');
    setWordLanginnerHTML('withdrawNetTotal', 'NETTOTAL');
    setWordLanginnerHTML('wdFiatbutton', 'withdrawMay');
    setWordLanginnerHTML('fiatWithdraw2', 'withdrawWithSPan');
    setWordLanginnerHTML('fiatWithdraw3', 'withdrawWithSPan');
    setWordLanginnerHTML('withdrawFIat2AmR', 'AMOUNTTOWITHDRAW');
    setWordLanginnerHTML('withdrawFIat2AmR3', 'AMOUNTTOWITHDRAW');
    setWordLanginnerHTML('with2FiatFees', 'fees');
    setWordLanginnerHTML('with2FiatFees2', 'fees');
    setWordLanginnerHTML('withFiatNT2', 'nettotal');
    setWordLanginnerHTML('withFiatNT23', 'nettotal');
    setWordLanginnerHTML('with2FiatCD', 'DestinationAccount');
    setWordLanginnerHTML('withdrawFiatConfirmResend', 'resendCode');
    setWordLanginnerHTML('withdrawFiatConfirmResend2', 'resendCode');
    setWordLanginnerHTML('wdFiatbuttonV', 'VALIDATE');
    setWordLanginnerHTML('wdFiatbuttonV2', 'VALIDATE');
    setWordLanginnerHTML('wdFiatbuttonA', 'CANCEL');
    setWordLanginnerHTML('wdFiatbuttonA2', 'CANCEL');
    setWordLanginnerHTML('depFiat1T', 'depositWithSpan');
    setWordLanginnerHTML('depFiat1SS', 'YOURBALANCE');
    setWordLanginnerHTML('reportDTFiat', 'ReportDeposit');
    setWordLanginnerHTML('p2cfiat', 'UsingP2C');
    setWordLanginnerHTML('DestinationBankDepFiatT', 'DestinationBank');
    setWordLanginnerHTML('depFiatAmDe', 'DepositAmount');
    setWordLanginnerHTML('depFiatDate', 'date');
    setWordLanginnerHTML('refFiatDep1', 'Reference');
    setWordLanginnerHTML('depFiatVoucherReceipt', 'VoucherReceipt');
    setWordLanginnerHTML('selDepFiat1', 'select');
    setWordLanginnerHTML('fiatFees1Dep', 'FEES');
    setWordLanginnerHTML('fiatFees1DepPM', 'FEES');
    setWordLanginnerHTML('netTotalDepFiat1', 'NETTOTAL');
    setWordLanginnerHTML('netTotalDepFiat1PM', 'NETTOTAL');
    setWordLanginnerHTML('PMTextInp', 'var49');
    setWordLanginnerHTML('depFiatAccept', 'ToAccept');
    setWordLanginnerHTML('depFiatInfIdButton', 'search');
    setWordLanginnerHTML('bankDest2Fiat', 'DestinationBank');
    setWordLanginnerHTML('Am2Fiat', 'portfolio2');
    setWordLanginnerHTML('id2Fiat', 'IdentificationCard');
    setWordLanginnerHTML('phone2Fiat', 'CellPhone');
    setWordLanginnerHTML('depFiatDep', 'ToAccept');
    setWordLanginnerHTML('movVesFiat1', 'movButtonBTC');
    setWordLanginnerHTML('movFiat1S', 'status');
    setWordLanginnerHTML('datVES', 'date');
    setWordLanginnerHTML('movFiat1D', 'Description');
    setWordLanginnerHTML('amountVES', 'portfolio2');
    setWordLanginnerHTML('dataFiatMov1', 'AVAILABLE');
    setWordLanginnerHTML('dataFiatMov2', 'DEFERRED');
    setWordLanginnerHTML('dataFiatMov3', 'COMMITTED');
    setWordLanginnerHTML('movVESBack', 'BACK');
    setWordLanginnerHTML('movDetailTit', 'withdrawWithSPan');
    setWordLanginnerHTML('detailFees', 'fees');
    setWordLanginnerHTML('detailNetT', 'nettotal');
    setWordLanginnerHTML('detailAc', 'DestinationAccount');
    setWordLanginnerHTML('detailDate', 'date');
    setWordLanginnerHTML('resend', 'SeeVoucher');
    setWordLanginnerHTML('detailFiatButton', 'ToAccept');
    setWordLanginnerHTML('confirmT', 'OrderConfirmation');
    setWordLanginnerHTML('confirmLabelP', 'pair');
    setWordLanginnerHTML('confirmLabelTypeOrder', 'OrderType');
    setWordLanginnerHTML('confirmLabelTypeAc', 'TypeAction');
    setWordLanginnerHTML('confirmAmLabel', 'portfolio2');
    setWordLanginnerHTML('confirmLabelFees', 'fees');
    setWordLanginnerHTML('confirmLabelPriceEf', 'EffectivePrice');
    setWordLanginnerHTML('cardAmountRoundedTextLastText', 'NETTOTALOBTAINED');
    setWordLanginnerHTML('confirmLabelMess1', 'confirmLabel1');
    setWordLanginnerHTML('confirmOrderContinue', 'continue');
    setWordLanginnerHTML('confirmOrderCancel', 'cancel');
    setWordLanginnerHTML('attLabel', 'Attention');
    setWordLanginnerHTML('amountValidationText', 'amountValidationText');
    setWordLanginnerHTML('orderAttentionContinue', 'continue');
    setWordLanginnerHTML('orderAttentionCancel', 'cancel');
    setWordLanginnerHTML('expired1', 'expired1');
    setWordLanginnerHTML('expired2', 'expired2');
    setWordLanginnerHTML('expSessionButton', 'continue');
    setWordLanginnerHTML('wdFiatbuttonI', 'TRYAGAIN');
    setWordLanginnerHTML('messageInfCountdown', 'var47');
    setWordLanginnerHTML('wdFiatbuttonI', 'TRYAGAIN');
    setWordLanginnerHTML('ts', 'ts');
    setWordLanginnerHTML('reportDTFiat2', 'ReportW');
    setWordLanginnerHTML('p2cfiat2', 'ReportWP');
    setWordLanginnerHTML('bankDest2Fiat2', 'bank');
    setWordLanginnerHTML('Am2Fiat2', 'iden');
    setWordLanginnerHTML('Am2Fiat22', 'AmountToWithdraw');
    setWordLanginnerHTML('Am2Fiat3', 'CellPhoneA');
    setWordLanginnerHTML('wdFiatbutton2', 'withdrawMay');
    setWordLanginnerHTML('wdFiatbuttonI', 'TRYAGAIN');
    setWordLanginnerHTML('feeComents', 'feeComents');
    setWordLanginnerHTML('SelectPhoneA', 'var27');
    setWordLanginnerHTML('with2FiatCD2', 'iden');
    setWordLanginnerHTML('with2FiatCD3', 'CellPhoneA');
    setWordLanginnerHTML('with2FiatCD4', 'bank');

    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'));

}