$(document).ready(function(){

    var
        $table = $('#table-line'),
        $tableContent = $('<tbody>'),
        $tableBody = $table.find('tbody').first(),
        activeLines = [],
        currentActiveLine,
        dataTable;
    
    function valueFormat(value)
    {
        var
            currencyFields = ['admoney', 'salemoney', 'usdollarmoney', 'localmoney'],
            isCurrencyValue = currencyFields.indexOf(currentActiveLine) > -1,
            format = (isCurrencyValue) ? d3.format(',.2f') : d3.format(',.0f');
    
        return format(value);
    }
    
    function RenderInterval(dataLineChartStat)
    {
        var dataPeriod = dataLineChartStat['period'];

        dataTable = dataLineChartStat;

        // Добавляем строку "Итого":
        $row = $('<tr style="font-weight: bold;">');
        $row.append($('<td>').html("Итого"));
        activeLines.forEach(function(item){
            currentActiveLine = item;
            
            var totalValue = 0;
            for(var i = dataPeriod.length-1; i >= 0; i--) {
                totalValue += dataTable[item][i];
            }

            $row.append($('<td>').html(valueFormat(totalValue)));
        });
        $row.appendTo($tableContent);
        
        // Сортировка строк в таблице:
        var
            sortField = false,
            $selectedField = $('#table-line thead th b.selected'),
            isDesc = true;
        
        if ($selectedField.length > 0) {
            sortField = $selectedField.attr('id');
            isDesc = $selectedField.hasClass('desc');
        }
        
        if (sortField) {
            
            //console.log('AAA sortField = ', sortField);
            //console.log('AAA dataTable = ', dataTable);
            
            var dataTableForSort = [];
            
            dataTable.period.forEach(function(dataTableItem, ind){
                var dataTableSortItem = {};
                dataTableSortItem['period'] = dataTableItem;
                activeLines.forEach(function(activeLine){
                    currentActiveLine = activeLine;
                    dataTableSortItem[activeLine] = valueFormat(dataTable[activeLine][ind]);
                });
                dataTableForSort.push(dataTableSortItem);
            });
            
            dataTableForSort.sort(function(a,b){
                if (isDesc) {
                    return b[sortField]-a[sortField];
                } else {
                    return a[sortField]-b[sortField];
                }
            });
            //console.log('AAA dataTableForSort = ', dataTableForSort);
            
            dataTableForSort.forEach(function(item){

                $row = $('<tr>');
                $row.append($('<td>').html(item['period']));
                activeLines.forEach(function(line){
                    $row.append($('<td>').html(item[line]));
                });
                $row.appendTo($tableContent);
                
            });
            
        } else {
            
            for(var i = 0; i < dataPeriod.length; i++) {

                var
                    date = dataPeriod[i],
                    values = {};

                activeLines.forEach(function(activeLine){
                    currentActiveLine = activeLine;
                    values[activeLine] = valueFormat(dataTable[activeLine][i]);
                });

                $row = $('<tr>');
                $row.append($('<td>').html(date));
                activeLines.forEach(function(item){
                    $row.append($('<td>').html(values[item]));
                });
                $row.appendTo($tableContent);
            }
        }
        
    }
    
    $.extend({
        TableStat: {
            Render: function(dataLineChartStat) {
                
                // Формируем список переключателей (категорий) activeLines:
                activeLines = [];
                $('thead.metric.sortable th b.cat', $table).each(function(){
                    activeLines.push($(this).attr('id'));
                });
               
                //console.log('AAA TableStat render: ', dataLineChartStat);
                //console.log('AAA activeLines: ', activeLines);

                dataTable = {};
                activeLines.forEach(function(item){
                    dataTable[item] = [];
                });

                if (dataLineChartStat.type == 'interval') {
                    RenderInterval(dataLineChartStat);
                }

                $tableBody.html('').append($tableContent.children());
                
            },
            // Определяем список категорий, отмеченных галочками в таблице:
            CheckedCategories: function() {
                var listCats = [];
                $('thead.metric.sortable th input[type="checkbox"]', $table).each(function(){
                    if ($(this).is(":checked")) {
                        listCats.push($(this).data('field'));
                    }
                });
                return listCats;
            },
            
        }
    });

});

