$(document).ready(function(){

    var
        $table = $('#table-line'),
        $tableContent = $('<tbody>'),
        $tableBody = $table.find('tbody').first(),
        activeLines = [],
        currentActiveLine,
        dataTable,
        currencyFields = ['admoney', 'salemoney', 'usdollarmoney', 'localmoney', 'AdMoney', 'OrderSum'],
        notFormatFields = ['Timestamp', 'Basket'];
        
    // Шаблон содержимого ячейки Basket
    var templateBasketContent = _.template('\n'+
    
    '       <div class="b-basket-content">   \n' +
    '       <table>   \n' +
    '           <tbody>   \n' +
    '           <% _.each(data, function(item) { %>   \n' +
    '               <tr>   \n' +
    '                   <td><a class="basket-link" href="<%=item.URL %>" target="_blank"><%=item.Title %></a></td>   \n' +
    '                   <td><span class="quantity"><%=item.Quantity %></span></td>   \n' +
    '                   <td><span class="price"><%=item.Price %> грн.</span></td>   \n' +
    '               </tr>   \n' +
    '           <% }) %>  \n' +
    '           </tbody>   \n' +
    '       </table>   \n' +
    '       </div>  \n' +
    
    
    '');
    
    var templateTimestampContent = _.template('\n'+
    '           <b><%=data.time %></b><br />   \n' +
    '           <span><%=data.date %></span><br />   \n' +
    '');
    
    
    
    function valueFormat(value)
    {
        var
            isCurrencyValue = currencyFields.indexOf(currentActiveLine) > -1,
            isNonFormatValue = notFormatFields.indexOf(currentActiveLine) > -1,
            format = (isCurrencyValue) ? d3.format(',.0f') : d3.format(',.0f');
    
        if (isNonFormatValue) {
            return value;
        }
    
        if (isCurrencyValue) {
            return format(value) + ' грн.';
        } else {
            return format(value);
        }
    }
    
    function RenderInterval(dataLineChartStat)
    {
        var dataPeriod = dataLineChartStat['period'];

        dataTable = dataLineChartStat;

        // Добавляем строку "Итого":
        if (!dataLineChartStat.report == 'transaction') {
        
            $row = $('<tr style="font-weight: bold;">');
            $row.append($('<td>').html("Итого"));
            activeLines.forEach(function(item){
                currentActiveLine = item;

                var isNotSumValue = notFormatFields.indexOf(currentActiveLine) > -1;

                if (!isNotSumValue) {
                    var totalValue = 0;
                    for(var i = dataPeriod.length-1; i >= 0; i--) {
                        totalValue += dataTable[item][i];
                    }
                } else {
                    totalValue = '';
                }

                $row.append($('<td>').html(valueFormat(totalValue)));
            });
            $row.appendTo($tableContent);

        }
        
        // Сортировка строк в таблице:
        var
            $selectedField = $('#table-line thead th b.selected'),
            sortField = false,
            isDesc = true;
        
        if ($selectedField.length > 0) {
            sortField = $selectedField.attr('id');
            isDesc = $selectedField.hasClass('desc');
        }
        
        if (sortField) {
            
            //console.log('AAA sortField = ', sortField, '  isDesc = ', isDesc);
            //console.log('AAA dataTable = ', dataTable);
            
            var dataTableForSort = [];
            
            dataTable.period.forEach(function(dataTableItem, ind){
                var dataTableSortItem = {};
                dataTableSortItem['period'] = dataTableItem;
                activeLines.forEach(function(activeLine){
                    dataTableSortItem[activeLine] = dataTable[activeLine][ind];
                });
                dataTableForSort.push(dataTableSortItem);
            });
            
            //console.log('AAA dataTableForSort 111= ', dataTableForSort);
            dataTableForSort.sort(function(a,b){
                
                if (sortField == 'Timestamp') {
                    
                    var
                        aT = new Date(a[sortField]),
                        bT = new Date(b[sortField]);
                    
                    return (isDesc) ? bT-aT : aT-bT;
                    
                } else {
                    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){
                    if (line == 'Basket') {
                        $row.append($('<td class="'+ line +'">').append(templateBasketContent({data: item[line]})));
                    } else if (line == 'Timestamp') {
                        var
                            dateTimeValue = item[line].split(' '),
                            dateVal = dateTimeValue[0],
                            timeVal = dateTimeValue[1].split(':'),
                            timeValCorrected = timeVal[0]+':'+timeVal[1];
                        
                        $row.append($('<td class="'+ line +'">').append(templateTimestampContent({
                            data: {date: dateVal, time: timeValCorrected}
                        })));
                        
                    } else {
                        currentActiveLine = line;
                        $row.append($('<td class="'+ line +'">').html(valueFormat(item[line])));
                    }
                });
                $row.appendTo($tableContent);
            });
            
        } else {
            
            for(var i = dataPeriod.length-1; i >= 0; 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){
                    if (item == 'Basket') {
                        $row.append($('<td class="'+ item +'">').append(templateBasketContent({data: values[item]})));
                    } else if (item == 'Timestamp') {
                        var
                            dateTimeValue = values[item].split(' '),
                            dateVal = dateTimeValue[0],
                            timeVal = dateTimeValue[1].split(':'),
                            timeValCorrected = timeVal[0]+':'+timeVal[1];
                        
                        $row.append($('<td class="'+ item +'">').append(templateTimestampContent({
                            data: {date: dateVal, time: timeValCorrected}
                        })));
                    } else {
                        $row.append($('<td class="'+ item +'">').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);
                }

                if (dataLineChartStat.report == 'transaction') {
                    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;
            },
            
        }
    });

});

