feesInf = '';
curInfR = ''

function start() {

    // Go back
    document.getElementById('previous-button').addEventListener("click", function () {
        gotoPage('step', 'transferCryptoAc', { 'cid': getParameterByName('cid'), 'q': getParameterByName('q') })
    });

    // Go step 4
    document.getElementById('next-button').addEventListener("click", function () {
        verifyNextButton()
    });



    // Go back R
    document.getElementById('previous-buttonR').addEventListener("click", function () {
        gotoPage('step', 'transferCryptoAc', { 'cid': getParameterByName('cid'), 'q': getParameterByName('q') })
    });

    // Go step 4 R
    document.getElementById('next-buttonR').addEventListener("click", function () {
        verifyNextButton()
    });

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

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

    // Session Update


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

    // Finalizar fail
    document.getElementById('wdFiatbuttonI').addEventListener("click", function () {
        document.getElementsByClassName('failure')[0].style.display = "none"
        document.getElementById('failureMsg').innerHTML = ''
    });

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

        transactionsValidation(req)
    });

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


    init()

    //Mostrar HTML cargado
    esconderHTML(false);


}



function sessionUpdate(req) {
    callWS('GET', 'session/update', req, response);
    function response(status, rsp) {

        switch (status) {
            case 200:
                document.getElementsByClassName('expired')[0].style.display = "none";
                init()
                break;
            case 400:
                break;
            case 401:
                gotoPage('login', 'main', '');
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

function init() {
    setLang()
}

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

    function response(status, rsp) {
        switch (status) {
            case 200:
                if (JSON.parse(rsp).notifications > 0) {
                    document.getElementById('messageNotification').style.display = "table"
                    document.getElementById('messageNotification').children[0].innerHTML = JSON.parse(rsp).notifications
                } else {
                    document.getElementById('messageNotification').style.display = "none"
                    document.getElementById('messageNotification').children[0].innerHTML = ""
                }
                entrydata = (JSON.parse(rsp).entry)
                putName(entrydata);
                var req = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'action': 4, /*1 INtercambio, 2 Deposito, 3 Retiro, 4 Transferencia
                    'currencyid': getParameterByName('cid)*/
                }
                document.getElementById('withdrawBTCConfirmEmail').innerHTML = document.getElementById('withdrawBTCConfirmEmail').innerHTML + entrydata.usr
                accountsPortfolio(req)
                break;
            case 204:
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

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

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

    function response(status, rsp) {


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


function accountsPortfolio(req) {
    callWS('GET', 'accounts/portfolio', req, response);
    function response(status, rsp) {

        switch (status) {
            case 200:
                curInf = null;
                JSON.parse(rsp).records.forEach(currency => {
                    if (currency.currency.id == getParameterByName('cid')) {
                        curInf = currency;
                    }
                });
                req = {
                    'sessionid': sessionStorage.getItem('sessionid'),
                    'currencyid': getParameterByName('cid')
                }
                feesEntry(req, curInf)
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

// fees/entry
function feesEntry(req, accPor) {
    callWS('GET', 'fees/entry', req, response);
    function response(status, rsp) {

        switch (status) {
            case 200:
                loadData(accPor, JSON.parse(rsp))
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}


// xfer/make 
function transactionsCancel(req) {

    callWS('GET', 'transactions/cancel', req, response);
    function response(status, rsp) {

        switch (status) {
            case 200:
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByTagName('body')[0].classList.remove('hidden')
                break;
            case 401:
                expiredSession();
                break;
            default:
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

function transactionsValidation(req) {

    callWS('GET', 'transactions/validation', req, response);
    function response(status, rsp) {

        switch (status) {
            case 200:
                break;
            case 400:
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            default:
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

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

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


    TransactionsAccept(req)
}

function verifyNextButton() {
    var req = {
        'originaccountid': curInf.id,
        'amount': getParameterByName('q'),
        'usr': getParameterByName('ad'),
        'sessionid': sessionStorage.getItem('sessionid')
    }
    xferMake(req)

}

function loadData(currency, fees) {
    document.getElementById('titP').children[0].innerHTML = currency.currency.symbol
    document.getElementById('destBankC').innerHTML = getParameterByName('ad')
    document.getElementById('totalC').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(getParameterByName('q')).noExponents(), curInf.currency.decimals)
    if (fees.entry.xfer.nmalfee) {
        document.getElementById('feesC').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(fees.entry.xfer.nmalfee.number), curInf.currency.decimals)
        document.getElementById('amountC').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(parseFloat(getParameterByName('q')) - parseFloat(fees.entry.xfer.nmalfee.number)).noExponents(), curInf.currency.decimals)
        document.getElementById('amountC').setAttribute('number', parseFloat(parseFloat(getParameterByName('q')) - parseFloat(fees.entry.xfer.nmalfee.number)))
    }
    else if (fees.entry.xfer.pctfee) {
        document.getElementById('feesC').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(fees.entry.xfer.pctfee.number) * parseFloat(getParameterByName('q') / 100),
            curInf.currency.decimals)
        document.getElementById('amountC').innerHTML = curInf.currency.symbol + ' ' + number_format(parseFloat(parseFloat(1 - parseFloat(fees.entry.xfer.pctfee.number) / 100) * parseFloat(getParameterByName('q'))).noExponents(),
            curInf.currency.decimals)
        document.getElementById('amountC').setAttribute('number', parseFloat(1 - parseFloat(fees.entry.xfer.pctfee.number) / 100) * parseFloat(getParameterByName('q')))

    } else {
        console.log('N/A')
    }
    document.getElementById('withdrawBTCConfirmUser').innerHTML = getParameterByName('ad')
    document.getElementById('withdrawBTCConfirmFee').innerHTML = document.getElementById('feesC').innerHTML
    document.getElementById('withdrawBTCConfirmTotalN').innerHTML = document.getElementById('amountC').innerHTML
    document.getElementById('withdrawBTCConfirmAmount').innerHTML = document.getElementById('totalC').innerHTML
}

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

// xfer/make 
function transactionsCancel(req) {

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

function transactionsValidation(req) {

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

function verifywdFiatbuttonV() {

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

    }

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

    TransactionsAccept(req, 'Fiat')
}

function verifywdBTCbuttonV() {

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

    }

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

    }

    TransactionsAccept(req, 'BTC')
}

function TransactionsAccept(req) {

    callWS('GET', 'transactions/accept', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                gotoPage('step', 'final', "")
                break;
            case 400:
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                error('withdrawBTCConfirmCode', 'ewithdrawBTCConfirmCode', getLangById('var2')[lang]);
                document.getElementById('ewithdrawBTCConfirmCode').style.display = 'block';
                document.getElementById('ewithdrawBTCConfirmCode').style.marginLeft = '20px';
                break;
            case 403:
                error('withdrawBTCConfirmCode', 'ewithdrawBTCConfirmCode', getLangById('var3')[lang]);
                document.getElementById('ewithdrawBTCConfirmCode').style.display = 'block';
                document.getElementById('ewithdrawBTCConfirmCode').style.marginLeft = '20px';
                break;
            default:
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "none"
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

// xfer/make 
function xferMake(req) {

    callWS('GET', 'xfer/make', req, response);
    function response(status, rsp) {

        switch (status) {
            case 200:
                document.getElementById('withdrawBTCConfirmWallet').innerHTML = JSON.parse(rsp).destinationuser.name
                document.getElementsByClassName('transferBTCConfirm')[0].setAttribute('idWI', JSON.parse(rsp).transactionid)
                document.getElementsByClassName('transferBTCConfirm')[0].setAttribute('tridWI', JSON.parse(rsp).transactionid)
                document.getElementsByClassName('transferBTCConfirm')[0].style.display = "table"
                break;
            case 400:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            default:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }
}

function setLang() {

    addFooter()

    lang = sessionStorage.getItem('lang');

    /* inner HTML */
    setWordLanginnerHTML('home', 'home');
    setWordLanginnerHTML('balance', 'balance');
    setWordLanginnerHTML('preferences', 'preferences');
    setWordLanginnerHTML('homeR', 'home');
    setWordLanginnerHTML('balanceR', 'balance');
    setWordLanginnerHTML('preferencesR', 'preferences');
    setWordLanginnerHTML('langIcon', 'langIcon');


    setWordLanginnerHTML('titlePage', 'titlePage');
    setWordLanginnerHTML('step1', 'step1');
    setWordLanginnerHTML('step2', 'step2');
    setWordLanginnerHTML('step3', 'step3');
    setWordLanginnerHTML('step4', 'step4');
    setWordLanginnerHTML('step5', 'step5');
    setWordLanginnerHTML('t1', 't1');

    setWordLanginnerHTML('t2', 't2');
    setWordLanginnerHTML('willT', 'willT');
    setWordLanginnerHTML('toUser', 'toUser');
    setWordLanginnerHTML('feesLabel', 'feeLabel');
    setWordLanginnerHTML('feeLabel', 'feeLabel');
    setWordLanginnerHTML('cardAmountRoundedTextLastText', 'cardAmountRoundedTextLastText');
    setWordLanginnerHTML('infMin', 'infMin');
    setWordLanginnerHTML('maxBuy', 'maxBuy');

    setWordLanginnerHTML('failureTitle', 'failureTitle');
    setWordLanginnerHTML('wdFiatbuttonI', 'wdFiatbuttonI');
    setWordLanginnerHTML('parcComplete', 'parcComplete');
    setWordLanginnerHTML('wdFiatbuttonFYellow', 'wdFiatbuttonFYellow');

    setWordLanginnerHTML('previous-button', 'RETURN');
    setWordLanginnerHTML('next-button', 'continue');
    setWordLanginnerHTML('previous-buttonR', 'RETURN');
    setWordLanginnerHTML('next-buttonR', 'continue');


    setWordLanginnerHTML('buttonAdv', 'ADVANCEDMODE');
    setWordLanginnerHTML('question', 'question');
    setWordLanginnerHTML('expired1', 'expired1');
    setWordLanginnerHTML('expired2', 'expired2');
    setWordLanginnerHTML('expSessionButton', 'continue');
    setWordLanginnerHTML('ts', 'ts');

    setWordLanginnerHTML('transferAm2', 'AmountToTransfer');
    setWordLanginnerHTML('transferBTCFees2', 'fees');
    setWordLanginnerHTML('transferTNBTC2', 'nettotal');
    setWordLanginnerHTML('userTransfer2', 'user');
    setWordLanginnerHTML('destTransfer2BTC', 'Addressee');
    setWordLanginnerHTML('withdrawBTCConfirmResend', 'resendCode');
    setWordLanginnerHTML('wdBTCbuttonV', 'VALIDATE');
    setWordLanginnerHTML('wdBTCbuttonA', 'CANCEL');
    setWordLanginnerHTML('titP', 'titP');

    setWordLanginnerHTML('withdrawBTCConfirmEmail', 'withdrawBTCConfirmEmail');


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

    getEntry(sessionStorage.getItem('sessionid'));

}
