<!-- Global Javascript. Implemented as template, so we can use tags, filters and context. -->

<script type="text/javascript">
    /* Global constants */
    const DEFAULT_LENGTH_MENU = [[10, 25, 50, 100 -1], [10, 25, 50, 100, "All"]]
    const DEFAULT_PAGE_LENGTH = 50
    const B_DIVIDER = 9

    /* Global functions */
    // Remove the formatting to get integer data for summation
    var intVal = function (i) {
        return typeof i === 'string' ?
            i.replace(/[\$,]/g, '') * 1 :
            typeof i === 'number' ?
                i : 0;
    };

    // Format ISK values for output
    // magnitude: show value with given magnitude, else magnitude will be calculated
    function formatisk(data, magnitude=null) {
        if ( data != null ) {
            const power_map = {'t': 12, 'b': 9, 'm': 6, 'k': 3, '': 0}
            if (!power_map.hasOwnProperty(magnitude)) {
                if (data >= 10 ** 12) magnitude = 't';
                else if (data >= 10 ** 9) magnitude = 'b';
                else if (data >= 10 ** 6) magnitude = 'm';
                else if (data >= 10 ** 3) magnitude = 'k';
                else magnitude = '';
            }
            return (data / (10 ** power_map[magnitude])).toLocaleString(
                'en-US', {minimumFractionDigits: 1, maximumFractionDigits: 1}
            ) + magnitude;
        }
        else return "";
    }

    // DataTables renderer for ISK values
    $.fn.dataTable.render.formatisk = function(magnitude=null) {
        return function ( data, type, row ) {
            if ( type === 'display' ) {
                return formatisk(data, magnitude);
            }
            // Search, order and type can use the original data
            return data;
        };
    };

    // wrap boiler plate code for handling modal events
    function handle_modal_events(modalId, modalContentId,) {
        $('#' + modalId ).on('show.bs.modal', function (event) {
            $(this).find('.modal-body').load("{% url 'moonmining:modal_loader_body' %}?is_night_mode={{NIGHT_MODE}}")
            var button = $(event.relatedTarget)
            var ajax_url = button.data('ajax_url');
            $('#' + modalContentId).load(ajax_url)
        });
    }
</script>
