WS_waitscreen = true;

window.onload = function(){
    
    // Go back
    document.getElementById('previous-button').addEventListener("click", function(){
        gotoPage('step','sellCryptoAm',{ 'sessionid' : getParameterByName('sessionid'), 'cid' : getParameterByName('cid'), 'crid' : getParameterByName('crid') })
    });
    
    // Go step 4
    document.getElementById('next-button').addEventListener("click", function(){
        //gotoPage('step','final',{ 'sessionid' : getParameterByName('sessionid') })
        verifyNextButton()
    });
    
    // Go back R
    document.getElementById('previous-buttonR').addEventListener("click", function(){
        gotoPage('step','sellCryptoAm',{ 'sessionid' : getParameterByName('sessionid'), 'cid' : getParameterByName('cid'), 'crid' : getParameterByName('crid') })
    });
    
    // Go step 4 R
    document.getElementById('next-buttonR').addEventListener("click", function(){
        //gotoPage('step','final',{ 'sessionid' : getParameterByName('sessionid') })
        verifyNextButton()
    });
    
    // Balance
    document.getElementById('floatButton').addEventListener("click",function(){
        gotoPage('dashboard','home',{ 'sessionid' : getParameterByName('sessionid') })
        
    })
    
    // Session Update
    document.getElementById('expSessionButton').addEventListener("click",function(){
        var req = {
            'sessionid': getParameterByName('sessionid')
        }
        sessionUpdate(req)
    })
    
    // Finalizar fail
    document.getElementById('wdFiatbuttonI').addEventListener("click", function(){
        document.getElementsByClassName('failure')[0].style.display = "none"
        document.getElementById('failureMsg').innerHTML = ''
        document.getElementById('failureTitle').innerHTML="Transacción </br> Fallida"
        document.getElementById('wdFiatbuttonI').innerHTML = "INTENTE DE NUEVO"
    });
    
    // 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 ordersDetails(req){
    console.log(req)
    callWS('GET', 'orders/details', req, response);
    function response(status, rsp){
        console.log('orders/details')
        console.log(status) 
        switch(status){
            case 200:
                console.log(JSON.parse(rsp));
                loadDetails(JSON.parse(rsp).entry)
                break;
            case 400:
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                break;
            case 403:
                break;
            case 500:
                break;
            default:
                break;
        }
    }   
}

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

function getEntry(sessionid){
    callWS("GET", "users/entry", { 'sessionid' : sessionid}, response);
        
    function response(status, rsp){
        switch(status){
            case 200:
                entrydata = (JSON.parse(rsp).entry)
                putName(entrydata);
                var req = {
                    'sessionid': getParameterByName('sessionid'),
                    'currencyid': getParameterByName('cid'),
                    'refcurrencyid': getParameterByName('crid'),
                    'action' : 2
                }
                ordersDetails(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('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 loadDetails(detailsOrder){
    console.log(detailsOrder)
    number = parseFloat(getParameterByName('q')).noExponents()
    
    document.getElementById('amountBuy').innerHTML = detailsOrder.currency.id == getParameterByName('cid') ? 
                                                     detailsOrder.currency.symbol + ' ' + number_format(parseFloat(getParameterByName('q')).noExponents(),detailsOrder.currency.decimals) :
                                                     detailsOrder.refcurrency.symbol + ' ' + number_format(parseFloat(getParameterByName('q')).noExponents(),detailsOrder.refcurrency.decimals);
                                                     
    document.getElementById('rate').innerHTML = detailsOrder.currency.id == getParameterByName('cid') ? 
                                                detailsOrder.refcurrency.symbol + ' ' + detailsOrder.bid.formatted + ' por ' + detailsOrder.currency.symbol :
                                                detailsOrder.currency.symbol + ' ' + detailsOrder.bid.formatted + ' por ' + detailsOrder.refcurrency.symbol
                                                
    document.getElementById('debit').innerHTML = detailsOrder.currency.id == getParameterByName('cid') ? 
                                                 detailsOrder.refcurrency.symbol + ' ' + number_format((parseFloat(getParameterByName('q')) * detailsOrder.bid.number).noExponents(),detailsOrder.refcurrency.decimals) :
                                                 detailsOrder.currency.symbol + ' ' + number_format((parseFloat(getParameterByName('q')) * detailsOrder.bid.number).noExponents(),detailsOrder.currency.decimals)
    
    document.getElementById('fee').innerHTML = detailsOrder.currency.id == getParameterByName('crid') ? 
                                               detailsOrder.currency.symbol + ' ' +  
                                                    number_format(parseFloat(calculateFees(detailsOrder.fees.market,parseFloat(getParameterByName('q')) * detailsOrder.bid.number)).noExponents(),detailsOrder.currency.decimals) :
                                               detailsOrder.refcurrency.symbol + ' ' +   
                                                    number_format(parseFloat(calculateFees(detailsOrder.fees.market,parseFloat(getParameterByName('q')) * detailsOrder.bid.number)).noExponents(),detailsOrder.refcurrency.decimals)
                                               
    document.getElementById('confirmOrderFinal').innerHTML = detailsOrder.currency.id == getParameterByName('crid') ? 
                                                             detailsOrder.currency.symbol + ' ' + 
                                                                number_format((parseFloat(number).noExponents() - parseFloat(calculateFees(detailsOrder.fees.market,parseFloat(getParameterByName('q')) * detailsOrder.bid.number)).noExponents()).noExponents(),detailsOrder.currency.decimals) :
                                                             detailsOrder.refcurrency.symbol + ' ' +   
                                                             number_format((parseFloat(number).noExponents() - parseFloat(calculateFees(detailsOrder.fees.market,parseFloat(getParameterByName('q')) * detailsOrder.bid.number)).noExponents()).noExponents(),detailsOrder.refcurrency.decimals)
    
    document.getElementById('next-button').setAttribute('parid',detailsOrder.id)
}

function calculateFees(fee,number1){
    number = parseFloat(number1).noExponents()
    if(fee.nmalfee){
        return (parseFloat(fee.nmalfee.number)).noExponents()
    }
    else if(fee.pctfee){
        console.log((parseFloat(number * (fee.pctfee.number/100))).noExponents())
        return (parseFloat(number * (fee.pctfee.number/100))).noExponents()
    }else{
        return 0
    }
}

function verifyNextButton(){
    req = {
        'pairid': document.getElementById('next-button').getAttribute('parid'),
        'qty': parseFloat(getParameterByName('q')).noExponents(),
        'type': 1,
        'side': 1,
        'sessionid': getParameterByName('sessionid')
    }
    
    console.log(req)
    
    ordersInsert(req)
}

function ordersInsert(req){
    callWS('POST', 'orders/insert', req, response);
    function response(status, rsp){
        console.log('orders/insert')
        console.log(status)
        console.log(rsp)
        switch(status){
            case 200:
                console.log('ok')
                gotoPage('step','final',{ 'sessionid' : getParameterByName('sessionid'), 'type' : 'buy'})
                break;
            case 400:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 401:
                expiredSession();
                break;
            case 402:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 403:
                document.getElementById('failureMsg').innerHTML = JSON.parse(rsp).msg
                document.getElementsByClassName('failure')[0].style.display = "table"
                break;
            case 406:
                document.getElementById('failureMsg').innerHTML = 'No hay liquidez, espere o coloque una orden tipo límite.'
                document.getElementsByClassName('failure')[0].style.display = "table"
                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;
        }
    }   
}
