var type = 0;
var isBPWorks = false;
var isBPInterface = false;
function start() {
    if (getParameterByName('cin') == 1) isBPInterface = true;


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

    // Go step 4
    document.getElementById('next-button').addEventListener("click", function () {
        if (type == 0) {
            verifyNextButton()
        } else {
            verifyNextButtonPM()
        }
    });



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

    // Go step 4 R
    document.getElementById('next-buttonR').addEventListener("click", function () {
        if (type == 0) {
            verifyNextButton()
        } else {
            verifyNextButtonPM()
        }
    });

    // 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


    // Affiliate
    document.getElementById('affiliate').addEventListener("click", function () {
        gotoPage('preferences', 'main', "")
    })


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

    // Tab 2 Retiro Fiat
    if (isBPInterface) {
        document.getElementById('p2cfiat2').addEventListener("click", function (e) {
            if (isBPWorks) {
                type = 1
                openTabFiat('p2cfiat2', 'p2c2');
            }
        });
    }
    document.getElementById('withdrawFiatAccount2').addEventListener("change", function () {
        if (document.getElementById('withdrawFiatAccount2').value != '') {
            document.getElementById("withdrawFiatAccount2").classList.remove("selectwdFiatBank");
            document.getElementById("withdrawFiatAccount2").classList.add("selectwdFiat");
            document.getElementById('ewithdrawFiatAccount2').innerHTML = ''
        }
    });

    // Remove red errors in Withd Fiat
    document.getElementsByTagName('body')[0].addEventListener("click", function () {
        if (document.getElementById('depFiatInfPhonePM2').value != '' && document.getElementById('phoneNumberPM').value != '') {
            document.getElementById('edepFiattPhonePM22').style.display = 'none'
        }

    });

    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'),
                    'paym': 1
                }
                accountsList(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 accountsList(req) {
    callWS('GET', 'accounts/list', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                loadData(JSON.parse(rsp))
                req = {
                    'sessionid': sessionStorage.getItem('sessionid')
                }
                //DESHABILITADO PRD
                if (isBPInterface) getp2pBanks(req);
                document.getElementById('reportDTFiat2').dispatchEvent(new Event("click"));
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}

function loadData(list) {
    var tbl;
    var node;
    tbl = document.getElementById('table');
    var node = tbl.children[0].cloneNode(true);
    tbl.innerHTML = "";
    var tmp = null; tmp = node.cloneNode(true);
    if (list.numofrecords == 0) {
        var ele = null;
        ele = tmp.cloneNode(true);
        ele.style.display = "none";
        tbl.appendChild(ele);
    } else {
        for (var i = 0; i < list.records.length; i++) {
            if (list.records[i].currency.id == getParameterByName('cid')) {
                var ele = null;
                ele = tmp.cloneNode(true);
                ele.style.display = "table";
                ele.children[0].children[0].innerHTML = list.records[i].paymentmethod.dsc
                ele.children[1].children[0].innerHTML = list.records[i].details1
                ele.children[2].children[0].children[0].setAttribute('idC', list.records[i].id)
                ele.children[2].children[0].children[0].innerHTML = lang == "esp" ? "SELECCIONAR" : "SELECT"

                if (tbl.children.length % 2 == 0) {
                    ele.classList.add('oddRow')
                }
                tbl.appendChild(ele);
            }

        }
        buttonsEffect()
    }
}

function buttonsEffect() {
    var buttons = document.getElementsByClassName('crypto');
    for (i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener("click", function (evt) {
            document.getElementById('error').style.display = 'none'
            var buttons = document.getElementsByClassName('crypto');
            for (i = 0; i < buttons.length; i++) {
                buttons[i].classList.remove('blueButton')
                buttons[i].classList.add('whiteButton')
                buttons[i].classList.remove('accept-button')
                buttons[i].classList.add('cancel-button')
                buttons[i].classList.remove('selectCrypto')
            }
            evt.srcElement.classList.add('blueButton')
            evt.srcElement.classList.remove('whiteButton')
            evt.srcElement.classList.add('accept-button')
            evt.srcElement.classList.remove('cancel-button')
            evt.srcElement.classList.add('selectCrypto')
        });
    }
}

function verifyNextButton() {
    if (document.getElementsByClassName('selectCrypto').length == 0) {
        document.getElementById('error').innerHTML = lang == "esp" ? 'Seleccione una cuenta.' : 'Select an account.'
        document.getElementById('error').style.display = 'block'
    } else {
        gotoPage('step', 'withdrawFundsCo', {
            'cid': getParameterByName('cid'),
            'q': getParameterByName('q'), 'ac': document.getElementsByClassName('selectCrypto')[0].getAttribute('idc')
        })
    }
}

function verifyNextButtonPM() {
    /*if(document.getElementsByClassName('selectCrypto').length == 0){
        document.getElementById('error').innerHTML = lang == "esp" ? 'Seleccione una cuenta.' : 'Select an account.'
        document.getElementById('error').style.display = 'block'
    }else{
        gotoPage('step','withdrawFundsCo',{ 'cid' : getParameterByName('cid'),
                  'q' : getParameterByName('q'), 'ac' : document.getElementsByClassName('selectCrypto')[0].getAttribute('idc')
        })
    }*/

    var req = {
        'sessionid': sessionStorage.getItem('sessionid'),
        'bankid': document.getElementById("withdrawFiatAccount2").value,
        'phone': document.getElementById("phoneNumberPM").value + document.getElementById("depFiatInfPhonePM2").value,
        'amount': getParameterByName('q'),
        'currencyid': getParameterByName('cid'),
        'bankDsc': document.getElementById("withdrawFiatAccount2").options[document.getElementById("withdrawFiatAccount2").selectedIndex].text,
        'iden': document.getElementById('depFiatInfAmountPM22').value
    }

    verifywdFiatbutton2(req)
}

function verifywdFiatbutton2(req) {
    if (document.getElementById('withdrawFiatAccount2').value == '' || document.getElementById('phoneNumberPM').value == '' || document.getElementById('depFiatInfPhonePM2').value == '') {
        if (document.getElementById('withdrawFiatAccount2').value == '') {
            error('withdrawFiatAccount2', 'ewithdrawFiatAccount2', getLangById('var35')[lang]);
            document.getElementById("withdrawFiatAccount2").classList.remove("selectwdFiat");
            document.getElementById("withdrawFiatAccount2").classList.add("selectwdFiatBank");
            document.getElementById('ewithdrawFiatAccount2').style.display = 'block'
            document.getElementById('ewithdrawFiatAccount2').style.marginLeft = '20px'
        }
        if (document.getElementById('phoneNumberPM').value == '' || document.getElementById('depFiatInfPhonePM2').value == '') {
            document.getElementById('edepFiattPhonePM22').innerHTML = getLangById('var211')[lang];
            document.getElementById('edepFiattPhonePM22').style.display = 'block'
            document.getElementById('edepFiattPhonePM22').style.marginLeft = '20px'
        }
        return;
    }



    sessionStorage.setItem('wp2p', JSON.stringify(req));

    gotoPage('step', 'withdrawFundsCoP', {
        'cid': getParameterByName('cid'),
        'q': getParameterByName('q')
    })

    //wInsertPM(req)
}


function getp2pBanks(req) {
    callWS('GET', 'p2p/banks', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                isBPWorks = true;
                WAccountsArrayPM = JSON.parse(rsp)
                addOptionsPM('withdrawFiatAccount2', JSON.parse(rsp).bancos)
                addCP2InfL2()
                document.getElementById('reportDTFiat2').dispatchEvent(new Event("click"));
                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 addCP2InfL2() {
    if (entrydata.person) {
        document.getElementById('depFiatInfAmountPM22').value = entrydata.person.document.dsc.value
        document.getElementById('selectPM2').value = entrydata.person.document.type.id
    } else {
        document.getElementById('depFiatInfAmountPM22').value = entrydata.company.document.dsc.value
        document.getElementById('selectPM2').value = 4
    }
}


function removeOptions(selectElement) {
    x = document.getElementById(selectElement)
    var i, L = x.options.length - 1;
    for (i = L; i >= 0; i--) {
        x.remove(i);
    }
}

function addOptionsPM(domElement, array) {
    removeOptions(domElement)
    var selector = document.getElementById(domElement);
    var firstOopcion = document.createElement("option");
    firstOopcion.disabled = true;
    firstOopcion.text = lang == "esp" ? "Selecciona" : "Select"
    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 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 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('bankLabel', 't3');
    setWordLanginnerHTML('accLabel', 't4');
    setWordLanginnerHTML('affiliate', 't5');

    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('reportDTFiat2', 'ReportW');
    setWordLanginnerHTML('p2cfiat2', 'ReportWP');
    setWordLanginnerHTML('bankDest2Fiat2', 't3');
    setWordLanginnerHTML('Am2Fiat2', 'iden');
    setWordLanginnerHTML('Am2Fiat3', 'CellPhoneA');
    setWordLanginnerHTML('SelectPhoneA', 'select');


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

}