WS_waitscreen = true;
var decimCoin = 0; 
var idR = ''
var feesInf = ''
var currency = ''
window.onload = function(){ 
     
    // Go back
    document.getElementById('previous-button').addEventListener("click", function(){   
        gotoPage('step','depositFunds',{ 'sessionid' : getParameterByName('sessionid') })
    });
        
    // Go step 4 
    document.getElementById('next-button').addEventListener("click", function(){ 
        //gotoPage('step','depositFundsData',{ 'sessionid' : getParameterByName('sessionid') })
        depositFiat()
    });  
     
    // Go back R
    document.getElementById('previous-buttonR').addEventListener("click", function(){ 
        gotoPage('step','depositFunds',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go step 4 R
    document.getElementById('next-buttonR').addEventListener("click", function(){
        //gotoPage('step','depositFundsData',{ 'sessionid' : getParameterByName('sessionid') })
        depositFiat()
    });
    
    // Balance
    document.getElementById('floatButton').addEventListener("click",function(){
        gotoPage('dashboard','home',{ 'sessionid' : getParameterByName('sessionid') })
        
    })
    
    document.getElementById('depFiatInfDestinationBank1').addEventListener("change", function(){
        if (document.getElementById('depFiatInfDestinationBank1').value!=''){
            putDepositDataFiat(document.getElementById('depFiatInfDestinationBank1').value)
        }
    });
    
    // copyFiat
    document.getElementById('copyIconFiat').addEventListener("click", function(){
        document.getElementById('copyDepFiat').select();
        document.execCommand('copy');
    });
    
    document.getElementById('depFiatInfIdButton').addEventListener("click", function(){
        document.getElementById("depFiatInfId").dispatchEvent(new MouseEvent('click'));
    });
    
    // Finalizar fail
    document.getElementById('wdFiatbuttonI').addEventListener("click", function(){
        document.getElementsByClassName('failure')[0].style.display = "none"
        document.getElementById('failureMsg').innerHTML = ''
    });
    
    // Add file
    document.getElementById('depFiatInfId').addEventListener('change', function (evt) {
            if(evt.target.files[0].name !== 'Seleccione'){
                // Asignar el nombre y color
                console.log(evt.target)
                evt.target.offsetParent.previousElementSibling.children[0].textContent = evt.target.files[0].name
                evt.target.offsetParent.previousElementSibling.children[0].style.color = "#262624"
                //getFiles()
                //getFiles2(JSON.parse(event.target.result))
                
                console.log(this.files)
                const reader = new FileReader();
                
                
                reader.addEventListener("load", () => {
                    localStorage.setItem('file',reader.result)
                    
                    
                })
                reader.readAsDataURL(this.files[0])
              
  
            }
    });
    
    // 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 !== '' && document.getElementById('depFiatInfAmount').getAttribute('datanumber') >= feesInf.entry.deposits.min.number &&
            document.getElementById('depFiatInfAmount').getAttribute('datanumber') <= feesInf.entry.deposits.max.number ){
            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'
        }
    }); 
    
    // Session Update
    document.getElementById('expSessionButton').addEventListener("click",function(){
        var req = {
            'sessionid': getParameterByName('sessionid')
        }
        sessionUpdate(req)
    })
    
    // Go to preferences
    document.getElementById('preferences').addEventListener("click", function(){
        gotoPage('preferences','main',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to preferences
    document.getElementById('preferencesR').addEventListener("click", function(){
        gotoPage('preferences','main',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to balance
    document.getElementById('balance').addEventListener("click", function(){
        gotoPage('balance','balance',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    // Go to balance
    document.getElementById('balanceR').addEventListener("click", function(){
        gotoPage('balance','balance',{ 'sessionid' : getParameterByName('sessionid') })
    });
    
    document.getElementById('example-element-toggle2').checked = false;
    
    // Bar
    document.getElementById('togglebar').addEventListener("click", function(){
        var el = document.getElementById('addView2')
        document.getElementById('addView2').style.display = 'block'
        setTimeout(function(){ 
            document.getElementById('example-element-toggle2').checked = !document.getElementById('example-element-toggle2').checked;
        }, 15);   
        
    });
    
    // Logout
    document.getElementById('logouticon').addEventListener("click", function(){
        logout();
    });
    
    // Logout
    document.getElementById('logouticon2').addEventListener("click", function(){
        logout();
    });
    
    
    init()
    
    var fieldAmo = ["depFiatInfAmount"];
    formatAmount(fieldAmo);
    
    //Mostrar HTML cargado
    esconderHTML(false);
    
    var waitScreen = document.getElementById("waitScreen");
    document.body.removeChild(waitScreen);
    WS_waitscreen = false;
    document.getElementsByClassName('pageCnt')[0].style.visibility="visible"
    
}

function expiredSession(){
    document.getElementsByClassName('expired')[0].style.display = "table"
    WS_waitscreen = false;
    var seconds = 30;
    var countdown = setInterval(countDown, 1000);
    
    function countDown(){
        seconds--;
        if(seconds == 0){
            if(document.getElementsByClassName('expired')[0].style.display == "table"){
                gotoPage('login','main','');
                clearInterval(countdown);
            }
        }
        if(document.getElementsByClassName('expired')[0].style.display == "none"){
            clearInterval(countdown)
        }
    }
}

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

function init(){
    getEntry(getParameterByName('sessionid'));
}

function getEntry(sessionid){
    callWS("GET", "users/entry", { 'sessionid' : sessionid}, response);
        
    function response(status, rsp){
        switch(status){
            case 200:
                entrydata = (JSON.parse(rsp).entry)
                putName(entrydata);
                depositsAccounts(getParameterByName('cid'))
                break;
            case 204:
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }    
}

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

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

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



function 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(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 ='';
                var req = {
                    'sessionid': getParameterByName('sessionid'),
                    'action': 2
                }
                accountsPortfolio(req)
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

function addOptions(array) {
    removeOptions('depFiatInfDestinationBank1')
    var selector = document.getElementById('depFiatInfDestinationBank1');
    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;
        opcion.value = array.records[i].id
        selector.add(opcion);
    }
    setTimeout(function(){ 
        firstOopcion.selected = true
    }, 1000);
}

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

// Service accounts/entry
function accountsEntry(id){
    var req ={
        'sessionid': getParameterByName('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)
        switch(status){
            case 200:
                currency = JSON.parse(rsp).entry.currency
                document.getElementById('depFiatInfBalance').innerHTML = (JSON.parse(rsp).entry.currency.symbol) + ' ' + (JSON.parse(rsp).entry.balance.formatted)
                document.getElementById('titD').children[0].innerHTML =  JSON.parse(rsp).entry.currency.dsc
                req = {
                    'sessionid': getParameterByName('sessionid'),
                    'currencyid': getParameterByName('cid'),
                }
                feesEntry(req)
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

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

// fees/entry
function feesEntry(req){
    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:
                feesInf = JSON.parse(rsp)
                if(JSON.parse(rsp).entry.deposits.nmalfee){
                    document.getElementById('depFiatInFee').parentElement.previousElementSibling.children[0].innerHTML = "COMISIÓN";
                    document.getElementById('depFiatInFee').innerHTML = (((JSON.parse(rsp).entry.deposits.nmalfee.number).toFixed(decimCoin)).replace('.', ','));
                    document.getElementById('depFiatInNeTotal').innerHTML = (((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 ("+(((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);
                            }
                    });
                }
                break;
            case 400:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            default:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }   
}

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

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


function depositFiat(){
    console.log(JSON.parse(localStorage.getItem('files')))

    var req ={
        'sessionid': getParameterByName('sessionid'),
        'accountid': idR,
        '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]
        'paymentfile' : document.getElementById('depFiatInfRec').children[0].innerHTML
    }
    
    console.log(req)
    
    //Usage example:
    if(localStorage.getItem('file')) var file = dataURLtoFile(localStorage.getItem('file'),document.getElementById('depFiatInfRec').children[0].innerHTML);
    
    localStorage.setItem('deposit', JSON.stringify(req));
    
    verifyDepositsInsert(req)

}

function dataURLtoFile(dataurl, filename) {
 
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), 
        n = bstr.length, 
        u8arr = new Uint8Array(n);
            
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
        
    return new File([u8arr], filename, {type:mime});
}

function verifyDepositsInsert(req){
    
    now = new Date();
    nowDate = now.getFullYear() + '-' + (now.getMonth()+1) + '-' + now.getDate()
    
    if( document.getElementById('depFiatInfAmount').value=='' || document.getElementById('depFiatInfDestinationBank1').value=='' || document.getElementById('depFiatInfDate').value =='' ||
        document.getElementById('depFiatInfRef').value=='' || document.getElementById('depFiatInfId').value=='' || now.getTime() < new Date(document.getElementById('depFiatInfDate').value).getTime()){
         
        if (document.getElementById('depFiatInfAmount').value==''){
            //error('depFiatInfAmount','edepFiatInfAmount','Seleccione un pais.');
            document.getElementById('depFiatInfAmount').style.border ="2px solid #D0021B";
            document.getElementById('edepFiatInfAmount').innerHTML = '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.');
            document.getElementById('edepFiatInfRec').innerHTML = 'Ingrese un archivo.';
            document.getElementById('edepFiatInfRec').style.display = 'block'
        }
        if (now.getTime() < new Date(document.getElementById('depFiatInfDate').value).getTime()){
            error('depFiatInfDate','edepFiatInfDate','No puede reportar fechas futuras.');
            document.getElementById('edepFiatInfDate').style.display = 'block'
        }
        
        return;
        
    }
    else if(document.getElementById('depFiatInfAmount').getAttribute('datanumber') > feesInf.entry.deposits.max.number){
        document.getElementById('depFiatInfAmount').style.border ="2px solid #D0021B";
        document.getElementById('edepFiatInfAmount').innerHTML = 'Monto máximo mensual autorizado '+ feesInf.entry.deposits.max.formatted + ' ' + currency.symbol
        document.getElementById('edepFiatInfAmount').style.display = 'block'
    }
    else if(document.getElementById('depFiatInfAmount').getAttribute('datanumber') < feesInf.entry.deposits.min.number){
        document.getElementById('depFiatInfAmount').style.border ="2px solid #D0021B";
        document.getElementById('edepFiatInfAmount').innerHTML = 'Monto mínimo autorizado '+ feesInf.entry.deposits.min.formatted + ' ' + currency.symbol
        document.getElementById('edepFiatInfAmount').style.display = 'block'
    }
    else{
        console.log(req)
        //depositsInsert(req)   
        gotoPage('step','depositFundsCo',{ 'sessionid' : getParameterByName('sessionid'), 'cid' : getParameterByName('cid')})
    }
}

// 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:
                gotoPage('step','final',{ 'sessionid' : getParameterByName('sessionid')})
                break;
            case 400:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 403:
                error('depFiatInfAmount','edepFiatInfAmount',JSON.parse(rsp).msg);
                document.getElementById('edepFiatInfAmount').style.display = 'block'
                document.getElementById('edepFiatInfAmount').style.marginLeft = '20px'
                break;
            case 500:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }   
}


