function start() {

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

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

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



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

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

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

    // Session Update


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


    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 ordersDetails(req) {

    callWS('GET', 'orders/details', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:

                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() {
    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'),
                    '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('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 loadDetails(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 + getLangById('var1')[lang] + detailsOrder.currency.symbol :
        detailsOrder.currency.symbol + ' ' + detailsOrder.bid.formatted + getLangById('var1')[lang] + 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) {
        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': sessionStorage.getItem('sessionid')
    }



    ordersInsert(req)
}

function ordersInsert(req) {
    callWS('POST', 'orders/insert', req, response);
    function response(status, rsp) {
        switch (status) {
            case 200:
                gotoPage('step', 'final', { '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 = lang == "esp" ? 'No hay liquidez, espere o coloque una orden tipo l��mite.' : 'No liquidity, wait or place a limit type order.'
                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;
        }
    }
}


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('amountBuyLabel', 'amountBuyLabel');
    setWordLanginnerHTML('rateLabel', 'rateLabel');
    setWordLanginnerHTML('debitLabel', 'debitLabel');
    setWordLanginnerHTML('feeLabel', 'feeLabel');
    setWordLanginnerHTML('cardAmountRoundedTextLastText', 'cardAmountRoundedTextLastText');
    setWordLanginnerHTML('infMin', 'infMin');
    setWordLanginnerHTML('maxBuy', 'maxBuy');

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

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


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


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

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

}
