<!-- 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

    // 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 "";
    }

    // sum numbers in column and write result in footer row
    // Args:
    // - api: current api object
    // - columnIdx: Index number of columns to sum, starts with 0
    // - format: format of output. either 'number' or 'isk'
    function dataTableFooterSumColumn(api, columnIdx, format='number') {
        // Remove the formatting to get integer data for summation
        const intVal = function (i) {
            return typeof i === 'string' ?
                i.replace(/[\$,]/g, '') * 1 :
                typeof i === 'number' ?
                    i : 0;
        };

        const columnTotal = api
            .column(columnIdx)
            .data()
            .reduce(function (a, b) {
                    return intVal(a) + intVal(b);
                },
                0
            );
        let result;
        if (format == 'isk'){
            result = formatisk(columnTotal)
        } else {
            result = columnTotal.toLocaleString('en-US', {maximumFractionDigits: 0})
        }
        $(api.column(columnIdx).footer()).html(result);
    }

    // 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;
        };
    };
</script>
