$(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 = [],
        weekDatesDataStart,
        specialFields = $.ReportsConf.SpecialFields,
        percentsFields = $.ReportsConf.PercentsFields,
        notCategoryIdFields = $.ReportsConf.NotCategoryIdFields;
        
    // Временные интервалы для отображения на оси:
    for (var i = 0; i < 24; i++) {
        timeInterval.push(pad(i) + ':00');
    }
    
    /*
    for (var i = 0; i < 288; i++) {
        var time = new Date(i * 1000 * 60 * 5);
        timeInterval.push(pad(time.getUTCHours()) +':'+ pad(time.getMinutes()));
    }
    */
        
    // Добавление впереди 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 = $.ReportsConf.CurrencyFields,
            isCurrencyValue = currencyFields.indexOf(activeLine) > -1,
            format = (isCurrencyValue) ? d3.format(',.2f') : d3.format(',.0f');
            
        if (['cpm', 'siteCpm', 'systemCpm'].indexOf(activeLine) > -1) {
            format = d3.format(',.3f');
        }
        
        if (percentsFields.indexOf(activeLine)>=0) {
            format = d3.format(".2%");
        }
    
        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 = $.ReportsConf.CurrencyFields,
            isCurrencyValue = currencyFields.indexOf(activeLine) > -1,
            format = (isCurrencyValue) ? d3.format(',.2f') : d3.format(',.0f');
        
        if (activeLine == 'cpm') {
            format = d3.format(',.3f');
        }
        
        if (percentsFields.indexOf(activeLine)>=0) {
            format = d3.format(".2%");
        }
    
        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.getMonth()+1) +'/'+ pad(startWeekDay.getDate()) + '-' + (value.getMonth()+1) +'/'+ pad(value.getDate());
        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: {
            ProviderStat: function(dataLineChartStat) {
                
                activeLine = $(selectorActiveLine).data('filter-category'),
                activeTime = $(selectorActiveTime).data('filter-category');
                activeDays = $(selectorActiveDays).data('filter-category');
            
                //console.log('AAA ProviderStat: ', dataLineChartStat);
                //console.log('AAA activeLine: ', activeLine, '   activeTime: ', activeTime);
                
                var providers = [];
                for (var key in dataLineChartStat) {
                    if (['period','metric','type'].indexOf(key)<0) providers.push(key);
                }
                
                var
                    dataPeriod,
                    dataValue = [],
                    dataColumnsTemp,
                    names = {},
                    types = {},
                    axes = {},
                    showPoint = false;
                
                if (dataLineChartStat.type == 'interval') { // compare
                    
                    var
                        rotateX = null,
                        titleFormat = formatDate,
                        formatTimeX = '%m-%d';
                    
                    showPoint = true;
                    
                    if (activeDays == 'day') {
                        dataPeriod = dataLineChartStat['period'];
                        for (var i = 0; i < providers.length; i++) {
                            dataValue.push(dataLineChartStat[providers[i]][activeLine]);
                        }
                    }
                    
                    if (activeDays == 'week') {
                        weekDatesDataStart = new Date(dataLineChartStat['period'][0]);
                        formatTimeX = formatDateWeek;
                        titleFormat = formatDateWeek;
                        
                        var
                            i,j,
                            sumInterval,
                            weekDay,
                            isLastWeekDay,
                            dataCorrectTime = [];
                        
                        for (i = 0; i < dataLineChartStat['period'].length; i++) {
                            weekDay = (new Date(dataLineChartStat['period'][i])).getUTCDay();
                            isLastWeekDay = (weekDay == 0 || (i == dataLineChartStat['period'].length -1 && (weekDay != 0)));
                            
                            if (isLastWeekDay) {
                                dataCorrectTime.push(dataLineChartStat['period'][i]);
                            }
                        }
                        dataPeriod = dataCorrectTime;
                        
                        for (var i = 0; i < providers.length; i++) {
                            dataCorrectTime = [];
                            if (specialFields.indexOf(activeLine)>=0)
                            {
                                var
                                    calcParams = $.ReportsConf.GetCalculationParams(dataLineChartStat['metric'], activeLine),
                                    koef = calcParams['k'],
                                    fieldNum = calcParams['n'],
                                    fieldDen = calcParams['d'],
                                    sumNum = 0,
                                    sumDen = 0;
                                
                                for (j = 0; j < dataLineChartStat[providers[i]][activeLine].length; j++) {
                                    weekDay = (new Date(dataLineChartStat['period'][j])).getUTCDay();
                                    isLastWeekDay = (weekDay == 0 || (j == dataLineChartStat['period'].length -1 && (weekDay != 0)));
                                    
                                    sumNum += dataLineChartStat[providers[i]][fieldNum][j];
                                    sumDen += dataLineChartStat[providers[i]][fieldDen][j];

                                    if (isLastWeekDay) {
                                        dataCorrectTime.push((sumDen==0) ? 0 : sumNum/sumDen*koef);
                                        sumNum = 0;
                                        sumDen = 0;
                                    }
                                }
                                
                            }
                            else
                            {
                                sumInterval = 0;
                                for (j = 0; j < dataLineChartStat[providers[i]][activeLine].length; j++) {
                                    sumInterval += dataLineChartStat[providers[i]][activeLine][j];
                                    weekDay = (new Date(dataLineChartStat['period'][j])).getUTCDay();
                                    isLastWeekDay = (weekDay == 0 || (j == dataLineChartStat['period'].length -1 && (weekDay != 0)));
                                    if (isLastWeekDay) {
                                        dataCorrectTime.push(sumInterval);
                                        sumInterval = 0;
                                    }
                                }
                            }
                            dataValue.push(dataCorrectTime);
                        }
                        
                    }
                    
                    if (activeDays == 'month') {
                        formatTimeX = formatDateMonth;
                        titleFormat = formatDateMonth;
                        
                        var
                            i,j,
                            sumInterval,
                            weekDay,
                            lastDayInMonth,
                            isLastDayInMonth,
                            dataCorrectTime = [];
                        
                        for (i = 0; i < dataLineChartStat['period'].length; i++) {
                            weekDay = new Date(dataLineChartStat['period'][i]);
                            lastDayInMonth = new Date(weekDay.getYear(), weekDay.getMonth() + 1, 0).getDate();
                            isLastDayInMonth = ((weekDay.getDate() == lastDayInMonth) || ((i == dataLineChartStat['period'].length - 1) && (weekDay.getDate() != lastDayInMonth)));
                            
                            if (isLastDayInMonth) {
                                dataCorrectTime.push(dataLineChartStat['period'][i]);
                            }
                            
                        }
                        dataPeriod = dataCorrectTime;
                        
                        for (var i = 0; i < providers.length; i++) {
                            dataCorrectTime = [];
                            if (specialFields.indexOf(activeLine)>=0)
                            {
                                var
                                    calcParams = $.ReportsConf.GetCalculationParams(dataLineChartStat['metric'], activeLine),
                                    koef = calcParams['k'],
                                    fieldNum = calcParams['n'],
                                    fieldDen = calcParams['d'],
                                    sumNum = 0,
                                    sumDen = 0;
                                
                                for (j = 0; j < dataLineChartStat[providers[i]][activeLine].length; j++) {
                                    weekDay = new Date(dataLineChartStat['period'][j]);
                                    lastDayInMonth = new Date(weekDay.getYear(), weekDay.getMonth() + 1, 0).getDate();
                                    isLastDayInMonth = ((weekDay.getDate() == lastDayInMonth) || ((j == dataLineChartStat['period'].length - 1) && (weekDay.getDate() != lastDayInMonth)));

                                    sumNum += dataLineChartStat[providers[i]][fieldNum][j];
                                    sumDen += dataLineChartStat[providers[i]][fieldDen][j];

                                    if (isLastDayInMonth) {
                                        dataCorrectTime.push((sumDen==0) ? 0 : sumNum/sumDen*koef);
                                        sumNum = 0;
                                        sumDen = 0;
                                    }
                                }
                            }
                            else
                            {
                                sumInterval = 0;
                                for (j = 0; j < dataLineChartStat[providers[i]][activeLine].length; j++) {
                                    sumInterval += dataLineChartStat[providers[i]][activeLine][j];
                                    weekDay = new Date(dataLineChartStat['period'][j]);
                                    lastDayInMonth = new Date(weekDay.getYear(), weekDay.getMonth() + 1, 0).getDate();
                                    isLastDayInMonth = ((weekDay.getDate() == lastDayInMonth) || ((j == dataLineChartStat['period'].length - 1) && (weekDay.getDate() != lastDayInMonth)));

                                    if (isLastDayInMonth) {
                                        dataCorrectTime.push(sumInterval);
                                        sumInterval = 0;
                                    }
                                }
                            }
                            dataValue.push(dataCorrectTime);
                        }
                        
                    }
                    
                   
                    dataColumnsTemp = [['x'].concat(dataPeriod)];
                    
                    for (var i = 1; i <= providers.length; i++) {
                        dataColumnsTemp.push(['data'+i].concat(dataValue[i-1]));
                        names['data'+i] = providers[i-1];
                        types['data'+i] = 'area';
                        axes['data'+i] = 'y';
                    }

                    var chart = c3.generate({
                        bindto: selectorGraphChartStat,
                        data: {
                            x: 'x',
                            //xFormat: '%H:%M',
                            columns: dataColumnsTemp,
                            names: names,
                            types: types,
                            axes: axes,
                            colors: {
                                data1: '#2ca02c',
                                data2: '#ff0000'
                            }
                        },
                        axis: {
                            x: {
                                type: 'timeseries',
                                padding: {left: 0},
                                tick: {
                                    culling: {max: 25},
                                    format: formatTimeX,
                                    rotate: rotateX
                                }
                            },
                            y: {
                                min: 0,
                                padding: {top: 50, bottom: 0},
                                tick: {
                                    format: valueFormatTick
                                },
                            }
                        },
                        point: {show: showPoint},
                        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');
                            }
                        });
                    }
                }
                
                if (dataLineChartStat.type == 'day') {
                    
                    if (activeTime == 'hour')
                    {
                        //console.log('AAA преобразуем часовой интервал: ', dataLineChartBidStat);
                        var i,j;
                        var sumInterval;
                        var dataCorrectTime = [];

                        showPoint = true;

                        for (i = 0; i < dataLineChartStat['period'].length; i++) {
                            if (i % 12 == 0) {
                                dataCorrectTime.push(dataLineChartStat['period'][i]);
                            }
                        }
                        dataPeriod = dataCorrectTime;

                        for (i = 0; i < providers.length; i++) {
                            dataCorrectTime = [];
                            if (specialFields.indexOf(activeLine)>=0)
                            {
                                var
                                    calcParams = $.ReportsConf.GetCalculationParams(dataLineChartStat['metric'], activeLine),
                                    koef = calcParams['k'],
                                    fieldNum = calcParams['n'],
                                    fieldDen = calcParams['d'],
                                    sumNum = 0,
                                    sumDen = 0;
                            
                                for (j = 0; j < dataLineChartStat[providers[i]][activeLine].length; j++) {
                                    
                                    sumNum += dataLineChartStat[providers[i]][fieldNum][j];
                                    sumDen += dataLineChartStat[providers[i]][fieldDen][j];
                                    
                                    if ((j+1) % 12 == 0) {
                                        dataCorrectTime.push((sumDen==0) ? 0 : sumNum/sumDen*koef);
                                        sumNum = 0;
                                        sumDen = 0;
                                    }
                                }
                                
                            }
                            else
                            {
                                sumInterval = 0;
                                for (j = 0; j < dataLineChartStat[providers[i]][activeLine].length; j++) {
                                    sumInterval += dataLineChartStat[providers[i]][activeLine][j]*5;
                                    if ((j+1) % 12 == 0) {
                                        dataCorrectTime.push(sumInterval);
                                        sumInterval = 0;
                                    }
                                }
                            }
                            dataValue[i] = dataCorrectTime;
                        }

                    }
                    else
                    {
                        dataPeriod = dataLineChartStat['period'];
                        for (i = 0; i < providers.length; i++) {
                            dataValue[i] = dataLineChartStat[providers[i]][activeLine];
                        }
                    }

                    dataColumnsTemp = [['x'].concat(dataPeriod)];
                    
                    for (var i = 1; i <= providers.length; i++) {
                        dataColumnsTemp.push(['data'+i].concat(dataValue[i-1]));
                        names['data'+i] = providers[i-1];
                        types['data'+i] = 'area';
                        axes['data'+i] = 'y';
                    }


                    var chart = c3.generate({
                        bindto: selectorGraphChartStat,
                        data: {
                            x: 'x',
                            xFormat: '%H:%M',
                            columns: dataColumnsTemp,
                            names: names,
                            types: types,
                            axes: axes,
                            colors: {
                                data1: '#2ca02c',
                                data2: '#ff0000'
                            },
                        },
                        axis: {
                            x: {
                                type: 'timeseries',
                                min: "00:00",
                                max: "24:00",
                                padding: {left: 0},
                                tick: {
                                    //culling: {max: 25},
                                    //count: 25,
                                    //fit: true,
                                    format: '%H:%M',
                                    values: timeInterval,
                                    //outer: false
                                }
                            },
                            y: {
                                min: 0,
                                padding: {top: 50, bottom: 0},
                                tick: {
                                    //format: axisY1format
                                    format: valueFormatTick
                                },
                            }
                        },
                        point: {show: showPoint},
                        grid: {
                            x: {show: true},
                            y: {show: true},
                        },
                        tooltip: {
                            format: {
                                title: formatTime,
                                value: valueFormat
                            }
                        },
                        legend: {
                            show: true,
                            item: {
                                onclick: function (id) {
                                    toggleData(chart, id);
                                }
                            }
                        },
                    });
                    
                }
                
                chart.toggle(toggelDates);
            },
            DateStat: function(dataLineChartStat) {
                
                activeLine = $(selectorActiveLine).data('filter-category');
                activeTime = $(selectorActiveTime).data('filter-category');
                activeDays = $(selectorActiveDays).data('filter-category');
                
                if (dataLineChartStat.metric == 'minstat') {
                    var activeData = $(selectorActiveData).data('filter-category');
                    //console.log('AAA activeData: ', activeData);
                    if (activeLine == 'money') {
                        if (activeData == 'sum') activeLine = 'sspMoney';
                        if (activeData == 'site') activeLine = 'sspSiteMoney';
                        if (activeData == 'system') activeLine = 'sspSystemMoney';
                    }
                    if (activeLine == 'ratio') {
                        if (activeData == 'sum') activeLine = 'sumRatio';
                        if (activeData == 'site') activeLine = 'siteRatio';
                        if (activeData == 'system') activeLine = 'systemRatio';
                    }
                    if (activeLine == 'cpm') {
                        if (activeData == 'sum') activeLine = 'cpm';
                        if (activeData == 'site') activeLine = 'siteCpm';
                        if (activeData == 'system') activeLine = 'systemCpm';
                    }
                    if (activeLine == 'cpc') {
                        if (activeData == 'sum') activeLine = 'cpc';
                        if (activeData == 'site') activeLine = 'siteCpc';
                        if (activeData == 'system') activeLine = 'systemCpc';
                    }
                }
                
                //console.log('AAA DateStat: ', dataLineChartStat);
                //console.log('AAA activeLine: ', activeLine, '   activeTime: ', activeTime);

                // Данные для графиков сравнения (две даты):
                if (dataLineChartStat.type == 'compare') {
                    
                    var days = [];
                    for (var key in dataLineChartStat) {
                        if (['period','metric','type'].indexOf(key)<0) days.push(key);
                    }

                    var
                        today = new Date(),
                        yesterday = new Date(today - 1*24*60*60*1000),
                        dbyesterday = new Date(today - 2*24*60*60*1000),
                        todayDate = formatDate(today),
                        yesterdayDate = formatDate(yesterday),
                        dbyesterdayDate = formatDate(dbyesterday),
                        dataPeriod,
                        dataValue = [],
                        showPoint = false;

                    if (activeTime == 'hour')
                    {
                        //console.log('AAA преобразуем часовой интервал: ', dataLineChartStat);
                        var i,j;
                        var sumInterval;
                        var dataCorrectTime = [];

                        showPoint = true;

                        for (i = 0; i < dataLineChartStat['period'].length; i++) {
                            if (i % 12 == 0) {
                                dataCorrectTime.push(dataLineChartStat['period'][i]);
                            }
                        }
                        dataPeriod = dataCorrectTime;

                        for (i = 0; i < days.length; i++) {
                            dataCorrectTime = [];
                            if (specialFields.indexOf(activeLine)>=0)
                            {
                                var
                                    calcParams = $.ReportsConf.GetCalculationParams(dataLineChartStat['metric'], activeLine),
                                    koef = calcParams['k'],
                                    fieldNum = calcParams['n'],
                                    fieldDen = calcParams['d'],
                                    sumRunCnt = 0,
                                    sumLoadCnt = 0;
                                
                                for (j = 0; j < dataLineChartStat[days[i]][activeLine].length; j++) {
                                    
                                    sumRunCnt += dataLineChartStat[days[i]][fieldNum][j];
                                    sumLoadCnt += dataLineChartStat[days[i]][fieldDen][j];
                                    
                                    if ((j+1) % 12 == 0) {
                                        dataCorrectTime.push((sumLoadCnt==0) ? 0 : sumRunCnt/sumLoadCnt*koef);
                                        sumRunCnt = 0;
                                        sumLoadCnt = 0;
                                    }
                                }
                            }
                            else
                            {
                                sumInterval = 0;
                                for (j = 0; j < dataLineChartStat[days[i]][activeLine].length; j++) {
                                    sumInterval += dataLineChartStat[days[i]][activeLine][j]*5;
                                    if ((j+1) % 12 == 0) {
                                        dataCorrectTime.push(sumInterval);
                                        sumInterval = 0;
                                    }
                                }
                            }
                            dataValue[i] = dataCorrectTime;
                        }

                    }
                    else
                    {
                        dataPeriod = dataLineChartStat['period'];
                        for (i = 0; i < days.length; i++) {
                            dataValue[i] = dataLineChartStat[days[i]][activeLine];
                        }
                    }

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

                    // Определяем названия в легенде:
                    for (var i = 1; i <= days.length; i++) {
                        dataColumnsTemp.push(['data'+i].concat(dataValue[i-1]));
                        if (days[i-1] == dbyesterdayDate) {
                            names['data'+i] = 'Позавчера';
                        } else if (days[i-1] == yesterdayDate) {
                            names['data'+i] = 'Вчера';
                        } else if (days[i-1] == todayDate) {
                            names['data'+i] = 'Сегодня';
                        } else {
                            names['data'+i] = days[i-1];
                        }
                        types['data'+i] = 'area';
                        axes['data'+i] = 'y';
                    }

                    // http://c3js.org/reference.html
                    var chart = c3.generate({
                        bindto: selectorGraphChartStat,
                        data: {
                            x: 'x',
                            xFormat: '%H:%M',
                            columns: dataColumnsTemp,
                            names: names,
                            types: types,
                            axes: axes,
                            colors: {
                                data1: '#2ca02c',
                                data2: '#ff0000'
                            }
                        },
                        axis: {
                            x: {
                                type: 'timeseries',
                                min: "00:00",
                                max: "24:00",
                                padding: {left: 0},
                                tick: {
                                    //culling: {max: 25},
                                    //count: 25,
                                    format: '%H:%M',
                                    values: timeInterval,
                                }
                            },
                            y: {
                                min: 0,
                                padding: {top: 50, bottom: 0},
                                tick: {
                                    format: valueFormatTick
                                },
                            }
                        },
                        point: {show: showPoint},
                        grid: {
                            x: {show: true},
                            y: {show: true},
                        },
                        tooltip: {
                            format: {
                                title: formatTime,
                                value: valueFormat
                            }
                        },
                        legend: {show: true},
                    });
                }

                // Данные в пределах одних суток:
                if (dataLineChartStat.type == 'day') {

                    var dataPeriod;
                    var dataValue;
                    var showPoint = false;

                    if (activeTime == 'hour')
                    {
                        //console.log('AAA преобразуем часовой интервал: ', dataLineChartStat);
                        var i,j;
                        var sumInterval;
                        var dataCorrectTime = [];

                        showPoint = true;

                        for (i = 0; i < dataLineChartStat['period'].length; i++) {
                            if (i % 12 == 0) {
                                dataCorrectTime.push(dataLineChartStat['period'][i]);
                            }
                        }
                        dataPeriod = dataCorrectTime;

                        dataCorrectTime = [];
                        
                        if (specialFields.indexOf(activeLine)>=0)
                        {
                            var
                                calcParams = $.ReportsConf.GetCalculationParams(dataLineChartStat['metric'], activeLine),
                                koef = calcParams['k'],
                                fieldNum = calcParams['n'],
                                fieldDen = calcParams['d'],
                                sumRunCnt = 0,
                                sumLoadCnt = 0;
                            
                            for (j = 0; j < dataLineChartStat[activeLine].length; j++) {
                                
                                sumRunCnt += dataLineChartStat[fieldNum][j];
                                sumLoadCnt += dataLineChartStat[fieldDen][j];
                                
                                if ((j+1) % 12 == 0) {
                                    dataCorrectTime.push((sumLoadCnt==0) ? 0 : sumRunCnt/sumLoadCnt*koef);
                                    sumRunCnt = 0;
                                    sumLoadCnt = 0;
                                }
                            }
                            
                        }
                        else
                        {
                            sumInterval = 0;
                            for (j = 0; j < dataLineChartStat[activeLine].length; j++) {
                                sumInterval += dataLineChartStat[activeLine][j]*5;
                                if ((j+1) % 12 == 0) {
                                    dataCorrectTime.push(sumInterval);
                                    sumInterval = 0;
                                }
                            }
                        }
                        dataValue = dataCorrectTime;

                    }
                    else
                    {
                        dataPeriod = dataLineChartStat['period'];
                        dataValue = dataLineChartStat[activeLine];
                    }

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

                    // Определяем названия в легенде:
                    dataColumnsTemp.push(['data'].concat(dataValue));
                    names['data'] = activeLine;
                    types['data'] = 'area';
                    axes['data'] = 'y';

                    var chart = c3.generate({
                        bindto: selectorGraphChartStat,
                        data: {
                            x: 'x',
                            xFormat: '%H:%M',
                            columns: dataColumnsTemp,
                            names: names,
                            types: types,
                            axes: axes,
                            colors: {
                                data: '#2ca02c',
                            }
                        },
                        axis: {
                            x: {
                                type: 'timeseries',
                                min: "00:00",
                                max: "24:00",
                                padding: {left: 0},
                                tick: {
                                    //culling: {max: 25},
                                    //count: 25
                                    //fit: true,
                                    format: '%H:%M',
                                    values: timeInterval
                                }
                            },
                            y: {
                                min: 0,
                                padding: {top: 50, bottom: 0},
                                tick: {
                                    format: valueFormatTick
                                }
                            }
                        },
                        point: {show: showPoint},
                        grid: {
                            x: {show: true},
                            y: {show: true},
                        },
                        tooltip: {
                            format: {
                                title: formatTime,
                                value: valueFormat
                            }
                        },
                        legend: {show: false},
                    });
                }

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

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

                    if (activeDays == 'day') {
                        dataPeriod = dataLineChartStat['period'];
                        dataValue = dataLineChartStat[activeLine];
                    }
                    
                    if (activeDays == 'week') {
                        
                        weekDatesDataStart = new Date(dataLineChartStat['period'][0]);
                        formatTimeX = formatDateWeek;
                        titleFormat = formatDateWeek;
                        //rotateX = 90;
                        
                        var
                            i,j,
                            sumInterval,
                            weekDay,
                            isLastWeekDay,
                            dataCorrectTime = [];
                        
                        for (i = 0; i < dataLineChartStat['period'].length; i++) {
                            weekDay = (new Date(dataLineChartStat['period'][i])).getUTCDay();
                            isLastWeekDay = (weekDay == 0 || (i == dataLineChartStat['period'].length -1 && (weekDay != 0)));
                            
                            if (isLastWeekDay) {
                                dataCorrectTime.push(dataLineChartStat['period'][i]);
                            }
                        }
                        dataPeriod = dataCorrectTime;
                        
                        dataCorrectTime = [];
                        
                        if (specialFields.indexOf(activeLine)>=0)
                        {
                            var
                                calcParams = $.ReportsConf.GetCalculationParams(dataLineChartStat['metric'], activeLine),
                                koef = calcParams['k'],
                                fieldNum = calcParams['n'],
                                fieldDen = calcParams['d'],
                                sumRunCnt = 0,
                                sumLoadCnt = 0;
                            
                            for (j = 0; j < dataLineChartStat[activeLine].length; j++) {
                                weekDay = (new Date(dataLineChartStat['period'][j])).getUTCDay();
                                isLastWeekDay = (weekDay == 0 || (j == dataLineChartStat['period'].length -1 && (weekDay != 0)));
                                sumRunCnt += dataLineChartStat[fieldNum][j];
                                sumLoadCnt += dataLineChartStat[fieldDen][j];
                                
                                if (isLastWeekDay) {
                                    dataCorrectTime.push((sumLoadCnt==0) ? 0 : sumRunCnt/sumLoadCnt*koef);
                                    sumRunCnt = 0;
                                    sumLoadCnt = 0;
                                }
                            }
                        }
                        else
                        {
                            sumInterval = 0;
                            for (j = 0; j < dataLineChartStat[activeLine].length; j++) {
                                sumInterval += dataLineChartStat[activeLine][j];
                                weekDay = (new Date(dataLineChartStat['period'][j])).getUTCDay();
                                isLastWeekDay = (weekDay == 0 || (j == dataLineChartStat['period'].length -1 && (weekDay != 0)));
                                if (isLastWeekDay) {
                                    dataCorrectTime.push(sumInterval);
                                    sumInterval = 0;
                                }
                            }
                        }
                        dataValue = dataCorrectTime;
                    }
                    
                    if (activeDays == 'month') {
                        
                        formatTimeX = formatDateMonth;
                        titleFormat = formatDateMonth;
                        
                        var
                            i,j,
                            sumInterval,
                            weekDay,
                            lastDayInMonth,
                            isLastDayInMonth,
                            dataCorrectTime = [];
                        
                        for (i = 0; i < dataLineChartStat['period'].length; i++) {
                            weekDay = new Date(dataLineChartStat['period'][i]);
                            lastDayInMonth = new Date(weekDay.getYear(), weekDay.getMonth() + 1, 0).getDate();
                            isLastDayInMonth = ((weekDay.getDate() == lastDayInMonth) || ((i == dataLineChartStat['period'].length - 1) && (weekDay.getDate() != lastDayInMonth)));
                            
                            if (isLastDayInMonth) {
                                dataCorrectTime.push(dataLineChartStat['period'][i]);
                            }
                            
                        }
                        dataPeriod = dataCorrectTime;
                        
                        dataCorrectTime = [];
                        
                        if (specialFields.indexOf(activeLine)>=0)
                        {
                            var
                                calcParams = $.ReportsConf.GetCalculationParams(dataLineChartStat['metric'], activeLine),
                                koef = calcParams['k'],
                                fieldNum = calcParams['n'],
                                fieldDen = calcParams['d'],
                                sumRunCnt = 0,
                                sumLoadCnt = 0;
                                                        
                            for (j = 0; j < dataLineChartStat[activeLine].length; j++) {
                                weekDay = new Date(dataLineChartStat['period'][j]);
                                lastDayInMonth = new Date(weekDay.getYear(), weekDay.getMonth() + 1, 0).getDate();
                                isLastDayInMonth = ((weekDay.getDate() == lastDayInMonth) || ((j == dataLineChartStat['period'].length - 1) && (weekDay.getDate() != lastDayInMonth)));
                                sumRunCnt += dataLineChartStat[fieldNum][j];
                                sumLoadCnt += dataLineChartStat[fieldDen][j];
                                
                                if (isLastDayInMonth) {
                                    dataCorrectTime.push((sumLoadCnt==0) ? 0 : sumRunCnt/sumLoadCnt*koef);
                                    sumRunCnt = 0;
                                    sumLoadCnt = 0;
                                }
                            }
                        }
                        else
                        {
                            sumInterval = 0;
                            for (j = 0; j < dataLineChartStat[activeLine].length; j++) {
                                sumInterval += dataLineChartStat[activeLine][j];
                                weekDay = new Date(dataLineChartStat['period'][j]);
                                lastDayInMonth = new Date(weekDay.getYear(), weekDay.getMonth() + 1, 0).getDate();
                                isLastDayInMonth = ((weekDay.getDate() == lastDayInMonth) || ((j == dataLineChartStat['period'].length - 1) && (weekDay.getDate() != lastDayInMonth)));
                                
                                if (isLastDayInMonth) {
                                    dataCorrectTime.push(sumInterval);
                                    sumInterval = 0;
                                }
                            }
                        }
                        dataValue = dataCorrectTime;
                        
                    }

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

                    // Определяем названия в легенде:
                    dataColumnsTemp.push(['data'].concat(dataValue));
                    names['data'] = activeLine;
                    types['data'] = 'area';
                    axes['data'] = 'y';

                    var chart = c3.generate({
                        bindto: selectorGraphChartStat,
                        data: {
                            x: 'x',
                            //xFormat: '%H:%M',
                            columns: dataColumnsTemp,
                            names: names,
                            types: types,
                            axes: axes,
                            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: false},
                    });

                    // Подсвечиваем Определяем индексы воскресенья:
                    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');
                            }
                        });
                    }
                }
                
            },
            CategoryStat: function(dataLineChartStat) {
                
                var dataStat = {};
                for (var key in dataLineChartStat) {
                   dataStat[key] = dataLineChartStat[key];
                }
                
                activeLine = $(selectorActiveLine).data('filter-category'),
                activeTime = $(selectorActiveTime).data('filter-category');
                activeDays = $(selectorActiveDays).data('filter-category');
            
                if (dataLineChartStat.metric == 'minstat') {
                    var activeData = $(selectorActiveData).data('filter-category');
                    //console.log('AAA activeData: ', activeData);
                    if (activeLine == 'money') {
                        if (activeData == 'sum') activeLine = 'sspMoney';
                        if (activeData == 'site') activeLine = 'sspSiteMoney';
                        if (activeData == 'system') activeLine = 'sspSystemMoney';
                    }
                    if (activeLine == 'ratio') {
                        if (activeData == 'sum') activeLine = 'sumRatio';
                        if (activeData == 'site') activeLine = 'siteRatio';
                        if (activeData == 'system') activeLine = 'systemRatio';
                    }
                    if (activeLine == 'cpm') {
                        if (activeData == 'sum') activeLine = 'cpm';
                        if (activeData == 'site') activeLine = 'siteCpm';
                        if (activeData == 'system') activeLine = 'systemCpm';
                    }
                    if (activeLine == 'cpc') {
                        if (activeData == 'sum') activeLine = 'cpc';
                        if (activeData == 'site') activeLine = 'siteCpc';
                        if (activeData == 'system') activeLine = 'systemCpc';
                    }
                }
            
                //console.log('AAA SiteStat: ', dataStat);
                //console.log('AAA activeLine: ', activeLine, '   activeTime: ', activeTime, '   activeDays: ', activeDays);
                
                var
                    byCategory = $.ReportsConf.GetCategoryType(dataLineChartStat),
                    sites = [],
                    listCategories = $.TableStat.CheckedCategories();
                
                if ($.TableStat.GetSiteState())
                {
                    Object.keys(dataStat).forEach(function(zoneId){
                        if (notCategoryIdFields.indexOf(zoneId) < 0) {
                            var zoneData = dataStat[zoneId];
                            var zoneViews = 0;
                            var zoneClicks = 0;
                            zoneData['sspClicksCnt'].forEach(function(item){
                                zoneClicks += item;
                            });
                            zoneData['sspViewsCnt'].forEach(function(item){
                                zoneViews += item;
                            });
                            if (!(zoneClicks==0 && zoneViews<5)) {
                                sites.push(zoneId);
                            }
                        }
                    });
                }
                else
                {
                    if (listCategories)
                    {
                        listCategories.forEach(function(siteId){
                            // Проверяем наличие siteId (выбранного сайта в таблице) в полученных данных:
                            if (dataStat[siteId]) {
                                sites.push(siteId);
                            }
                        });
                    }
                    if (!listCategories || sites.length == 0)
                    {
                        var dataCommonSites = {};
                        var catsAdded = false;
                        for (var siteId in dataStat) {
                            if (notCategoryIdFields.indexOf(siteId)<0) {
                                // Добавляем категории:
                                if (!catsAdded) {
                                    for (var cat in dataStat[siteId]) {
                                        dataCommonSites[cat] = [];
                                        dataStat[siteId][cat].forEach(function(){
                                            dataCommonSites[cat].push(0);
                                        });
                                    }
                                    catsAdded = true;
                                }

                                for (var cat in dataStat[siteId]) {
                                    dataStat[siteId][cat].forEach(function(item, i){
                                        dataCommonSites[cat][i] += item;
                                    });
                                }
                            };
                        }
                        sites.push('common');
                        dataStat['common'] = dataCommonSites;
                    }
                }
                
                var
                    dataPeriod,
                    dataValue = [],
                    dataColumnsTemp,
                    names = {},
                    types = {},
                    axes = {},
                    showPoint = false;
                
                if (dataStat.type == 'interval') {
                    
                    var
                        rotateX = null,
                        titleFormat = formatDate,
                        formatTimeX = '%m-%d';
                    
                    showPoint = true;
                    
                    if (activeDays == 'day')
                    {
                        dataPeriod = dataStat['period'];
                        for (var i = 0; i < sites.length; i++) {
                            dataValue.push(dataStat[sites[i]][activeLine]);
                        }
                    }
                    
                    if (activeDays == 'week')
                    {
                        weekDatesDataStart = new Date(dataStat['period'][0]);
                        formatTimeX = formatDateWeek;
                        titleFormat = formatDateWeek;
                        
                        var
                            i,j,
                            sumInterval,
                            weekDay,
                            isLastWeekDay,
                            dataCorrectTime = [];
                        
                        for (i = 0; i < dataStat['period'].length; i++) {
                            weekDay = (new Date(dataStat['period'][i])).getUTCDay();
                            isLastWeekDay = (weekDay == 0 || (i == dataStat['period'].length -1 && (weekDay != 0)));
                            
                            if (isLastWeekDay) {
                                dataCorrectTime.push(dataStat['period'][i]);
                            }
                        }
                        dataPeriod = dataCorrectTime;
                        
                        for (var i = 0; i < sites.length; i++) {
                            dataCorrectTime = [];
                            if (specialFields.indexOf(activeLine)>=0)
                            {
                                var
                                    calcParams = $.ReportsConf.GetCalculationParams(dataStat['metric'], activeLine),
                                    koef = calcParams['k'],
                                    fieldNum = calcParams['n'],
                                    fieldDen = calcParams['d'],
                                    sumNum = 0,
                                    sumDen = 0;
                                
                                for (j = 0; j < dataStat[sites[i]][activeLine].length; j++) {
                                    weekDay = (new Date(dataStat['period'][j])).getUTCDay();
                                    isLastWeekDay = (weekDay == 0 || (j == dataStat['period'].length -1 && (weekDay != 0)));
                                    
                                    sumNum += dataStat[sites[i]][fieldNum][j];
                                    sumDen += dataStat[sites[i]][fieldDen][j];

                                    if (isLastWeekDay) {
                                        dataCorrectTime.push((sumDen==0) ? 0 : sumNum/sumDen*koef);
                                        sumNum = 0;
                                        sumDen = 0;
                                    }
                                }
                                
                            }
                            else
                            {
                                sumInterval = 0;
                                for (j = 0; j < dataStat[sites[i]][activeLine].length; j++) {
                                    sumInterval += dataStat[sites[i]][activeLine][j];
                                    weekDay = (new Date(dataStat['period'][j])).getUTCDay();
                                    isLastWeekDay = (weekDay == 0 || (j == dataStat['period'].length -1 && (weekDay != 0)));
                                    if (isLastWeekDay) {
                                        dataCorrectTime.push(sumInterval);
                                        sumInterval = 0;
                                    }
                                }
                            }
                            dataValue.push(dataCorrectTime);
                        }
                        
                    }
                    
                    if (activeDays == 'month')
                    {
                        formatTimeX = formatDateMonth;
                        titleFormat = formatDateMonth;
                        
                        var
                            i,j,
                            sumInterval,
                            weekDay,
                            lastDayInMonth,
                            isLastDayInMonth,
                            dataCorrectTime = [];
                        
                        for (i = 0; i < dataStat['period'].length; i++) {
                            weekDay = new Date(dataStat['period'][i]);
                            lastDayInMonth = new Date(weekDay.getYear(), weekDay.getMonth() + 1, 0).getDate();
                            isLastDayInMonth = ((weekDay.getDate() == lastDayInMonth) || ((i == dataStat['period'].length - 1) && (weekDay.getDate() != lastDayInMonth)));
                            
                            if (isLastDayInMonth) {
                                dataCorrectTime.push(dataStat['period'][i]);
                            }
                            
                        }
                        dataPeriod = dataCorrectTime;
                        
                        for (var i = 0; i < sites.length; i++) {
                            dataCorrectTime = [];
                            if (specialFields.indexOf(activeLine)>=0)
                            {
                                var
                                    calcParams = $.ReportsConf.GetCalculationParams(dataStat['metric'], activeLine),
                                    koef = calcParams['k'],
                                    fieldNum = calcParams['n'],
                                    fieldDen = calcParams['d'],
                                    sumNum = 0,
                                    sumDen = 0;
                                
                                for (j = 0; j < dataStat[sites[i]][activeLine].length; j++) {
                                    weekDay = new Date(dataStat['period'][j]);
                                    lastDayInMonth = new Date(weekDay.getYear(), weekDay.getMonth() + 1, 0).getDate();
                                    isLastDayInMonth = ((weekDay.getDate() == lastDayInMonth) || ((j == dataStat['period'].length - 1) && (weekDay.getDate() != lastDayInMonth)));

                                    sumNum += dataStat[sites[i]][fieldNum][j];
                                    sumDen += dataStat[sites[i]][fieldDen][j];

                                    if (isLastDayInMonth) {
                                        dataCorrectTime.push((sumDen==0) ? 0 : sumNum/sumDen*koef);
                                        sumNum = 0;
                                        sumDen = 0;
                                    }
                                }
                            }
                            else
                            {
                                sumInterval = 0;
                                for (j = 0; j < dataStat[sites[i]][activeLine].length; j++) {
                                    sumInterval += dataStat[sites[i]][activeLine][j];
                                    weekDay = new Date(dataStat['period'][j]);
                                    lastDayInMonth = new Date(weekDay.getYear(), weekDay.getMonth() + 1, 0).getDate();
                                    isLastDayInMonth = ((weekDay.getDate() == lastDayInMonth) || ((j == dataStat['period'].length - 1) && (weekDay.getDate() != lastDayInMonth)));

                                    if (isLastDayInMonth) {
                                        dataCorrectTime.push(sumInterval);
                                        sumInterval = 0;
                                    }
                                }
                            }
                            dataValue.push(dataCorrectTime);
                        }
                        
                    }
                   
                    dataColumnsTemp = [['x'].concat(dataPeriod)];
                    
                    for (var i = 1; i <= sites.length; i++) {
                        dataColumnsTemp.push(['data'+i].concat(dataValue[i-1]));
                        if (dataLineChartStat.bySites) {
                            names['data'+i] = dataLineChartStat[byCategory][sites[i-1]] || 'Суммарно';
                        }
                        if (dataLineChartStat.byZones) {
                            names['data'+i] = (dataLineChartStat[byCategory][sites[i-1]]) ? sites[i-1] + '-' + dataLineChartStat[byCategory][sites[i-1]] : 'Суммарно';
                        }
                        if (dataLineChartStat.byCountries) {
                            if (sites[i-1] == 'common') {
                                names['data'+i] = 'Суммарно';
                            } else {
                                names['data'+i] = (dataLineChartStat[byCategory][sites[i-1]]) ? dataLineChartStat[byCategory][sites[i-1]] : sites[i-1];
                            }
                        }
                        types['data'+i] = 'area';
                        axes['data'+i] = 'y';
                    }

                    var chart = c3.generate({
                        bindto: selectorGraphChartStat,
                        data: {
                            x: 'x',
                            //xFormat: '%H:%M',
                            columns: dataColumnsTemp,
                            names: names,
                            types: types,
                            axes: axes,
                            colors: {
                                data1: '#2ca02c',
                                data2: '#ff0000'
                            }
                        },
                        axis: {
                            x: {
                                type: 'timeseries',
                                padding: {left: 0},
                                tick: {
                                    culling: {max: 25},
                                    format: formatTimeX,
                                    rotate: rotateX
                                }
                            },
                            y: {
                                min: 0,
                                padding: {top: 50, bottom: 0},
                                tick: {
                                    format: valueFormatTick
                                },
                            }
                        },
                        point: {show: showPoint},
                        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');
                            }
                        });
                    }
                }
                
                if (dataStat.type == 'day') {
                    
                    if (activeTime == 'hour')
                    {
                        //console.log('AAA преобразуем часовой интервал: ', dataLineChartBidStat);
                        var i,j;
                        var sumInterval;
                        var dataCorrectTime = [];

                        showPoint = true;

                        for (i = 0; i < dataStat['period'].length; i++) {
                            if (i % 12 == 0) {
                                dataCorrectTime.push(dataStat['period'][i]);
                            }
                        }
                        dataPeriod = dataCorrectTime;

                        for (i = 0; i < sites.length; i++) {
                            dataCorrectTime = [];
                            if (specialFields.indexOf(activeLine)>=0)
                            {
                                var
                                    calcParams = $.ReportsConf.GetCalculationParams(dataStat['metric'], activeLine),
                                    koef = calcParams['k'],
                                    fieldNum = calcParams['n'],
                                    fieldDen = calcParams['d'],
                                    sumNum = 0,
                                    sumDen = 0;
                            
                                for (j = 0; j < dataStat[sites[i]][activeLine].length; j++) {
                                    
                                    sumNum += dataStat[sites[i]][fieldNum][j];
                                    sumDen += dataStat[sites[i]][fieldDen][j];
                                    
                                    if ((j+1) % 12 == 0) {
                                        dataCorrectTime.push((sumDen==0) ? 0 : sumNum/sumDen*koef);
                                        sumNum = 0;
                                        sumDen = 0;
                                    }
                                }
                                
                            }
                            else
                            {
                                sumInterval = 0;
                                for (j = 0; j < dataStat[sites[i]][activeLine].length; j++) {
                                    sumInterval += dataStat[sites[i]][activeLine][j]*5;
                                    if ((j+1) % 12 == 0) {
                                        dataCorrectTime.push(sumInterval);
                                        sumInterval = 0;
                                    }
                                }
                            }
                            dataValue[i] = dataCorrectTime;
                        }

                    }
                    else
                    {
                        dataPeriod = dataStat['period'];
                        for (i = 0; i < sites.length; i++) {
                            dataValue[i] = dataStat[sites[i]][activeLine];
                        }
                    }

                    dataColumnsTemp = [['x'].concat(dataPeriod)];
                    
                    for (var i = 1; i <= sites.length; i++) {
                        dataColumnsTemp.push(['data'+i].concat(dataValue[i-1]));
                        names['data'+i] = dataLineChartStat[byCategory][sites[i-1]] || 'Суммарно';
                        types['data'+i] = 'area';
                        axes['data'+i] = 'y';
                    }

                    var chart = c3.generate({
                        bindto: selectorGraphChartStat,
                        data: {
                            x: 'x',
                            xFormat: '%H:%M',
                            columns: dataColumnsTemp,
                            names: names,
                            types: types,
                            axes: axes,
                            colors: {
                                data1: '#2ca02c',
                                data2: '#ff0000'
                            },
                        },
                        axis: {
                            x: {
                                type: 'timeseries',
                                min: "00:00",
                                max: "24:00",
                                padding: {left: 0},
                                tick: {
                                    //culling: {max: 25},
                                    //count: 25,
                                    //fit: true,
                                    format: '%H:%M',
                                    values: timeInterval,
                                    //outer: false
                                }
                            },
                            y: {
                                min: 0,
                                padding: {top: 50, bottom: 0},
                                tick: {
                                    //format: axisY1format
                                    format: valueFormatTick
                                },
                            }
                        },
                        point: {show: showPoint},
                        grid: {
                            x: {show: true},
                            y: {show: true},
                        },
                        tooltip: {
                            format: {
                                title: formatTime,
                                value: valueFormat
                            }
                        },
                        legend: {
                            show: true,
                            item: {
                                onclick: function (id) {
                                    toggleData(chart, id);
                                }
                            }
                        },
                    });
                    
                }
                
                chart.toggle(toggelDates);
            },
        }
    });

});
