$(document).ready(function(){

    var
        selectorGraphChartStat = '#chart-graph-stat',
        selectorActiveLine = '.b-filter__switch.current-metric .m-filter__switch-item_active',
        selectorActiveTime = '.b-filter__switch.time .m-filter__switch-item_active',
        selectorActiveDays = '.b-filter__switch.days .m-filter__switch-item_active',
        selectorActiveData = '.b-filter__switch.metric-data .m-filter__switch-item_active',
        activeLine = $(selectorActiveLine).data('filter-category'),
        activeTime,
        activeDays,
        timeInterval = [],
        toggelDates = [],
        selectedCategoriesId = [],
        weekDatesDataStart,
        colorsActiveLines = {
            'shows' : '#2CA02C',
            'clicks' : '#D62728',
            'transactions' : '#1F77B4',
            'salemoney' : '#FF7F0E',
            'admoney' : '#9467BD' 
        };
        
    // Временные интервалы для отображения на оси:
    for (var i = 0; i < 24; i++) {
        timeInterval.push(pad(i) + ':00');
    }
    
        
    // Добавление впереди 0 у однозначных значений
    function pad(number) {
        var r = String(number);
        if ( r.length === 1 ) {
          r = '0' + r;
        }
        return r;
    }
    
    // Форматирование даты
    function formatDate(date)
    {
        return date.getFullYear() +'-'+ pad(date.getMonth()+1) +'-'+ pad(date.getDate());
    }
    
    // Форматирование времени
    function formatTime(time)
    {
        return pad(time.getHours()) +':'+ pad(time.getMinutes());
    }
    
    function valueFormat(value, ratio, id)
    {
        var
            currencyFields = ['admoney', 'salemoney', 'usdollarmoney', 'localmoney'],
            isCurrencyValue = currencyFields.indexOf(activeLine) > -1,
            format = (isCurrencyValue) ? d3.format(',.2f') : d3.format(',.0f');
        
        if (parseFloat(format(value)) == 0 && value != 0) {
            var accuracy = Math.abs(Math.floor(Math.log10(value)));
            return value.toFixed(accuracy);
        }
        
        return format(value);
    }
    
    function valueFormatTick(value)
    {
        var
            currencyFields = ['admoney', 'salemoney'],
            isCurrencyValue = currencyFields.indexOf(activeLine) > -1,
            format = (isCurrencyValue) ? d3.format(',.2f') : d3.format(',.0f');
    
        return format(value);
    }
    
    function formatDateMonth(value)
    {
        var monthes = ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'];
        return monthes[value.getMonth()];
    }
    
    function formatDateWeek(value)
    {
        var
            monthes = ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'],
            startWeekDay = new Date(value),
            currentDay = value.getDay(),
            diff = (currentDay == 0) ? 6 : currentDay-1;
        
        startWeekDay.setDate(value.getDate() - diff);
        if (weekDatesDataStart.getTime() - startWeekDay.getTime() > 0) {
            startWeekDay = weekDatesDataStart;
        }
        return startWeekDay.getDate() + monthes[startWeekDay.getMonth()] + '-' + value.getDate() + monthes[value.getMonth()];
    }
    
    function toggleData(chart, id)
    {
        chart.toggle(id);
        if (toggelDates.indexOf(id)<0) {
            toggelDates.push(id)
        } else {
            delete toggelDates[toggelDates.indexOf(id)];
        }
        
    }
    
    $.extend({
        ChartStat: {
            DateStat: function(dataLineChartStat) {
                
                var activeLines = ['shows', 'clicks', 'transactions', 'salemoney', 'admoney'];
                activeLine = 'shows';
                
                //console.log('AAA DateStat: ', dataLineChartStat);

                // Диапазон дат:
                if (dataLineChartStat.type == 'interval') {

                    var
                        dataPeriod,
                        dataValue,
                        rotateX = null,
                        titleFormat = formatDate,
                        formatTimeX = '%m-%d';

                    dataPeriod = dataLineChartStat['period'];
                    
                    var
                        dataColumnsTemp = [['x'].concat(dataPeriod)],
                        names = {},
                        types = {},
                        axes = {},
                        colors = {};

                    // Определяем названия в легенде:
                    var selectedCategoriesId = $.TableStat.CheckedCategories();
                    //console.log('AAA selectedCategoriesId = ', selectedCategoriesId);
                    for (var i = 1; i <= activeLines.length; i++) {
                        var currentActiveLine = activeLines[i-1];
                        if (!selectedCategoriesId || selectedCategoriesId.length == 0 || selectedCategoriesId.indexOf(currentActiveLine) > -1) {
                            dataColumnsTemp.push(['data'+i].concat(dataLineChartStat[currentActiveLine]));
                            names['data'+i] = currentActiveLine,
                            types['data'+i] = 'area-spline';
                            axes['data'+i] = 'y';
                            colors['data'+i] = colorsActiveLines[currentActiveLine];
                        }
                        
                    }

                    //console.log('AAA dataColumnsTemp ', dataColumnsTemp);

                    var chart = c3.generate({
                        bindto: selectorGraphChartStat,
                        data: {
                            x: 'x',
                            //xFormat: '%H:%M',
                            columns: dataColumnsTemp,
                            names: names,
                            types: types,
                            axes: axes,
                            colors: colors,
                            /*
                            colors: {
                                data: '#2ca02c',
                            },*/
                        },
                        axis: {
                            x: {
                                type: 'timeseries',
                                categories: dataPeriod,
                                padding: {left: 0},
                                tick: {
                                    culling: {max: 25},
                                    format: formatTimeX,
                                    rotate: rotateX
                                }
                            },
                            y: {
                                min: 0,
                                padding: {top: 50, bottom: 0},
                                tick: {
                                    format: valueFormatTick
                                }
                            }
                        },
                        grid: {
                            x: {show: true},
                            y: {show: true},
                        },
                        tooltip: {
                            format: {
                                title: titleFormat,
                                value: valueFormat
                            }
                        },
                        legend: {
                            show: true,
                            item: {
                                onclick: function (id) {
                                    //toggleData(chart, id);
                                }
                            }
                        },
                    });

                    // Подсвечиваем Определяем индексы воскресенья:
                    if (activeDays == 'day') {
                        dataPeriod.forEach(function(date, ind) {
                            if ((new Date(date)).getUTCDay() == 0) {
                                $('.c3-axis.c3-axis-x .tick').eq(ind).attr('class', 'tick sunday');
                            }
                        });
                    }
                    
                    chart.toggle(toggelDates);
                }
                
            },
        }
    });

});
