var decimCoin = 0;
var idR = ''
var feesInf = ''
var currency = ''
var depositsAccountsArrayPM = {}
var selectType = 0;
var isBPInterface = false;
var isBPWorks = false;
if (getParameterByName('cid') == 1) isBPInterface = true;
function start() {

    // Go back
    document.getElementById('previous-button').addEventListener("click", function () {
        gotoPage('step', 'depositFunds', "")
    });

    // Go step 4 
    document.getElementById('next-button').addEventListener("click", function () {
        //gotoPage('step','depositFundsData',"")
        if (selectType === 0) {
            depositFiat()
        } else {
            depositFiatPM()
        }
    });



    // Go back R
    document.getElementById('previous-buttonR').addEventListener("click", function () {
        gotoPage('step', 'depositFunds', "")
    });

    // Go step 4 R
    document.getElementById('next-buttonR').addEventListener("click", function () {
        //gotoPage('step','depositFundsData',"")
        if (selectType === 0) {
            depositFiat()
        } else {
            depositFiatPM()
        }
    });

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

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

        var valid = validarFile(evt.target)
        if (valid) {
            if (evt.target.files[0].name !== getLangById("select")[lang]) {
                document.getElementById('edepFiatInfRec').style.display = 'none';
                // 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"
                //getFiles()
                //getFiles2(JSON.parse(event.target.result))

                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 && document.getElementById('depFiatInfAmount').value != number_format(0, decimCoin)) {
            noError('depFiatInfAmount', 'edepFiatInfAmount')
            document.getElementById('edepFiatInfAmount').style.display = 'none'
        }
        if (document.getElementById('depFiatInfAmountPM').value !== '') {
            noError('depFiatInfAmountPM', 'edepFiatInfAmountPM')
            document.getElementById('edepFiatInfAmountPM').style.display = 'none'
        }
        if (document.getElementById('depFiatInfDestinationBank1').value !== '') {
            document.getElementById('depFiatInfDestinationBank1').style.border = "1px solid #D5DCE5 !important";
            document.getElementById("depFiatInfDestinationBank1").classList.remove("selectwdFiatBank");
            document.getElementById("depFiatInfDestinationBank1").classList.add("selectwdFiat");
            document.getElementById('edepFiatInfDestinationBank1').innerHTML = '';
            document.getElementById('edepFiatInfDestinationBank1').style.display = 'none'
        }
        if (document.getElementById('depFiatInfDestinationBank2').value !== '') {
            document.getElementById('depFiatInfDestinationBank2').style.border = "1px solid #D5DCE5 !important";
            document.getElementById("depFiatInfDestinationBank2").classList.remove("selectwdFiatBank");
            document.getElementById("depFiatInfDestinationBank2").classList.add("selectwdFiat");
            document.getElementById('edepFiatInfDestinationBank2').innerHTML = '';
            document.getElementById('edepFiatInfDestinationBank2').style.display = 'none'
        }
        if (document.getElementById('depFiatInfDate').value !== '' && now.getTime() >= new Date(document.getElementById('depFiatInfDate').value).getTime()) {
            noError('depFiatInfDate', 'edepFiatInfDate')
            document.getElementById('edepFiatInfDate').style.display = 'none'
        }
        if (document.getElementById('depFiatInfRef').value !== '') {
            noError('depFiatInfRef', 'edepFiatInfRef')
            document.getElementById('edepFiatInfRef').style.display = 'none'
        }
        if (document.getElementById('depFiatInfId').value !== '') {
            noError('depFiatInfRec', 'edepFiatInfRec')
            document.getElementById('edepFiatInfRec').style.display = 'none'
        }
        if (document.getElementById('depFiatInfCIPM').value !== '') {
            noError('depFiatInfCIPM', 'edepFiatInfCIPM')
            document.getElementById('edepFiatInfCIPM').style.display = 'none'
        }
        if (document.getElementById('depFiatInfPhonePM').value !== '') {
            noError('depFiatInfPhonePM', 'edepFiatInfPhonePM')
            document.getElementById('edepFiatInfPhonePM').style.display = 'none'
        }
        if (document.getElementById('codePM').value !== '') {
            noError('codePM', 'ecodePM')
            document.getElementById('ecodePM').style.display = 'none'
        }
    });


    init()

    var fieldAmo = ["depFiatInfAmount", "depFiatInfAmountPM"];
    formatAmount(fieldAmo);

    //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);
                depositsAccounts(getParameterByName('cid'))
                reqPM = {
                    'sessionid': sessionStorage.getItem('sessionid')
                }
                //DESHABILITADO PRD
                if (isBPInterface) depositsAccountsPM(reqPM);
                break;
            case 204:
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

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

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

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

}

function 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 depositsAccounts(currencyid) {
    var req = {
        'sessionid': sessionStorage.getItem('sessionid'),
        'currencyid': currencyid,
    }

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

        switch (status) {
            case 200:
                depositsAccountsArray = JSON.parse(rsp)
                addOptions(JSON.parse(rsp))
                document.getElementById('depFiatInfAmount').value = '';
                document.getElementById('depFiatInfAmount').setAttribute("dataNumber", "");
                document.getElementById('depFiatInfAmountPM').value = '';
                document.getElementById('depFiatInfAmountPM').setAttribute("dataNumber", "");
                document.getElementById('depFiatInfDestinationBank1').value = '';
                document.getElementById('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': sessionStorage.getItem('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 = getLangById("select")[lang]
    firstOopcion.value = ''
    firstOopcion.selected = true
    selector.add(firstOopcion);
    for (var i = 0; i < array.records.length; i++) {
        var opcion = document.createElement("option");
        opcion.text = array.records[i].paymentmethod.dsc;
        opcion.value = array.records[i].id
        selector.add(opcion);
    }
    setTimeout(function () {
        firstOopcion.selected = true
    }, 1000);
}

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


function 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': sessionStorage.getItem('sessionid'),
        'id': id
    }

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

    function response(status, rsp) {


        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': sessionStorage.getItem('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) {


        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) {
    callWS('GET', 'fees/entry', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                feesInf = JSON.parse(rsp)
                if (JSON.parse(rsp).entry.deposits.nmalfee) {
                    document.getElementById('depFiatInFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById("FEES")[lang]
                    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 {
                            if (((((document.getElementById('depFiatInfAmount').value).replace(',', '.')) - JSON.parse(rsp).entry.deposits.nmalfee.number)) < 0) {
                                document.getElementById('depFiatInNeTotal').innerHTML = number_format(0, decimCoin)
                            } else {
                                document.getElementById('depFiatInNeTotal').innerHTML = number_format(((((document.getElementById('depFiatInfAmount').value).replace(',', '.')) - JSON.parse(rsp).entry.deposits.nmalfee.number)), decimCoin);
                            }

                        }
                    });

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

                        }
                    });
                }
                else if (JSON.parse(rsp).entry.deposits.pctfee) {
                    document.getElementById('depFiatInFee').parentElement.previousElementSibling.children[0].innerHTML = getLangById("FEES")[lang] + " (" + (((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);
                    });

                    document.getElementById('depFiatInFeePM').parentElement.previousElementSibling.children[0].innerHTML = getLangById("FEES")[lang] + " (" + (((JSON.parse(rsp).entry.deposits.pctfee.number).toFixed(2)).replace('.', ',')) + "%)";
                    document.getElementById('depFiatInfAmountPM').addEventListener("keyup", function () {
                        //CONTROLA decimales y numero signitificaivo máx
                        var noVal = formatCurrency(decimCoin, this.value);
                        if (noVal !== "") this.value = noVal;
                        document.getElementById('depFiatInFeePM').innerHTML = number_format((((document.getElementById('depFiatInfAmountPM').value).replace(',', '.') * JSON.parse(rsp).entry.deposits.pctfee.number / 100)), decimCoin);
                        document.getElementById('depFiatInNeTotalPM').innerHTML = number_format(((document.getElementById('depFiatInfAmountPM').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.getElementById('depFiatInfAmountPM').addEventListener("keyup", function () {
                        //CONTROLA decimales y numero signitificaivo máx
                        var noVal = formatCurrency(decimCoin, this.value);
                        if (noVal !== "") this.value = noVal;

                        if (document.getElementById('depFiatInfAmountPM').value == "") {
                            document.getElementById('depFiatInNeTotalPM').innerHTML = '0'
                        } else {
                            document.getElementById('depFiatInNeTotalPM').innerHTML = number_format(((((document.getElementById('depFiatInfAmountPM').value).replace(',', '.')))), decimCoin);
                        }
                    });

                }
                break;
            case 502:
                document.getElementById('error').innerHTML = getLangById('errconmsg')[lang]
                document.getElementById('error').style.display = 'block'
                break;
            case 400:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            default:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;

        }
        if (status != 200) {
            document.getElementById("next-button").parentElement.parentElement.removeChild(document.getElementById("next-button").parentElement);
        }
    }
}

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() {
    var req = {
        'sessionid': sessionStorage.getItem('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
    }



    //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 depositFiatPM() {

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



    verifyDepositsInsertPM(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 = getLangById('var17')[lang];
            document.getElementById('edepFiatInfAmount').style.display = 'block'
        }
        if (document.getElementById('depFiatInfDestinationBank1').value == '') {
            document.getElementById('depFiatInfDestinationBank1').style.border = "";
            document.getElementById("depFiatInfDestinationBank1").classList.remove("selectwdFiat");
            document.getElementById("depFiatInfDestinationBank1").classList.add("selectwdFiatBank");
            document.getElementById('edepFiatInfDestinationBank1').innerHTML = getLangById('var18')[lang];
            document.getElementById('edepFiatInfDestinationBank1').style.display = 'block'
        }
        if (document.getElementById('depFiatInfDate').value == '') {
            error('depFiatInfDate', 'edepFiatInfDate', getLangById('var19')[lang]);
            document.getElementById('edepFiatInfDate').style.display = 'block'
        }
        if (document.getElementById('depFiatInfRef').value == '') {
            error('depFiatInfRef', 'edepFiatInfRef', getLangById('var20')[lang]);
            document.getElementById('edepFiatInfRef').style.display = 'block'
        }
        if (document.getElementById('depFiatInfId').value == '' || document.getElementById('depFiatInfId').value == undefined) {
            //error('depFiatInfRec','edepFiatInfRec','Introduzca un código postal.');
            document.getElementById('edepFiatInfRec').innerHTML = getLangById('var21')[lang];
            document.getElementById('edepFiatInfRec').style.display = 'block'
        }
        if (now.getTime() < new Date(document.getElementById('depFiatInfDate').value).getTime()) {
            error('depFiatInfDate', 'edepFiatInfDate', getLangById('var22')[lang]);
            document.getElementById('edepFiatInfDate').style.display = 'block'
        }

        return;

    }

    else if (number_format(0, decimCoin) == document.getElementById('depFiatInNeTotal').innerHTML) {
        document.getElementById('depFiatInfAmount').style.border = "2px solid #D0021B";
        document.getElementById('edepFiatInfAmount').innerHTML = getLangById('var23')[lang]
        document.getElementById('edepFiatInfAmount').style.display = 'block'
    }
    else if (document.getElementById('depFiatInfAmount').getAttribute('datanumber') > feesInf.entry.deposits.max.number) {
        document.getElementById('depFiatInfAmount').style.border = "2px solid #D0021B";
        document.getElementById('edepFiatInfAmount').innerHTML = getLangById('var24')[lang] + 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 = getLangById('var25')[lang] + feesInf.entry.deposits.min.formatted + ' ' + currency.symbol
        document.getElementById('edepFiatInfAmount').style.display = 'block'
    }
    else {

        //depositsInsert(req)   
        gotoPage('step', 'depositFundsCo', { 'cid': getParameterByName('cid') })
    }
}

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

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

        return;

    } else {

        depositsInsertPM(req)
    }
}

// deposits/insert

function depositsInsert(req) {

    callWS('POST', 'deposits/insert', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                gotoPage('step', 'final', "")
                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;
        }
    }
}

// c2p/insert

function depositsInsertPM(req) {

    callWS('POST', 'c2p/insert', req, response);
    function response(status, rsp) {
        /*
        console.log('Aqui c2p/insert')
        
        */
        switch (status) {
            case 200:
                gotoPage('step', 'final', "")
                break;
            case 400:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                //error('depFiatInfAmount','edepFiatInfAmount',JSON.parse(rsp).msg);
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 403:
                error('depFiatInfAmountPM', 'edepFiatInfAmountPM', JSON.parse(rsp).msg);
                document.getElementById('edepFiatInfAmountPM').style.display = 'block'
                document.getElementById('edepFiatInfAmountPM').style.marginLeft = '20px'
                break;
            case 500:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                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('titD', 't1');

    setWordLanginnerHTML('t2', 't2');
    setWordLanginnerHTML('avLabel', 'AVAILABLE');
    setWordLanginnerHTML('bankDest', 'DestinationBank');
    setWordLanginnerHTML('amDepLabel', 'amountDep');
    setWordLanginnerHTML('dateLabel', 'date');
    setWordLanginnerHTML('refLabel', 'Reference');
    setWordLanginnerHTML('VoucherReceipt', 'VoucherReceipt');
    setWordLanginnerHTML('depFiatInfIdButton', 'search');
    setWordLanginnerHTML('FeesLabel', 'FEES');
    setWordLanginnerHTML('netTotal', 'NETTOTAL');

    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('failureTitle', 'failureTitle');
    setWordLanginnerHTML('wdFiatbuttonI', 'wdFiatbuttonI');
    setWordLanginnerHTML('parcComplete', 'parcComplete');
    setWordLanginnerHTML('wdFiatbuttonFYellow', 'wdFiatbuttonFYellow');


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

    if (getParameterByName('cid') != 1) {
        document.getElementById('tabDepFiat').style.display = "none"
    } else {
        document.getElementById('p2c').style.display = "block"
        // Tab 1 Retiro Fiat
        document.getElementById('reportDTFiat').addEventListener("click", function () {
            selectType = 0
            openTabFiat('reportDTFiat', 'depTr')
        });

        // Tab 2 Retiro Fiat
        if (isBPInterface) {
            document.getElementById('p2cfiat').addEventListener("click", function (e) {
                if (isBPWorks) {
                    e.preventDefault();
                    selectType = 1
                    openTabFiat('p2cfiat', 'p2c');
                }
            });
        }

        document.getElementById('reportDTFiat').dispatchEvent(new Event("click"));

        setWordLanginnerHTML('reportDTFiat', 'ReportDeposit');
        setWordLanginnerHTML('p2cfiat', 'UsingP2C');
        setWordLanginnerHTML('bankDest2Fiat', 'DestinationBank');
        setWordLanginnerHTML('Am2Fiat', 'portfolio2');
        setWordLanginnerHTML('id2Fiat', 'IdentificationCard');
        setWordLanginnerHTML('phone2Fiat', 'CellPhone');
        setWordLanginnerHTML('depFiatDep', 'depLabel');
        setWordLanginnerHTML('fiatFees1DepPM', 'FEES');
        setWordLanginnerHTML('netTotalDepFiat1PM', 'NETTOTAL');
        setWordLanginnerHTML('PMTextInp', 'var49');

    }

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

}

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



