WS_waitscreen = true;
portfolio = [];
var markersListArray = {};
var depositsAccountsArray ={} 
var entrydata; 
var decimCoinCurrency = 0; 
var decimCoinRefCurrency = 0;  
var dashboardUpdate;
var feesOrders;
var pairDetailsVar;
var canvas; 
var ctx;
 
window.onload = function(){
    
    //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': getParameterByName('sessionid'),
                'ordernumofrec': 25,
                'exchangenumofrec': 25,
                'pairid' : document.getElementById('pairName').getAttribute('pairId')
            }
            dashboardEntry(reqDashboardEntry,'',0)
            console.log('click in refresh')
            
        })
        
        // 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'));
    });
    
    // Call Entry 
    //getEntry(getParameterByName('sessionid'));
    //getEntry(null) 
    document.getElementById('example-element-toggle2').checked = false;
    
    //changePortfolio();
    //changeOrders();  
    
    // Go to preferences
    document.getElementById('preferences').addEventListener("click", function(){
        gotoPage('preferences','main',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to preferences
    document.getElementById('preferencesR').addEventListener("click", function(){
        gotoPage('preferences','main',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to balance
    document.getElementById('balance').addEventListener("click", function(){
        gotoPage('balance','balance',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to balance
    document.getElementById('balanceR').addEventListener("click", function(){
        gotoPage('balance','balance',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    //markersList();
    //markersEntry();
    //markersChart();
    //ordersList();
    //transactionsList();
    
    //accountsPortfolio();
    
    document.getElementById('logouticon').addEventListener("click", function(){
        logout();
    });
    document.getElementById('logouticon2').addEventListener("click", function(){
        logout();
    });
    
    // Bar
    document.getElementById('togglebar').addEventListener("click", function(){
        var el = document.getElementById('addView2')
        //el.style.display = 'block';
        //el.style.display = (el.style.display == 'none') ? 'block' : 'none';
        //document.getElementById('datas').style.display = 'none'
        document.getElementById('addView2').style.display = 'block'
        setTimeout(function(){ 
            document.getElementById('example-element-toggle2').checked = !document.getElementById('example-element-toggle2').checked;
        }, 15);   
        
    });
    
    // Retirar Fiat
    document.getElementById('withdrawFiat').addEventListener("click", function(){
        if(entrydata.level.id == 0){
            document.getElementById('failureMsg').innerHTML = 'Debe verificar primero su identidad.'
            document.getElementById('failureTitle').innerHTML="Atención"
            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
            document.getElementsByClassName('failure')[0].style.display = "table"
        }else{
            document.getElementById('withdrawFiatAmount').value = '';
            document.getElementById('withdrawFiatAmount').setAttribute("dataNumber","");
            document.getElementById('withdrawFiatAccount').value = '';
            document.getElementById('withdrawFiatFee').innerHTML = 0;
            document.getElementById('withdrawFiatTotal').innerHTML = 0;
            document.getElementById('withdrawFiatTotal').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()
    });
    
    // Anular Fiat
    document.getElementById('wdFiatbuttonA').addEventListener("click", function(){
        var req = {
            'id': document.getElementsByClassName('withdrawFiatConfirm')[0].getAttribute('tridWI'),
            'sessionid': getParameterByName('sessionid')
        }
        transactionsCancel(req)
    });
    
    // Validar Fiat
    document.getElementById('wdFiatbuttonV').addEventListener("click", function(){
        verifywdFiatbuttonV()
    });
    
    
    // Retirar BTC
    document.getElementById('withdrawBTC').addEventListener("click", function(){
        if(entrydata.level.id == 0){
            document.getElementById('failureMsg').innerHTML = 'Debe verificar primero su identidad.'
            document.getElementById('failureTitle').innerHTML="Atención"
            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
            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': getParameterByName('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(){
        if(entrydata.level.id == 0){
            document.getElementById('failureMsg').innerHTML = 'Debe verificar primero su identidad.'
            document.getElementById('failureTitle').innerHTML="Atención"
            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
            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');
        }
    });
    
    //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': getParameterByName('sessionid')
        }
        transactionsCancel(req)
    });
    
    // Validar BTC
    document.getElementById('trBTCbuttonV').addEventListener("click", function(){
        verifytrBTCbuttonV()
    });
    
    // Movimientos BTC 
    document.getElementById('movButtonBTC').addEventListener("click", function(){
        if(entrydata.level.id == 0){
            document.getElementById('failureMsg').innerHTML = 'Debe verificar primero su identidad.'
            document.getElementById('failureTitle').innerHTML="Atención"
            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
            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(){
        if(entrydata.level.id == 0){
            document.getElementById('failureMsg').innerHTML = 'Debe verificar primero su identidad.'
            document.getElementById('failureTitle').innerHTML="Atención"
            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
            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(){
        if(entrydata.level.id == 0){
            document.getElementById('failureMsg').innerHTML = 'Debe verificar primero su identidad.'
            document.getElementById('failureTitle').innerHTML="Atención"
            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
            document.getElementsByClassName('failure')[0].style.display = "table"
        }else{
            /*if(document.getElementById('disabledPortfolio').getAttribute('accidReal') == 0){
                document.getElementById('failureMsg').innerHTML = 'Esta moneda se encuentra inactiva.'
                document.getElementById('failureTitle').innerHTML="Error"
                document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
                document.getElementsByClassName('failure')[0].style.display = "table"
            }*/
            //if{
                if(document.getElementById("disabledPortfolio").getAttribute("interface") == 4 || document.getElementById("disabledPortfolio").getAttribute("interface") == 5){
                    seeMovements(document.getElementById("disabledPortfolio").getAttribute("accidReal"),'BTC')
                }else if(document.getElementById("disabledPortfolio").getAttribute("interface") == 1){
                    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="Transacción </br> Fallida"
        document.getElementById('wdFiatbuttonI').innerHTML = "INTENTE DE NUEVO"
    });
    
    // Abrir address AFX - BTC
    document.getElementById('addressBTC').addEventListener("click", function(){
        if(entrydata.level.id == 0){
            document.getElementById('failureMsg').innerHTML = 'Debe verificar primero su identidad.'
            document.getElementById('failureTitle').innerHTML="Atención"
            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
            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': getParameterByName('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('copyBtc').value = document.getElementById('copyInfAFX').innerHTML
        document.getElementById('copyBtc').select();
        document.getElementById('copyBtc').setSelectionRange(0, 99999); 
        document.execCommand('copy');*/
        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(){
        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){
        e.preventDefault();
        return false;
        openTabFiat('p2cfiat','p2c');
    });
    
    // Abrir Depositar Fiat
    document.getElementById('depFiat').addEventListener("click", function(){
        if(entrydata.level.id == 0){
            document.getElementById('failureMsg').innerHTML = 'Debe verificar primero su identidad.'
            document.getElementById('failureTitle').innerHTML="Atención"
            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
            document.getElementsByClassName('failure')[0].style.display = "table"
        }else{
            console.log(document.getElementById('FiatPortfolio').getAttribute('icCur'))
            depositsAccounts(document.getElementById('FiatPortfolio').getAttribute('icCur'))   
        }
    });

    // Add file
    document.addEventListener('change', function (evt) {
        if (evt.target.className === 'file') {
            if(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'){
            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('withdrawFiatAccount','ewithdrawFiatAccount')
            document.getElementById('ewithdrawFiatAccount').style.display = 'none'
            noError('withdrawFiatConfirmCode','ewithdrawFiatConfirmCode')
            document.getElementById('ewithdrawFiatConfirmCode').style.display = 'none'
            document.getElementById("withdrawFiatAccount").classList.remove("selectwdFiatBank");
            document.getElementById("withdrawFiatAccount").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')
            document.getElementById('edepFiatInfAmount').style.display = 'none'
            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'
            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'
            
            // 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')
            
        }
    });
    
    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");
        }
    });
    
    // 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('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('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'
        }
    }); 
    
    // Remove red errors in Withd BTC
    document.getElementsByTagName('body')[0].addEventListener("click", function(){
        if (document.getElementById('withdrawBTCAmount').value !== '' && parseFloat(document.getElementById('withdrawBTCAmount').value) <= 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('withdrawFiatConfirmCode').value != ''){
            noError('withdrawFiatConfirmCode','ewithdrawFiatConfirmCode')
            document.getElementById('ewithdrawFiatConfirmCode').style.display = 'none'
        }
    }); 
    
    // Remove red errors in Xfer BTC
    document.getElementsByTagName('body')[0].addEventListener("click", function(){
        if (document.getElementById('transferBTCAmount').value !== '' && parseFloat(document.getElementById('transferBTCAmount').value) <= 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('depFiatInfAmount').addEventListener("keyup", function(){
        document.getElementById('depFiatInFee').innerHTML = fixDecimals(((   (document.getElementById('depFiatInfAmount').value).replace(',', '.')     * 0.02).toFixed(2)).replace('.', ','));
        document.getElementById('depFiatInNeTotal').innerHTML = fixDecimals(((   (document.getElementById('depFiatInfAmount').value).replace(',', '.')     * 0.98).toFixed(2)).replace('.', ','));
    }); 
    
    document.getElementById('withdrawFiatAmount').addEventListener("keyup", function(){
        document.getElementById('withdrawFiatFee').innerHTML = fixDecimals(((   (document.getElementById('withdrawFiatAmount').value).replace(',', '.')     * 0.02).toFixed(2)).replace('.', ','));
        document.getElementById('withdrawFiatTotal').innerHTML = fixDecimals(((   (document.getElementById('withdrawFiatAmount').value).replace(',', '.')     * 0.98).toFixed(2)).replace('.', ','));
    }); 
    
    document.getElementById('transferBTCAmount').addEventListener("keyup", function(){
        document.getElementById('transferBTCFee').innerHTML = fixDecimals(((   (document.getElementById('transferBTCAmount').value).replace(',', '.')     * 0.02).toFixed(8)).replace('.', ','));
        document.getElementById('transferBTCTotal').innerHTML = fixDecimals(((   (document.getElementById('transferBTCAmount').value).replace(',', '.')     * 0.98).toFixed(8)).replace('.', ','));
    }); */
    
    document.getElementById('movDetailFiatSeeComprobant').addEventListener("click", function(){
        window.open(document.getElementById('movDetailFiatSeeComprobant').getAttribute('comp'), '_blank');
    }); 
    
    document.getElementById('withdrawBTCConfirmResend').addEventListener("click", function(){
        var req = {
            'id': document.getElementsByClassName('withdrawBTCConfirm')[0].getAttribute('tridwi'),
            'sessionid': getParameterByName('sessionid')
        }
        
        transactionsValidation(req)
    });
    
    document.getElementById('withdrawFiatConfirmResend').addEventListener("click", function(){
        var req = {
            'id': document.getElementsByClassName('withdrawFiatConfirm')[0].getAttribute('tridwi'),
            'sessionid': getParameterByName('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': getParameterByName('sessionid')
        }
        
        transactionsValidation(req)
    });
    
    document.getElementById("resend").addEventListener("click",function(){
        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 = '<p class="poppins-medium">Precio  <i class="fas fa-exclamation-circle popup" id="tooltip"><span class="popuptext poppins-regular">Precio referencial del mercado.</span></i></p>'
        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">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('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 = '<p class="poppins-medium">Precio  <i class="fas fa-exclamation-circle popup" id="tooltip"><span class="popuptext poppins-regular">Precio referencial del mercado.</span></i></p>'
            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 = 'Precio Market Estimado: ' + 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(){
        //console.log('focus')
        moveCursorToEnd(document.getElementById('BuyAndSellPrice'))
        //document.getElementById('BuyAndSellPrice').dispatchEvent(new Event(""))
    })
    
    //document.getElementById('BuyAndSellPrice').addEventListener("focus",function(){
        //console.log('focus')
    //    moveCursorToEnd(document.getElementById('BuyAndSellPrice'))
    //})

/*
    // Precio    
    document.getElementById('BuyAndSellPrice').addEventListener("keyup",function(){
        console.log( 'in BuyAndSellPrice' )
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency(decimCoin,this.value);
        if(noVal!=="")this.value = noVal;
        document.getElementById('BuyAndSellPrice').setAttribute("dataNumber",document.getElementById('BuyAndSellPrice').value);
        
        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"));
    })
    
    // Total
    document.getElementById('BuyAndSellTotal').addEventListener("keyup",function(){
        console.log( 'in BuyAndSellTotal' )
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency(decimCoin,this.value);
        if(noVal!=="")this.value = noVal;
        document.getElementById('BuyAndSellTotal').setAttribute("dataNumber",parseFloat(document.getElementById('BuyAndSellTotal').value).noExponents());
        
        if(document.getElementById('BuyAndSellTotal').getAttribute("dataNumber")!='' && document.getElementById('BuyAndSellPrice').getAttribute("dataNumber")!=''){
            document.getElementById('BuyAndSellAmount').value = parseFloat(document.getElementById('BuyAndSellTotal').getAttribute("dataNumber")).noExponents() / parseFloat(document.getElementById('BuyAndSellPrice').getAttribute("dataNumber")).noExponents()
        }else{
            document.getElementById('BuyAndSellAmount').value = 0   
            //document.getElementById('BuyAndSellPrice').value = number_format(document.getElementById('BuyAndSellTotal').getAttribute("dataNumber") / document.getElementById('BuyAndSellAmount').getAttribute("dataNumber"),
            //                                                     document.getElementById('BuyAndSellPrice').getAttribute("icDecim"))
        }
        // Cantidad es un numero
        
        
        document.getElementById('BuyAndSellAmount').setAttribute("dataNumber",parseFloat(document.getElementById('BuyAndSellAmount').value).noExponents());
        document.getElementById('BuyAndSellAmount').setAttribute("type","text");
        document.getElementById('BuyAndSellAmount').value = number_format(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute("dataNumber")).noExponents(),document.getElementById('BuyAndSellAmount').getAttribute("icDecim"));
    })
    
    // Cantidad
    document.getElementById('BuyAndSellAmount').addEventListener("keyup",function(){
        console.log( 'in BuyAndSellAmount' )
        decimCoin = this.getAttribute("icDecim");
        var noVal = formatCurrency(decimCoin,this.value);
        if(noVal!=="")this.value = noVal;
        document.getElementById('BuyAndSellAmount').setAttribute("dataNumber",document.getElementById('BuyAndSellAmount').value);
        
        // Si el precio o el monto existen
        if(document.getElementById('BuyAndSellPrice').getAttribute("dataNumber")!='' && document.getElementById('BuyAndSellAmount').getAttribute("dataNumber")!=''){
            // El total es el precio por el monto
            document.getElementById('BuyAndSellTotal').value = document.getElementById('BuyAndSellPrice').getAttribute("dataNumber") * document.getElementById('BuyAndSellAmount').getAttribute("dataNumber")
        
        // Si no
        }else{
            document.getElementById('BuyAndSellTotal').value = 0   
        }
        document.getElementById('BuyAndSellTotal').setAttribute("dataNumber",document.getElementById('BuyAndSellTotal').value);
        document.getElementById('BuyAndSellTotal').setAttribute("type","text");
        document.getElementById('BuyAndSellTotal').value = number_format(document.getElementById('BuyAndSellTotal').getAttribute("dataNumber"),document.getElementById('BuyAndSellTotal').getAttribute("icDecim"));
    })
    */
    document.getElementById('BuyAndSellPrice').addEventListener("focusin",function(){
        decimCoin = this.getAttribute("icDecim");
    });
    document.getElementById('BuyAndSellTotal').addEventListener("focusin",function(){
        decimCoin = this.getAttribute("icDecim");
    });
    document.getElementById('BuyAndSellAmount').addEventListener("focusin",function(){
        decimCoin = this.getAttribute("icDecim");
    });
    // 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;
            }
        }
    })
    // 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;
            }
        }
    })
    // Cantidad
    document.getElementById('BuyAndSellAmount').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');
        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 = (price.getAttribute("dataNumber") * qty.getAttribute("dataNumber"));
                formatval = formatCurrency2(tot.getAttribute("icDecim"),val.toString());
                //tot.dispatchEvent(new Event("focusin"));tot.dispatchEvent(new Event("focusout"));
                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
                price = (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': getParameterByName('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': getParameterByName('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': getParameterByName('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': getParameterByName('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': getParameterByName('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': getParameterByName('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': getParameterByName('sessionid'),
            'ordernumofrec': 25,
            'exchangenumofrec': 25,
            'pairid' : document.getElementById('pairName').getAttribute('pairId'),
            'ownexchange' : 1
        }
        dashboardEntry(reqDashboardEntry,'exchanges',1)
    })
    
    // First dashboardEntry
    
    var reqDashboardEntry = { 
        'sessionid': getParameterByName('sessionid'), 
        'ordernumofrec': 25, 
        'exchangenumofrec': 25 
    } 
    
    /*if(sessionStorage.getItem('pairid')){
        reqDashboardEntry.pairid = sessionStorage.getItem('pairid')
    }*/
    console.log(reqDashboardEntry)
    //dashboardEntry(reqDashboardEntry,'initial',0);
    
    // Order
    document.getElementById('orderBuy').addEventListener("click", function(){
        var hasAc = true;
        if(entrydata.level.id == 0){
            document.getElementById('failureMsg').innerHTML = 'Debe verificar primero su identidad.'
            document.getElementById('failureTitle').innerHTML="Atención"
            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
            document.getElementsByClassName('failure')[0].style.display = "table"
        }else{ 
            console.log(document.getElementById('BuyAndSellTotal').getAttribute('currencyId'))
            if(dashboardUpdate.dashboard.portfolio.accounts == null){
                document.getElementById('failureMsg').innerHTML = 'No posee cuentas para realizar esta operación.'
                document.getElementById('failureTitle').innerHTML="Error"
                document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
                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')){
                        //console.log(dashboardUpdate.dashboard.portfolio.accounts[i].total.number(document.getElementById('BuyAndSellTotal').getAttribute('dataNumber'))
                        //console.log(dashboardUpdate.dashboard.portfolio.accounts[i].total.number)
                        //console.log(document.getElementById('BuyAndSellTotal').getAttribute('dataNumber'))
                        if(dashboardUpdate.dashboard.portfolio.accounts[i].id == 0){
                            hasAc = false;
                            document.getElementById('failureMsg').innerHTML = 'No posee cuenta en ' + document.getElementById('cardBuyAndSellPriceText').innerHTML + ' para realizar esta operación.'
                            document.getElementById('failureTitle').innerHTML="Error"
                            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
                            document.getElementsByClassName('failure')[0].style.display = "table"
                        }
                        else{
                            if(dashboardUpdate.dashboard.portfolio.accounts[i].total.number< parseFloat(document.getElementById('BuyAndSellTotal').getAttribute('dataNumber'))){
                                document.getElementById('failureMsg').innerHTML = 'Saldo Insuficiente.'
                                document.getElementById('failureTitle').innerHTML="Error"
                                document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
                                document.getElementsByClassName('failure')[0].style.display = "table"
                            }   
                        }
                    }
                }
                if(document.getElementById('failureMsg').innerHTML != 'Saldo Insuficiente.'){
                    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 = 'compra'
                                document.getElementById('amountValidationText').children[1].innerHTML = 'mayor o igual'
                                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;
        if(entrydata.level.id == 0){
            document.getElementById('failureMsg').innerHTML = 'Debe verificar primero su identidad.'
            document.getElementById('failureTitle').innerHTML="Atención"
            document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
            document.getElementsByClassName('failure')[0].style.display = "table"
        }
        else{
            if(dashboardUpdate.dashboard.portfolio.accounts == null){
                document.getElementById('failureMsg').innerHTML = 'No posee cuentas para realizar esta operación.'
                document.getElementById('failureTitle').innerHTML="Error"
                document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
                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 = 'No posee cuenta en ' + document.getElementById('cardBuyAndSellAmountText').innerHTML + ' para realizar esta operación.'
                                document.getElementById('failureTitle').innerHTML="Error"
                                document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
                                document.getElementsByClassName('failure')[0].style.display = "table"
                        }else{
                            if(dashboardUpdate.dashboard.portfolio.accounts[i].total.number < parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('dataNumber'))){
                                document.getElementById('failureMsg').innerHTML = 'Saldo Insuficiente.'
                                document.getElementById('failureTitle').innerHTML="Error"
                                document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar"
                                document.getElementsByClassName('failure')[0].style.display = "table"
                            }   
                        }
                    }
                }
                if(document.getElementById('failureMsg').innerHTML != 'Saldo Insuficiente.'){
                    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 = 'venta'
                            document.getElementById('amountValidationText').children[1].innerHTML = 'menor o igual'
                            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 = 'El botón para continuar se deshabilitará en <span>15</span> segundos.'
        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"
    });
    
    /* CANVA */
    canvas = document.getElementById('canvasId')
    canvas.width =  document.getElementById('divCanva').clientWidth;
    canvas.height = document.getElementById('divCanva').clientHeight;
    ctx = document.getElementById('canvasId').getContext('2d');
    console.log(ctx)
    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)
            //console.log(arrayBars)
            // 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); 
    
    document.getElementById('totalPortfolioSel').addEventListener("change",function(){
        var reqDashboardEntry = {
            'sessionid': getParameterByName('sessionid'),
            'ordernumofrec': 25,
            'exchangenumofrec': 25,
            'pairid' : document.getElementById('pairName').getAttribute('pairId')
        }
        dashboardEntry(reqDashboardEntry,'portfolioTotal',0)
        
    })
    
    // Session Update
    document.getElementById('expSessionButton').addEventListener("click",function(){
        var req = {
            'sessionid': getParameterByName('sessionid')
        }
        sessionUpdate(req)
    })
    
    // Step
    document.getElementById('floatButton').addEventListener("click",function(){
        var popup = document.getElementById("floatButton").children[0].children[0];
        if(popup.classList.contains('show')){
            gotoPage('step','main',{ 'sessionid' : getParameterByName('sessionid') })
        }else{
            popup.classList.toggle("show");
        }
    })
    
    init()
    
    var fieldAmo = ["withdrawBTCAmount","transferBTCAmount","depFiatInfAmount","withdrawFiatAmount","BuyAndSellPrice","BuyAndSellAmount","BuyAndSellTotal"];
    //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);
    //Mostrar HTML cargado
    esconderHTML(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:
                sessionValidUpdate(0)
                entrydata = (JSON.parse(rsp).entry)
                putName(entrydata);
                document.getElementsByClassName('pageCnt')[0].style.visibility="visible"
                // Window Load
                var waitScreen = document.getElementById("waitScreen");
                document.body.removeChild(waitScreen);
                WS_waitscreen = false;
                
                var reqDashboardEntry = { 
                    'sessionid': getParameterByName('sessionid'), 
                    'ordernumofrec': 25, 
                    'exchangenumofrec': 25 
                } 
                console.log(reqDashboardEntry)
                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('name').innerHTML = name
    document.getElementById('name2').innerHTML = name
}

function changePortfolio(){
    /*portfolio = [
        {
            'src' : './img/bitcoin.svg',
            'name' : 'BTC',
            'amount' : '7,236.00',
            'ptc' : '28%'
        },
        {
            'src' : './img/ether.svg',
            'name' : 'ETH',
            'amount' : '1.9876,31',
            'ptc' : '36%'
        },
        {
            'src' : '',
            'name' : 'Ves',
            'amount' : '40,659.58',
            'ptc' : '12%'
        },
        {
            'src' : './img/bitcoin.svg',
            'name' : 'BTC',
            'amount' : '7,236.00',
            'ptc' : '28%'
        },
        {
            'src' : './img/ether.svg',
            'name' : 'ETH',
            'amount' : '1.9876,31',
            'ptc' : '36%'
        },
        {
            'src' : '',
            'name' : 'Ves',
            'amount' : '40,659.58',
            'ptc' : '12%'
        }
    ]*/
    /*portfolio = [
        {
            'src' : './img/bitcoin.svg',
            'name' : 'BTC',
            'amount' : '7,236.00',
            'ptc' : '28%'
        },
        {
            'src' : '',
            'name' : 'Ves',
            'amount' : '40,659.58',
            'ptc' : '12%'
        }
    ]
    
    listDraw(portfolio, 'portfolio')*/
}

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 === 'portfolio'){
        tbl = document.getElementsByClassName("card3")[0];
        var node = tbl.children[3].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 = "";
        }
    }
    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   
                    console.log(ele.children[1].children[0])
                    ele.children[1].children[0].addEventListener("click",function(e){
                        if(e.srcElement.parentNode.parentNode.getAttribute('name')=='BTC'){
                            console.log('test')
                            //markersListArray = {};
                            var currency;
                            var refCurrency;
                            for (var i = 0; i < markersListArray.numofrecords ; i++){
                                console.log(markersListArray)
                                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
                                }
                            }
                            console.log(markersListArray)
                            accountsPortfolio(5,currency,refCurrency)

                            console.log(e.srcElement.parentNode.parentNode.getAttribute('currencyId'))
                            // Pinta 
                        }
                        if(e.srcElement.parentNode.parentNode.getAttribute('name')=='PTR'){
                            console.log('test')
                            //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
                                }
                            }
                            console.log(markersListArray)
                            console.log(currency)
                            accountsPortfolio(6,currency,refCurrency)

                            console.log(e.srcElement.parentNode.parentNode.getAttribute('currencyId'))
                            // 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;
                    for(var j=0; j<icons.length; j++){
                        if(icons[j].name == rsp[i].dsc){

                            ele.children[0].children[0].children[0].setAttribute("style","background-image: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].addEventListener("click",function(e){
                        decimCoin = this.getAttribute("icDecim");
                        //AGREGAR AQUÍ LA VALIDACIÓN CON MONEDAS

                        if(this.getAttribute("interface") == 4 || this.getAttribute("interface") == 5){ 
                            //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("transferBTC").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");
                                }
                            }

                            if(e.srcElement.parentNode.parentNode.getAttribute('accidReal')==0){
                                //accountsGenerate(e.srcElement.parentNode.parentNode.getAttribute('icCur'))
                            }
                            console.log(this.getAttribute("status"))
                            if(this.getAttribute("status") == 1){
                                
                                document.getElementById("BTCPortfolio").setAttribute("accidReal",e.srcElement.parentNode.parentNode.getAttribute('accidReal'));
                                document.getElementById("BTCPortfolio").setAttribute("icCur",e.srcElement.parentNode.parentNode.getAttribute('icCur'));
                                document.getElementById("BTCPortfolio").setAttribute("icDecim",e.srcElement.parentNode.parentNode.getAttribute('icDecim'));
                                document.getElementById("BTCPortfolio").setAttribute("interface",e.srcElement.parentNode.parentNode.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") == 3){
                            console.log(this.getAttribute("interface"))
                        }
                        
                        else if(this.getAttribute("interface") == 1 || this.getAttribute("interface") == 2){
                            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){
                                
                                document.getElementById("FiatPortfolio").setAttribute("accidReal",e.srcElement.parentNode.parentNode.getAttribute('accidReal'));
                                document.getElementById("FiatPortfolio").setAttribute("icCur",e.srcElement.parentNode.parentNode.getAttribute('icCur'));
                                document.getElementById("FiatPortfolio").setAttribute("icDecim",e.srcElement.parentNode.parentNode.getAttribute('icDecim'));
                                document.getElementById("FiatPortfolio").setAttribute("interface",e.srcElement.parentNode.parentNode.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'
                                })
                            }
                        }
                    });
                    //tbl.insertBefore(ele,document.getElementById('totalPortfolio'))
                    tbl.children[3].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){
                                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)
                        
                        
                               // rsp[i].type == 3 -> Transferencia
                            if(rsp[i].type != 3){
                                console.log(rsp[i].type)
                                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[5].innerHTML = ''
                            }
                       
                        
                        if(i % 2 != 0){
                            ele.children[0].style.backgroundColor = 'rgba(245, 246, 248, 0.800000011920929)'
                        }
                        tbl.appendChild(ele);
                    }
                }
                if(changeName==='dataFiat'){
                    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[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 == "Transferencia" || 
                           rsp[i].description == "Comisión de Transferencia" || 
                           rsp[i].description == "Depósito inicial de pruebas" || 
                           rsp[i].description == "Comisión de Depósito inicial de pruebas" || 
                           rsp[i].description == "Transferencia" || 
                           rsp[i].description == "Comisión de Transferencia" ||
                           rsp[i].description == "Depósito" || 
                           rsp[i].description == "Comisión de Depósito"){
                            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 == "Transferencia" || 
                           rsp[i].description == "Comisión de Transferencia" || 
                           rsp[i].description == "Depósito inicial de pruebas" || 
                           rsp[i].description == "Comisión de Depósito inicial de pruebas" || 
                           rsp[i].description == "Transferencia" || 
                           rsp[i].description == "Comisión de Transferencia" ||
                           rsp[i].description == "Depósito" || 
                           rsp[i].description == "Comisión de Depósito"){
                            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);
                    }
                    
                }

            }
            
        }
    
    }
}

// Service markers/list
function markersList(){
    
    var sessionid = getParameterByName('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){
        console.log('markers/list')
        console.log(JSON.parse(rsp));
        console.log(status)
        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{
        //debugger;
        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);
            if(sessionStorage.getItem('pairid')){
                if(sessionStorage.getItem('pairid')==rsp[i].id){
                    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': getParameterByName('sessionid'),
                            'ordernumofrec': 25,
                            'exchangenumofrec': 25,
                            'pairid' : this.getAttribute("parid")
                        }
                        console.log('10')
                        dashboardEntry(reqDashboardEntry,'portfolio',0);   
                    });
                }else{
                    ele.addEventListener("click",function(){
                        console.log('IN ELSE')
                        console.log(reason)
                        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': getParameterByName('sessionid'),
                            'ordernumofrec': 25,
                            'exchangenumofrec': 25,
                            'pairid' : this.getAttribute("parid")
                        }
                        console.log('10')
                        console.log('reqDashboardEntry: ',reqDashboardEntry)
                        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': getParameterByName('sessionid'),
                        'ordernumofrec': 25,
                        'exchangenumofrec': 25,
                        'pairid' : this.getAttribute("parid")
                    }
                    console.log('10')
                    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++){
                console.log()
                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{
        //debugger;
        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 = getParameterByName('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){
        //console.log(JSON.parse(rsp));
        //console.log(status)
        switch(status){
            case 200:
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

// Service markers/chart
function markersChart(){
    
    var sessionid = getParameterByName('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){
        //console.log(JSON.parse(rsp));
        //console.log(status)
        switch(status){
            case 200:
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

// Service accounts/portfolio
function accountsPortfolio(parid,currency, refCurrency){
    
    var sessionid = getParameterByName('sessionid')
    
    var req ={
        'sessionid': sessionid,
        'parid' : parid
    }
    callWS('GET', 'accounts/portfolio', req, response);
    
    console.log('accounts/portfolio')

    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
                    })
                    
                    //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
                    })
                }
                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
                        })
                    }else{
                        portfolio.push({
                            'src':'',
                            'name': refCurrency.symbol,
                            'amount': 0,
                            'ptc': '0,00%',
                            'id': 0,
                            'currencyid': refCurrency.id,
                            'decimals': refCurrency.decimals,
                            'dsc' : refCurrency.dsc
                        })
                    }
                }
                console.log(portfolio)
                listDraw(portfolio, 'portfolio');
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

// Service transactions/list
function transactionsList(){
    
    var sessionid = getParameterByName('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){
        //console.log(JSON.parse(rsp));
        //console.log(status)
        switch(status){
            case 200:
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

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

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

function 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'
        }
        //console.log(toggle)
        //console.log(toggle[i])
        
        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 = getParameterByName('sessionid');
    var req ={
        'sessionid': sessionid,
        'currencyid' : currencyid
    }
    console.log(req)
    callWS('GET', 'accounts/generate', req, response);
    function response(status, rsp){
        console.log(status)
        console.log(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 500:
                break;
            default:
                break;
        }
    }   
}

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

// Service accounts/entry
function accountsEntry(id,action){
    
    var sessionid = getParameterByName('sessionid')
    var id = id
    
    var req ={
        'sessionid': sessionid,
        'id' : id
    }
    console.log(req)
    callWS('GET', 'accounts/entry', req, response);

    function response(status, rsp){
        console.log('Aqui accounts/entry')
        console.log(JSON.parse(rsp));
        console.log(status)
        console.log(action)
        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.details1.value;
                    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
                    });
                    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': getParameterByName('sessionid'),
                        'currencyid': document.getElementById('BTCPortfolio').getAttribute('icCur')
                    }
                    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)
                    accountsList(JSON.parse(rsp).entry.currency.id)
                }
                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= 'Se envió un código de validación a su correo '+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': getParameterByName('sessionid'),
                        'currencyid': document.getElementById('BTCPortfolio').getAttribute('icCur')
                    }
                    feesEntry(req,'transferBTC')
                }
                else if(action == 'verifytrBTCbutton'){
                    document.getElementById('transferBTCConfirmEmail').innerHTML= document.getElementById('transferBTCEmail').value
                    document.getElementById('transferBTCConfirmAmount').innerHTML= fixDecimals((parseFloat((document.getElementById('transferBTCAmount').value).replace(',', '.')).toFixed(decimCoin)).replace('.', ','));
                    document.getElementById('transferBTCConfirmFee').innerHTML= document.getElementById('transferBTCFee').innerHTML
                    document.getElementById('transferBTCConfirmTotalN').innerHTML= document.getElementById('transferBTCTotal').innerHTML
                    document.getElementById('transferBTCConfirmEmailConfirm').innerHTML= 'Se envió un código de validación a su correo '+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': getParameterByName('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 = getParameterByName('sessionid')
    
    var req ={
        'sessionid': sessionid,
        'paym':1,
    }
    
    callWS('GET', 'accounts/list', req, response);

    function response(status, rsp){
        console.log('Aqui accounts/list')
        console.log(JSON.parse(rsp));
        console.log(status)
        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)
                }else{
                    console.log('AAAAAA')
                    addOptions('withdrawFiatAccount',arrayAccounts)
                    error('withdrawFiatAccount','ewithdrawFiatAccount','Agregue una cuenta de retiro en el menú de Preferencias. La cuenta debe ser verificada por AFX para que pueda ser utilizada.');
                    document.getElementById("withdrawFiatAccount").classList.remove("selectwdFiat");
                    document.getElementById("withdrawFiatAccount").classList.add("selectwdFiatBank");
                    document.getElementById('ewithdrawFiatAccount').style.display = 'block'
                    document.getElementById('ewithdrawFiatAccount').style.marginLeft = '20px'
                }
                req = {
                    'sessionid': getParameterByName('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){
    console.log(req)
    callWS('POST', 'deposits/insert', req, response);
    function response(status, rsp){
        console.log('Aqui deposits/insert')
        console.log(JSON.parse(rsp));
        console.log(status)
        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:
                console.log('Monto no autorizado')
                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;
        }
    }   
}

function depositFiat(){
    
    console.log('depFiatAccept Depósito')
    
    var req ={
        'sessionid': getParameterByName('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")
    console.log(document.getElementById("FiatPortfolio").getAttribute("accidReal"))
    console.log(req)
    console.log(depositsAccountsArray)
    
    verifyDepositsInsert(req)
}

function verifyDepositsInsert(req){
    
    console.log('in verifyDepositsInsert')
    
    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 = 'Ingrese una cantidad.';
            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 = 'Seleccione un banco.';
            document.getElementById('edepFiatInfDestinationBank1').style.display = 'block'
        }
        if (document.getElementById('depFiatInfDate').value==''){
            error('depFiatInfDate','edepFiatInfDate','Seleccione una fecha.');
            document.getElementById('edepFiatInfDate').style.display = 'block'
        }
        if (document.getElementById('depFiatInfRef').value==''){ 
            error('depFiatInfRef','edepFiatInfRef','Introduzca una referencia.');
            document.getElementById('edepFiatInfRef').style.display = 'block'
        }
        if (document.getElementById('depFiatInfId').value=='' || document.getElementById('depFiatInfId').value == undefined){
            //error('depFiatInfRec','edepFiatInfRec','Introduzca un código postal.');
            console.log('entro')
            document.getElementById('edepFiatInfRec').innerHTML = 'Ingrese un archivo.';
            document.getElementById('edepFiatInfRec').style.display = 'block'
        }
        if (now.getTime() < new Date(document.getElementById('depFiatInfDate').value).getTime()){
            console.log('No puede reportar fehcas futuras')
            error('depFiatInfDate','edepFiatInfDate','No puede reportar fechas futuras.');
            document.getElementById('edepFiatInfDate').style.display = 'block'
        }
        
        return;
        
    }else{
        console.log(req)
        depositsInsert(req)   
    }
}
 
// transactions/movements

function transactionsMovements(req,type){
    console.log(req)
    callWS('GET', 'transactions/movements', req, response);
    function response(status, rsp){
        console.log('Aqui transactions/movements')
        console.log(JSON.parse(rsp));
        console.log(status)
        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){

    console.log('see Movements')
    
    var req ={
        'sessionid': getParameterByName('sessionid'),
        //'search': '',
        'accountid': id,
        'time': 0,
        //'offset': '',
        //'numofrecords': ''
    }
    
    transactionsMovements(req,type)
}

function transformTransactionsMovementsVES(data){
    dataArray = []
    console.log(data)
    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,
        })
    }
    listDraw(dataArray, 'dataFiat')
    document.getElementsByClassName('movVES')[0].style.display = "table"
    document.getElementsByTagName('body')[0].classList.add('hidden')
}

function transformTransactionsMovementsBTC(data){
    dataArray = []
    console.log(data)
    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
        })
    }
    //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){
    console.log(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;
                console.log(trans);
                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';
                    document.getElementById('movDetailFiatAccount').innerHTML = this.transformAccountString(JSON.parse(rsp).entry.destination.account.paymentmethod.dsc,JSON.parse(rsp).entry.destination.account.details1)
                    document.getElementById("movDetailTit").innerHTML = "Retiro - "+ 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{
                        console.log(JSON.parse(rsp).entry.destination.account.details1)
                        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 = "Cantidad retirada";

                }else if(trans.destination){
                        document.getElementById("movDetailTit").innerHTML = "Depósito - "+ trans.destination.account.currency.symbol; 

                        document.getElementById('movDetailFiatAddress').style.display = 'table';
                        document.getElementById('movDetailFiatAddressHr').style.display = 'block';
                        document.getElementById('movDetailFiatAccount').innerHTML = this.transformAccountString(JSON.parse(rsp).entry.destination.account.paymentmethod.dsc,JSON.parse(rsp).entry.destination.account.details1)
                        document.getElementById("resend").parentElement.parentElement.style.display = "table";
                    /*}else{
                        console.log(JSON.parse(rsp).entry.destination.account.details1)
                        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 = "Cantidad depositada";
                    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){
    console.log(id)
    var req ={
        'sessionid': getParameterByName('sessionid'),
        'id': id,
        'time': 0,
    }
    
    transactionsEntry(req)
}

function transformAccountString(paymentmethod, details1){
    return(paymentmethod + '(****' + details1.substr(-4) + ')')
}

function depositsAccounts(currencyid){
    var req ={
        'sessionid': getParameterByName('sessionid'),
        'currencyid': currencyid,
    }
    console.log(req)
    callWS('GET', 'deposits/accounts', req, response);
    function response(status, rsp){
        console.log('Aqui deposits/accounts')
        console.log(JSON.parse(rsp));
        console.log(status)
        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('depFiatInfDestinationBank1').value ='';
                document.getElementById('depFiatInfDate').value = '';
                document.getElementById('depFiatInfRef').value ='';
                document.getElementById('depFiatInFee').innerHTML = '0';
                document.getElementById('depFiatInNeTotal').innerHTML = '0';
                document.getElementById('depFiatInfId').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) {
    console.log(array)
    removeOptions(domElement)
    var selector = document.getElementById(domElement);
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = 'Selecciona'
    firstOopcion.value =''
    firstOopcion.selected = true
    selector.add(firstOopcion);
    for (var i in array.records) {
        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 = ''
    console.log(selectElement)
    x = document.getElementById(selectElement)
    var i, L = x.options.length - 1;
    for(i = L; i >= 0; i--) {
       x.remove(i);
    }
}

function putDepositDataFiat(id){
    console.log(id)
    console.log(depositsAccountsArray)
    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(){
    //debugger;
    if(document.getElementById('withdrawBTCAmount').value == '' || document.getElementById('withdrawBTCWallet').value == '' ){
        if (document.getElementById('withdrawBTCAmount').value == ''){
            error('withdrawBTCAmount','ewithdrawBTCAmount','Introduzca una cantidad.');
            document.getElementById('ewithdrawBTCAmount').style.display = 'block'
            document.getElementById('ewithdrawBTCAmount').style.marginLeft = '20px'
        }
        if(document.getElementById('withdrawBTCWallet').value == ''){
            error('withdrawBTCWallet','ewithdrawBTCWallet','Introduzca un wallet.');
            document.getElementById('ewithdrawBTCWallet').style.display = 'block'
            document.getElementById('ewithdrawBTCWallet').style.marginLeft = '20px'
        }
        return;
    }
    if(!onlyAlphanumeric(document.getElementById('withdrawBTCWallet'))){
        error('withdrawBTCWallet','ewithdrawBTCWallet','Introduzca un wallet válida.');
        document.getElementById('ewithdrawBTCWallet').style.display = 'block'
        document.getElementById('ewithdrawBTCWallet').style.marginLeft = '20px'
        return;
    }
    if(document.getElementById('withdrawBTCAmount').getAttribute("dataNumber")<=0){
        error('withdrawBTCAmount','ewithdrawBTCAmount','La cantidad debe se mayor a cero.');
        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','Saldo insuficiente.');
        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','Saldo insuficiente.');
        document.getElementById('ewithdrawBTCAmount').style.display = 'block'
        document.getElementById('ewithdrawBTCAmount').style.marginLeft = '20px'
        return;
    }
    if(document.getElementById('withdrawBTCFee').innerHTML > document.getElementById('withdrawBTCAmount').value){
        error('withdrawBTCAmount','ewithdrawBTCAmount','La cantidad debe ser mayor a la comisión.');
        document.getElementById('ewithdrawBTCAmount').style.display = 'block'
        document.getElementById('ewithdrawBTCAmount').style.marginLeft = '20px'
        return;
    }
    
    
    document.getElementById('withdrawBTCConfirmAmount').innerHTML= fixDecimals((parseFloat((document.getElementById('withdrawBTCAmount').value).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= 'Se envió un código de validación a su correo '+entrydata.usr
    document.getElementById('withdrawBTCConfirmCode').value= ''
    
    var req = {
        'accountid': document.getElementById('BTCPortfolio').getAttribute('accidreal'),
        'amount': document.getElementById('withdrawBTCAmount').getAttribute("dataNumber"),//.slice(0, -3),//.slice(0, -3), // document.getElementById('withdrawBTCConfirmAmount').innerHTML, Dummy
        'paymentwallet': document.getElementById('withdrawBTCConfirmWallet').innerHTML,
        'sessionid': getParameterByName('sessionid')
    }
    
    withdrawalsInsert(req,'BTC')
}


// withdrawals/insert

function withdrawalsInsert(req,type){
    console.log(req)
    callWS('POST', 'withdrawals/insert', req, response);
    function response(status, rsp){
        console.log('Aqui withdrawals/insert')
        console.log(JSON.parse(rsp));
        console.log(status) 
        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){
    console.log(req)
    callWS('GET', 'transactions/accept', req, response);
    function response(status, rsp){
        console.log('Aqui transactions/accept')
        console.log(JSON.parse(rsp));
        console.log(status)
        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('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.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:
                if(type == 'BTC'){
                    error('withdrawBTCConfirmCode','ewithdrawBTCConfirmCode','Código inválido.'); 
                    document.getElementById('ewithdrawBTCConfirmCode').style.display = 'block';
                    document.getElementById('ewithdrawBTCConfirmCode').style.marginLeft = '20px';
                }
                if(type == 'Fiat'){
                    error('withdrawFiatConfirmCode','ewithdrawFiatConfirmCode','Código inválido.');
                    document.getElementById('ewithdrawFiatConfirmCode').style.display = 'block'
                    document.getElementById('ewithdrawFiatConfirmCode').style.marginLeft = '20px'
                }
                if(type == 'BTCxfer'){
                    error('transferBTCConfirmCode','etransferBTCConfirmCode','Código inválido.');
                    document.getElementById('etransferBTCConfirmCode').style.display = 'block'
                    document.getElementById('etransferBTCConfirmCode').style.marginLeft = '20px'
                }
                break;
            case 403:
                if(type == 'BTC'){
                    error('withdrawBTCConfirmCode','ewithdrawBTCConfirmCode','Código expirado.'); 
                    document.getElementById('ewithdrawBTCConfirmCode').style.display = 'block';
                    document.getElementById('ewithdrawBTCConfirmCode').style.marginLeft = '20px';
                }
                if(type == 'Fiat'){
                    error('withdrawFiatConfirmCode','ewithdrawFiatConfirmCode','Código expirado.');
                    document.getElementById('ewithdrawFiatConfirmCode').style.display = 'block'
                    document.getElementById('ewithdrawFiatConfirmCode').style.marginLeft = '20px'
                }
                if(type == 'BTCxfer'){
                    error('transferBTCConfirmCode','etransferBTCConfirmCode','Código expirado.');
                    document.getElementById('etransferBTCConfirmCode').style.display = 'block'
                    document.getElementById('etransferBTCConfirmCode').style.marginLeft = '20px'
                }
                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 verifywdBTCbuttonV(){
    
    if(document.getElementById('withdrawBTCConfirmCode').value == ''){
        error('withdrawBTCConfirmCode','ewithdrawBTCConfirmCode','Introduzca un código.');
        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': getParameterByName('sessionid')
        
    }
    
    TransactionsAccept(req,'BTC')
}


function withdrawFiatButton(){
    document.getElementById('withdrawFiatAmount').value = '';
    document.getElementById('withdrawFiatAmount').setAttribute("dataNumber","");
    document.getElementById('withdrawFiatAccount').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','Introduzca una cantidad.');
            document.getElementById('ewithdrawFiatAmount').style.display = 'block'
            document.getElementById('ewithdrawFiatAmount').style.marginLeft = '20px'
        }
        if(document.getElementById('withdrawFiatAccount').value == ''){
            error('withdrawFiatAccount','ewithdrawFiatAccount','Seleccione una cuenta.');
            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','Saldo insuficiente.');
        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': getParameterByName('sessionid')
    }
    console.log(req)
    withdrawalsInsert(req,'Fiat')
}

function verifywdFiatbuttonV(){
    
    if(document.getElementById('withdrawFiatConfirmCode').value == ''){
        error('withdrawFiatConfirmCode','ewithdrawFiatConfirmCode','Introduzca un código.');
        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': getParameterByName('sessionid')
    }
    //document.getElementsByClassName('withdrawFiatConfirm')[0].style.display = "none"
   // document.getElementsByClassName('success')[0].style.display = "table"
    
    TransactionsAccept(req,'Fiat')
}


// xfer/make 
function xferMake(req){
    console.log(req)
    callWS('GET', 'xfer/make', req, response);
    function response(status, rsp){
        console.log('xfer/make')
        console.log(JSON.parse(rsp));
        console.log(status) 
        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','Usuario no registrado o  verificado en AFX.');
                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','Introduzca una cantidad.');
            document.getElementById('etransferBTCAmount').style.display = 'block'
            document.getElementById('etransferBTCAmount').style.marginLeft = '20px'
        }
        if(document.getElementById('transferBTCEmail').value == ''){
            error('transferBTCEmail','etransferBTCEmail','Introduzca un email.');
            document.getElementById('etransferBTCEmail').style.display = 'block'
            document.getElementById('etransferBTCEmail').style.marginLeft = '20px'
        }
        if(!document.getElementById('transferBTCEmail').validity.valid){
            error('transferBTCEmail','etransferBTCEmail','El email es incorrecto.');
            document.getElementById('etransferBTCEmail').style.display = 'block'
            document.getElementById('etransferBTCEmail').style.marginLeft = '20px'
        }
        return;
    }
    if(parseFloat(document.getElementById('transferBTCAmount').value) > parseFloat(document.getElementById('transferBTCBalance').getAttribute('numberAmount'))){
        error('transferBTCAmount','etransferBTCAmount','Saldo insuficiente.');
        document.getElementById('etransferBTCAmount').style.display = 'block'
        document.getElementById('etransferBTCAmount').style.marginLeft = '20px'
        return;
    }
    
    accountsEntry(document.getElementById('BTCPortfolio').getAttribute('accidreal'),'verifytrBTCbutton')
    
    var req = {
        'originaccountid': document.getElementById('BTCPortfolio').getAttribute('accidreal'),
        'amount': document.getElementById('transferBTCAmount').getAttribute("dataNumber"),
        'usr': document.getElementById('transferBTCEmail').value,
        'sessionid': getParameterByName('sessionid')
    }
    console.log(req)
    xferMake(req)
    
}

function verifytrBTCbuttonV(){
    if(document.getElementById('transferBTCConfirmCode').value == ''){
        error('transferBTCConfirmCode','etransferBTCConfirmCode','Introduzca un código.');
        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': getParameterByName('sessionid')
    }
    console.log(req)
    
    TransactionsAccept(req,'BTCxfer')
}

// xfer/make 
function transactionsCancel(req){
    console.log(req)
    callWS('GET', 'transactions/cancel', req, response);
    function response(status, rsp){
        console.log('transactions/cancel')
        console.log(JSON.parse(rsp));
        console.log(status) 
        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.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('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 expiredSession(){
    document.getElementsByClassName('expired')[0].style.display = "table"
    //var waitScreen = document.getElementById("waitScreen");
    //document.body.removeChild(waitScreen);
    WS_waitscreen = false;
    var seconds = 30;
    /*if(document.getElementById("expiredp")){
        var countdown = setInterval(function() {
            seconds--;
            document.getElementById("expiredp").textContent = seconds + ' segundos';
            if (seconds == 1) document.getElementById("expiredp").textContent = 1  + ' segundo';
            if (seconds == 0) gotoPage('login','main','');
            if (seconds < 0){
                document.getElementById("expiredp").textContent = 0 + ' segundos'; 
                gotoPage('login','main','');
            }
        }, 1000);   
    }*/
    var countdown = setInterval(countDown, 1000);
    
    function countDown(){
        seconds--;
        if(seconds == 0){
            if(document.getElementsByClassName('expired')[0].style.display == "table"){
                gotoPage('login','main','');
                clearInterval(countdown);
            }
        }
        if(document.getElementsByClassName('expired')[0].style.display == "none"){
            clearInterval(countdown)
        }
    }
}

// fees/entry
var decimCoin = 0;
function feesEntry(req,type){
    console.log(req)
    callWS('GET', 'fees/entry', req, response);
    function response(status, rsp){
        console.log('fees/entry')
        console.log(JSON.parse(rsp));
        console.log(status) 
        switch(status){
            case 200:
                /**SECCION MODIFICADA MANEJO DE DECIMAL EN MONTOS CON VARIABLE GLOBAL**/
                if(type=='depositBTC'){
                    if(JSON.parse(rsp).entry.deposits.nmalfee){
                        document.getElementById("depositCriptoFee").innerHTML = (JSON.parse(rsp).entry.deposits.nmalfee.number).toFixed(decimCoin);
                    }
                    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 = "COMISIÓN";
                        document.getElementById('withdrawBTCFee').innerHTML = fixDecimals((JSON.parse(rsp).entry.withdrawals.nmalfee.number).toFixed(decimCoin).replace('.', ','));
                        document.getElementById('withdrawBTCTotal').innerHTML = fixDecimals((JSON.parse(rsp).entry.withdrawals.nmalfee.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).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).toFixed(decimCoin)).replace('.', ',')));
                                    document.getElementById('withdrawBTCTotal').style.color="#262624"
                                }
                                
                           }
                        }); 
                    }
                    else if(JSON.parse(rsp).entry.withdrawals.pctfee){
                        document.getElementById('withdrawBTCFee').parentElement.previousElementSibling.children[0].innerHTML = "COMISIÓN ("+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).toFixed(decimCoin)).replace('.', ','));
                            document.getElementById('withdrawBTCTotal').innerHTML = fixDecimals(((  (document.getElementById('withdrawBTCAmount').value).replace(',', '.')   * (1 - JSON.parse(rsp).entry.withdrawals.pctfee.number / 100)).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 = "COMISIÓN";
                        document.getElementById('transferBTCFee').innerHTML = fixDecimals((JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ','));
                        document.getElementById('transferBTCTotal').innerHTML = fixDecimals((JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin).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;

                            if(document.getElementById('transferBTCAmount').value == ""){
                                document.getElementById('transferBTCTotal').innerHTML = '0'
                            }else{
                                document.getElementById('transferBTCTotal').innerHTML =  fixDecimals(((parseFloat((document.getElementById('transferBTCAmount').value).replace(',','.')) - JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin)).replace('.', ','));
                            }
                        }); 
                    }
                    else if(JSON.parse(rsp).entry.xfer.pctfee){
                        document.getElementById('transferBTCFee').parentElement.previousElementSibling.children[0].innerHTML = "COMISIÓN ("+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;
                            document.getElementById('transferBTCFee').innerHTML = fixDecimals(((  (document.getElementById('transferBTCAmount').value).replace(',', '.')   * JSON.parse(rsp).entry.xfer.pctfee.number / 100).toFixed(decimCoin)).replace('.', ','));
                            document.getElementById('transferBTCTotal').innerHTML = fixDecimals(((  (document.getElementById('transferBTCAmount').value).replace(',', '.')   * (1 - JSON.parse(rsp).entry.xfer.pctfee.number / 100)).toFixed(decimCoin)).replace('.', ','));
                        }); 
                    }
                   document.getElementsByClassName('transferBTC')[0].style.display = "table"
                   document.getElementsByTagName('body')[0].classList.add('hidden')
                }
                /*
                if(type=='transferBTC'){
                    if(JSON.parse(rsp).entry.xfer.nmalfee){
                        document.getElementById('transferBTCFee').innerHTML = fixDecimals((JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin).replace('.', ','));
                        document.getElementById('transferBTCTotal').innerHTML = fixDecimals((JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin).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;

                            if(document.getElementById('transferBTCAmount').value == ""){
                                document.getElementById('transferBTCTotal').innerHTML = '0'
                            }else{
                                document.getElementById('transferBTCTotal').innerHTML =  fixDecimals(((parseFloat((document.getElementById('transferBTCAmount').value).replace(',','.')) - JSON.parse(rsp).entry.xfer.nmalfee.number).toFixed(decimCoin)).replace('.', ','));
                            }
                        }); 
                    }
                    else if(JSON.parse(rsp).entry.xfer.pctfee){
                        document.getElementById('transferBTCAmount').addEventListener("keyup", function(){
                            //CONTROLA decimales y numero signitificaivo máx
                            var noVal = formatCurrency(decimCoin,this.value);
                            if(noVal!=="")this.value = noVal;

                            console.log('keyup')
                            document.getElementById('transferBTCFee').innerHTML = fixDecimals(((  (document.getElementById('transferBTCAmount').value).replace(',', '.')   * JSON.parse(rsp).entry.xfer.pctfee.number / 100).toFixed(decimCoin)).replace('.', ','));
                            document.getElementById('transferBTCTotal').innerHTML = fixDecimals(((  (document.getElementById('transferBTCAmount').value).replace(',', '.')   * (1 - JSON.parse(rsp).entry.xfer.pctfee.number / 100)).toFixed(decimCoin)).replace('.', ','));
                        }); 
                    }
                   document.getElementsByClassName('transferBTC')[0].style.display = "table"
                }*/
                if(type=='depFiatInfButton'){
                    console.log(JSON.parse(rsp).entry)
                    if(JSON.parse(rsp).entry.deposits.nmalfee){
                        document.getElementById('depFiatInFee').parentElement.previousElementSibling.children[0].innerHTML = "COMISIÓN";
                        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 = "COMISIÓN ("+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);
                            }
                        });
                    }
                   document.getElementsByClassName('depFiatInf')[0].style.display = "table" 
                   document.getElementsByTagName('body')[0].classList.add('hidden')
                }
                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 = "COMISIÓN";
                        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 = "COMISIÓN ("+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(',','.')))));
                            }
                        }); 
                    }
                   document.getElementsByClassName('withdrawFiat')[0].style.display = "table"
                   document.getElementsByTagName('body')[0].classList.add('hidden')
                }
                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;
        }
    }   
}

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){
    console.log(req)
    callWS('GET', 'transactions/validation', req, response);
    function response(status, rsp){
        console.log('transactions/validation')
        console.log(JSON.parse(rsp));
        console.log(status) 
        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){
    console.log('IN DASHBOARD ENTRY REASON: ', reason)
    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'))
        }
    }
    console.log(req)
    console.log(reason)
    console.log(num)
    callWS('GET', 'dashboard/entry', req, response);
    function response(status, rsp){
        console.log('dashboard/entry')
        console.log(req)
        console.log(status) 
        switch(status){
            case 200: 
                dashboardUpdate = JSON.parse(rsp)
                console.log(JSON.parse(rsp));
                switch (reason){
                    case 'initial':
                        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': getParameterByName('sessionid'),
                                'ordernumofrec': 25,
                                'exchangenumofrec': 25,
                                'pairid' : document.getElementById('pairName').getAttribute('pairId'),
                            }
                            dashboardEntryRefresh(req)
                        }, 3000);
                        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
    }
    console.log(req)
    callWSWithoutWS('GET', 'dashboard/entry', req, response);
    function response(status, rsp){
        console.log('dashboard/entry') 
        console.log(req)
        console.log(JSON.parse(rsp)); 
        console.log(status) 
        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': getParameterByName('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;
    console.log('IN CHARGEPAIRS ', pairs)
    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': getParameterByName('sessionid')
                   }*/
                   req = {
                       'id': this.getAttribute('orderId'),
                       'sessionid': getParameterByName('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': getParameterByName('sessionid')
                   }*/
                   req = {
                       'id': this.getAttribute('orderId'),
                       'sessionid': getParameterByName('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){
    console.log('in chargePortfolio with reason: ', reason)
    console.log('portfolio: ',portfolio)
    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++){
        //if(portfolio.accounts[i].currency.id == currency.id || portfolio.accounts[i].currency.id == refCurrency.id){
            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
            })   
            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
            }
        }   
    }
    console.log('newCurrencieArray: ',newCurrencieArray)
    console.log(portfolioArray)
    //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){
        console.log('in chargePairDetails')
        
        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.dsc){
            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){
    console.log(req) // side 1 Venta / 2 Compra. 
    callWS('POST', 'orders/insert', req, response);
    function response(status, rsp){
        console.log('orders/insert')
        console.log(status)
        console.log(rsp)
        //
        console.log(status) 
        switch(status){
            case 200:
                console.log(JSON.parse(rsp));
                var reqDashboardEntry = {
                    'sessionid': getParameterByName('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 = 'No hay liquidez, espere o coloque una orden tipo límite.'
                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){
    console.log(req) 
    callWS('POST', 'orders/insert', req, response);
    function response(status, rsp){
        console.log('orders/insert')
        console.log(status)
        console.log(rsp)
        //
        console.log(status) 
        switch(status){
            case 200:
                if(req.side == 2){
                    document.getElementById('failureMsgYellow').innerHTML = 'No existe liquidez suficiente. Por lo tanto, se ejecutó una orden parcial por '+ 
                                                                            number_format(parseFloat(req.qty),document.getElementById('BuyAndSellAmount').getAttribute("icDecim"))
                                                                            + ' ' + document.getElementById('cardBuyAndSellAmountText').innerHTML
                                                                            + ' a un precio ponderado de ' + 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 = 'No existe liquidez suficiente. Por lo tanto, se ejecutó una orden parcial por '+ 
                                                                            number_format(parseFloat(req.qty),document.getElementById('BuyAndSellAmount').getAttribute("icDecim"))
                                                                            + ' ' + document.getElementById('cardBuyAndSellAmountText').innerHTML
                                                                            + ' a un precio ponderado de ' + 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': getParameterByName('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 = 'No hay liquidez, espere o coloque una orden tipo límite.'
                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){
        console.log('orders/cancel')
        console.log(JSON.parse(rsp));
        console.log(status) 
        switch(status){
            case 200:
                var reqDashboardEntry = {
                    'sessionid': getParameterByName('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(){
    
    console.log("parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')).noExponents()", parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')).noExponents())
    console.log("document.getElementById('BuyAndSellAmount').getAttribute('icDecim')", document.getElementById('BuyAndSellAmount').getAttribute("icDecim"))
    //console.log("number_format",number_format(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')).noExponents(),document.getElementById('BuyAndSellAmount').getAttribute("icDecim")) )
    //console.log("replace.",number_format(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')).noExponents(),document.getElementById('BuyAndSellAmount').getAttribute("icDecim")).replaceAll('.',''))
    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': getParameterByName('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': getParameterByName('sessionid')
    }
    replace*/
    
    // Si es limit debo mandar el precio
    if(req.type == 2){
        req.price = parseFloat(document.getElementById('BuyAndSellPrice').getAttribute('dataNumber'))
    } 
    
    console.log(req)
    
    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 = '<p class="poppins-medium">Precio  <i class="fas fa-exclamation-circle popup" id="tooltip"><span class="popuptext poppins-regular">Precio referencial del mercado.</span></i></p>'
    
    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 = 'Precio Market Estimado: ' + document.getElementById('BuyAndSellPrice').value
    document.getElementById('BuyAndSellPrice').disabled = true;
     
    openConfirmOrder(type)
}

function openConfirmOrder(type){
    console.log(feesOrders)
    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)){
        console.log('1')
        document.getElementById('failureMsg').innerHTML = 'Monto mínimo autorizado ' + feesOrders.min.formatted + ' ' + document.getElementById('cardBuyAndSellAmountText').innerHTML;
        document.getElementById('failureTitle').innerHTML="Error";
        document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar";
        document.getElementsByClassName('failure')[0].style.display = "table";
        return;
    }
    
    if(calculateMinimum(type)){
        return;
    }
        
    console.log(calculateTotalM(type))
    console.log(document.getElementById('BuyAndSellTotal').getAttribute("icDecim"))
    console.log(number_format(calculateTotalM(type),document.getElementById('BuyAndSellTotal').getAttribute("icDecim")))
        
        
    console.log(document.getElementById('BuyAndSellSelect').value)
    document.getElementById('textInCardResumeDivTextPrice').innerHTML = document.getElementById('BuyAndSellSelect').value == 1 ? 'Precio' : 'Precio Estimado'
        
    if(document.getElementById('BuyAndSellSelect').value == 1){
        document.getElementById('textInCardResumeDivTextPrice').innerHTML = 'Precio'
    }else{
        document.getElementById('textInCardResumeDivTextPrice').innerHTML = 'Precio Estimado <i class="fas fa-exclamation-circle popup2" id="tooltip2"><span class="popuptext poppins-regular">Precio referencial del mercado.</span></i>'
        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))
    //console.log(document.getElementById('confirmOrderEstimatedPrice').innerHTML)
    //console.log(calculateTotalM(type)/document.getElementById('BuyAndSellAmount').getAttribute('dataNumber'),document.getElementById('BuyAndSellTotal').getAttribute("icDecim")))
    //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(){ 
            console.log('en el settimeout')
            
            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 = 'El Total Neto a Obtener debe ser mayor a 0.'
            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 = 'El botón para continuar se deshabilitó.'
                    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 = 'El botón para continuar se deshabilitará en <span>15</span> segundos.'
                    clearInterval(tm);
                }
            }          
        }
}

function calculateMinimum(type){
    console.log(type)
    console.log(feesOrders)
    //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 = 'Monto mínimo autorizado ' + feesOrders.min.formatted + ' ' + document.getElementById('cardBuyAndSellTotalText').innerHTML;
        document.getElementById('failureTitle').innerHTML="Error";
        document.getElementById('wdFiatbuttonI').innerHTML = "Aceptar";
        document.getElementsByClassName('failure')[0].style.display = "table";
        return true
    }
    return false;
}

function calculateTotalWithFees(typeSelect,typeButton){
    console.log(typeSelect)
    console.log(typeButton)
    console.log(feesOrders)
    // Limit
    if(typeSelect == 1){
        // Compra - Limit
        if(typeButton == 'bid'){
            console.log(parseFloat(calculateFeesConfirmOrder(parseFloat(document.getElementById('BuyAndSellAmount').getAttribute('datanumber')),feesOrders.orders.limit)))
            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){
    console.log(typeSelect)
    console.log(typeButton)
    console.log(feesOrders)
    // 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){
    console.log(number)
    console.log(fee)
    if(fee.pctfee){
        console.log(parseFloat(number - number * (fee.pctfee.number/100)))
        console.log((parseFloat(number - number * (fee.pctfee.number/100))).noExponents())
        return (parseFloat(number - number * (fee.pctfee.number/100))).noExponents()
    }else if(fee.nmalfee){
        console.log(parseFloat(number - fee.nmalfee.number))
        console.log((parseFloat(number - fee.nmalfee.number)).noExponents())
        return (parseFloat(number - fee.nmalfee.number)).noExponents()
    }
    else{
        return 0
    }
}

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

function setFeesOrders(value){
    if(value == 1){
        if(feesOrders.orders.limit.nmalfee){
            return 'Comisión: ' + pairDetailsVar.currency.nmalfee
        }
        else if(feesOrders.orders.limit.pctfee){
            return 'Comisión: ' + feesOrders.orders.limit.pctfee.formatted + '%'
        }
        else{
            return 'No existe comisión'
        }
    }
    else if(value == 2 || value == 3){
        if(feesOrders.orders.market.nmalfee){
            return 'Comisión: ' + pairDetailsVar.currency.nmalfee
        }
        else if(feesOrders.orders.market.pctfee){
            return 'Comisión: ' + feesOrders.orders.market.pctfee.formatted + '%'
        }
        else{
            return 'No existe comisión'
        }
    }
    else{
        return ''
    }
}

function calculateFees(typeOrder, typeLM){
    // Limit
    console.log(feesOrders)
    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;
    }
    
/* OLD VERSION */
/*let canvas = document.getElementById('canvasId')
canvas.width =  document.getElementById('divCanva').clientWidth; // Ancho del card ((863px))
canvas.height = document.getElementById('divCanva').clientHeight; // Largo del card: 270px;

let ctx = canvas.getContext('2d');
console.log(ctx)

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

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

let chartDummy = {
    "pair":"BTC/VES",
    "timeframe":1, //1->1Hr, 2->4Hr, 3->24hrs
    "lines":{
        "max":20000,
        "records":[
            {
                "label":"10:00",
                "value":18400,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"11:00",
                "value":18800,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"12:00",
                "value":18500,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"13:00",
                "value":18900,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"14:00",
                "value":18500,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"15:00",
                "value":22000,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"16:00",
                "value":1000,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"17:00",
                "value":18900,//Precio del ultimo intercambio durante ese timeframe
            }
        ],
    },
    "bars":{
        "max":0.000500,
        "records":[
            {
                "label":"10:00",
                "value":0.000400//Volume de intercambios en moneda base durante ese timeframe
            },
            {
                "label":"11:00",
                "value":0.000450,//Volume de intercambios en moneda base durante ese timeframe
            },
            {
                "label":"12:00",
                "value":0.000480,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"13:00",
                "value":0.001400,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"14:00",
                "value":0.078400,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"15:00",
                "value":1,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"16:00",
                "value":1.000400,//Precio del ultimo intercambio durante ese timeframe
            },
            {
                "label":"17:00",
                "value":0.000500,//Precio del ultimo intercambio durante ese timeframe
            }
        ]
    }
}

// Dibuja los cuadritos grises de fondo
function drawGrids(){
    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();
    
    yGrid = parseFloat(canvas.width/12); // ((78.45px))
    xGrid = parseFloat(canvas.height/11); // 24.54px
}

drawGrids()


// Devuelve unidades de bloque.
function blocks(count,axis){
    return (axis == 'X' ? count*ySize : count*xSize );
}

let array1 = ['$1.500M', '$1.400M', '$1.300M', '$1.200M', '$1.100M', '$1.000M', '$900M', '$800M', '$700']
let array2 = ['12:00', '9', '12:00', '10', '12:00', '11', '12:00', '12', '12:00']
let array3 = ['12100', '12000', '11900', '11800', '11700', '11600', '11500', '11400', '11300','11200']

// Leyenda
function drawLegend(){
    //console.log('on drawAxis')
    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 12px Roboto';
        ctx.textAlign = 'right';
        ctx.fillStyle = 'white';
        ctx.fillText(array1[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 = 'white';
        ctx.fillText(array3[i], blocks(11.2,'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 = 'white';
        ctx.fillText(array2[i], blocks(xPlot,'X'), blocks(10.8,'Y'));
        xPlot = xPlot - 1
    }
    
    ctx.stroke();
}

drawLegend()

    
let dummyArrayY = Array.from({length: 60}, () => getRandomInt(0, 5000));
let maxNum = 10000;
let maxLine = maxNum * 1.03 // 10.300
let difference = maxNum * 0.03
//dummyArrayY[0] = 0
//dummyArrayY[59] = 10000
let tamBloqueNumber = maxLine / 9 // 1144 -> En cada bloque 

function drawLines(){
    ctx.beginPath();
    ctx.lineWidth = 2;
    ctx.strokeStyle = '#4287CE'
    ctx.fillStyle = '#4287CE';
    //console.log(blocks(5,'X'),blocks(5,'Y'),blocks(5,'X'),blocks(40,'Y'))
    
    // Draw Lines 
    
    //var dummyArrayY = new Array(60)
    
    
    //let dummyArrayY = Array.from({length: 60}, () => getRandomInt(0, 10000));
    
    
    //console.log(dummyArrayY);
    
    
    // Necesito pintar del X = 1 en bloques al X = 10.2 en bloques
    
    
    // 10300 / 9 = 1144 -> En cada bloque
    
    //tamBloqueNumber = maxLine / 9 // 1144 -> En cada bloque 
    
    ctx.moveTo(blocks(1,'X'),blocks((((dummyArrayY[0]+difference)/ tamBloqueNumber)+1),'Y'))
    
    for( var eX = 1; eX < 11 ; eX ++){
        for( var eY = 0; eY < 6 ; eY ++){
            //if(eX + (eY/6) > 10.4){
            //    console.log('no hagas nada')
            //}else{
            //    console.log(eX + (eY/6), (eX-1)*6 + eY)
            //}
            //console.log(eX + (eY/6), (eX-1)*6 + eY, ' numero transformado: ', (dummyArrayY[(eX-1)*6 + eY] / tamBloqueNumber))  // Aqui me imprime bien los X (del 1 al 11) y bien los Y (del 0 al 59)
            //console.log(' numero transformado: ', (dummyArrayY[(eX-1)*6 + eY] / tamBloqueNumber))
            
            
            ctx.lineTo( blocks(eX + (eY/6),'X'), blocks(((dummyArrayY[(eX-1)*6 + eY]+difference)/ tamBloqueNumber)+1,'Y'))
            ctx.stroke();
            
            //console.log(parseFloat(eX + parseFloat(eY/6)), parseInt((eX-1)*6 +eY))
        }
    }
    ctx.stroke();
    
    //ctx.moveTo(blocks(1,'X'),blocks(2,'Y'))
    //ctx.lineTo(blocks(2,'X'),blocks(3,'Y'))
    //ctx.lineTo(blocks(3,'X'),blocks(4,'Y'))
    //ctx.lineTo(blocks(4,'X'),blocks(4,'Y'))
    //ctx.lineTo(blocks(5,'X'),blocks(3,'Y'))
    //ctx.lineTo(blocks(6,'X'),blocks(5,'Y'))
    //ctx.lineTo(blocks(7,'X'),blocks(3,'Y'))
    //ctx.lineTo(blocks(8,'X'),blocks(8,'Y'))
    //ctx.lineTo(blocks(9,'X'),blocks(1,'Y'))
    //ctx.lineTo(blocks(10,'X'),blocks(5,'Y'))
    //ctx.lineTo(blocks(10.2,'X'),blocks(3,'Y'))
    ctx.stroke();
    
    arrayY = [2,3,4,4,3,5,3,8,1,5,3]
    
    //console.log(blocks(1,'X')) //71 al 143
    //console.log(blocks(2,'X'))

    // Fill lines
    for(var i = 1; i < 10.4 ; i ++){
        //if(i != 10){
        //   m = findSlope(blocks(i,'X'),blocks(arrayY[i-1],'Y'),blocks(i+1,'X'),blocks(arrayY[i],'Y'))
        //   b = findB(blocks(arrayY[i-1],'Y'),m,blocks(i,'X'))
        //    
        //    for( var j = blocks(i,'X'); j < blocks(i+1,'X') ; j ++ ){
        //        
        //        drawThinBar(ctx,j,findValueY(m,j,b),j,blocks(10,'Y'),'#4287CE2E') //2E
        //        
        //    }   
        //}else{
        //    m = findSlope(blocks(i,'X'),blocks(arrayY[i-1],'Y'),blocks(i+0.2,'X'),blocks(arrayY[i],'Y'))
        //    b = findB(blocks(arrayY[i-1],'Y'),m,blocks(i,'X'))
        //    
        //    for( var j = blocks(10,'X'); j < blocks(10.2,'X') ; j ++ ){
        //        
        //        drawThinBar(ctx,j,findValueY(m,j,b),j,blocks(10,'Y'),'#4287CE2E') //2E
        //        
        //    }   
        //}
        for( var eY = 0; eY < 6 ; eY ++){
            
            //console.log(i + (eY/6), (i-1)*6 + eY, ' numero transformado: ', (dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber))  // Aqui me imprime bien los X (del 1 al 11) y bien los Y (del 0 al 59)
            
            //console.log(blocks(i + (eY/6),'X'), blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),'Y'), blocks(i + 2*(eY/6),'X'), blocks((dummyArrayY[(i-1)*6 + eY + 1] / tamBloqueNumber),'Y'))
            
            //m = findSlope( blocks(i + (eY/6),'X'), blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),'Y'), blocks(i + 2*(eY/6),'X'), blocks((dummyArrayY[(i-1)*6 + eY + 1] / tamBloqueNumber),'Y'))
            //console.log('blocks(i + (eY/6),"X"): ', blocks(i + (eY/6),'X'))
            //console.log('blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),"Y"): ',blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),'Y'))
            //console.log('blocks(i + 2*(eY/6),"X"): ',blocks(i + ((eY+1)/6),'X'))
            //console.log('blocks((dummyArrayY[(i-1)*6 + eY + 1] / tamBloqueNumber),"Y"): ',blocks((dummyArrayY[(i-1)*6 + eY + 1] / tamBloqueNumber),'Y'))
            //console.log('---------------------')
            
            //console.log( i + (eY/6), blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),'Y'), i + ((eY+1)/6), blocks((dummyArrayY[(i-1)*6 + eY + 1] / tamBloqueNumber),'Y'))
            //console.log(blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),'Y'))
            //console.log(blocks((dummyArrayY[(i-1)*6 + eY + 1] / tamBloqueNumber),'Y'))
            
            //X1, Y1, X2, Y2
            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'))
            
            // y, m, x
            b = findB( blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),'Y') , m , blocks(i + (eY/6),'X') )
            
            //console.log(blocks(i + (eY/6),'X'))
            for( var j = blocks(i + (eY/6),'X') ; j < blocks(i + ((eY+1)/6),'X') ; j ++ ){
                
                // ctx,startX,startY,endX,endY,color
                drawThinBar(ctx,j,findValueY(m,j,b)+xSize+ blocks(difference/tamBloqueNumber,'Y'),j,blocks(10,'Y'),'#4287CE2E')
            }
            
            //ctx.moveTo(ySize, blocks(((dummyArrayY[59]+difference)/tamBloqueNumber)+1,'Y'))
            
            //m = findSlope(blocks(i,'X'),blocks(arrayY[i-1],'Y'),blocks(i+1,'X'),blocks(arrayY[i],'Y'))
            //b = findB(blocks(arrayY[i-1],'Y'),m,blocks(i,'X'))
            //for( var j = blocks(i,'X'); j < blocks(i+1,'X') ; j ++ ){
            //    drawThinBar(ctx,j,findValueY(m,j,b),j,blocks(10,'Y'),'#4287CE2E') //2E
            //} 
        }
    }
    
    //console.log(blocks(1,'X'),blocks(2,'Y'))
    //console.log(blocks(2,'X'),blocks(3,'Y'))

    
}   

// 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 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();
}

drawLines()


//let dummyArrayY = Array.from({length: 60}, () => getRandomInt(5000, 10000));
//let maxNum = 10000;
//let maxLine = maxNum * 1.03 // 10.300
//let difference = maxNum * 0.03
//let tamBloqueNumber = maxLine / 9 // 1144 -> En cada bloque

var barsArray = [10,15,30,10,4,2,7,2,12,9]

function drawBars(){
    for( var i = 0; i < barsArray.length-1 ; i ++){
        //drawBar(ctx,blocks(10,'Y') + 5 ,blocks(10,'Y') + 10,ySize,barsArray[i],'#D8D8D8')
        //console.log(ctx,ySize*(i+1),blocks(9,'Y') - barsArray[i],ySize,barsArray[i],'#D8D8D8')
        drawBar(ctx,ySize*(i+1),blocks(9,'Y') - barsArray[i],ySize,barsArray[i],'#D8D8D8')
    }
    drawBar(ctx,ySize*(i+1),blocks(9,'Y') - barsArray[i],ySize*0.2,barsArray[i],'#D8D8D8')
}

// 67.83 ----- 210 ------------------------------- 67---- 10
// 135.66 ---- 205------------------------------- 67----- 15
// 203.5 ----- 190 (mas volumen en la grafica)---- 67---- 30 (mas volumen en la grafica)
// 271.33 -----210---------------------------------- 67- 10
// DIferencia: 67,83


            //console.log('blocks(i + (eY/6),"X"): ', blocks(i + (eY/6),'X'))
            //console.log('blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),"Y"): ',blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),'Y'))
            //console.log('blocks(i + 2*(eY/6),"X"): ',blocks(i + ((eY+1)/6),'X'))
            //console.log('blocks((dummyArrayY[(i-1)*6 + eY + 1] / tamBloqueNumber),"Y"): ',blocks((dummyArrayY[(i-1)*6 + eY + 1] / tamBloqueNumber),'Y'))
            //console.log('---------------------')
            
            //console.log( i + (eY/6), blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),'Y'), i + ((eY+1)/6), blocks((dummyArrayY[(i-1)*6 + eY + 1] / tamBloqueNumber),'Y'))
            //console.log(blocks((dummyArrayY[(i-1)*6 + eY] / tamBloqueNumber),'Y'))
            //console.log(blocks((dummyArrayY[(i-1)*6 + eY + 1] / tamBloqueNumber),'Y'))
            
            
 
let dummyArrayYB = Array.from({length: 60}, () => getRandomInt(0, 2000));
let maxNumB = 4000;
//let maxLineB = maxNumB * 1.03 // 10.300
//let differenceB = maxNumB * 0.03
let tamBloqueNumberB = maxNumB / 9 // 444 -> En cada bloque
console.log(tamBloqueNumberB)

console.log(dummyArrayYB)
console.log(dummyArrayYB/tamBloqueNumberB)

function drawBars2(){
    
    //console.log(' on drawBars ')
    
    for(var i = 1; i < 10.4 ; i ++){
        for( var eY = 0; eY < 6 ; eY ++){
            if(i == 10 && eY == 5){
                
            }else{
                //onsole.log('-----------------------------')
                //console.log('upperLeftCornerX: ', blocks(i + (eY/6),'X'))
                //console.log('upperLeftCornerY: ', blocks(10,'Y') - (dummyArrayYB[(i-1)*6 + eY]/tamBloqueNumberB))
                //console.log('width: ', (ySize/6))
                //console.log('height: ', blocks(dummyArrayYB[(i-1)*6 + eY]/tamBloqueNumberB,'Y'))
                //drawBar( ctx , ySize*(i + (eY/6)) , blocks(9,'Y') - (dummyArrayYB[(i-1)*6 + eY]/tamBloqueNumberB) , (ySize/6) , dummyArrayYB[(i-1)*6 + eY] ,'#D8D8D8')
                drawBar(ctx,  // ok
                        blocks(i + (eY/6),'X'), // ok
                        blocks(10,'Y') - blocks((dummyArrayYB[(i-1)*6 + eY]/tamBloqueNumberB),'Y') , 
                        (ySize/6), // ok
                        blocks(dummyArrayYB[(i-1)*6 + eY]/tamBloqueNumberB,'Y') , 
                        '#D8D8D8' ) // ok    
            }
            
        }
    }
    
    for( var i = 0; i < dummyArrayYB.length-1 ; i ++){
        //drawBar(ctx,blocks(10,'Y') + 5 ,blocks(10,'Y') + 10,ySize,barsArray[i],'#D8D8D8')
        
        //drawBar( ctx , ySize*(i+1) , blocks(10,'Y') - dummyArrayYB[i] , ySize , dummyArrayYB[i] ,'#D8D8D8')
    }
}

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

drawBars2()
    
    
    //blocks(10,'X'),blocks(arrayY[i-1],'Y'),blocks(i+0.2,'X'),blocks(arrayY[i],'Y')
    

function drawDottedLines(){
    ctx.setLineDash([2, 4]);//dashes are 5px and spaces are 3px
    ctx.lineWidth = 1;
    ctx.strokeStyle = '#FFFFFF'
    ctx.fillStyle = '#FFFFFF';
    ctx.beginPath();
    
    //console.log(dummyArrayY)
    
    // 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();
}



            
 //           ctx.lineTo( blocks(10 + (5/6),'X'), blocks(((dummyArrayY[(10-1)*6 + 5]+difference)/ tamBloqueNumber)+1,'Y'))
   //         ctx.stroke();
            

    
    
    
    
drawDottedLines()


function writeMessage(canvas, message) {
    var context = canvas.getContext('2d');
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.font = '18pt Calibri';
    context.fillStyle = 'black';
    context.fillText(message, 10, 25);
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

var positionX1 = -1;
var positionY1 = -1;

canvas.addEventListener('mousemove', function(evt) {
    var mousePos = getMousePos(canvas, evt);
    //console.log(mousePos)
    var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
    //ctx.clearRect(positionX1, positionY1, canvas.width, 0);
    
    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);
        document.getElementById('canvasId').style.cursor = 'crosshair'
        ctx.setLineDash([0, 0]);
        drawLegend()
        drawGrids()
        ctx.setLineDash([0, 0]);
        drawLines()
        drawBars2()
        drawDottedLines()
        
        //positionX1 = mousePos.x
        //positionY1 = mousePos.y
        
        ctx.setLineDash([2, 4]);
        ctx.lineWidth = 4;
        ctx.strokeStyle = 'green'
        ctx.fillStyle = 'green';
        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();   
    }else{
        document.getElementById('canvasId').style.cursor = 'initial'
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    
        ctx.setLineDash([0, 0]);
        drawLegend()
        drawGrids()
        ctx.setLineDash([0, 0]);
        drawLines()
        drawBars2()
        drawDottedLines()
    }
}, false); */

/* CLEAN OLD VERSION */

// 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
        }
    }
    //console.log(resultDates)
    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]
    
    /*for(var i = 0; i < legendBottom[0].length; i ++){
        if(i < legendBottom[0].length - (5-lastLabel)){
            legendBottom[0][i] = legendBottomTemp[i + (5-lastLabel)]
        }else{
            legendBottom[0][i] = null
        }
    }*/
    
    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 moveCursorToEnd(el) {
    console.log(typeof el.selectionStart)
    //el.focus();
    var data = el.getAttribute('datanumber');
    el.value = ''; 
    console.log(el.value)
    el.value = data;
    console.log(el.value)
}

function chargePortfolioSelectInitial(portfolio){
    var selector = document.getElementById('totalPortfolioSel');
    for (var i = 0; i < portfolio.total.currencies.length; i++){
        var opcion = document.createElement("option");
        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 = portfolio.total.formatted
}

function chargePortfolioSelect(portfolio){
    document.getElementById('totalPortfolioAmountTotal').innerHTML = portfolio.total.formatted
}

function estimatedPriceM(type,qty,price,totalN){
    // Compra: Cantidad x Precio / Total Neto a Obtener
    if(type == 'bid'){
        console.log(qty)
        console.log(price)
        console.log(qty*price)
        console.log(totalN)
        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 sessionUpdate(req){
    callWS('GET', 'session/update', req, response);
    function response(status, rsp){
        console.log('session/update')
        console.log(JSON.parse(rsp));
        console.log(status) 
        switch(status){
            case 200:
                document.getElementsByClassName('expired')[0].style.display = "none"
                var req = {
                    'sessionid': getParameterByName('sessionid'),
                    'ordernumofrec': 25,
                    'exchangenumofrec': 25
                }
                if(document.getElementById('pairName').getAttribute('pairId')){
                    req.pairid = document.getElementById('pairName').getAttribute('pairId')
                    dashboardEntryRefresh(req)
                }else{
                    dashboardEntry(req,'initial',0);
                }
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

function setLang(){
    
    lang = localStorage.getItem('lang');
    
    /* inner HTML */
    setWordLanginnerHTML('home','home');
    setWordLanginnerHTML('balance','balance');
    setWordLanginnerHTML('preferences','preferences');
    setWordLanginnerHTML('homeR','home');
    setWordLanginnerHTML('balanceR','balance');
    setWordLanginnerHTML('preferencesR','preferences');
    setWordLanginnerHTML('langIcon','langIcon');
    setWordLanginnerHTML('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('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('withdrawFIat2AmR','AMOUNTTOWITHDRAW');
    setWordLanginnerHTML('with2FiatFees','fees');
    setWordLanginnerHTML('withFiatNT2','nettotal');
    setWordLanginnerHTML('with2FiatCD','DestinationAccount');
    setWordLanginnerHTML('withdrawFiatConfirmResend','resendCode');
    setWordLanginnerHTML('wdFiatbuttonV','VALIDATE');
    setWordLanginnerHTML('wdFiatbuttonA','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('netTotalDepFiat1','NETTOTAL');
    setWordLanginnerHTML('depFiatAccept','ToAccept');
    setWordLanginnerHTML('depFiatInfIdButton','search');
    setWordLanginnerHTML('bankDest2Fiat','DestinationBank');
    setWordLanginnerHTML('Am2Fiat','portfolio2');
    setWordLanginnerHTML('id2Fiat','IdentificationCard');
    setWordLanginnerHTML('phone2Fiat','CellPhone');
    setWordLanginnerHTML('depFiatDep','depLabel');
    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('wdFiatbuttonI','TRYAGAIN');
    setWordLanginnerHTML('wdFiatbuttonI','TRYAGAIN');
    setWordLanginnerHTML('wdFiatbuttonI','TRYAGAIN');
    setWordLanginnerHTML('wdFiatbuttonI','TRYAGAIN');
    setWordLanginnerHTML('wdFiatbuttonI','TRYAGAIN');
    setWordLanginnerHTML('wdFiatbuttonI','TRYAGAIN');
    setWordLanginnerHTML('wdFiatbuttonI','TRYAGAIN');
    setWordLanginnerHTML('wdFiatbuttonI','TRYAGAIN');
    setWordLanginnerHTML('wdFiatbuttonI','TRYAGAIN');

    
    document.getElementById('floatClose').addEventListener("click",function(event){
        var popup = document.getElementById("floatButton").children[0].children[0];
        popup.classList.remove("show")
        event.stopPropagation()
    })
    
    getEntry(getParameterByName('sessionid'));

}