WS_waitscreen = true;
var decimCoin = 0; 
var idR = ''
curInfR = ''

window.onload = function(){
    
    // Go back
    document.getElementById('previous-button').addEventListener("click", function(){
        gotoPage('step','depositFundsAm',{ 'sessionid' : getParameterByName('sessionid'), 'cid' : getParameterByName('cid') })
    });
    
    // Go step 4
    document.getElementById('next-button').addEventListener("click", function(){
        depositFiat()
    });
    
    // Go back R
    document.getElementById('previous-buttonR').addEventListener("click", function(){
        gotoPage('step','depositFundsAm',{ 'sessionid' : getParameterByName('sessionid'), 'cid' : getParameterByName('cid') })
    });
    
    // Go step 4 R
    document.getElementById('next-buttonR').addEventListener("click", function(){
        depositFiat()
    });
    
    // Step
    document.getElementById('floatButton').addEventListener("click",function(){
        var popup = document.getElementById("floatButton").children[0].children[0];
        if(popup.classList.contains('show')){
            gotoPage('dashboard','home',{ 'sessionid' : getParameterByName('sessionid') })
        }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()
    })
    
    // Finalizar fail
    document.getElementById('wdFiatbuttonI').addEventListener("click", function(){
        document.getElementsByClassName('failure')[0].style.display = "none"
        document.getElementById('failureMsg').innerHTML = ''
    });
    
    // 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()
    
    //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(){
    setLang()
}

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:
                JSON.parse(rsp).records.forEach(element => {
                    if (element.id == JSON.parse(localStorage.getItem('deposit')).paymentaccountid){
                        document.getElementById('Bank').innerHTML = element.paymentmethod.dsc
                        document.getElementById('acDest').innerHTML = element.details1
                        document.getElementById('tit').innerHTML = element.details2
                    }
                });
                var req = {
                    'sessionid': getParameterByName('sessionid'),
                    'action': 2
                }
                accountsPortfolio(req)
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

// 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:
                //document.getElementById('depFiatInfBalance').innerHTML = (JSON.parse(rsp).entry.currency.symbol) + ' ' + (JSON.parse(rsp).entry.balance.formatted)
                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)
                        curInfR = element;
                        decimCoin = element.currency.decimals
                        idR = element.id
                        document.getElementById('amount').innerHTML = element.currency.symbol + ' ' + number_format(JSON.parse(localStorage.getItem('deposit')).amount,decimCoin)
                        req = {
                            'sessionid': getParameterByName('sessionid'),
                            'currencyid': getParameterByName('cid'),
                        }
                        feesEntry(req,element.currency.symbol)
                    }
                });
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

// fees/entry
function feesEntry(req,symbol){
    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:
                console.log(curInfR)
                if(JSON.parse(rsp).entry.deposits.nmalfee){
                    document.getElementById('fees').innerHTML = curInfR.currency.symbol + ' ' + number_format(parseFloat(JSON.parse(rsp).entry.deposits.nmalfee.number),curInfR.currency.decimals)
                    document.getElementById('totalN').innerHTML = curInfR.currency.symbol + ' ' + number_format((parseFloat(JSON.parse(localStorage.getItem('deposit')).amount) - JSON.parse(rsp).entry.deposits.nmalfee.number),curInfR.currency.decimals)
                    document.getElementById('totalN').setAttribute('number',parseFloat(parseFloat(JSON.parse(localStorage.getItem('deposit')).amount) - parseFloat(JSON.parse(rsp).entry.deposits.nmalfee.number)))
                }
                else if(JSON.parse(rsp).entry.deposits.pctfee){
                    document.getElementById('fees').innerHTML = curInfR.currency.symbol + ' ' + number_format(parseFloat(JSON.parse(rsp).entry.deposits.pctfee.number) * parseFloat(JSON.parse(localStorage.getItem('deposit')).amount / 100),
                                                                                                                                                 curInfR.currency.decimals)
                    document.getElementById('totalN').innerHTML = curInfR.currency.symbol + ' ' + number_format(parseFloat(1 - parseFloat(JSON.parse(rsp).entry.deposits.pctfee.number)/100) * parseFloat(JSON.parse(localStorage.getItem('deposit')).amount ),
                                                                                                                curInfR.currency.decimals)
                    document.getElementById('totalN').setAttribute('number',parseFloat(1 - parseFloat(JSON.parse(rsp).entry.deposits.pctfee.number)/100) * parseFloat(JSON.parse(localStorage.getItem('deposit')).amount ))
                    
                }else{
                    console.log('N/A')
                }   
                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 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:
                document.getElementsByClassName('failure')[0].style.display = "table"
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                break;
            case 500:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            default:
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
        }
    }   
}

function depositFiat(){

    var req = JSON.parse(localStorage.getItem('deposit')) 
    
    req.paymentfile = dataURLtoFile(localStorage.getItem('file'),req.paymentfile)
    
    console.log(req)
    depositsInsert(req)
    // gotoPage('step','final',{ 'sessionid' : getParameterByName('sessionid') })
}

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 setLang(){
    
    lang = localStorage.getItem('lang');
    
    /* inner HTML */
    setWordLanginnerHTML('home','home');
    setWordLanginnerHTML('balance','balance');
    setWordLanginnerHTML('preferences','preferences');
    setWordLanginnerHTML('homeR','home');
    setWordLanginnerHTML('balanceR','balance');
    setWordLanginnerHTML('preferencesR','preferences');
    setWordLanginnerHTML('langIcon','langIcon');
    
    setWordLanginnerHTML('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','bankLabel');
    setWordLanginnerHTML('accLabel','DestinationAccount');
    setWordLanginnerHTML('titLabel','titLabel');
    setWordLanginnerHTML('amountLabel','amountLabel');
    setWordLanginnerHTML('feesLabel','feeLabel');
    
    setWordLanginnerHTML('failureTitle','failureTitle');
    setWordLanginnerHTML('wdFiatbuttonI','wdFiatbuttonI');
    
    
    
    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');

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

}
