var ID_VIEW_DATA = document.getElementById("clientIdGoogleAps").getAttribute("data-gaViewId");
var TOKEN = document.getElementById("clientIdGoogleAps").getAttribute("data-token");

var DATA_START = document.getElementById("clientIdGoogleAps").getAttribute("data-dateStart");
var DATA_END = document.getElementById("clientIdGoogleAps").getAttribute("data-dateEnd");

if(DATA_START != '' && DATA_END != ''){
    var SET_INFO = {query: {
        'start-date': DATA_START,
        'end-date': DATA_END,
        'ids': 'ga:'+ID_VIEW_DATA,
    }};
} else {
    var currentDate = new Date();
    var year = currentDate.getFullYear();
    var month = currentDate.getMonth() + 1;
    var monthStart = new Date(year, month-1, 1);
    var monthEnd = new Date(year, month, 1);
    var monthLength = Math.round((monthEnd - monthStart) / (1000 * 60 * 60 * 24));
    $('#from').val(year + '-' + month + '-01');
    $('#to').val(year + '-' + month + '-' + monthLength);
    if(month < 10){
        month = '0' + month;
    }
    var SET_INFO = {query: {
        'start-date': year + '-' + month + '-01',
        'end-date': year + '-' + month + '-' + monthLength,
        'ids': 'ga:'+ID_VIEW_DATA,
    }};
}

//console.log(SET_INFO);
// Pobiera daty:
$( function() {
    $( "#datepicker" ).datepicker({
        defaultDate: DATA_START,
        dateFormat: "yy-mm-dd",
        maxDate: 'today',
        onChangeMonthYear: function (year, month) {
            var DATE_YEAR = year;
            var DATE_MONTH = month;
            if(DATE_MONTH < 10){
                DATE_MONTH = '0' + DATE_MONTH;
            }
            var monthStart2 = new Date(year, month-1, 1);
            var monthEnd2 = new Date(year, month, 1);
            var monthLength2 = Math.round(((monthEnd2) - (monthStart2)) / (1000 * 60 * 60 * 24));
           // var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
            var dataStart = DATE_YEAR + '-' + DATE_MONTH + '-01';
            var dataEnd = DATE_YEAR + '-' + DATE_MONTH + '-' + monthLength2;
            $('#from').val(dataStart).prop('readonly', true);
            $('#to').val(dataEnd).prop('readonly', true);
            $('.dateFromToForm').submit();
        }
    });

    var dateFormat = "yy-mm-dd",
        from = $( "#from" )
            .datepicker({
                dateFormat: "yy-mm-dd",
                defaultDate: "-1m",
                changeMonth: true,
                numberOfMonths: 1,
                maxDate: 'today',
            })
            .on( "change", function() {
                to.datepicker( "option", "minDate", getDate( this ) );
            }),
        to = $( "#to" ).datepicker({
            dateFormat: "yy-mm-dd",
            defaultDate: "+1d",
            changeMonth: true,
            numberOfMonths: 1,
            maxDate: 'today',
        })
            .on( "change", function() {
                from.datepicker( "option", "maxDate", getDate( this ) );
            });

    function getDate( element ) {
        var date;
        try {
            date = $.datepicker.parseDate( dateFormat, element.value );
        } catch( error ) {
            date = null;
        }

        return date;
    }
} );


// Pobieranie statystyk
(function(w,d,s,g,js,fjs){
    g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
    js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
    js.src='https://apis.google.com/js/platform.js';
    fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));



gapi.analytics.ready(function() {
    if ((TOKEN != '') && ( ID_VIEW_DATA != '')) {
        gapi.analytics.auth.authorize({
            serverAuth: {
                access_token: TOKEN
            }
        });

        var sessionLiczba = new gapi.analytics.googleCharts.DataChart({
            reportType: 'ga',
            query: {
                'metrics': 'ga:sessions'
            },
            chart: {
                'container': 'sessions-liczba',
                'type': 'TABLE',
                'options': {}
            }
        });
        var usersLiczba = new gapi.analytics.googleCharts.DataChart({
            reportType: 'ga',
            query: {
                'metrics': 'ga:users'
            },
            chart: {
                'container': 'users-liczba',
                'type': 'TABLE',
                'options': {}
            }
        });
        var pageviewsLiczba = new gapi.analytics.googleCharts.DataChart({
            reportType: 'ga',
            query: {
                'metrics': 'ga:pageviews'
            },
            chart: {
                'container': 'pageviews-liczba',
                'type': 'TABLE',
                'options': {}
            }
        });
        var bounceRateLiczba = new gapi.analytics.googleCharts.DataChart({
            reportType: 'ga',
            query: {
                'metrics': 'ga:bounceRate',
            },
            chart: {
                'container': 'bounceRate-liczba',
                'type': 'TABLE',
                'options': {},
            },
        });
        var sessionWykres = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions, ga:organicSearches',
                'dimensions': 'ga:date'
            },
            chart: {
                'container': 'sessions-wykres',
                'type': 'LINE',
                'options': {
                    'width': '100%',
                    series: {
                        0: {},
                        1: {color: '#8bba13'},
                    },

                }
            }
        });


        var channelGroupingWykres = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions',
                'dimensions': 'ga:channelGrouping'
            },
            chart: {
                'container': 'channelGrouping-wykres',
                'type': 'PIE',
                'options': {
                    'sliceVisibilityThreshold': '.01',
                    pieHole: 4 / 9,
                    'slices': {
                        0: {offset: 0, color: '#bbbbbb'},
                        1: {offset: 0.05, color: '#8bba13'},
                        2: {offset: 0, color: '#ff9900'},
                        3: {offset: 0, color: '#dc3912'},
                    },
                },
            }
        });

        var channelGroupingTabela = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions,ga:percentNewSessions,ga:newUsers, ga:bounceRate, ga:bounces, ga:totalEvents, ga:goalCompletionsAll',
                'dimensions': 'ga:channelGrouping',
            },
            chart: {
                'container': 'channelGrouping-tabela',
                'type': 'TABLE',
                'options': {
                    'title': 'Porównanie kanałów',
                }
            }
        });

        var campaignGroupingTabela = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions,ga:percentNewSessions,ga:newUsers, ga:bounceRate, ga:bounces, ga:totalEvents, ga:goalCompletionsAll',
                'dimensions': 'ga:campaign',
            },
            chart: {
                'container': 'campaignGrouping-tabela',
                'type': 'TABLE',
                'options': {
                    'title': 'Porównanie kampani',
                }
            }
        });

        var sessionSEOLiczba = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions, ga:users, ga:pageviews, ga:hits',
                'filters': 'ga:medium==organic',
            },
            chart: {
                'container': 'sessionsSEO-liczba',
                'type': 'TABLE',
                'options': {}
            }
        });

        var sessionPaidLiczba = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions, ga:users, ga:pageviews, ga:hits',
                'filters': 'ga:medium==cpc',
            },
            chart: {
                'container': 'sessionsPaid-liczba',
                'type': 'TABLE',
                'options': {}
            }
        });

        var sessionSocialLiczba = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions, ga:users, ga:pageviews, ga:hits',
                'filters': 'ga:channelGrouping==Social',
            },
            chart: {
                'container': 'sessionsSocial-liczba',
                'type': 'TABLE',
                'options': {}
            }
        });

        var sessionEmailLiczba = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions, ga:users, ga:pageviews, ga:hits',
                'filters': 'ga:medium==email',
            },
            chart: {
                'container': 'sessionsEmail-liczba',
                'type': 'TABLE',
                'options': {}
            }
        });

        var sessionDirectLiczba = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions, ga:users, ga:pageviews, ga:hits',
                'filters': 'ga:medium==(none)',
            },
            chart: {
                'container': 'sessionsDirect-liczba',
                'type': 'TABLE',
                'options': {}
            }
        });

        var sessionReferralLiczba = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions, ga:users, ga:pageviews, ga:hits',
                'filters': 'ga:medium==referral',
            },
            chart: {
                'container': 'sessionsReferral-liczba',
                'type': 'TABLE',
                'options': {}
            }
        });

        var usersSwiatMapa = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:users',
                'dimensions': 'ga:country',
                'sort': '-ga:users',
            },
            chart: {
                'container': 'usersSwiat-mapa',
                'type': 'GEO',
                'options': {
                    'title': 'mapka',
                    'displayMode': 'region',
                    'width': '100%',
                    'height': 'auto',
                }
            }
        });

        var usersPolskaMapa = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:users',
                'dimensions': 'ga:region',
                'filters': 'ga:countryIsoCode==PL',
                'sort': '-ga:users',
            },
            chart: {
                'container': 'usersPolska-mapa',
                'type': 'GEO',
                'options': {
                    'title': 'mapka',
                    'displayMode': 'region',
                    'region': 'PL',
                    'resolution': 'provinces',
                    'width': '100%',
                    'height': 'auto',
                    //'enableRegionInteractivity': 'true',
                    //'colorAxis': {colors: ['green', 'blue']},
                    //'sizeAxis': { minValue: 0, maxValue: 50 },
                }
            }
        });

        var sessionsPolskaTabela = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:users, ga:sessions, ga:bounceRate, ga:totalEvents, ga:goalCompletionsAll',
                'dimensions': 'ga:city',
                'filters': 'ga:countryIsoCode==PL',
                'sort': '-ga:sessions',
            },
            chart: {
                'container': 'sessionsPolska-tabela',
                'type': 'TABLE',
                'options': {}
            }
        });

        var sessionsSwiatTabela = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:users, ga:sessions, ga:bounceRate, ga:totalEvents, ga:goalCompletionsAll',
                'dimensions': 'ga:country',
                'sort': '-ga:sessions',
            },
            chart: {
                'container': 'sessionsSwiat-tabela',
                'type': 'TABLE',
                'options': {}
            }
        });

        var devicesWykres = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions',
                'dimensions': 'ga:deviceCategory'
            },
            chart: {
                'container': 'devices-wykres',
                'type': 'PIE',
                'options': {
                    'sliceVisibilityThreshold': '.01',
                    pieHole: 4 / 9,
                    'slices': {
                        0: {offset: 0, color: '#3366cc'},
                        1: {offset: 0, color: '#dc3912'},
                    },
                },
            }
        });

        var devicesTabela = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions,ga:percentNewSessions,ga:newUsers, ga:bounceRate, ga:bounces, ga:totalEvents, ga:goalCompletionsAll',
                'dimensions': 'ga:deviceCategory',
            },
            chart: {
                'container': 'devices-tabela',
                'type': 'TABLE',
                'options': {
                    'title': 'Porównanie kanałów',
                }
            }
        });

        var sessionMobileWykres = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions, ga:bounces',
                'dimensions': 'ga:date',
                'segments': 'gaid::-11',
            },
            chart: {
                'container': 'sessionMobile-wykres',
                'type': 'LINE',
                'options': {
                    'width': '100%',
                    series: {
                        0: {},
                        1: {color: '#dc3912'},
                    },

                }
            }
        });

        var devicesModelTabela = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions,ga:percentNewSessions,ga:newUsers, ga:bounceRate, ga:bounces',
                'dimensions': 'ga:mobileDeviceInfo',
                'sort': '-ga:sessions',
            },
            chart: {
                'container': 'devicesModel-tabela',
                'type': 'TABLE',
                'options': {}
            }
        });

        var browserTabela = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions,ga:percentNewSessions,ga:newUsers, ga:bounceRate, ga:bounces',
                'dimensions': 'ga:browser',
                'sort': '-ga:sessions',
            },
            chart: {
                'container': 'browser-tabela',
                'type': 'TABLE',
                'options': {}
            }
        });

        var browserSizeTabela = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions,ga:percentNewSessions,ga:newUsers, ga:bounceRate, ga:bounces',
                'dimensions': 'ga:browserSize',
                'sort': '-ga:sessions',
            },
            chart: {
                'container': 'browserSize-tabela',
                'type': 'TABLE',
                'options': {}
            }
        });

        var landingPageTabela = new gapi.analytics.googleCharts.DataChart({
            query: {
                'metrics': 'ga:sessions, ga:pageviews, ga:pageviewsPerSession, ga:percentNewSessions, ga:newUsers, ga:bounceRate, ga:bounces, ga:hits, ga:totalEvents, ga:goalCompletionsAll',
                'dimensions': 'ga:landingPagePath',
                'sort': '-ga:sessions',
            },
            chart: {
                'container': 'landingPage-tabela',
                'type': 'TABLE',
                'options': {}
            }
        });


        setTimeout(function () {
            pageviewsLiczba.set(SET_INFO).execute();
            sessionLiczba.set(SET_INFO).execute();
            bounceRateLiczba.set(SET_INFO).execute();
            usersLiczba.set(SET_INFO).execute();
            sessionWykres.set(SET_INFO).execute();

            setTimeout(function () {
                channelGroupingWykres.set(SET_INFO).execute();
                channelGroupingTabela.set(SET_INFO).execute();
                campaignGroupingTabela.set(SET_INFO).execute();
            }, 2000);

            setTimeout(function () {
                sessionSEOLiczba.set(SET_INFO).execute();
                sessionPaidLiczba.set(SET_INFO).execute();
                sessionSocialLiczba.set(SET_INFO).execute();
                sessionEmailLiczba.set(SET_INFO).execute();
                sessionDirectLiczba.set(SET_INFO).execute();
                sessionReferralLiczba.set(SET_INFO).execute();
            }, 4000);

            setTimeout(function () {
                devicesWykres.set(SET_INFO).execute();
                devicesTabela.set(SET_INFO).execute();
                sessionMobileWykres.set(SET_INFO).execute();
                devicesModelTabela.set(SET_INFO).execute();
                browserTabela.set(SET_INFO).execute();
                browserSizeTabela.set(SET_INFO).execute();
            }, 6000);

            setTimeout(function () {
                sessionsPolskaTabela.set(SET_INFO).execute();
                sessionsSwiatTabela.set(SET_INFO).execute();
                setTimeout(function () {
                    usersSwiatMapa.set(SET_INFO).execute();
                    usersPolskaMapa.set(SET_INFO).execute();
                }, 8000);
            }, 8000);

            setTimeout(function () {
                landingPageTabela.set(SET_INFO).execute();
            }, 11000);

            /* ---------------------------------------- */
            /* Wyłączanie Animacji Wait */
            setTimeout(function () {
                $('#calyRaportWait').hide();
            }, 16000);
        }, 100);
        gapi.analytics.auth.on('error', function (response) {
            $('#calyRaportError').show();
        });

        // Stylowanie tabel
        bounceRateLiczba.on('success', function (result) {
            var odczytanaWartosc = result.data.rows[0].c[0].v;
            var nowaWartosc = odczytanaWartosc.toFixed(2) + ' %';
            $('#bounceRate-liczba table tbody td.google-visualization-table-td-number').html(nowaWartosc);
        });

        channelGroupingTabela.on('success', function (result) {
            $('#channelGrouping-tabela table thead tr:nth-child(1) th:nth-child(1)').html('Channels');
            $('#channelGrouping-tabela table thead tr:nth-child(1) th:nth-child(2)').html('Sessions');
            $('#channelGrouping-tabela table thead tr:nth-child(1) th:nth-child(3)').html('% New sessions');
            $('#channelGrouping-tabela table thead tr:nth-child(1) th:nth-child(4)').html('New <br>users');
            $('#channelGrouping-tabela table thead tr:nth-child(1) th:nth-child(5)').html('Bounce <br>rate');
            $('#channelGrouping-tabela table thead tr:nth-child(1) th:nth-child(6)').html('Bounces');
            $('#channelGrouping-tabela table thead tr:nth-child(1) th:nth-child(7)').html('Events ');
            $('#channelGrouping-tabela table thead tr:nth-child(1) th:nth-child(8)').html('Goals');

            var i = 1;
            $.each(result.data.rows, function (key, value) {
                $('#channelGrouping-tabela table tbody tr:nth-child(' + i + ') td:nth-child(3)').html(value.c[2].v.toFixed(2) + ' %');
                $('#channelGrouping-tabela table tbody tr:nth-child(' + i + ') td:nth-child(5)').html(value.c[4].v.toFixed(2) + ' %');
                i++;
            });

            $('#channelGrouping-tabela table tbody tr:nth-child(1) td:nth-child(1)').prepend('<span class="kolko szare"></span>');
            $('#channelGrouping-tabela table tbody tr:nth-child(1) td:nth-child(1)').attr('title', 'Direct and unidentified inputs');

            $('#channelGrouping-tabela table tbody tr:nth-child(2) td:nth-child(1)').prepend('<span class="kolko zielone"></span>');
            $('#channelGrouping-tabela table tbody tr:nth-child(2) td:nth-child(1)').attr('title', 'Inputs of natural search results (SEO / Positioning)');

            $('#channelGrouping-tabela table tbody tr:nth-child(3) td:nth-child(1)').prepend('<span class="kolko pomaranczowe"></span>');
            $('#channelGrouping-tabela table tbody tr:nth-child(3) td:nth-child(1)').attr('title', 'Entrances from other websites');

            $('#channelGrouping-tabela table tbody tr:nth-child(4) td:nth-child(1)').prepend('<span class="kolko czerwone"></span>');
            $('#channelGrouping-tabela table tbody tr:nth-child(4) td:nth-child(1)').attr('title', 'Inputs from social networks');
        });

        campaignGroupingTabela.on('success', function (result) {
            $('#campaignGrouping-tabela table thead tr:nth-child(1) th:nth-child(1)').html('Channels');
            $('#campaignGrouping-tabela table thead tr:nth-child(1) th:nth-child(2)').html('Sessions');
            $('#campaignGrouping-tabela table thead tr:nth-child(1) th:nth-child(3)').html('% New sessions');
            $('#campaignGrouping-tabela table thead tr:nth-child(1) th:nth-child(4)').html('New <br>users');
            $('#campaignGrouping-tabela table thead tr:nth-child(1) th:nth-child(5)').html('Bounce <br>rate');
            $('#campaignGrouping-tabela table thead tr:nth-child(1) th:nth-child(6)').html('Bounces');
            $('#campaignGrouping-tabela table thead tr:nth-child(1) th:nth-child(7)').html('Events ');
            $('#campaignGrouping-tabela table thead tr:nth-child(1) th:nth-child(8)').html('Goals');

            var i = 0;
            $.each(result.data.rows, function (key, value) {
                i++;
                $('#campaignGrouping-tabela table tbody tr:nth-child(' + i + ') td:nth-child(3)').html(value.c[2].v.toFixed(2) + ' %');
                $('#campaignGrouping-tabela table tbody tr:nth-child(' + i + ') td:nth-child(5)').html(value.c[4].v.toFixed(2) + ' %');
            });

            if (i > 3) {
                $('#raportGA .pokazKampanie').show();
            }
        });

        sessionSEOLiczba.on('success', function (result) {
            $('#sessionsSEO-liczba table thead tr:nth-child(1) th:nth-child(1)').html('Visits');
            $('#sessionsSEO-liczba table thead tr:nth-child(1) th:nth-child(2)').html('Users');
            $('#sessionsSEO-liczba table thead tr:nth-child(1) th:nth-child(3)').html('Open pages');
            $('#sessionsSEO-liczba table thead tr:nth-child(1) th:nth-child(4)').html('Interaction');
        });

        sessionPaidLiczba.on('success', function (result) {
            $('#sessionsPaid-liczba table thead tr:nth-child(1) th:nth-child(1)').html('Visits');
            $('#sessionsPaid-liczba table thead tr:nth-child(1) th:nth-child(2)').html('Users');
            $('#sessionsPaid-liczba table thead tr:nth-child(1) th:nth-child(3)').html('Open pages');
            $('#sessionsPaid-liczba table thead tr:nth-child(1) th:nth-child(4)').html('Interaction');
        });

        sessionSocialLiczba.on('success', function (result) {
            $('#sessionsSocial-liczba table thead tr:nth-child(1) th:nth-child(1)').html('Visits');
            $('#sessionsSocial-liczba table thead tr:nth-child(1) th:nth-child(2)').html('Users');
            $('#sessionsSocial-liczba table thead tr:nth-child(1) th:nth-child(3)').html('Open pages');
            $('#sessionsSocial-liczba table thead tr:nth-child(1) th:nth-child(4)').html('Interaction');
        });

        sessionEmailLiczba.on('success', function (result) {
            $('#sessionsEmail-liczba table thead tr:nth-child(1) th:nth-child(1)').html('Visits');
            $('#sessionsEmail-liczba table thead tr:nth-child(1) th:nth-child(2)').html('Users');
            $('#sessionsEmail-liczba table thead tr:nth-child(1) th:nth-child(3)').html('Open pages');
            $('#sessionsEmail-liczba table thead tr:nth-child(1) th:nth-child(4)').html('Interaction');
        });

        sessionDirectLiczba.on('success', function (result) {
            $('#sessionsDirect-liczba table thead tr:nth-child(1) th:nth-child(1)').html('Visits');
            $('#sessionsDirect-liczba table thead tr:nth-child(1) th:nth-child(2)').html('Users');
            $('#sessionsDirect-liczba table thead tr:nth-child(1) th:nth-child(3)').html('Open pages');
            $('#sessionsDirect-liczba table thead tr:nth-child(1) th:nth-child(4)').html('Interaction');
        });

        sessionReferralLiczba.on('success', function (result) {
            $('#sessionsReferral-liczba table thead tr:nth-child(1) th:nth-child(1)').html('Visits');
            $('#sessionsReferral-liczba table thead tr:nth-child(1) th:nth-child(2)').html('Users');
            $('#sessionsReferral-liczba table thead tr:nth-child(1) th:nth-child(3)').html('Open pages');
            $('#sessionsReferral-liczba table thead tr:nth-child(1) th:nth-child(4)').html('Interaction');
        });

        sessionsPolskaTabela.on('success', function (result) {
            $('#sessionsPolska-tabela table thead tr:nth-child(1) th:nth-child(1)').html('Vity');
            $('#sessionsPolska-tabela table thead tr:nth-child(1) th:nth-child(2)').html('Użytkownicy');
            $('#sessionsPolska-tabela table thead tr:nth-child(1) th:nth-child(3)').html('Sessions');
            $('#sessionsPolska-tabela table thead tr:nth-child(1) th:nth-child(4)').html('Bounce rate');
            $('#sessionsPolska-tabela table thead tr:nth-child(1) th:nth-child(5)').html('Events');
            $('#sessionsPolska-tabela table thead tr:nth-child(1) th:nth-child(6)').html('Goals');
            var i = 1;
            $.each(result.data.rows, function (key, value) {
                $('#sessionsPolska-tabela table tbody tr:nth-child(' + i + ') td:nth-child(4)').html(value.c[3].v.toFixed(2) + ' %');
                i++;
            });
            $('#iloscMiast').html('(total: ' + i + ')');
            if (i > 7) {
                $('#raportGA .pokazMiasta').show();
            }
        });

        sessionsSwiatTabela.on('success', function (result) {
            $('#sessionsSwiat-tabela table thead tr:nth-child(1) th:nth-child(1)').html('Country');
            $('#sessionsSwiat-tabela table thead tr:nth-child(1) th:nth-child(2)').html('Użytkownicy');
            $('#sessionsSwiat-tabela table thead tr:nth-child(1) th:nth-child(3)').html('Session');
            $('#sessionsSwiat-tabela table thead tr:nth-child(1) th:nth-child(4)').html('Bounce rate');
            $('#sessionsSwiat-tabela table thead tr:nth-child(1) th:nth-child(5)').html('Events');
            $('#sessionsSwiat-tabela table thead tr:nth-child(1) th:nth-child(6)').html('Goals');
            var i = 1;
            $.each(result.data.rows, function (key, value) {
                $('#sessionsSwiat-tabela table tbody tr:nth-child(' + i + ') td:nth-child(4)').html(value.c[3].v.toFixed(2) + ' %');
                i++;
            });
            $('#iloscPanstw').html('(total: ' + i + ')');
            if (i > 7) {
                $('#raportGA .pokazPanstwa').show();
            }
        });

        devicesTabela.on('success', function (result) {

            $('#devices-tabela table thead tr:nth-child(1) th:nth-child(1)').html('Devices');
            $('#devices-tabela table thead tr:nth-child(1) th:nth-child(2)').html('Session');
            $('#devices-tabela table thead tr:nth-child(1) th:nth-child(3)').html('% new Sessions');
            $('#devices-tabela table thead tr:nth-child(1) th:nth-child(4)').html('New <br>users');
            $('#devices-tabela table thead tr:nth-child(1) th:nth-child(5)').html('Bounce <br>rate');
            $('#devices-tabela table thead tr:nth-child(1) th:nth-child(6)').html('Bounces');
            $('#devices-tabela table thead tr:nth-child(1) th:nth-child(7)').html('Events');
            $('#devices-tabela table thead tr:nth-child(1) th:nth-child(8)').html('Goals');

            var i = 1;
            $.each(result.data.rows, function (key, value) {
                $('#devices-tabela table tbody tr:nth-child(' + i + ') td:nth-child(3)').html(value.c[2].v.toFixed(2) + ' %');
                $('#devices-tabela table tbody tr:nth-child(' + i + ') td:nth-child(5)').html(value.c[4].v.toFixed(2) + ' %');
                i++;
            });

            $('#devices-tabela table tbody tr:nth-child(1) td:nth-child(1)').prepend('<span class="kolko deviceDesktop"></span>');
            $('#devices-tabela table tbody tr:nth-child(1) td:nth-child(1)').attr('title', 'Inputs from desktops and laptops');

            $('#devices-tabela table tbody tr:nth-child(2) td:nth-child(1)').prepend('<span class="kolko deviceMobile"></span>');
            $('#devices-tabela table tbody tr:nth-child(1) td:nth-child(1)').attr('title', 'Inputs from smartphones');

            $('#devices-tabela table tbody tr:nth-child(3) td:nth-child(1)').prepend('<span class="kolko pomaranczowe"></span>');
            $('#devices-tabela table tbody tr:nth-child(1) td:nth-child(1)').attr('title', 'Inputs from tablets');

        });

        devicesModelTabela.on('success', function (result) {

            $('#devicesModel-tabela table thead tr:nth-child(1) th:nth-child(1)').html('Device model');
            $('#devicesModel-tabela table thead tr:nth-child(1) th:nth-child(2)').html('Session');
            $('#devicesModel-tabela table thead tr:nth-child(1) th:nth-child(3)').html('% New session');
            $('#devicesModel-tabela table thead tr:nth-child(1) th:nth-child(4)').html('New <br>users');
            $('#devicesModel-tabela table thead tr:nth-child(1) th:nth-child(5)').html('Bounce <br>rate');
            $('#devicesModel-tabela table thead tr:nth-child(1) th:nth-child(6)').html('Bounces');

            var i = 1;
            if (typeof result.data.rows !== 'undefined') {
                $.each(result.data.rows, function (key, value) {
                    $('#devicesModel-tabela table tbody tr:nth-child(' + i + ') td:nth-child(3)').html(value.c[2].v.toFixed(2) + ' %');
                    $('#devicesModel-tabela table tbody tr:nth-child(' + i + ') td:nth-child(5)').html(value.c[4].v.toFixed(2) + ' %');
                    i++;
                });
            }

            $('#iloscUrzadzen').html('(total: ' + i + ')');
            if (i > 7) {
                $('#raportGA .pokazUrzadzenia').show();
            }

        });

        browserTabela.on('success', function (result) {

            $('#browser-tabela table thead tr:nth-child(1) th:nth-child(1)').html('Browser');
            $('#browser-tabela table thead tr:nth-child(1) th:nth-child(2)').html('Session');
            $('#browser-tabela table thead tr:nth-child(1) th:nth-child(3)').html('% New session');
            $('#browser-tabela table thead tr:nth-child(1) th:nth-child(4)').html('New <br>users');
            $('#browser-tabela table thead tr:nth-child(1) th:nth-child(5)').html('Bounce <br>rate');
            $('#browser-tabela table thead tr:nth-child(1) th:nth-child(6)').html('Bounces');

            var i = 1;
            $.each(result.data.rows, function (key, value) {
                $('#browser-tabela table tbody tr:nth-child(' + i + ') td:nth-child(3)').html(value.c[2].v.toFixed(2) + ' %');
                $('#browser-tabela table tbody tr:nth-child(' + i + ') td:nth-child(5)').html(value.c[4].v.toFixed(2) + ' %');
                i++;
            });
            $('#iloscPrzegladarek').html('(total: ' + i + ')');
            if (i > 7) {
                $('#raportGA .pokazPrzegladarki').show();
            }

        });

        browserSizeTabela.on('success', function (result) {

            $('#browserSize-tabela table thead tr:nth-child(1) th:nth-child(1)').html('Resolution');
            $('#browserSize-tabela table thead tr:nth-child(1) th:nth-child(2)').html('Session');
            $('#browserSize-tabela table thead tr:nth-child(1) th:nth-child(3)').html('% New session');
            $('#browserSize-tabela table thead tr:nth-child(1) th:nth-child(4)').html('New <br>users');
            $('#browserSize-tabela table thead tr:nth-child(1) th:nth-child(5)').html('Bounce <br>rate');
            $('#browserSize-tabela table thead tr:nth-child(1) th:nth-child(6)').html('Bounces');

            var i = 1;
            $.each(result.data.rows, function (key, value) {
                $('#browserSize-tabela table tbody tr:nth-child(' + i + ') td:nth-child(3)').html(value.c[2].v.toFixed(2) + ' %');
                $('#browserSize-tabela table tbody tr:nth-child(' + i + ') td:nth-child(5)').html(value.c[4].v.toFixed(2) + ' %');
                i++;
            });
            $('#iloscRozdzielczosci').html('(total: ' + i + ')');
            if (i > 7) {
                $('#raportGA .pokazRozdzielczosc').show();
            }

        });

        landingPageTabela.on('success', function (result) {

            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(1)').html('Page');
            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(2)').html('Session');
            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(3)').html('Number of views <br>pages');
            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(4)').html('Watching <br>pages for sessions');
            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(5)').html('% new session');
            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(6)').html('New <br>users');
            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(7)').html('Bounce rate');
            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(8)').html('Bounces');
            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(9)').html('Hits');
            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(10)').html('Total Events');
            $('#landingPage-tabela table thead tr:nth-child(1) th:nth-child(11)').html('Goals');

            var i = 1;
            $.each(result.data.rows, function (key, value) {
                $('#landingPage-tabela table tbody tr:nth-child(' + i + ') td:nth-child(4)').html(value.c[3].v.toFixed(2) + '');
                $('#landingPage-tabela table tbody tr:nth-child(' + i + ') td:nth-child(5)').html(value.c[4].v.toFixed(2) + ' %');
                $('#landingPage-tabela table tbody tr:nth-child(' + i + ') td:nth-child(7)').html(value.c[6].v.toFixed(2) + ' %');
                i++;
            });

        });
    }
});


$(document).ready(function(){

    $('#raportGA .pokazKampanie').click(function(){
        $('#raportGA #campaignGrouping-tabela table tbody tr').show();
        $('#raportGA .pokazKampanie').hide();
        return false;
    });
    $('#raportGA .pokazMiasta').click(function(){
        $('#raportGA #sessionsPolska-tabela table tbody tr').show();
        $('#raportGA .pokazMiasta').hide();
        return false;
    });
    $('#raportGA .pokazPanstwa').click(function(){
        $('#raportGA #sessionsSwiat-tabela table tbody tr').show();
        $('#raportGA .pokazPanstwa').hide();
        return false;
    });
    $('#raportGA .pokazUrzadzenia').click(function(){
        $('#raportGA #devicesModel-tabela table tbody tr').show();
        $('#raportGA .pokazUrzadzenia').hide();
        return false;
    });
    $('#raportGA .pokazPrzegladarki').click(function(){
        $('#raportGA #browser-tabela table tbody tr').show();
        $('#raportGA .pokazPrzegladarki').hide();
        return false;
    });
    $('#raportGA .pokazRozdzielczosci').click(function(){
        $('#raportGA #browserSize-tabela table tbody tr').show();
        $('#raportGA .pokazRozdzielczosci').hide();
        return false;
    });
});