{% extends 'kfet/base.html' %}
{% load staticfiles %}

{% block extra_head %}
<link rel="stylesheet" style="text/css" href="{% static 'kfet/css/jquery-ui.min.css' %}">
<link rel="stylesheet" style="text/css" href="{% static 'kfet/css/kpsul_grid.css' %}">
<script src="{% static "autocomplete_light/autocomplete.js" %}" type="text/javascript"></script>
<script type="text/javascript" src="{% static 'kfet/js/js.cookie.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/reconnecting-websocket.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/jquery-ui.min.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/jquery-confirm.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/moment.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/moment-fr.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/moment-timezone-with-data-2010-2020.js' %}"></script>
<script type="text/javascript" src="{% url 'js_reverse' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/history.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/kfet.api.js' %}"></script>
<script type="text/javascript" src="{% static 'kfet/js/kpsul.js' %}"></script>
{% endblock %}

{% block title %}K-Psul{% endblock %}

{% block content-header %}{% endblock %}

{% block help %}

<div class="row">
  <div class="col-md-6">
    <div class="block">
      <h4>Opérations</h4>
      <div class="row">
        <div class="col-xs-3"><b>F3</b></div>
        <div class="col-xs-9">Charge</div>
      </div>
      <div class="row">
        <div class="col-xs-3"><b>Shift + F3</b></div>
        <div class="col-xs-9">Retrait</div>
      </div>
      <div class="row">
        <div class="col-xs-3"><b>F8</b></div>
        <div class="col-xs-9">Edition</div>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <div class="block">
      <h4>Général</h4>
      <div class="row">
        <div class="col-xs-3"><b>F1</b></div>
        <div class="col-xs-9">Reset</div>
      </div>
      <div class="row">
        <div class="col-xs-3"><b>F2</b></div>
        <div class="col-xs-9">Reset panier</div>
      </div>
      <div class="row">
        <div class="col-xs-3"><b>Shift + F2</b></div>
        <div class="col-xs-9">Reset compte</div>
      </div>
      <div class="row">
        <div class="col-xs-3"><b>F9</b></div>
        <div class="col-xs-9">Majoration</div>
      </div>
      <div class="row">
        <div class="col-xs-3"><b>F10</b></div>
        <div class="col-xs-9">Hard reset</div>
      </div>
    </div>
  </div>
</div>

{% endblock %}

{% block content %}

{% include 'kfet/base_messages.html' %}

<div class="row kpsul_top">
  <div class="col-sm-8">
    <div class="row" id="account">
      <div class="col-lg-3 col-xs-4" id="account_form">
        {{ trigramme_form.trigramme }}
      </div>
      <div class="col-lg-9 col-xs-8" id="account_data">
        <div id="account-balance_ukf" class="data_line"></div>
        <div id="account-name" class="data_line"></div>
        <div id="account-nickname" class="data_line"></div>
        <div class="data_line">
          <span id="account-is_cof"></span>
          <span id="account-departement"></span>
          <span id="account-promo"></span>
        </div>
        <div id="account-email" class="data_line"></div>
        <div class="buttons">
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-4" id="checkout">
    <div id="checkout_form">
      {{ checkout_form.checkout }}
    </div>
    <div id="checkout_data">
      <div>
        <b>En caisse:</b> <span id="checkout-balance"></span> €
      </div>
      <div id="last_statement" style="display:none">
        <b>Dernier relevé:</b><br>
        <span id="checkout-last_statement_balance_new"></span>€ le <span id="checkout-last_statement_at"></span> par <span id="checkout-last_statement_by"></span>
      </div>
      <div class="buttons">
      </div>
    </div>
  </div>
</div>

<div class="row kpsul_middle">
  <div class="col-sm-8 kpsul_middle_left_col">
    <div class="kpsul_middle_left">
      <div class="kpsul_middle_left_top">
        <div id="special_operations">
          <button role="button" class="btn" id="operation_deposit">Charge (F3)</button>
          <button role="button" class="btn" id="operation_withdraw">Retrait (Shift+F3)</button>
          <button role="button" class="btn" id="cool_reset">RAZ (F1)</button>
          <button role="button" class="btn" id="ask_addcost">Major. (F9)</button>
        </div>
        <div id="article_selection">
          <input type="text" id="article_autocomplete" autocomplete="off">
          <input type="number" id="article_number" step="1" min="1">
          <span type="stock" id="article_stock"></span>
        </div>
        <div id="articles_data">
        </div>
      </div>
      <div class="row kpsul_middle_left_bottom">
        <div class="col-sm-6">
          <div id="basket">
            <table id="basket_table">
            </table>
          </div>
        </div>
        <div class="col-sm-3">
          <div id="basket_rel">
          </div>
        </div>
        <div class="col-sm-3">
          <div id="previous_op">
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-4 kpsul_middle_right_col">
    <div id="history">
    </div>
  </div>
</div>

<div id="history2">
</div>

<form id="operationgroup_form" style="display:none;">{{ operationgroup_form }}</form>
<form id="operation_formset" style="display:none;">{{ operation_formset }}</form>

<div style="display:none;" id="operation_empty_html" data-opeindex="__prefix__">
    {{ operation_formset.empty_form }}
</div>

{% csrf_token %}

<script type="text/javascript">
$(document).ready(function() {
    'use strict';

    // -----
    // Auth
    // -----

    function askComment(callback) {
        var comment = $('#id_comment').val();
        var commentDialog = new UserDialog({
            title: 'Commentaire requis',
            content: '<input type="text" name="comment_opegroup" value="'+comment+'" autofocus>',

        });

        function confirm_callback(comment) {
            $('#id_comment').val(comment);
            callback();
        }

        commentDialog.open({
            callback: confirm_callback,
            next_focus: kpsul,
        });
    }

    function resetComment() {
        $('#id_comment').val('');
    }

    // -----
    // Errors ajax
    // -----

    function displayErrors(html) {
        $.alert({
            title: 'Erreurs',
            content: html,
            backgroundDismiss: true,
            animation: 'top',
            closeAnimation: 'bottom',
            keyboardEnabled: true,
        });
    }

    // -----
    // Perform operations
    // -----

    var performButton  = $('#perform_operations');
    var operationGroup = $('#operationgroup_form');
    var operations     = $('#operation_formset');

    function performOperations() {
        var data = operationGroup.serialize() + '&' + operations.serialize();
        api_with_auth({
            url: Urls['kfet.kpsul.perform_operations'](),
            data: data,
            on_success: function() {
                updatePreviousOp();
                coolReset();
            },
            on_400: function(response) {
                if ('need_comment' in response['errors'])
                    askComment(performOperations);
                else
                    displayErrors(getErrorsHtml(response));
            },
            next_focus: kpsul,
        });
    }

    // Event listeners
    performButton.on('click', function() {
        performOperations();
    });

    // -----
    // Cancel operations
    // -----

    var cancelButton = $('#cancel_operations');
    var cancelForm   = $('#cancel_form');

    function cancelOperations(opes_array) {
        var data = { 'operations' : opes_array }
        api_with_auth({
            url: Urls['kfet.kpsul.cancel_operations'](),
            data: data,
            on_success: function() {
                coolReset();
            },
            on_400: function(response) {
                displayErrors(getErrorsHtml(response));
            },
            next_focus: kpsul.account_manager,
        });
    }

    // Event listeners
    cancelButton.on('click', function() {
        cancelOperations();
    });

    // -----
    // Basket
    // -----

    var item_basket_default_html = '<tr><td class="amount"></td><td class="number"></td><td ><span class="lowstock glyphicon glyphicon-alert"></span></td><td class="name"></td></tr>';
    var basket_container = $('#basket table');
    var arrowKeys = /^(37|38|39|40)$/;

    function amountEuroPurchase(article, nb) {
        var amount_euro = - article.price * nb ;
        if (Config.get('addcost_for')
              && Config.get('addcost_amount')
              && kpsul.account_manager.account.trigramme != Config.get('addcost_for')
              && article.category.has_addcost)
            amount_euro -= Config.get('addcost_amount') * nb;
        var reduc_divisor = 1;
        if (kpsul.account_manager.account.is_cof)
            reduc_divisor = 1 + Config.get('subvention_cof') / 100;
        return amount_euro / reduc_divisor;
    }

    function addPurchase(article, nb) {

        var existing = false;
        formset_container.find('[data-opeindex]').each(function () {
            var opeindex = $(this).attr('data-opeindex');
            var article_id = $(this).find('#id_form-'+opeindex+'-article').val();
            if (article_id == article.id) {
                existing = true ;
                addExistingPurchase(opeindex, nb);
            }
        });
        if (!existing) {
            var amount_euro = amountEuroPurchase(article, nb).toFixed(2);
            var index = addPurchaseToFormset(article.id, nb, amount_euro);
            var article_basket_html = $(item_basket_default_html);
            article_basket_html
                .attr('data-opeindex', index)
                .find('.number').text(nb).end()
                .find('.name').text(article.name).end()
                .find('.amount').text(amountToUKF(amount_euro, kpsul.account_manager.account.is_cof));
            basket_container.prepend(article_basket_html);
            if (article.is_low_stock(nb))
                article_basket_html.find('.lowstock')
                                   .show();
            updateBasketRel();
        }
    }

    function addDeposit(amount) {
        var deposit_basket_html = $(item_basket_default_html);
        var amount = parseFloat(amount).toFixed(2);
        var index = addDepositToFormset(amount);
        deposit_basket_html
            .attr('data-opeindex', index)
            .find('.number').text(amount+"€").end()
            .find('.name').text('Charge').end()
            .find('.amount').text(amountToUKF(amount, kpsul.account_manager.account.is_cof));
        basket_container.prepend(deposit_basket_html);
        updateBasketRel();
    }

    function addEdit(amount) {
        var deposit_basket_html = $(item_basket_default_html);
        var amount = parseFloat(amount).toFixed(2);
        var index = addEditToFormset(amount);
        deposit_basket_html
            .attr('data-opeindex', index)
            .find('.number').text(amount+"€").end()
            .find('.name').text('Édition').end()
            .find('.amount').text(amountToUKF(amount, kpsul.account_manager.account.is_cof));
        basket_container.prepend(deposit_basket_html);
        updateBasketRel();
    }

    function addWithdraw(amount) {
        var withdraw_basket_html = $(item_basket_default_html);
        var amount = (- parseFloat(amount)).toFixed(2);
        var index = addWithdrawToFormset(amount);
        withdraw_basket_html
            .attr('data-opeindex', index)
            .find('.number').text(amount+"€").end()
            .find('.name').text('Retrait').end()
            .find('.amount').text(amountToUKF(amount, kpsul.account_manager.account.is_cof));
        basket_container.prepend(withdraw_basket_html);
        updateBasketRel();
    }

    basket_container.selectable({
        filter: 'tr',
    });

    $(document).on('keydown', function (e) {
        switch(e.which) {
            case 46:
                // DEL (Suppr)
                basket_container.find('.ui-selected').each(function () {
                    deleteFromBasket($(this).data('opeindex'));
                });
                break;
            case 38:
                // Arrow up
                basket_container.find('.ui-selected').each(function () {
                    addExistingPurchase($(this).data('opeindex'), 1);
                });
                break;
            case 40:
                // Arrow down
                basket_container.find('.ui-selected').each(function () {
                    addExistingPurchase($(this).data('opeindex'), -1);
                });
                break;
        }
    });

    function isBasketEmpty() {
        return !basket_container.find('[data-opeindex]').length;
    }

    function getAmountBasket() {
        var total = 0;
        formset_container.find('[data-opeindex]').each(function () {
            var opeindex = $(this).attr('data-opeindex');
            if (!$(this).find('#id_form-'+opeindex+'-DELETE').prop('checked'))
                total += parseFloat($(this).find('#id_form-'+opeindex+'-amount').val());
        });
        return total;
    }

    function updateBasketAmount() {
        formset_container.find('[data-opeindex]').each(function () {
            var opeindex = $(this).attr('data-opeindex');
            var deleted = $(this).find('#id_form-'+opeindex+'-DELETE').prop('checked');
            var type = $(this).find('#id_form-'+opeindex+'-type').val();
            var article_id = $(this).find('#id_form-'+opeindex+'-article').val();
            var article_nb = $(this).find('#id_form-'+opeindex+'-article_nb').val();
            var amount = $(this).find('#id_form-'+opeindex+'-amount');
            if (!deleted && type == "purchase")
                amount.val(amountEuroPurchase(article_id, article_nb));
            basket_container.find('[data-opeindex='+opeindex+'] .amount').text(amountToUKF(amount.val(), kpsul.account_manager.account.is_cof, false));
        });
    }

    var basketrel_container = $('#basket_rel');

    function updateBasketRel() {
        var basketrel_html = '';
        var account = kpsul.account_manager.account;
        var trigramme = account.trigramme;
        var is_cof = account.is_cof;
        if (trigramme == 'LIQ' && !isBasketEmpty()) {
            var amount = - getAmountBasket();
            basketrel_html += '<div>Total: '+amount.toFixed(2)+' €</div>';
            if (amount < 5)
                basketrel_html += '<div>Sur 5€: '+ (5-amount).toFixed(2) +' €</div>';
            if (amount < 10)
                basketrel_html += '<div>Sur 10€: '+ (10-amount).toFixed(2) +' €</div>';
            if (amount < 20)
                basketrel_html += '<div>Sur 20€: '+ (20-amount).toFixed(2) +' €</div>';
        } else if (trigramme != '' && !isBasketEmpty()) {
            var amount = getAmountBasket();
            var amountUKF = amountToUKF(amount, is_cof);
            var newBalance = account.balance + amount;
            var newBalanceUKF = amountToUKF(newBalance, is_cof, true);
            basketrel_html += '<div>Total: '+amountUKF+'</div>';
            basketrel_html += '<div>Nouveau solde: '+newBalanceUKF+'</div>';
            if (newBalance < 0)
                basketrel_html += '<div>Manque: '+ (-newBalance).toFixed(2) +' €</div>';
        }
        basketrel_container.html(basketrel_html);
    }

    function deleteFromBasket(opeindex) {
        basket_container.find('[data-opeindex='+opeindex+']').remove();
        deleteFromFormset(opeindex);
        updateBasketRel();
    }

    function addExistingPurchase(opeindex, nb) {
        var type = formset_container.find("#id_form-"+opeindex+"-type").val();
        var id = formset_container.find("#id_form-"+opeindex+"-article").val();
        var article = kpsul.article_manager.get_article(parseInt(id));
        var nb_before = formset_container.find("#id_form-"+opeindex+"-article_nb").val();
        var nb_after = parseInt(nb_before) + parseInt(nb);
        var amountEuro_after = amountEuroPurchase(article, nb_after);
        var amountUKF_after = amountToUKF(amountEuro_after, kpsul.account_manager.account.is_cof, false);

        if (type == 'purchase') {
            if (nb_after == 0) {
                deleteFromBasket(opeindex);
            } else if (nb_after > 0 && nb_after <= 25) {
                if (nb_before > 0) {
                    var article_html = basket_container.find('[data-opeindex='+opeindex+']');
                    article_html.find('.amount').text(amountUKF_after).end()
                                .find('.number').text('('+nb_after+'/'+article.stock+')').end() ;

                } else {
                    article_html = $(item_basket_default_html);
                    article_html
                        .attr('data-opeindex', opeindex)
                        .find('.number').text('('+nb_after+'/'+article.stock+')').end()
                        .find('.name').text(article.name).end()
                        .find('.amount').text(amountUKF_after);
                    basket_container.prepend(article_basket_html);

                }

                    if (article.is_low_stock(nb_after))
                        article_html.find('.lowstock')
                                    .show();
                    else
                        article_html.find('.lowstock')
                                    .hide();
                updateExistingFormset(opeindex, nb_after, amountEuro_after);
                updateBasketRel();
            }
        }
    }

    function resetBasket() {
        basket_container.find('tr').remove();
        mngmt_total_forms = 1;
        mngmt_total_forms_input.val(1);
        formset_container.find('div').remove();
        updateBasketRel();
        kpsul.article_manager.reset();
    }

    // -----
    // Ask deposit or withdraw
    // -----

    function askDeposit() {
        var depositDialog = new UserDialog({
            title: 'Montant de la charge',
            content: '<input type="number" lang="en" step="0.01" min="0.01" autofocus placeholder="€">',
        });

        function callback(amount) {
            if (!$.isNumeric(amount) || amount <= 0)
                return false;
            addDeposit(amount);
        }

        depositDialog.open({
            callback: callback,
            next_focus: kpsul.article_manager,
        });
    }

    function askEdit() {
        var editDialog = new UserDialog({
            title: "Montant de l'édition",
            content: '<input type="number" lang="en" step="0.01" min="0.01" autofocus placeholder="€">',
        });

        function callback(amount) {
            if (!$.isNumeric(amount))
                return false;
            addEdit(amount);
        }

        editDialog.open({
            callback: callback,
            next_focus: kpsul.article_manager,
        });
    }

    function askWithdraw() {
        var withdrawDialog = new UserDialog({
            title: 'Montant du retrait',
            content: '<input type="number" lang="en" step="0.01" min="0.01" autofocus placeholder="€">',
        });

        function callback(amount) {
            if (!$.isNumeric(amount) || amount <= 0)
                return false;
            addWithdraw(amount);
        }

        withdrawDialog.open({
            callback: callback,
            next_focus: kpsul.article_manager,
        });
    }

    // Event

    var depositButton = $('#operation_deposit');
    var withdrawButton = $('#operation_withdraw');

    depositButton.on('click', function() { askDeposit(); });
    withdrawButton.on('click', function() { askWithdraw(); });

    // -----
    // Operation formset management
    // -----

    var operation_empty_html = $('#operation_empty_html')
        .removeAttr('id')
        .find('label').remove().end()
        .find('#id_form-__prefix__-DELETE').css('display','none').end();
    $('#id_form-0-DELETE').prop('checked',true);

    var formset_container = $('#operation_formset');
    var mngmt_total_forms_input = $('#id_form-TOTAL_FORMS');
    var mngmt_total_forms = 1;
    var prefix_regex = /__prefix__/;

    function addOperationToFormset(type, amount, article='', article_nb='') {
        var operation_html = operation_empty_html.clone();
        var index = mngmt_total_forms;

        operation_html.attr('data-opeindex', index);

        operation_html
            .find('#id_form-__prefix__-type').val(type).end()
            .find('#id_form-__prefix__-amount').val((parseFloat(amount)).toFixed(2)).end()
            .find('#id_form-__prefix__-article').val(article).end()
            .find('#id_form-__prefix__-article_nb').val(article_nb).end();

        mngmt_total_forms_input.val(index+1);
        mngmt_total_forms++;

        operation_html.find(':input').each(function() {
            var name = $(this).attr('name').replace(prefix_regex, index);
            var id = 'id_' + name;
            $(this).attr({'name': name, 'id': id});
        });
        formset_container.append(operation_html);

        return index;
    }

    function addDepositToFormset(amount) {
        return addOperationToFormset('deposit', amount, '', '');
    }

    function addEditToFormset(amount) {
        return addOperationToFormset('edit', amount, '', '');
    }

    function addWithdrawToFormset(amount) {
        return addOperationToFormset('withdraw', amount, '', '');
    }

    function addPurchaseToFormset(article_id, article_nb, amount=0) {
        return addOperationToFormset('purchase', amount, article_id, article_nb);
    }

    function deleteFromFormset(opeindex) {
        updateExistingFormset(opeindex, 0, '0.00');
    }

    function updateExistingFormset(opeindex, nb, amount) {
        formset_container
            .find('#id_form-'+opeindex+'-amount').val((parseFloat(amount)).toFixed(2)).end()
            .find('#id_form-'+opeindex+'-article_nb').val(nb).end()
            .find('#id_form-'+opeindex+'-DELETE').prop('checked', !nb);
    }

    // -----
    // History
    // -----

    var khistory = new KHistory();

    function getHistory() {
        var data = {
            from: moment().subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss'),
        };
        $.ajax({
            dataType: "json",
            url     : "{% url 'kfet.history.json' %}",
            method  : "POST",
            data    : data,
        })
        .done(function(data) {
            for (var i=0; i<data['opegroups'].length; i++) {
                khistory.addOpeGroup(data['opegroups'][i]);
            }
        });
    }

    var previousop_container = $('#previous_op');

    function updatePreviousOp() {
        var previousop_html = '';
        var trigramme = kpsul.account_manager.account.trigramme;
        previousop_html += '<div class="trigramme">Trigramme : '+trigramme+'</div>';
        previousop_html += basketrel_container.html();
        previousop_container.html(previousop_html);
    }

    function resetPreviousOp() {
        previousop_container.html('');
    }

    // -----
    // Addcost
    // -----

    var addcost_default_html = '<div id="addcost">Majoration vers <span class="addcost_for"></span> de <span class="addcost_amount"></span>€</div>';

    function displayAddcost() {
        $('#addcost').remove();
        $('body').css('animation', 'none');
        if (Config.get('addcost_for') && Config.get('addcost_amount')) {
            var addcost_html = $(addcost_default_html);
            addcost_html
                .find('.addcost_for').text(Config.get('addcost_for')).end()
                .find('.addcost_amount').text(Config.get('addcost_amount').toFixed(2)).end();
            kpsul.checkout_manager._$container.prepend(addcost_html);
            $('body').css('animation', 'colorchange 3s infinite');
        }
    }


    function askAddcost(errors = '') {
        var addcostDialog = new UserDialog({
            'title': 'Majoration',
            'content': '<input type="text" placeholder="Trigramme" autocomplete="off" name="trigramme" spellcheck="false" style="text-transform:uppercase" autofocus><input type="number" lang="en" step="0.01" min="0.01" placeholder="€" name="amount">',
        });

        function callback(data) {
            api_with_auth({
                url: Urls['kfet.kpsul.update_addcost'](),
                data: data,
                on_400: function(response) {
                    askAddcost(getErrorsHtml(response));
                },
                next_focus: kpsul.account_manager,
            });
        }

        addcostDialog.open({
            callback: callback,
            pre_content: errors,
            next_focus: kpsul.account_manager,
        });
    }


    // -----
    // Cancel from history
    // -----

    khistory.$container.selectable({
        filter: 'div.opegroup, div.ope',
        selected: function(e, ui) {
            $(ui.selected).each(function() {
                if ($(this).hasClass('opegroup')) {
                    var opegroup = $(this).data('opegroup');
                    $(this).siblings('.ope').filter(function() {
                        return $(this).data('opegroup') == opegroup
                    }).addClass('ui-selected');
                }
            });
        },
    });

    $(document).on('keydown', function (e) {
        if (e.keyCode == 46) {
            // DEL (Suppr)
            var opes_to_cancel = [];
            khistory.$container.find('.ope.ui-selected').each(function () {
                opes_to_cancel.push($(this).data('ope'));
            });
            if (opes_to_cancel.length > 0)
                cancelOperations(opes_to_cancel);
        }
    });

    // -----
    // Synchronization
    // -----

    OperationWebSocket.add_handler(function(data) {
        for (var i=0; i<data['opegroups'].length; i++) {
            if (data['opegroups'][i]['add']) {
                khistory.addOpeGroup(data['opegroups'][i]);
            } else if (data['opegroups'][i]['cancellation']) {
                khistory.cancelOpeGroup(data['opegroups'][i]);
            }
        }
        for (var i=0; i<data['opes'].length; i++) {
            if (data['opes'][i]['cancellation']) {
                khistory.cancelOpe(data['opes'][i]);
            }
        }
        for (var i=0; i<data['checkouts'].length; i++) {
            if (checkout_data['id'] == data['checkouts'][i]['id']) {
                checkout_data['balance'] = data['checkouts'][i]['balance'];
                displayCheckoutData();
            }
        }

        kpsul.article_manager.update_data(data);

        if (data['addcost']) {
            Config.set('addcost_for', data['addcost']['for']);
            Config.set('addcost_amount', data['addcost']['amount']);
            displayAddcost();
        }
    });

    // -----
    // General
    // -----

    // Reset functions

    function coolReset(give_tri_focus=true) {
        kpsul.account_manager.reset();
        resetBasket();
        resetComment();
        resetSelectable();
        if (give_tri_focus)
            kpsul.account_manager.focus();
    }

    function hardReset(give_tri_focus=true) {
        coolReset(give_tri_focus);
        kpsul.checkout_manager.reset();
        resetPreviousOp();
        khistory.reset();
        Config.reset(function() {
            kpsul.article_manager.reset_data();
            displayAddcost();
            getHistory();
        });
    }

    function resetSelectable() {
        $('.ui-selected').removeClass('ui-selected');
    }

    // Shorcuts

    $('#cool_reset').click(function() {
        coolReset();
    });

    $('#ask_addcost').click(function() {
        askAddcost();
    });

    $(document).on('keydown', function(e) {
        switch (e.keyCode) {
            case 27:
                // Escape - Hide help
                $('.help').hide('fast');
                return false;
            case 72:
                if (e.ctrlKey) {
                    // Ctrl+H - Display help
                    e.preventDefault();
                    $('.help').show('fast');
                }
                return true;
            case 112:
                // F1 - Cool reset
                coolReset();
                return false;
            case 113:
                if (e.shiftKey) {
                    // Shift+F2 - Account reset
                    account_manager
                        .reset()
                        .focus();
                } else {
                    // F2 - Basket reset
                    resetBasket();
                    kpsul.article_manager.focus();
                }
                return false;
            case 114:
                if (e.shiftKey) {
                    // Shift+F3 - Withdraw
                    askWithdraw();
                } else {
                    // F3 - Withdraw
                    askDeposit();
                }
                return false;
            case 119:
                // F8 - Edition
                askEdit();
                return false;
            case 120:
                // F9 - Addcost
                askAddcost();
                return false;
            case 121:
                // F10 - Hard reset
                hardReset();
                return false;
        }
    });

    // -----
    // Initiliazing all
    // -----

    var env = {
        addPurchase: addPurchase,
        updateBasketAmount: updateBasketAmount,
        updateBasketRel: updateBasketRel,
        performOperations: performOperations,
    };

    window.kpsul = new KPsulManager(env);

    hardReset();

});
</script>

{% endblock %}
