$(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'),
        activeLines,
        //activeTime,
        activeDays,
        toggelDates = [],
        //selectedCategoriesId = [],
        weekDatesDataStart,
        colorsActiveLines = $(selectorGraphChartStat).data('colors');
        
        
    // Добавление впереди 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 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)];
        }
        
    }
    
    var chart;
    
    $.extend({
        ChartStat: {
            DateStat: function(dataLineChartStat) {
                //console.log('AAA DateStat: ', dataLineChartStat);
                
                //activeLines = ['shows', 'clicks', 'transactions', 'salemoney', 'admoney'];
                //activeLine = 'shows';
                if (dataLineChartStat.report == 'common') {
                    activeLines = ['Views', 'Clicks', 'Orders', 'OrderSum', 'AdMoney'];
                    activeLine = 'Views';
                }

                // Диапазон дат:
                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);
                    // Скрываем график, если в таблице не выбраны категории:
                    if (selectedCategoriesId.length == 0) {
                        $(selectorGraphChartStat).hide();
                        return false;
                    } else {
                        $(selectorGraphChartStat).show();
                    }
                    
                    for (var i = 1; i <= activeLines.length; i++) {
                        var currentActiveLine = activeLines[i-1];
                        if (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({
                    chart = c3.generate({
                        bindto: selectorGraphChartStat,
                        data: {
                            x: 'x',
                            //xFormat: '%H:%M',
                            columns: dataColumnsTemp,
                            names: names,
                            types: types,
                            axes: axes,
                            colors: colors,
                        },
                        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: false,
                            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);
                }
                
            },
            ToggleCats: function(toggelDates) {
                chart.toggle(toggelDates);
            }
            
        }
    });

});
