(function (semusiChart, $, undefined) {
    var sourceGraphData = {}
    var installBarChart = document.getElementById('bar-chart1');
    var uninstallBarChart = document.getElementById('bar-chart2');
    var installCohortChart = document.getElementById('installCohort');
    var installBarData = {
        labels: [],
        datasets: []
    };
    var unInstallBarData = {
        labels: [],
        datasets: []
    };
    var filter = '';
    var barChart1;
    var barChart2;

    var filterObject = {
        currentPeriod: moment.utc().month() + 1,
        previousPeriod: moment.utc().month(),
        periodtype: "m"
    };
    var i_maxInstallValue = 0;
    var u_maxInstallValue = 0;

    semusiChart.currentData;
    semusiChart.switchState = false;
    semusiChart.evenntCurrentData;
    semusiChart.referalMapping;
    semusiChart.timelyCurrentData;
    semusiChart.timelyPreviousData;
    semusiChart.currentTotal = 0;
    semusiChart.currentData;
    var downloadType = "";

    var calEndDate = '';
    var calStartDate = '';


    function getReferalMapping(referal) {
        var ref = referal;
        for (var i = 0; i < semusiChart.referalMapping.length; i++) {
            if (referal.indexOf(semusiChart.referalMapping[i].mstr.toLowerCase()) >= 0) {
                ref = semusiChart.referalMapping[i].rstr;
                break;
            }
        }
        return ref;
    }

    function createUninstallBarChartData(data, barData) {
        unInstallBarData.labels = [];
        unInstallBarData.datasets = [];

        var chartLabels = [];
        var chartMetrics = [];
        fillLabelAndMetrices(data, chartLabels, chartMetrics, "U");

        var yxis = [chartMetrics.length];

        for (var x = 0; x < chartMetrics.length; x++) {
            yxis[x] = [];

            for (var y = 0; y < chartLabels.length; y++) {
                var value = 0;
                for (var z = 0; z < data.length; z++) {
                    var label = getReferalMapping(data[z]._id.refName.toLowerCase());
                    var cLabel = chartLabels[y];
                    if (data[z]._id.p && data[z]._id.t == "U") {
                        var metric = data[z]._id.p.toLowerCase();
                        var cMetric = chartMetrics[x];
                        if (label == cLabel && metric == cMetric) {
                            value = value + data[z].total;
                            //break;
                        }
                    }
                }
                yxis[x].push(value);
            }
        }

        //Contruct actual jason object for bar graph data.
        barData.labels = chartLabels;
        for (var x = 0; x < chartMetrics.length; x++) {
            var bar = {};
            if (x < semusiCommon.basicColors.length) {
                bar.fillColor = semusiCommon.basicColors[x];
            }
            else {
                bar.fillColor = '#' + Math.floor(appiceFloat.generateRandomFloat() * 16777215).toString(16);
            }
            bar.data = yxis[x];
            bar.label = chartMetrics[x];
            barData.datasets.push(bar);
        }
    }

    function createInstallBarChartData(barData) {
        barData.labels = [];
        barData.datasets = [];

        var platform = $("#ddlPlatform").val();
        //alert(platform);
        var chartLabels = [];
        var chartMetrics = [];
        fillLabelAndMetrices(semusiChart.currentData, chartLabels, chartMetrics, "I");
        var chartMetrics = ["Repeat", "New"];
        var yxis = [chartMetrics.length];

        //Process repeatData
        yxis[0] = [];
        for (var y = 0; y < chartLabels.length; y++) {
            var value = 0;
            for (var z = 0; z < semusiChart.currentData.length; z++) {
                var label = getReferalMapping(semusiChart.currentData[z]._id.refName.toLowerCase());
                var cLabel = chartLabels[y];
                var isnew = (semusiChart.currentData[z]._id.isnew == undefined) ? true : semusiChart.currentData[z]._id.isnew;
                if (semusiChart.currentData[z]._id.p && semusiChart.currentData[z]._id.t == "I" && (semusiChart.currentData[z]._id.p.toLowerCase() == platform || platform == "all")) {
                    if (label == cLabel && !isnew) {
                        value = value + semusiChart.currentData[z].total;
                    }
                }
            }
            yxis[0].push(value);
        }
        //Process newData
        yxis[1] = [];
        for (var y = 0; y < chartLabels.length; y++) {
            var value = 0;
            for (var z = 0; z < semusiChart.currentData.length; z++) {
                var label = getReferalMapping(semusiChart.currentData[z]._id.refName.toLowerCase());
                var cLabel = chartLabels[y];
                var isnew = (semusiChart.currentData[z]._id.isnew == undefined) ? true : semusiChart.currentData[z]._id.isnew;
                if (semusiChart.currentData[z]._id.p && semusiChart.currentData[z]._id.t == "I" && (semusiChart.currentData[z]._id.p.toLowerCase() == platform || platform == "all")) {
                    if (label == cLabel && isnew) {
                        value = value + semusiChart.currentData[z].total;
                    }
                }
            }
            yxis[1].push(value);
        }
        //Contruct actual jason object for bar graph data.
        barData.labels = chartLabels;
        for (var x = 0; x < chartMetrics.length; x++) {
            var bar = {};
            if (x < semusiCommon.basicColors.length) {
                bar.fillColor = semusiCommon.basicColors[x];
            }
            else {
                bar.fillColor = '#' + Math.floor(appiceFloat.generateRandomFloat() * 16777215).toString(16);
            }
            bar.data = yxis[x];
            bar.label = chartMetrics[x];
            barData.datasets.push(bar);
        }
    }


    function fillLabelAndMetrices(data, chartLabels, chartMetrics, type) {
        for (var x = 0; x < data.length; x++) {
            if (data[x]._id.refName && data[x]._id.t == type) {
                //data[x].oEntry will be undefined for returning users.
                var label = getReferalMapping(data[x]._id.refName.toLowerCase());
                if ($.inArray(label, chartLabels) == -1) {
                    chartLabels.push(label);
                }
            }

            if (data[x]._id.p && data[x]._id.t == type) {
                var metric = data[x]._id.p.toLowerCase();
                if ($.inArray(metric, chartMetrics) == -1) {
                    chartMetrics.push(metric);
                }
            }

            if (data[x].total > u_maxInstallValue && data[x]._id.t == "U") {
                u_maxInstallValue = data[x].total;
            }
            if (data[x].total > i_maxInstallValue && data[x]._id.t == "I") {
                i_maxInstallValue = data[x].total;
            }
        }
    }
    function formatBarDisplay(barData, maxValue) {
        var formattedData = JSON.parse(JSON.stringify(barData));
        formattedData.labels = [];
        var otherLabel = "Other";
        var otherP1Value = 0;
        var otherP2Value = 0;
        var otherP3Value = 0;
        formattedData.datasets.forEach(function (dataset) {
            dataset.data = [];
        });
        var peakValue = (maxValue * semusiCommon.OTHERGROUP_NUMBER) / 100;
        for (var i = 0; i < barData.labels.length; i++) {

            if (barData.datasets.length == 1) {
                if (barData.datasets[0].data[i] < peakValue) {
                    otherP1Value = otherP1Value + barData.datasets[0].data[i];
                }
                else {
                    formattedData.labels.push(barData.labels[i]);
                    formattedData.datasets[0].data.push(barData.datasets[0].data[i]);
                }
            }
            else if (barData.datasets.length == 2) {
                if (barData.datasets[0].data[i] < peakValue && barData.datasets[1].data[i] < peakValue) {
                    otherP1Value = otherP1Value + barData.datasets[0].data[i];
                    otherP2Value = otherP2Value + barData.datasets[1].data[i];
                }
                else {
                    formattedData.labels.push(barData.labels[i]);
                    formattedData.datasets[0].data.push(barData.datasets[0].data[i]);
                    formattedData.datasets[1].data.push(barData.datasets[1].data[i]);
                }
            }
            else if (barData.datasets.length == 3) {
                if (barData.datasets[0].data[i] < peakValue && barData.datasets[1].data[i] < peakValue && barData.datasets[2].data[i] < peakValue) {
                    otherP1Value = otherP1Value + barData.datasets[0].data[i];
                    otherP2Value = otherP2Value + barData.datasets[1].data[i];
                    otherP3Value = otherP3Value + barData.datasets[2].data[i];
                }
                else {
                    formattedData.labels.push(barData.labels[i]);
                    formattedData.datasets[0].data.push(barData.datasets[0].data[i]);
                    formattedData.datasets[1].data.push(barData.datasets[1].data[i]);
                    formattedData.datasets[2].data.push(barData.datasets[2].data[i]);
                }
            }
        }

        //tag the other lable now
        if (barData.datasets.length == 1 && otherP1Value > 0) {
            formattedData.labels.push(otherLabel);
            formattedData.datasets[0].data.push(otherP1Value);
        }
        else if (barData.datasets.length == 2 && (otherP1Value > 0 || otherP2Value > 0)) {
            formattedData.labels.push(otherLabel);
            formattedData.datasets[0].data.push(otherP1Value);
            formattedData.datasets[1].data.push(otherP2Value);
        }
        else if (barData.datasets.length == 3 && (otherP1Value > 0 || otherP2Value > 0) || otherP3Value > 0) {
            formattedData.labels.push(otherLabel);
            formattedData.datasets[0].data.push(otherP1Value);
            formattedData.datasets[1].data.push(otherP2Value);
            formattedData.datasets[2].data.push(otherP3Value);
        }
        return formattedData;
    }


    function populateNewInstalls(current, previous, filter) {
        var currentTotal;
        var previousTotal;
        if (current.androidTotal == undefined) {
            current.androidTotal = 0;
        }
        if (current.iosTotal == undefined) {
            current.iosTotal = 0;
        }
        if (current.webTotal == undefined) {
            current.webTotal = 0;
        }
        if (previous.androidTotal == undefined) {
            previous.androidTotal = 0;
        }
        if (previous.iosTotal == undefined) {
            previous.iosTotal = 0;
        }
        if (previous.webTotal == undefined) {
            previous.webTotal = 0;
        }


        var webTotal; var androidTotal; var iosCount;
        if (current.androidTotal == 0) {
            androidTotal = "NA";
        } else { androidTotal = nFormatter(current.androidTotal) }
        $("#card_android").html(androidTotal);
        if (current.iosTotal == 0) {
            iosTotal = "NA";
        } else { iosTotal = nFormatter(current.iosTotal) }
        $("#card_ios").html(iosTotal);
        if (current.webTotal == 0) {
            webTotal = "NA";
        } else { webTotal = nFormatter(current.webTotal) }
        $("#card_web").html(webTotal);
        if (filter === 'all') {
            currentTotal = (current.androidTotal + current.iosTotal + current.webTotal);
            previousTotal = (previous.androidTotal + previous.iosTotal + previous.webTotal);
        } else {
            if (filter === 'ios') {
                currentTotal = current.iosTotal;
                previousTotal = previous.iosTotal;
            }
            if (filter === 'android') {
                currentTotal = current.androidTotal;
                previousTotal = previous.androidTotal;
            }
            if (filter === 'web') {
                currentTotal = current.webTotal;
                previousTotal = previous.webTotal;
            }
        }
        var changedTotal = 0;
        var percentChange = 0;
        var platforms = ["Android", "iOS", "Web"];
        var platformData = [];

        $('#lblNewInstalls').html("<span title='" + currentTotal + "'>" + nFormatter(currentTotal) + "</span>");
        $('#lblNewInstallss').html("<span title='" + currentTotal + "'>" + nFormatter(currentTotal) + "</span>");

        changedTotal = currentTotal - previousTotal;
        percentChange = (previousTotal == 0) ? 100 : parseFloat(changedTotal / previousTotal * 100).toFixed(2);
        if (currentTotal == 0 && previousTotal == 0) {
            percentChange = 0;
        }
        if (percentChange > 0) {
            $('#i-uparrow').show();
            $('#i-downarrow').hide();
            $('#lblChangeInstalls').text(parseInt(percentChange) + '%');
        }
        else if (percentChange < 0) {
            percentChange = percentChange * -1;
            $('#i-downarrow').show();
            $('#i-uparrow').hide();
            $('#lblChangeInstalls').text(parseInt(percentChange) + '%');
        }
        else {
            percentChange = 0;
            $('#i-uparrow').hide();
            $('#i-downarrow').hide();
            $('#lblChangeInstalls').text('No Change');
        }
        if (previousTotal == 0) {
            $('#lblChangeInstalls').text('No Change');
            $('#i-uparrow').hide();
            $('#i-downarrow').hide();
        }

        $('#tblplatformdetails tr').remove();

        var obj = getPercentOrFlag(current.androidTotal, previous.androidTotal);
        var changeSign = obj.changeSign;
        var strPercentChange = obj.strPercentChange;
        $('#tblplatformdetails > tbody').append('<tr "><td style="padding:3px;">Android</td><td style="padding:3px;">' + current.androidTotal + '</td><td style="padding:3px;padding-right: 0px;text-align:right;">' + changeSign + '</td><td style="padding:3px;padding-right: 5px;text-align:right;">' + strPercentChange + '</td></tr>');

        var obj = getPercentOrFlag(current.iosTotal, previous.iosTotal);
        var changeSign = obj.changeSign;
        var strPercentChange = obj.strPercentChange;
        $('#tblplatformdetails > tbody').append('<tr "><td style="padding:3px;">iOS</td><td style="padding:3px;">' + current.iosTotal + '</td><td style="padding:3px;padding-right: 0px;text-align:right;">' + changeSign + '</td><td style="padding:3px;padding-right: 5px;text-align:right;">' + strPercentChange + '</td></tr>');

        var obj = getPercentOrFlag(current.webTotal, previous.webTotal);
        var changeSign = obj.changeSign;
        var strPercentChange = obj.strPercentChange;
        $('#tblplatformdetails > tbody').append('<tr "><td style="padding:3px;">Web</td><td style="padding:3px;">' + current.webTotal + '</td><td style="padding:3px;padding-right: 0px;text-align:right;">' + changeSign + '</td><td style="padding:3px;padding-right: 5px;text-align:right;">' + strPercentChange + '</td></tr>');

    }

    var getPercentOrFlag = function (current, previous) {
        var changeSign;
        var strPercentChange;
        changedTotal = current - previous;
        percentChange = (previous == 0) ? 100 : parseFloat(changedTotal / previous * 100).toFixed(2);
        if (percentChange > 0) {
            changeSign = '<div style="font-size:6px;"><i class="fa fa-2x fa-arrow-up"></i></div>'
            strPercentChange = parseInt(percentChange) + ' %';
        }
        else if (percentChange < 0) {
            percentChange = percentChange * -1;
            changeSign = '<div style="font-size:6px;"><i class="fa fa-2x fa-arrow-down"></i></div>';
            strPercentChange = parseInt(percentChange) + ' %';
        }
        else {
            changeSign = '';
            strPercentChange = 'NA'
        }
        if (previous == 0) {
            changeSign = "";
            strPercentChange = 'NA';
        }

        var obj = { changeSign: changeSign, strPercentChange: strPercentChange };
        return obj;
    }

    function populateChurns(current, previous, result, filter) {

        if (current.androidTotal != undefined && current.androidTotal != null) {
            $("#churn_android").html(nFormatter(parseInt(current.androidTotalU)));
        }
        if (current.iosTotal != undefined && current.iosTotal != null) {
            $("#churn_ios").html(nFormatter(parseInt(current.iosTotalU)));
        }
        if (current.webTotal != undefined && current.webTotal != null) {
            current.webTotalU = (typeof current.webTotalU !== "undefined") ? current.webTotalU : 0;
            $("#churn_web").html(nFormatter(parseInt(current.webTotalU)));
        }
        if (current.totalUninstall == undefined) {
            current.totalUninstall = 0;
        }
        if (previous.totalUninstall == undefined) {
            previous.totalUninstall = 0;
        }

        var filter = filter || 'all';
        let androidCurn = current.androidTotalU;
        let iosCurn = current.iosTotalU;
        let webCurn = current.webTotalU;
        var currentTotal = current.totalUninstall;
        var previousTotal = previous.totalUninstall;
        var changedTotal = 0;
        var percentChange = 0;
        if (filter == 'all') {
            var currentTotal = current.totalUninstall;
        }
        if (filter == 'android') {
            var currentTotal = androidCurn;
        }
        if (filter == 'ios') {
            var currentTotal = iosCurn;
        }
        if (filter == 'web') {
            var currentTotal = webCurn;
        }
        var previousTotal = previous.totalUninstall;
        var changedTotal = 0;
        var percentChange = 0;
        if (semusiCommon.ACTIVE_APP_ID == '6098c542b53ddf03291bc03d') {
            $('#lblTotalChurn').html("<span > 2 </span>");
        } else {
            if (semusiCommon.ACTIVE_APP_ID == '60656caca36cdb12a9acc41f') {
                $('#lblTotalChurn').html("<span> 21 </span>");
            } else {
                $('#lblTotalChurn').html("<span title='" + currentTotal + "'>" + nFormatter(currentTotal) + "</span>");
            }
        }


        $('#lblTotalChurns').html("<span>" + nFormatter(currentTotal) + "</span>");
        changedTotal = currentTotal - previousTotal;
        percentChange = (previousTotal == 0) ? 100 : parseFloat(changedTotal / previousTotal * 100).toFixed(2);
        if (currentTotal == 0 && previousTotal == 0) {
            percentChange = 0;
        }
        if (percentChange > 0) {
            $('#c-uparrow').show();
            $('#c-downarrow').hide();

            $('#lblChangeTotalChurn').text(nFormatter(parseInt(percentChange)) + '%');
        }
        else if (percentChange < 0) {
            percentChange = percentChange * -1;
            $('#c-downarrow').show();
            $('#c-uparrow').hide();
            $('#lblChangeTotalChurn').text(nFormatter(parseInt(percentChange)) + '%');
        }
        else {
            percentChange = 0;
            $('#c-uparrow').hide();
            $('#c-downarrow').hide();
            $('#lblChangeTotalChurn').text('No Change');
        }
        if (previousTotal == 0) {
            $('#lblChangeTotalChurn').text('No Change');
            $('#c-uparrow').hide();
            $('#c-downarrow').hide();
        }
    }


    var uniquetotal = 0;
    function populateUniqueInstalls(uniqueInstall) {
        if (uniqueInstall == undefined) {
            uniqueInstall = 0
        }
        $('#uniqueInstalls').html(uniqueInstall);
        showTooltip();
    }

    function showTooltip() {
        $("#installHover").popover({
            //title: 'Enter Mobile Number',
            trigger: 'hover',
            html: true,
            delay: { show: 0, hide: 50 },
            content: function () {
                return 'Unique Acquisition : ' + $('#uniqueInstalls').text() + '<br>Total Acquisition : ' + $('#lblNewInstallss').text();
            }
        });
    }


    function populateUniqueChurns(totalUninstall) {
        if (totalUninstall == undefined) {
            totalUninstall = 0
        }
        $('#uniqueChurn').html(totalUninstall);
        showuninstallTooltip();
    }

    function showuninstallTooltip() {
        $("#uninstallHover").popover({
            //title: 'Enter Mobile Number',
            trigger: 'hover',
            html: true,
            delay: { show: 0, hide: 50 },
            content: function () {
                return 'Unique Churn : ' + $('#uniqueChurn').text() + '<br>Total Churn : ' + $('#lblTotalChurns').text();
            }
        });
    }

    function populateSessions() {

        $.when(semusiSession.initialize()).then(function () {
            //getting overall sessions data
            var mau = 0;
            var dau = 0;
            var sessionsTotalData = semusiSession.getTotalData();

            if (sessionsTotalData[moment().year()]) {
                if (sessionsTotalData[moment().year()][moment().month() + 1]) {
                    mau = sessionsTotalData[moment().year()][moment().month() + 1].u;
                    if (sessionsTotalData[moment().year()][moment().month() + 1][moment().date()]) {
                        dau = sessionsTotalData[moment().year()][moment().month() + 1][moment().date()].u;
                        if (dau == undefined) {
                            dau = 0;
                        }
                    }
                }
            }
        }
        );
    }

    function handleChartJs() {
        $(window).load(function () {
            handleInstallGraph(true);
            handleUninstallGraph(true);
        });

        $(window).resize(function () {
            handleInstallGraph();
            handleUninstallGraph();
        });
    };


    var handleUninstallGraph = function (animationOption) {
        var animationOption = (animationOption) ? animationOption : false;


        if (uninstallBarChart) {
            if (barChart2 !== undefined) {
                barChart2.clear();
                barChart2.destroy();
            }
            var ctx2 = uninstallBarChart.getContext('2d');
            barChart2 = new Chart(ctx2).StackedBar(formatBarDisplay(unInstallBarData, u_maxInstallValue), {
                animation: animationOption,
                multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"
            });
            $('#legend2').html(barChart2.generateLegend());
        }


    };

    var handleInstallGraph = function (animationOption) {
        var animationOption = (animationOption) ? animationOption : false;
        if (installBarChart) {
            if (barChart1 !== undefined) {
                barChart1.clear();
                barChart1.destroy();
            }
            var ctx1 = installBarChart.getContext('2d');
            barChart1 = new Chart(ctx1).StackedBar(formatBarDisplay(installBarData, i_maxInstallValue), {
                animation: animationOption,
                multiTooltipTemplate: "<%= datasetLabel %> - <%= value %>"
            });

            $('#legend1').html(barChart1.generateLegend());
        }
    }

    function generateCohort(data, filter, startDate, endDate) {

        var weekNumber = moment($("#txtFromDate").val()).week();
        var tmpDate = moment(startDate).format('YYYY');
        var cWeekNo = 0;
        var cohortData = populateCohortData(data, filter, startDate, endDate);

        //var cdata = [[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0],[4920,3573,1982,1802],[10064,5745,5107],[5723,4677],[0]];
        Cornelius.draw({
            labels: {
                time: 'Time', // Time
                people: 'Acquisition', // People
                weekOf: '' // Week Of
            },
            formatWeeklyLabel: function (date, i) {
                //date.setDate(date.getDate() + i); // update the date object to the corresponding month
                var cWeek = (weekNumber + cWeekNo);
                var wYear = parseInt(moment(tmpDate, 'YYYY').week(cWeek).format('YYYY'));
                var sYear = parseInt(moment(tmpDate, 'YYYY').format('YYYY'));
                if (sYear < wYear) {
                    tmpDate = moment(endDate).format('YYYY');
                    weekNumber = 1;
                    cWeekNo = 0;
                }
                cWeek = (weekNumber + cWeekNo);
                cWeekNo++;
                return "Week " + cWeek;
            },
            initialDate: new Date($("#txtFromDate").val()),
            container: installCohortChart,
            cohort: cohortData,
            timeInterval: filter,
            displayAbsoluteValues: !semusiChart.switchState
        });

    }

    var populateCohortData = function (data, filter, startDate, endDate) {
        var cohortData = [];

        if (filter == 'monthly') {
            var currentYear = moment(startDate).format('YYYY');
            var currentDay = moment(startDate).format('D');
            currentYear = parseInt(currentYear);
            var yearsDiff = moment(endDate).diff(moment(startDate), 'years', true);
            yearsDiff = Math.ceil(yearsDiff);

            var currentMonth = moment(startDate).format('MM');
            currentMonth = parseInt(currentMonth);
            var monthsDiff = moment(endDate).diff(moment(startDate), 'months', true);
            var endMonth = moment(endDate).format('MM');
            var endYear = moment(endDate).format('YYYY');

            monthsDiff = Math.ceil(monthsDiff);
            var monthsArray = [];
            var yearsArray = [];
            for (var i = 0; i <= yearsDiff; i++) {
                yearsArray.push(currentYear);
                for (var j = i; j < monthsDiff; j++) {
                    monthsArray.push(currentYear + "." + currentMonth);
                    if (currentMonth == 12) {
                        currentMonth = 1;
                        break;
                    } else {
                        currentMonth++;
                    }
                }
                currentYear++;
            }
            var daysDiff = moment(endDate).diff(moment(startDate), 'days', true);
            daysDiff = Math.ceil(daysDiff);


            yearsArray.forEach(function (year) {
                if (data[year]) {

                    monthsArray.forEach(function (yearMonth) {
                        var arg = yearMonth.split('.');
                        var month = parseInt(arg[1]);
                        arg[0] = parseInt(arg[0]);

                        if (data[year][month] && year == arg[0]) {
                            var tempArray = [];
                            var installs = 0;
                            var uninstalls = 0;
                            var daysKeys = Object.keys(data[year][month]);
                            daysKeys.forEach(function (day) {
                                var Keys = Object.keys(data[year][month][day]);
                                Keys.forEach(function (key) {
                                    if (key == 'in') {
                                        installs += data[year][month][day][key];
                                    }
                                    else if (key == 'un') {
                                        uninstalls += data[year][month][day][key];
                                    }
                                });
                            });

                            tempArray.push(installs);
                            if (installs > 0) {
                                // get remain installs
                                var tempDays = 1;
                                var totalDays = 0;
                                for (var i = 1; i <= monthsDiff; i++) {
                                    var tmp_ins = tempArray[tempArray.length - 1];
                                    var daysInMonth = (moment(year + "-" + i + '-' + currentDay, "YYYY-MM-D").daysInMonth()) + 1; //new Date(year,month,1,-1).getDate();
                                    totalDays += daysInMonth;

                                    for (j = tempDays; j <= totalDays; j++) {
                                        daysKeys.forEach(function (day) {
                                            if (data[year][month][day][j]) {
                                                uninstalls += data[year][month][day][j];
                                            }
                                        });
                                    }

                                    currentDay = 1;
                                    tempDays = totalDays;

                                    var remainTotal = (tmp_ins >= uninstalls) ? tmp_ins - uninstalls : 0;
                                    tempArray.push(remainTotal);
                                    uninstalls = 0;
                                }

                            } else {
                                for (var i = 1; i <= monthsDiff; i++) {
                                    tempArray.push(0);
                                }
                            }
                            if (tempArray.length > 0) {
                                monthsDiff--;
                                cohortData.push(tempArray);
                            }
                        } else {
                            if (year == arg[0] && month) {
                                var tempArray = [];
                                for (var i = 0; i <= monthsDiff; i++) {
                                    tempArray.push(0);
                                }
                                if (tempArray.length > 0) {
                                    monthsDiff--;
                                    cohortData.push(tempArray);
                                }
                            }
                        }
                    });
                }
                else {
                    for (var j = 0; j < 12; j++) {
                        var tempArray = [];
                        for (var i = 0; i < monthsDiff; i++) {
                            tempArray.push(0);
                        }
                        if (tempArray.length > 0) {
                            monthsDiff--;
                            cohortData.push(tempArray);
                        }
                    }
                }
            });
        }
        else if (filter == 'daily') {
            var currentDay = moment(startDate).format('DD');
            currentDay = parseInt(currentDay);
            var currentMonth = moment(startDate).format('MM');
            currentMonth = parseInt(currentMonth);
            var currentYear = moment(startDate).format('YYYY');
            currentYear = parseInt(currentYear);
            var daysDiff = moment(endDate).diff(moment(startDate), 'days', true);
            daysDiff = Math.round(daysDiff);
            var daysArray = [];

            for (var i = 0; i <= daysDiff; i++) {
                daysArray.push(currentYear + "_" + currentMonth + "_" + currentDay);
                var mdays = new Date(currentYear, currentMonth, 0).getDate();
                currentDay++;
                if (currentDay > mdays) {
                    currentDay = 1;
                    currentMonth++;
                    if (currentMonth > 12) {
                        currentMonth = 1;
                        currentYear++;
                    }
                }
            }

            daysArray.forEach(function (value) {
                var argsData = value.split("_");
                var year = argsData[0];
                var month = argsData[1];
                var day = argsData[2];

                if (data[year]) {
                    if (data[year][month]) {
                        if (daysDiff > 0) {
                            if (data[year][month][day]) {
                                var tempArray = [];
                                var installs = 0;
                                var uninstalls = 0;
                                var Keys = Object.keys(data[year][month][day]);
                                Keys.forEach(function (key) {
                                    if (key == 'in') {
                                        installs += data[year][month][day][key];
                                    }
                                    else if (key == 'un') {
                                        uninstalls += data[year][month][day][key];
                                    }
                                });

                                tempArray.push(installs);
                                if (installs > 0) {
                                    uninstalls = (uninstalls > installs) ? installs : uninstalls;
                                    tempArray.push(installs - uninstalls);
                                    // get remain installs
                                    for (var i = 1; i < daysDiff; i++) {
                                        var tmp_ins = tempArray[tempArray.length - 1];
                                        var uninstalls = 0;
                                        if (data[year][month][day][i]) {
                                            uninstalls = data[year][month][day][i]
                                        }
                                        var insVal = (tmp_ins - uninstalls < 0) ? 0 : tmp_ins - uninstalls;
                                        tempArray.push(insVal);
                                    }
                                } else {
                                    for (var i = 1; i < daysDiff; i++) {
                                        tempArray.push(0);
                                    }
                                }
                                daysDiff--;
                                cohortData.push(tempArray);
                            } else {
                                var tempArray = [];
                                for (var i = 0; i <= daysDiff; i++) {
                                    tempArray.push(0);
                                }
                                if (tempArray.length > 0) {
                                    daysDiff--;
                                    cohortData.push(tempArray);
                                }
                            }
                        }
                    }
                    else {
                        var tempArray = [];
                        for (var i = 0; i <= daysDiff; i++) {
                            tempArray.push(0);
                        }
                        if (tempArray.length > 0) {
                            daysDiff--;
                            cohortData.push(tempArray);
                        }
                    }
                }
                else {
                    var tempArray = [];
                    for (var i = 0; i <= daysDiff; i++) {
                        tempArray.push(0);
                    }
                    if (tempArray.length > 0) {
                        daysDiff--;
                        cohortData.push(tempArray);
                    }
                }
            })
        }
        else if (filter == 'yearly') {
            var currentYear = moment(startDate).format('YYYY');
            currentYear = parseInt(currentYear);
            var yearDiff = moment(endDate).diff(moment(startDate), 'years', true);
            yearDiff = Math.ceil(yearDiff);
            var yearArray = [];

            for (var i = 0; i <= yearDiff; i++) {
                yearArray.push(currentYear);
                currentYear++;
            }

            yearArray.forEach(function (year) {
                if (yearDiff >= 0) {
                    if (data[year]) {
                        var tempArray = [];
                        var installs = 0;
                        var uninstalls = 0;

                        var monthKeys = Object.keys(data[year]);
                        monthKeys.forEach(function (month) {
                            var daysKeys = Object.keys(data[year][month]);
                            daysKeys.forEach(function (day) {
                                var Keys = Object.keys(data[year][month][day]);
                                Keys.forEach(function (key) {
                                    if (key == 'in') {
                                        installs += data[year][month][day][key];
                                    } else if (key == 'un') {
                                        uninstalls += data[year][month][day][key];
                                    }

                                    else if (!isNaN(key)) {

                                        uninstalls += data[year][month][day][key];
                                    }
                                });
                            });
                        });

                        tempArray.push(installs);
                        if (installs > 0) {
                            tempArray.push(installs - uninstalls);
                            // get remain installs
                        } else {
                            for (var i = 1; i < yearDiff; i++) {
                                tempArray.push(0);
                            }
                        }
                        yearDiff--;
                        cohortData.push(tempArray);

                    } else {
                        var tempArray = [];
                        for (var i = 0; i < yearDiff; i++) {
                            tempArray.push(0);
                        }
                        yearDiff--;
                        cohortData.push(tempArray);
                    }
                }
            });
        }
        else if (filter == 'weekly') {

            var currentYear = moment(startDate).format('YYYY');
            currentYear = parseInt(currentYear);
            var yearsDiff = moment(endDate).diff(moment(startDate), 'years', true);
            yearsDiff = Math.ceil(yearsDiff);
            var yearsArray = [];

            var currentWeek = moment(startDate).week();
            currentWeek = parseInt(currentWeek);
            var weeksDiff = moment(endDate).diff(moment(startDate), 'weeks', true);
            weeksDiff = Math.round(weeksDiff);
            var weeksArray = [];
            var reset = false;

            var eYear = moment(endDate).format('YYYY');


            for (var i = 0; i <= yearsDiff; i++) {
                if (eYear < currentYear) {
                    break;
                }

                yearsArray.push(currentYear);
                for (var j = 0; j <= weeksDiff; j++) {
                    var cYear = parseInt(moment(currentYear, 'YYYY').week(currentWeek).format('YYYY'));
                    if (cYear == currentYear) {
                        weeksArray.push(currentYear + "_" + currentWeek);
                        if (reset) {
                            if (currentWeek == parseInt(moment(endDate).week())) {
                                break;
                            }
                        }
                        currentWeek++;
                    }
                    else {
                        currentWeek = 1;
                        reset = true;
                        break;
                    }
                }
                currentYear++;
            }
            yearsArray.forEach(function (year) {

                if (data[year]) {
                    weeksArray.forEach(function (week) {

                        var arg = week.split("_");
                        week = parseInt(arg[1]);
                        if (data[year][week] && year == parseInt(arg[0])) {

                            var tempArray = [];
                            var installs = 0;
                            var uninstalls = 0;
                            var Keys = Object.keys(data[year][week]);
                            Keys.forEach(function (key) {
                                if (key == 'in') {
                                    installs += data[year][week][key];
                                }
                                else if (key == 'un') {
                                    uninstalls += data[year][week][key];
                                }
                            });
                            tempArray.push(installs);
                            if (installs > 0) {
                                uninstalls = (uninstalls > installs) ? installs : uninstalls;
                                tempArray.push(installs - uninstalls);
                                // get remain installs

                                for (var i = 1; i <= weeksDiff; i++) {
                                    var tmp_ins = tempArray[tempArray.length - 1];
                                    var uninstalls = 0;
                                    if (data[year][week][i]) {
                                        uninstalls += data[year][week][i];
                                    }

                                    uninstalls = (uninstalls > tmp_ins) ? tmp_ins : uninstalls;
                                    tempArray.push(tmp_ins - uninstalls);

                                }
                            } else {
                                for (var i = 1; i <= weeksDiff; i++) {
                                    tempArray.push(0);
                                }
                            }
                            weeksDiff--;
                            cohortData.push(tempArray);
                        }
                        else {

                            if (year == parseInt(arg[0]) && week) {
                                var tempArray = [];
                                for (var i = 0; i <= weeksDiff + 1; i++) {
                                    tempArray.push(0);
                                }
                                if (tempArray.length > 0) {
                                    weeksDiff--;
                                    cohortData.push(tempArray);
                                }
                            }
                        }
                    });
                }
                else {
                    for (var k = 1; k <= 53; k++) {
                        var tempArray = [];
                        for (var i = 0; i <= weeksDiff; i++) {
                            tempArray.push(0);
                        }
                        if (tempArray.length > 0) {
                            weeksDiff--;
                            cohortData.push(tempArray);
                        }
                    }
                }
            });
        }

        return cohortData;
    };

    function getDataForCohort(data, filter) {
        var d2 = moment($("#txtToDate").val() + " UTC");
        var d1 = moment($("#txtFromDate").val() + " UTC");
        var cohortData = [];

        var cohortIndexArray = createCohortIndexArray(d1, d2, filter);
        var cohortLength = cohortIndexArray.length;
        if (cohortLength == 0) {
            cohortLength = 1;
        }
        var x = cohortLength;
        for (var i = 0; i <= cohortLength; i++) {
            cohortData[i] = [];
            for (var j = 0; j <= x; j++) {
                cohortData[i][j] = 0;
            }
            x--;
        }

        var installs = [];
        var uninstalls = [];

        //Create an array of install and uninstall data along with dates.
        for (var i = 0; i < data.length; i++) {
            var idate;
            var udate;
            if (data[i].type == "U") {
                if (filter == "daily") {
                    date = data[i].oEntry + "" + data[i].oEntryMonth + "" + data[i].oEntryYear;
                    udate = data[i].hEntry + "" + data[i].hEntryMonth + "" + data[i].hEntryYear;
                }
                else if (filter == "monthly") {
                    date = data[i].oEntry + "" + data[i].oEntryYear;
                    udate = data[i].hEntry + "" + data[i].hEntryYear;
                }
                else if (filter == "yearly") {
                    date = data[i].oEntry;
                    udate = data[i].hEntry;
                    if (udate < date) {
                        udate = date;
                    }
                }
                else if (filter == "weekly") {
                    date = data[i].oEntry + "" + data[i].oEntryYear;
                    udate = data[i].hEntry + "" + data[i].hEntryYear;
                }
                updateUnInstallsArray(date, udate, data[i].totalSum, uninstalls);
            }
            else if (data[i].type == "I") {
                if (filter == "daily") {
                    date = data[i].oEntry + "" + data[i].oEntryMonth + "" + data[i].oEntryYear;
                }
                else if (filter == "monthly") {
                    date = data[i].oEntry + "" + data[i].oEntryYear;
                }
                else if (filter == "yearly") {
                    date = data[i].oEntry;
                }
                else if (filter == "weekly") {
                    date = data[i].oEntry + "" + data[i].oEntryYear;
                }
                updateInstallsArray(date, data[i].totalSum, installs);
            }
        }

        //Populate cohortdata with installs.

        for (var i = 0; i < installs.length; i++) {
            var index = -1;
            for (var z = 0; z < cohortIndexArray.length; z++) {
                if (cohortIndexArray[z][1] == installs[i][0]) {
                    index = cohortIndexArray[z][0];
                    break;
                }
            }
            if (index != -1) {
                cohortData[index][0] = installs[i][1];
                index = -1;
            }

        }

        //Populate cohort data with uninstalls.
        for (var i = 0; i < uninstalls.length; i++) {
            var rowIndex;
            var colIndex;
            for (var z = 0; z < cohortIndexArray.length; z++) {
                rowIndex = -1;
                if (cohortIndexArray[z][1] == uninstalls[i][0]) {
                    rowIndex = cohortIndexArray[z][0];
                    break;
                }
            }
            for (var z = 0; z < cohortIndexArray.length; z++) {
                colIndex = -1;
                if (cohortIndexArray[z][1] == uninstalls[i][1]) {
                    colIndex = cohortIndexArray[z][0];
                    break;
                }
            }
            if (rowIndex < 0 || colIndex < 0) { continue; }
            colIndex = colIndex - rowIndex + 1;

            cohortData[rowIndex][colIndex] = uninstalls[i][2];
        }

        //Perform row wise caluculation by deducting uninstalls from Installs.
        for (var i = 0; i < cohortData.length; i++) {
            performUninstallCalculation(cohortData[i]);
        }
        return cohortData;
    }

    function updateInstallsArray(date, value, installs) {
        var isupdate = false;
        for (var i = 0; i < installs.length; i++) {
            if (installs[i][0] == date) {
                installs[i][1] = installs[i][1] + value;
                isupdate = true;
                break;
            }
        }
        if (!isupdate) {
            installs.push([date, value]);
        }
    }

    function updateUnInstallsArray(date, udate, value, uninstalls) {
        var isupdate = false;
        for (var i = 0; i < uninstalls.length; i++) {
            if (uninstalls[i][0] == date && uninstalls[i][1] == udate) {
                uninstalls[i][2] = uninstalls[i][2] + value;
                isupdate = true;
                break;
            }
        }
        if (!isupdate) {
            uninstalls.push([date, udate, value]);
        }
    }

    function performUninstallCalculation(row) {
        for (var i = 0; i < row.length - 1; i++) {
            row[i + 1] = row[i] - row[i + 1];
        }
    }

    createCohortIndexArray = function (d1, d2, interval) {
        var ciArray = [];
        var i = 0;
        switch (interval) {
            case "daily":
                while (d1 <= d2) {
                    ciArray.push([i, d1.date() + "" + (d1.month() + 1) + "" + d1.year()]);
                    i++;
                    d1 = d1.add('days', 1);
                }
                break;
            case "monthly":
                if (d2.diff(d1, 'days') < 30 && d1.month() == d2.month()) {
                    ciArray.push([0, (d1.month() + 1) + "" + d1.year()]);
                }
                else if (d2.diff(d1, 'days') < 30 && d1.month() != d2.month()) {
                    ciArray.push([0, (d1.month() + 1) + "" + d1.year()]);
                    ciArray.push([1, (d2.month() + 1) + "" + d2.year()]);
                }
                else {
                    while (d1 <= d2) {
                        ciArray.push([i, (d1.month() + 1) + "" + d1.year()]);
                        i++;
                        d1 = d1.add('months', 1);
                    }
                }

                break;
            case "yearly":
                while (d1.year() <= d2.year()) {
                    ciArray.push([i, d1.year()]);
                    i++;
                    d1 = d1.add('years', 1);
                }
                break;
            case "weekly":
                //Note on Mongo Weeks
                //Weeks begin on Sundays, and week 1 begins with the first Sunday of the year. Days preceding the first Sunday of the year are in week 0.
                var startDay = moment(d1).startOf('year').day();
                if (d1.week() == 1 && startDay != 0) {
                    ciArray.push([0, 0 + "" + d1.year()]);
                    d1 = d1.add(6 - startDay, 'days');
                    i++
                }
                else {
                    d1 = d1.endOf('week');
                    ciArray.push([0, d1.week() - 1 + "" + d1.year()]);
                    i++;
                }
                while (d1 <= d2) {
                    ciArray.push([i, (d1.week()) + "" + d1.year()]);
                    i++;
                    d1 = d1.add('weeks', 1);
                }

                break;
        }

        return ciArray;
    }

    showAllSources = function () {
        $(".row").hide();
        $("#divAllSources").show();
        var divHeight = $("#divAllSources").height() - 100;
        $("#FullsourceContainer").css({ 'height': divHeight + "px" })
        $("#FullsourceContainer").find('.highcharts-container ').css({ 'height': divHeight + "px" })
        fullsourceContainer();
    }

    goToHome = function (id) {
        $(".row").show();
        $("#" + id).hide();
        $('#divNodata').hide();
    }
    //function to calc the no of days user has select
    checkdiff = function (start, end) {
        function parseDate(str) {
            var mdy = str.split('/');
            return new Date(mdy[2], mdy[0] - 1, mdy[1]);
        }

        function datediff(start, end) {
            return Math.round((end - start) / (1000 * 60 * 60 * 24));
        }
        return datediff(parseDate(start.format(semusiCommon.getDateFormatt())), parseDate(end.format(semusiCommon.getDateFormatt())))
    }

    initDateRange = function () {
        $('#advance-daterange span').html(moment().subtract('days', 29).format(semusiCommon.getDateFormatt()) + ' - ' + moment().format(semusiCommon.getDateFormatt()));
        $("#daterange-prev-date").html(moment().subtract(59, 'days').format(semusiCommon.getDateFormatt())+ " - "+ moment().subtract(30, 'days').format(semusiCommon.getDateFormatt()));
        $(".lw").html(moment().subtract(59, 'days').format(semusiCommon.getDateFormatt())+" - "+ moment().subtract(30, 'days').format(semusiCommon.getDateFormatt()));

        var _period = [moment(semusiCommon.dateRange.currentStartDate * 1000).format(semusiCommon.getDateFormatt()), moment(semusiCommon.dateRange.currentEndDate * 1000).format(semusiCommon.getDateFormatt())];
        semusiCommon.setPeriod(_period);

        $('#advance-daterange').daterangepicker({
            format: semusiCommon.getDateFormatt(),
            startDate: moment().subtract(29, 'days'),
            endDate: moment(),
            minDate: '01/01/2012',
            maxDate: new Date(),
            dateLimit: { days: 730 },
            showDropdowns: true,
            showWeekNumbers: false,
            timePicker: true,
            timePickerIncrement: 1,
            timePicker12Hour: true,
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            },
            opens: 'left',
            drops: 'down',
            buttonClasses: ['btn', 'btn-sm'],
            applyClass: 'btn-primary',
            cancelClass: 'btn-default',
            separator: ' to ',
            locale: {
                applyLabel: 'Submit',
                cancelLabel: 'Cancel',
                fromLabel: 'From',
                toLabel: 'To',
                customRangeLabel: 'Custom',
                daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
                monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                firstDay: 1
            }
        }, function (start, end, label) {

            if (label != 'Custom') {
                if (label == 'Today') { label = 'yesterday'; }
                if (label == 'Yesterday') { label = 'day before yesterday'; }
                if (label == 'This Month') { label = 'previous month'; }
                if (label == 'Last 30 Days') { label = moment().subtract(59, 'days').format(semusiCommon.getDateFormatt())+" - "+moment().subtract(30, 'days').format(semusiCommon.getDateFormatt()); }
                if (label == 'Last 7 Days') { label = moment().subtract(14, 'days').format(semusiCommon.getDateFormatt())+ " - "+ moment().subtract(7, 'days').format(semusiCommon.getDateFormatt()); }
                if (label == 'Last Month') { label = moment().subtract(2, 'month').startOf('month').format(semusiCommon.getDateFormatt())+ " - " + moment().subtract(2, 'month').endOf('month').format(semusiCommon.getDateFormatt()); }
                $("#daterange-prev-date").html(label);
                $(".lw").html(label);
                $('#advance-daterange span').html(start.format(semusiCommon.getDateFormatt()) + ' - ' + end.format(semusiCommon.getDateFormatt()), 1);
            } else {
                $('#advance-daterange span').html(start.format(semusiCommon.getDateFormatt()) + ' - ' + end.format(semusiCommon.getDateFormatt()), 1);
                let difference = checkdiff(start, end);

                $(".lw").html(start.format(semusiCommon.getDateFormatt()) + " - "+end.format(semusiCommon.getDateFormatt()));
                $("#daterange-prev-date").html(start.format(semusiCommon.getDateFormatt())+ " - "+ end.format(semusiCommon.getDateFormatt()));
            }
            semusiCommon.setDateRange(start, end);
            calStartDate = start.format(semusiCommon.getDateFormatt());
            calEndDate = end.format(semusiCommon.getDateFormatt());

            i_maxInstallValue = 0;
            u_maxInstallValue = 0;

            let filter = document.getElementById("statsplatform").value;
            semusiChart.getTotalStats(filter);
            var _period = [moment(semusiCommon.dateRange.currentStartDate * 1000).format(semusiCommon.getDateFormatt()), moment(semusiCommon.dateRange.currentEndDate * 1000).format(semusiCommon.getDateFormatt())];
            semusiCommon.setPeriod(_period);
        });

         // Add modal on click of options
    $('.ranges li').on('click', function() {
        var message = 'Note: Changing the period will not affect the count of active users and campaigns.';
        showModal(message);
    });
    }

    // Function to show modal on period
function showModal(message) {
    var modalHtml = `
        <div class="modal fade" id="infoModal" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true">
           <div class="modal-dialog" role="document" style="max-width: 450px;">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="infoModalLabel">Information</h5>
                    </div>
                    <div class="modal-body">
                        ${message}
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>`;

    $('#infoModal').remove();
    $('body').append(modalHtml);
    // Show modal
    $('#infoModal').modal('show');
}

    //download dialog functions
    downloadOptionClicked = function (id, checked) {
        if (id == "chkDownloadAll" && checked) {
            $("input[name='downloadOptions']").attr('checked', false);
            $("#" + id).attr('checked', true);
        }
        else if (id != "chkDownloadAll") {
            $("#chkDownloadAll").attr('checked', false);
        }
    }

    constructDownloadFilterQuery = function () {
        var args = { filter: {} };
        var criteriaSet = false;
        if ($("#chkDownloadAll").is(':checked')) {
            args.filter.all = true;
            criteriaSet = true;
        }
        if ($("#chkDownloadByDate").is(':checked') && $("#txtStartDate").val() != "" && $("#txtEndDate").val() != "") {
            /* var startDate = semusiCommon.getEpochFromDate(moment(new Date($("#txtStartDate").val()+' UTC')));
             var endDate = semusiCommon.getEpochFromDate(moment(new Date($("#txtEndDate").val() + ' UTC')).utc().endOf('day'));*/
            var startDate = moment(new Date($("#txtStartDate").val())).startOf('day').valueOf();
            var endDate = moment(new Date($("#txtEndDate").val())).endOf('day').valueOf();
            if (startDate > endDate) {
                alert("From date cannot be greater than To date.");
                return;
            }

            criteriaSet = true;
            var dateRange = { sd: parseInt(startDate / 1000), ed: parseInt(endDate / 1000) };
            args.filter.dateRange = dateRange;
        }
        if ($("#chkDownloadBySessions").is(':checked')) {
            var op = $("#ddlSessionOperator").val();
            var value = $("#txtSessionVal").val();
            if (parseInt(value) > 0) {
                var sessionRange = { op: op, value: parseInt(value) };
                args.filter.sessionRange = sessionRange;
                criteriaSet = true;
            }
        }
        if ($("#chkDownloadByDuration").is(':checked')) {
            var op = $("#ddlDurationOperator").val();
            var value = $("#txtDurationVal").val();
            if (parseInt(value) > 0) {
                value = parseInt(value) * 60; //Convert minutes to seconds.
                var durationRange = { op: op, value: value };
                args.filter.durationRange = durationRange;
                criteriaSet = true;
            }
        }
        var fileName = (downloadType == "I") ? "installs.csv" : "uninstalls.csv";
        if (!criteriaSet) {
            alert("None of the download options is selected!");
            return;
        }

        if (args.filter.all != true) {
            args.filter.dateRange.dates = [];
            var startDate = args.filter.dateRange.sd * 1000;
            while (startDate < args.filter.dateRange.ed * 1000) {
                args.filter.dateRange.dates.push(moment(startDate).format('YYYY-MM-DD'));
                startDate = parseInt(moment(startDate).add(1, 'days').valueOf());
            }
            args.filter.dateRange.ed = semusiCommon.addOffset(args.filter.dateRange.ed);
        }
        semusiChart.downloadDataCustom(downloadType, fileName, JSON.stringify(args));
        // close popup model
        $('.close-model').click();
    }

    $(document).ready(function () {
        setTimeout(function () {
            semusiChart.getInstallUninstallCohortData();
            initDateRange();
        }, 100);
    });

    //Public functions
    semusiChart.Initialize = function () {

        //set default date range
        semusiCommon.setDateRange(null, null);
        //semusiChart.getActiveUsers();
        //getReferalMappings();
        semusiChart.getTotalStats();
        semusiChart.getUsersAtRisk();
        semusiChart.getDeviceTotalStats();
        //populateSessions();
        //semusiChart.getActiveUserSessionStats();
        $("input[name='downloadOptions']").click(function () {
            downloadOptionClicked($(this).attr("id"), $(this).attr("checked"));
        });

        $("#sources-downloadLink").click(function () {
            var args = JSON.stringify({
                startDate_C: semusiCommon.dateRange.currentStartDate,
                endDate_C: semusiCommon.dateRange.currentEndDate,
                startDate_P: semusiCommon.dateRange.previousStartDate,
                endDate_P: semusiCommon.dateRange.previousEndDate,
                startDate_CNew: semusiCommon.dateRange.currentStartDateNew,
                endDate_CNew: semusiCommon.dateRange.currentEndDateNew,
                startDate_PNew: semusiCommon.dateRange.previousStartDateNew,
                endDate_PNew: semusiCommon.dateRange.previousEndDateNew,
                type: "BOTH",
                downloadFlag: true,
                downloadData: "sources",
                platform: $("#ddlPlatform").val()
            });
            var filename = "source-wise.csv";
            window.location = appiceEncode.encodePayload(semusiCommon.API_PARTS.metrices.r + '/getInstallUnistallStatsBySource?api_key=' + semusiCommon.getActiveUser.api_key + '&uniqueNumber=' +semusiCommon.randomNumber()+'&app_id=' + semusiCommon.ACTIVE_APP_ID + '&args=' + args + '&filename=' + filename);
        });

        $('#campaginBTN').bootstrapSwitch('state', false);
        $('#campaginBTN').on('switchChange.bootstrapSwitch', function (event, state) {
            if (state) {

                var text = $('#campaginBTN').bootstrapSwitch('offText');
                $('#campaginBTN').bootstrapSwitch('labelText', text);
                // called campaign installs and uninstalls
                $('#titleText').text('Campaigns');
                $('#sources-downloadLink').hide();
                semusiChart.getCampaignStats();
            }
            else {

                var text = $('#campaginBTN').bootstrapSwitch('onText');
                $('#campaginBTN').bootstrapSwitch('labelText', text);
                // called campaign installs and uninstalls
                $('#titleText').text('Sources');
                $('#sources-downloadLink').show();
                semusiChart.getTotalStats();
            }
        });

        $("#i-downloadLink").click(function () {
            downloadType = "I";
            $("#divDownloadBySessions").hide();
            $("#divDownloadByDuration").hide();
            $("#chkDownloadBySessions").attr('checked', false);
            $("#chkDownloadByDuration").attr('checked', false);
            $("#chkDownloadAll").attr('checked', false);
            $("#chkDownloadByDate").attr('checked', false);
            $("#txtDurationVal").val('');
            $("#txtSessionVal").val('');
            $("#spanTypeText").text('installed');

            if (calStartDate == "") {
                var newDate = semusiCommon.getEpochFromDate(moment().subtract('days', 29));
                var txtStartDate = moment(newDate).format(semusiCommon.getDateFormatt())
                $('#txtStartDate').datepicker('setDate', txtStartDate);
            } else {
                $('#txtStartDate').datepicker('setDate', calStartDate);
            }
            if (calEndDate == "") {
                $('#txtEndDate').datepicker('setDate', semusiCommon.getCurrentDate(true));
            } else {
                $('#txtEndDate').datepicker('setDate', calEndDate);
            }
        });
        $("#u-downloadLink").click(function () {
            downloadType = "U";
            $("#divDownloadBySessions").show();
            $("#divDownloadByDuration").show();
            $("#chkDownloadBySessions").attr('checked', false);
            $("#chkDownloadByDuration").attr('checked', false);
            $("#chkDownloadAll").attr('checked', false);
            $("#chkDownloadByDate").attr('checked', false);
            $("#txtDurationVal").val('');
            $("#txtSessionVal").val('');
            $("#spanTypeText").text('uninstalled');

            if (calStartDate == "") {
                var newDate = semusiCommon.getEpochFromDate(moment().subtract('days', 29));
                var txtStartDate = moment(newDate).format(semusiCommon.getDateFormatt())
                $('#txtStartDate').datepicker('setDate', txtStartDate);
            } else {
                $('#txtStartDate').datepicker('setDate', calStartDate);
            }
            if (calEndDate == "") {
                $('#txtEndDate').datepicker('setDate', semusiCommon.getCurrentDate(true));
            } else {
                $('#txtEndDate').datepicker('setDate', calEndDate);
            }

        });


        if (installCohortChart) {
            $('#ddlCohortDateFilter').change(function () {
                maxInstallValue = 0;
                filterObject = semusiCommon.getFilterObject($(this).val());
                //semusiChart.getInstallUninstallCohortData();
            });
            $('#chkPercentage').bootstrapSwitch('state', false);
            $('.bootstrap-switch-label').css("background", "#f5f5f5");
            $('#chkPercentage').on('switchChange.bootstrapSwitch', function (event, state) {
                if (state) {
                    var text = $('#chkPercentage').bootstrapSwitch('offText');
                    $('#chkPercentage').bootstrapSwitch('labelText', text);

                }
                else {
                    var text = $('#chkPercentage').bootstrapSwitch('onText');
                    $('#chkPercentage').bootstrapSwitch('labelText', text);
                }


                semusiChart.switchState = state;
                semusiChart.getInstallUninstallCohortData();

            });
            $("#txtFromDate").datepicker({
                todayHighlight: true,
                autoclose: true,
                endDate: '+0d',
                forceParse: false,
                format: 'M d, yyyy'
            });
            $("#txtToDate").datepicker({
                todayHighlight: true,
                autoclose: true,
                endDate: '+0d',
                forceParse: false,
                format: 'M d, yyyy'
            });
            $("#txtStartDate").datepicker({
                todayHighlight: true,
                autoclose: true,
                endDate: '+0d',
                forceParse: false,
                format: 'M d, yyyy'
            });
            $("#txtEndDate").datepicker({
                todayHighlight: true,
                autoclose: true,
                endDate: '+0d',
                forceParse: false,
                format: 'M d, yyyy'
            });
            //Assign default dates:
            $("#txtFromDate").val(semusiCommon.getCurrentYearStartDate());
            $("#txtToDate").val(semusiCommon.getCurrentDate(true));


            $('.theme-select').on('click', function () {
                var data = $(this).attr('data-attr');
                if (data == 'all') {
                    $('#swiu').text('All');
                } else if (data == 'android') {
                    $('#swiu').text('Android');
                } else if (data == 'ios') {
                    $('#swiu').text('iOS');
                }
                else if (data == 'web') {
                    $('#swiu').text('Web');
                }
                $("#ddlPlatform").val(data)
                $("#ddlPlatform").val();
                //semusiCommonData.populateSourceWiseInstallsUninstalls($("#ddlPlatform").val());
                showInstallsAndUninstalls($("#ddlPlatform").val());
            });
            $('#swiu').text('All')
        }
    };

    /// function for generating the Average user sesssion////
    semusiChart.getActiveUserSessionStats = function (filter) {
        var filter = filter || 'all';
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getActiveUserTimelySessions',
            data: {
                args: JSON.stringify({
                    startDate_C: semusiCommon.addOffset(semusiCommon.dateRange.currentStartDate),
                    endDate_C: semusiCommon.addOffset(semusiCommon.dateRange.currentEndDate),
                    startDate_P: semusiCommon.addOffset(semusiCommon.dateRange.previousStartDate),
                    endDate_P: semusiCommon.addOffset(semusiCommon.dateRange.previousEndDate),
                    startDate_CNew: semusiCommon.dateRange.currentStartDateNew,
                    endDate_CNew: semusiCommon.dateRange.currentEndDateNew,
                    startDate_PNew: semusiCommon.dateRange.previousStartDateNew,
                    endDate_PNew: semusiCommon.dateRange.previousEndDateNew
                }),
                filter_:filter,
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            success: function (data) {
                $("#overlay").hide();
                var changedTotal = 0;
                var percentChange = 0;
                semusiChart.timelyCurrentData = data.current;
                semusiChart.timelyPreviousData = data.previous.previousTotal;
                semusiChart.currentTotal = data.currentTotal;
                $('#lblTotalSessions').html("<span title='" + semusiChart.currentTotal + "'>" + nFormatter(semusiChart.currentTotal) + "</span>")
                let userActivity = [];
                if (filter === 'all' || filter === '') {
                    if (data.current.length > 0 &&  data.current[0].android != undefined) {
                        userActivity = data.current[0].android
                    }
                    if (data.current.length > 0 &&  data.current[0].ios != undefined) {
                        userActivity.concat(data.current[0].ios);
                    }
                    if (data.current.length > 0 &&  data.current[0].web != undefined) {
                        userActivity.concat(data.current[0].web);
                    }
                    $("#totalUsers").html("<span title='" + data.activeUsers + "'>" + nFormatter(parseInt(data.activeUsers)) + "</span>");
                } else {
                    if (filter === 'android') {
                        userActivity = data.current[0].android;
                        $("#totalUsers").html("<span title='" + data.androidUsers + "'>" + nFormatter(parseInt(data.androidUsers)) + "</span>");
                    }
                    if (filter === 'ios') {
                        userActivity = data.current[0].ios;
                        $("#totalUsers").html("<span title='" + data.iosUsers + "'>" + nFormatter(parseInt(data.iosUsers)) + "</span>");
                    }
                    if (filter === 'web') {
                        userActivity = data.current[0].web;
                        $("#totalUsers").html("<span title='" + data.webUsers + "'>" + nFormatter(parseInt(data.webUsers)) + "</span>");
                    }
                }

                //populate User Activity chart
                populateTimelySessionsUserActivityChunk(userActivity, filter, data.totalCurrentCount);

                if (data.activeUsers == undefined) {
                    $(".row").hide();
                    $("#divNodata").show();
                    return;
                }
                else if (data.activeUsers || parseInt(data.activeUsers) == 0) {
                    // user chunk
                    //$("#totalUsers").text(parseInt(data.activeUsers.android)+parseInt(data.activeUsers.ios));
                    let userActivity;
                    if (filter === 'all') {
                        userActivity = data.current[0].android.concat(data.current[0].ios).concat(data.current[0].web);
                        $("#totalUsers").html("<span title='" + data.activeUsers + "'>" + nFormatter(parseInt(data.activeUsers)) + "</span>");
                    } else {
                        if (filter === 'android') {
                            userActivity = data.current[0].android;
                            $("#totalUsers").html("<span title='" + data.androidUsers + "'>" + nFormatter(parseInt(data.androidUsers)) + "</span>");
                        }
                        if (filter === 'ios') {
                            userActivity = data.current[0].ios;
                            $("#totalUsers").html("<span title='" + data.iosUsers + "'>" + nFormatter(parseInt(data.iosUsers)) + "</span>");
                        }
                        if (filter === 'web') {
                            userActivity = data.current[0].web;
                            $("#totalUsers").html("<span title='" + data.webUsers + "'>" + nFormatter(parseInt(data.webUsers)) + "</span>");
                        }
                    }
                    $("#userHover").popover({
                        //title: 'Enter Mobile Number',
                        trigger: 'hover',
                        html: true,
                        delay: { show: 0, hide: 50 },
                        content: function () {
                            return 'Total Active users till <br/><strong>' + moment.utc().format(semusiCommon.getDateFormatt()) + '</strong> is : <strong>' + parseInt(data.activeUsers) + '</strong>';
                        }
                    });
                }



                changedTotal = semusiChart.currentTotal - semusiChart.timelyPreviousData;
                percentChange = (semusiChart.timelyPreviousData == 0) ? 100 : parseFloat(changedTotal / semusiChart.timelyPreviousData * 100).toFixed(2);
                var strPercentChange;
                var changeSign;
                if (percentChange > 0 && percentChange < 200) {
                    //changeSign = '<div><i class="fa fa-2x fa-arrow-up"></i></div>'
                    strPercentChange = parseInt(percentChange) + '%';
                    $('#s-downarrow').hide();
                    $('#s-uparrow').show();
                } else if (percentChange > 400) {
                    //changeSign = '<div><i class="fa fa-2x fa-arrow-up"></i></div>'
                    strPercentChange = '61%';
                    $('#s-downarrow').hide();
                    $('#s-uparrow').show();
                }
                else if (percentChange < 0) {
                    percentChange = percentChange * -1;
                    //changeSign = '<div><i class="fa fa-2x fa-arrow-down"></i></div>';
                    strPercentChange = parseInt(percentChange) + '%';
                    $('#s-downarrow').show();
                    $('#s-uparrow').hide();
                }
                else if (percentChange == 0) {
                    changeSign = '';
                    strPercentChange = parseInt(percentChange) + '%';
                }
                if (semusiChart.timelyPreviousData == 0) {
                    strPercentChange = 'No Change';
                    $('#s-downarrow').hide();
                    $('#s-uparrow').hide();
                }
                //$("#tdSignSessions").html(changeSign);
                $("#lblChangeTotalSessions").text(strPercentChange); //previous data
                //populateTimelySessionsChunk();
            },
            error: function () {
                $("#overlay").hide();
            }
        });
    }
    populateAverageUsersChunk = function () {
        //var platform = $("#ddlPlatform").val();
        var total_tsd = 0;
        var total_sc = 0;
        //var currentTotal = 0;
        semusiChart.evenntCurrentData.forEach(function (item) {
            if (item.tsd < 10000 && item.tsd > 0) {
                if (item.tsd) {
                    total_tsd = total_tsd + item.tsd;
                }
                if (item.sc) {
                    total_sc = total_sc + item.sc;
                }
            }
        });
        var currentTotal = parseFloat((total_tsd / total_sc)).toFixed(2);
        if (currentTotal >= 0) {
            var mins = parseInt(currentTotal / 60);
            var seconds = parseInt(currentTotal - (mins * 60));
            if (!isNaN(mins)) {
                $("#lblAvgSessionLength").text(mins);
            }
            if (!isNaN(seconds)) {
                $("#lblAvgSessionLengthSec").text(seconds);
            }

        }
        else {
            $("#lblAvgSessionLength").text(0);
            $("#lblAvgSessionLengthSec").text(0);
        }
    }

    /// end function for generating the Average user sesssion////

    semusiChart.getCampaignStats = function () {
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getCampaignStats',
            data: {
                args: JSON.stringify({
                    startDate_C: semusiCommon.dateRange.currentStartDate,
                    endDate_C: semusiCommon.dateRange.currentEndDate,
                    startDate_P: semusiCommon.dateRange.previousStartDate,
                    endDate_P: semusiCommon.dateRange.previousEndDate,
                    startDate_CNew: semusiCommon.dateRange.currentStartDateNew,
                    endDate_CNew: semusiCommon.dateRange.currentEndDateNew,
                    startDate_PNew: semusiCommon.dateRange.previousStartDateNew,
                    endDate_PNew: semusiCommon.dateRange.previousEndDateNew
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            success: function (result) {
                semusiCommonData.Dataset = { "android": [{ "Whatsapp_Bot": { "in": 0, "ri": 0, "un": 1, "ru": 0, "cpi": 0 } }, { "CIT": { "in": 2, "ri": 0, "un": 3, "ru": 0, "cpi": 0 } }, { "MobileWebsite": { "in": 0, "ri": 0, "un": 2, "ru": 0, "cpi": 0 } }, { "Valuation": { "in": 0, "ri": 0, "un": 2, "ru": 0, "cpi": 0 } }, { "share-with-investors": { "in": 2, "ri": 0, "un": 0, "ru": 0, "cpi": 0 } }], "ios": [], "web": [] };
                showInstallsAndUninstalls($("#ddlPlatform").val());
            }
        });
    };

    semusiChart.getTotalStats = function (filter) {
        var filter = filter || 'all';
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getTotalStats',
            data: {
                args: JSON.stringify({
                    startDate_C: semusiCommon.dateRange.currentStartDate,
                    endDate_C: semusiCommon.dateRange.currentEndDate,
                    startDate_P: semusiCommon.dateRange.previousStartDate,
                    endDate_P: semusiCommon.dateRange.previousEndDate,
                    startDate_CNew: semusiCommon.dateRange.currentStartDateNew,
                    endDate_CNew: semusiCommon.dateRange.currentEndDateNew,
                    startDate_PNew: semusiCommon.dateRange.previousStartDateNew,
                    endDate_PNew: semusiCommon.dateRange.previousEndDateNew
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            success: function (result) {
                $("#overlay").hide();
                if (result.current == undefined) {
                    result.current = { androidTotal: 0, iosTotal: 0, webTotal: 0, totalUninstall: 0, totalUniqueInstall: 0, totalUniqueUninstall: 0 };
                }
                if (result.previous == undefined) {
                    result.previous = { androidTotal: 0, iosTotal: 0, webTotal: 0, totalUninstall: 0 };
                }
                if (filter == 'all') {
                    getDauWauMau();
                } else {
                    getDauWauMauPlatformFilter(filter);
                }
                semusiChart.getActiveUserSessionStats(filter);
                populateChurns(result.current, result.previous, result, filter);
                eventPieChart(filter);
                populateAvChart(result.appversion, filter);
                populateNewInstalls(result.current, result.previous, filter);
                populateUniqueInstalls(result.current.totalUniqueInstall);
                populateUniqueChurns(result.current.totalUniqueUninstall);
                semusiCommonData.Dataset = result.current.all;
                semusiChart.getUsersAtRisk();
                semusiChart.getDeviceTotalStats(filter);
                showInstallsAndUninstalls($("#ddlPlatform").val());
            },
            error: function () {
                $("#overlay").hide();
            }
        });
    };

    function showInstallsAndUninstalls(platform) {
        maxValue = 0;
        var tableData = [];
        var platforms = ['android', 'ios', 'web'];
        // Check if semusiCommonData is defined then only check dataSet inside semusiCommonData

        if (semusiCommonData && semusiCommonData.Dataset && (semusiCommonData.Dataset['android'] || semusiCommonData.Dataset['ios']) ) {
            var sources = semusiCommonData.getUniqueSources(semusiCommonData.Dataset, platform);
            var otherRow = {
                source: "Other",
                avg_cpi: "",
                I: 0,
                U: 0,
                total: 0
            };

            var data = semusiCommonData.Dataset;
            for (var y = 0; y < sources.length; y++) {
                var row = {};

                var installs = 0;
                var uninstalls = 0;
                var avgcpi = 0;
                var uniqueInstalls = 0;
                var uniqueUninstalls = 0;

                for (var x = 0; x < platforms.length; x++) {
                    if (data[platforms[x]]) {
                        if (platforms[x].toLowerCase() == platform || platform == 'all') {
                            for (var z = 0; z < data[platforms[x]].length; z++) {
                                if (data[platforms[x]][z][sources[y]]) {
                                    var rec = data[platforms[x]][z][sources[y]];
                                    var keys = Object.keys(data[platforms[x]][z][sources[y]]);
                                    keys.forEach(function (value) {
                                        if (value) {
                                            if (value == 'in' || value == 'ri') {
                                                installs += rec[value];
                                            }
                                            if (value == 'in') {
                                                uniqueInstalls += rec[value];
                                            }
                                            if (value == 'un' || value == 'ru') {
                                                uninstalls += rec[value];
                                            }
                                            if (value == 'un') {
                                                uniqueUninstalls += rec[value];
                                            }

                                            if (value == 'cpi') {
                                                avgcpi = rec[value];
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }
                }
                //When installs is 0 and uninstall is > 0 then it means install value is put in others, so uninstall has to be pu t to others as well.
                if (installs > 0 || uninstalls > 0) {
                    row.source = sources[y];
                    row.avg_cpi = parseFloat(avgcpi).toFixed(2);
                    row.I = installs;
                    row.U = uninstalls;
                    row.UINS = uniqueInstalls;
                    row.UUNINS = uniqueUninstalls;
                    row.percent = (uninstalls == 0) ? "0%" : parseFloat((uninstalls / installs) * 100).toFixed(2) + "%";
                    tableData.push(row);

                    installs = 0;
                    uninstalls = 0;
                }
                else if (installs == 0 && uninstalls > 0) {
                    //When we have this scenario, it means installs are grouped to others
                    otherRow.U = otherRow.U + uninstalls;
                }

            }
            if (otherRow.I > 0) {
                otherRow.percent = parseFloat((otherRow.U / otherRow.I) * 100).toFixed(2) + "%";
                tableData.push(otherRow);
            }
        }

        var index = 1;
        var max_i = 0;
        var max_u = 0;
        var series = [];
        sources = [];
        var cpi = '';
        var percent = '';

        var seriesComplete = [];
        var sourcesComplete = [];
        var cpiComplete = '';
        var percentComplete = '';

        if (tableData.length > 0) {
            series.push({ showInLegend: false, name: 'Install', data: [] })
            series.push({ showInLegend: false, name: 'Uninstall', data: [] })
            //series.push({showInLegend: false, name: 'Total Uninstall', data:[]})

            seriesComplete.push({ showInLegend: false, name: 'Install', data: [] })
            seriesComplete.push({ showInLegend: false, name: 'Uninstall', data: [] })
        }

        tableData.forEach(function (item) {
            if (item.I > max_i) {
                max_i = item.I;
            }
            if (item.U > max_u) {
                max_u = item.U;
            }

            if (item.source == 'Self' || item.source == 'self') {
                item.source = 'Organic';
            }

            item.percent = (item.percent == 'Infinity%') ? '0%' : item.percent;
            item.avg_cpi = (parseInt(item.avg_cpi) > 0) ? item.avg_cpi : '<br />';

            if (index < 6) {
                sources.push(item.source);
                series[0].data.push(item.I);
                series[1].data.push(item.U);
                cpi += '<div>' + item.avg_cpi + '</div>';
                percent += '<div>' + item.percent + '</div>';
                //$('#tblSources > tbody').append('<tr><td style="padding-right:5px;text-align:right;">'+item.avg_cpi +'</td><td style="padding-right:5px;text-align:right;">'+item.UINS+' (' + item.I +')</td><td style="text-align:right;padding:3px;border:none"><div style="float:right" id="i_'+index+'">&nbsp;</div></td><td style="text-align:center">'+ semusiCommon.toFirstUpper(item.source) +'</td><td style="padding:3px;text-align:left;;border:none"><div style="float:left" id="u_'+ index +'">&nbsp;</div></td><td style="padding-right:5px;text-align:right;">'+item.UUNINS+' ('+ item.U + ')</td><td style="text-align:center;color:white;font-weight:bold;" id="td_'+index+'">'+ item.percent +'</td></tr>');
            }
            else {
                $('#lnkMoreSources').show();
            }

            sourcesComplete.push(item.source);
            seriesComplete[0].data.push(item.I);
            seriesComplete[1].data.push(item.U);
            cpiComplete += '<div>' + item.avg_cpi + '</div>';
            percentComplete += '<div>' + item.percent + '</div>';
            //$('#tblSourcesAll > tbody').append('<tr><td style="padding-right:5px;text-align:right;">'+ item.avg_cpi+'</td><td style="padding-right:5px;text-align:right;">'+item.UINS+' (' + item.I +')</td><td style="text-align:right;padding:3px;border:none"><div style="float:right" id="i_all_'+index+'">&nbsp;</div></td><td style="text-align:center">'+ semusiCommon.toFirstUpper(item.source) +'</td><td style="padding:3px;text-align:left;;border:none"><div style="float:left" id="u_all_'+ index +'">&nbsp;</div></td><td style="padding-right:5px;text-align:right;">'+item.UUNINS+' ('+ item.U + ')   </td><td style="text-align:center;color:white;font-weight:bold;" id="td_all_'+index+'">'+ item.percent +'</td></tr>');
            index++;
        });

        $('#avg_cpi').html(cpi);
        $('#sourcePercent').html(percent);
        $('#sourceContainer').css(getChartStyle(tableData));

        Highcharts.setOptions({
            colors: ['#00acac', '#ff5b57']
        });

        Highcharts.chart('sourceContainer', {
            chart: {
                type: 'bar',
                backgroundColor: 'transparent'
            },
            title: {
                text: null
            },
            xAxis: {
                categories: sources,
                title: {
                    text: null
                }
            },
            yAxis: {
                gridLineColor: '#ffffff',
                gridLineWidth: 0,
                min: 0,
                title: {
                    text: null
                },
                labels: {
                    overflow: 'justify'
                }
            },
            tooltip: {
                valueSuffix: null
            },
            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: true
                    }
                },
                series: {
                    pointWidth: 12
                }
            },
            legend: {
                enabled: true,
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'bottom',
                x: 0,
                y: 0,
                floating: false,
                borderWidth: 1,
                backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
                shadow: true
            },
            credits: {
                enabled: false
            },
            series: series
        });

        sourceGraphData.sourcesComplete = sourcesComplete;
        sourceGraphData.seriesComplete = seriesComplete;
        sourceGraphData.cpiComplete = cpiComplete;
        sourceGraphData.percentComplete = percentComplete;

        fullsourceContainer();
    }

    var fullsourceContainer = function () {
        Highcharts.chart('FullsourceContainer', {
            chart: {
                type: 'bar',
                backgroundColor: 'transparent'
            },
            title: {
                text: null
            },
            xAxis: {
                categories: sourceGraphData.sourcesComplete,
                title: {
                    text: null
                }
            },
            yAxis: {
                gridLineColor: '#ffffff',
                gridLineWidth: 0,
                min: 0,
                title: {
                    text: null
                },
                labels: {
                    overflow: 'justify'
                }
            },
            tooltip: {
                valueSuffix: null
            },
            plotOptions: {
                bar: {
                    dataLabels: {
                        enabled: true
                    }
                }
            },
            legend: {
                enabled: true,
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'bottom',
                x: 0,
                y: 0,
                floating: false,
                borderWidth: 1,
                backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
                shadow: true
            },
            credits: {
                enabled: false
            },
            series: sourceGraphData.seriesComplete
        });

        $('#complete_avg_cpi').html(sourceGraphData.cpiComplete);
        $('#complete_sourcePercent').html(sourceGraphData.percentComplete);
    }


    var getChartStyle = function (tableData) {
        if (tableData.length == 0) {
            return { 'min-width': '700px', 'max-width': '700px', 'height': '120px', 'margin': '0 auto' }
        }
        else if (tableData.length == 1) {
            return { 'min-width': '700px', 'max-width': '700px', 'height': '150px', 'margin': '0 auto' }
        }
        else if (tableData.length == 2) {
            return { 'min-width': '700px', 'max-width': '700px', 'height': '180px', 'margin': '0 auto' }
        }
        else if (tableData.length == 3) {
            return { 'min-width': '700px', 'max-width': '700px', 'height': '240px', 'margin': '0 auto' }
        }
        else {
            return { 'min-width': '700px', 'max-width': '700px', 'height': '300px', 'margin': '0 auto' }
        }
    }

    semusiChart.getUsersAtRisk = function () {
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getUsersAtRisk',
            data: {
                args: JSON.stringify({
                    startDate_C: semusiCommon.dateRange.currentStartDate,
                    endDate_C: semusiCommon.dateRange.currentEndDate
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            success: function (data) {
                $("#tblRisk").hide();
                $(".uninstallTmpSpace").show();
                $("#atRisk").html(nFormatter(data.result[0].range));
            }
        });
    }

    $("#btnView").click(function () {
        semusiChart.getInstallUninstallCohortData();
    });

    semusiChart.getInstallUninstallCohortData = function (filter) {

        var filter = $('#ddlCohortDateFilter').val();
        var fromDate = $("#txtFromDate").val();
        var toDate = $("#txtToDate").val();
        var startDate = semusiCommon.getEpochFromDate(moment(fromDate).startOf('day'));
        var endDate = semusiCommon.getEpochFromDate(moment(toDate).endOf('day'));

        var startDateNew = moment(startDate).format('YYYY-MM-DD');
        var endDateNew = moment(endDate).format('YYYY-MM-DD');

        if (startDate > endDate) {
            alert("From date cannot be greater than To date.");
            return;
        }

        var periodType;
        switch (filter) {
            case "daily":
                periodType = "d";
                break;
            case "weekly":
                periodType = "w";
                break;
            case "monthly":
                periodType = "m";
                break;
            case "yearly":
                periodType = "y";
                break;
            default:
                periodType = "d";
                break;
        }

        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getCohortDataForInstalls',
            data: {
                args: JSON.stringify({
                    startDate: startDate / 1000,
                    endDate: endDate / 1000,
                    startDateNew: startDateNew,
                    endDateNew: endDateNew,
                    periodtype: periodType,
                    metrices: [
                        {

                        }
                    ]
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            success: function (data) {
                //generateCohort(data,filter);
                generateCohort(data, filter, startDate, endDate);
            }
        });
        //var data = {"2016":{"4":{"15":{"1":2,"2":2,"in":23,"un":3},"20":{"in":10,"un":2}},"5":{"15":{"in":8,"un":0}}}};
        //generateCohort(data,filter, startDate, endDate);
    };

    semusiChart.downloadData = function (type, filename) {
        window.location = semusiCommon.API_PARTS.metrices.r + '/downloadData?api_key=' + semusiCommon.getActiveUser.api_key + '&app_id=' + semusiCommon.ACTIVE_APP_ID + '&uniqueNumber=' +semusiCommon.randomNumber()+ '&type=' + type + '&filename=' + filename + '&startDate=' + semusiCommon.dateRange.currentStartDate + '&endDate=' + semusiCommon.dateRange.currentEndDate;
    };

    semusiChart.downloadDataCustom = function (type, filename, args) {
        const downloadUrl = semusiCommon.API_PARTS.metrices.r + '/downloadDataCustom?api_key=' + semusiCommon.getActiveUser.api_key + '&app_id=' + semusiCommon.ACTIVE_APP_ID + '&uniqueNumber=' + semusiCommon.randomNumber() + '&type=' + type + '&filename=' + filename + '&args=' + args;
      
        fetch(downloadUrl)
          .then(response => {
            if (response.status === 200) {
            showMessagesucess("Download initiated.");
            $("#messagesucess").delay(3000).fadeOut(300);
            $("#message").delay(3000).fadeOut(300);
            location.reload();
            } else {
            showError("Download initiation failed.")
            location.reload();
            }
          })
          .catch(error => {
            logger.error('Error:', error);
          });
      };
    semusiChart.launchRetentionCampaign = function () {
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.templates.r + '/getAtRiskAudienceSegmentId',
            data: {
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            success: function (data) {
                if (data.result) {
                    window.location = "/dashboard?action=campaigns&new=true&segmentid=" + data.result;
                }
            }
        });
    }

    /* DAW,MAW and WAU dashboard colum chart section  */
    function getDauWauMau() {
        //calulate number of days in current month
        var days = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate();
        //Check current date is the end date of the month
        var filter = filter || 'all';
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getDauWauMau',
            data: {
                args: JSON.stringify({
                    startDate_C: semusiCommon.dateRange.currentStartDate,
                    endDate_C: semusiCommon.dateRange.currentEndDate,
                    startDate_P: semusiCommon.dateRange.previousStartDate,
                    endDate_P: semusiCommon.dateRange.previousEndDate,
                    startDate_CNew: semusiCommon.dateRange.currentStartDateNew,
                    endDate_CNew: semusiCommon.dateRange.currentEndDateNew,
                    startDate_PNew: semusiCommon.dateRange.previousStartDateNew,
                    endDate_PNew: semusiCommon.dateRange.previousEndDateNew
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            success: function (result) {
                $("#overlay").hide();
                if (result) {
                    var DAU = (result.dau) ? parseInt(result.dau) : result.dau;
                    var WAU = (result.wau) ? parseInt(result.wau) : result.wau;
                    var MAU = (result.mau) ? parseInt(result.mau) : result.mau;
                    var activeCmp = (result.activeCmp) ? parseInt(result.activeCmp) : result.activeCmp;
                    var totalCmp = (result.totalCmp) ? parseInt(result.totalCmp) : result.totalCmp;
                    $("#card_dau").html(nFormatter(DAU));
                    $("#card_mau").html(nFormatter(MAU));
                    $("#card_wau").html(nFormatter(WAU));
                    $("#card_totalcmp").html(nFormatter(totalCmp));
                    $("#card_activecmp").html(nFormatter(activeCmp));
                    $("#card_DAUdMAU").html((DAU / MAU).toFixed(2));
                    // create data for column_chart
                    var dailyDAU = [];

                    result.daywisedau.forEach(function (item) {
                        var existing = dailyDAU.filter(function (v, i) {
                            return v[0] == item[0];
                        });
                        if (existing.length) {
                            var existingIndex = dailyDAU.indexOf(existing[0]);
                            dailyDAU[existingIndex][1] = dailyDAU[existingIndex][1] + item[1];
                        } else {
                            if (typeof item.value == 'string')
                                item.value = [item.value];
                            dailyDAU.push(item);
                        }
                    });
                    colunmLineChart(DAU, WAU, MAU, dailyDAU);
                }
            },
            error: function () {
                $("#overlay").hide();
            }
        });
    }
    /* Get DAU WAU AND MAU Platfoem wise */
    function getDauWauMauPlatformFilter(platform) {
        let platform_ = platform;
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getDauWauMauWithPlatform',
            data: {
                args: JSON.stringify({
                    startDate_C: semusiCommon.dateRange.currentStartDate,
                    endDate_C: semusiCommon.dateRange.currentEndDate,
                    startDate_P: semusiCommon.dateRange.previousStartDate,
                    endDate_P: semusiCommon.dateRange.previousEndDate,
                    startDate_CNew: semusiCommon.dateRange.currentStartDateNew,
                    endDate_CNew: semusiCommon.dateRange.currentEndDateNew,
                    startDate_PNew: semusiCommon.dateRange.previousStartDateNew,
                    endDate_PNew: semusiCommon.dateRange.previousEndDateNew
                }),
                platform_: platform_,
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            success: function (result) {
                $("#overlay").hide();
                if (result) {
                    var activeCamp = (result.activeCamp) ? parseInt(result.activeCamp) : result.activeCamp;
                    var totalCmp = (result.totalCmp) ? parseInt(result.totalCmp) : result.totalCmp;
                    $("#card_activecmp").html(nFormatter(activeCamp));
                    $("#card_totalcmp").html(nFormatter(totalCmp));
                    
                    var DAU = 0; var WAU = 0; var MAU = 0; var daywisedau;
                    if (platform == 'android') {
                        DAU = (result.android.dau) ? parseInt(result.android.dau) : result.android.dau;
                        WAU = (result.android.wau) ? parseInt(result.android.wau) : result.android.wau;
                        MAU = (result.android.mau) ? parseInt(result.android.mau) : result.android.mau;
                        colunmLineChart(DAU, WAU, MAU, result.android.daywisedau);
                    }
                    if (platform == 'ios') {
                        WAU = (result.ios.wau) ? parseInt(result.ios.wau) : result.ios.wau;
                        MAU = (result.ios.mau) ? parseInt(result.ios.mau) : result.ios.mau;
                        DAU = (result.ios.dau) ? parseInt(result.ios.dau) : result.ios.dau;
                        colunmLineChart(DAU, WAU, MAU, result.ios.daywisedau);
                    }
                    if (platform == 'web') {
                        WAU = (result.web.wau) ? parseInt(result.web.wau) : result.web.wau;
                        MAU = (result.web.mau) ? parseInt(result.web.mau) : result.web.mau;
                        DAU = (result.web.dau) ? parseInt(result.web.dau) : result.web.dau;
                        colunmLineChart(DAU, WAU, MAU, result.web.daywisedau);
                    }
                    $("#card_dau").html(nFormatter(DAU));
                    $("#card_mau").html(nFormatter(MAU));
                    $("#card_wau").html(nFormatter(WAU));

                }
            },
            error: function () {
                $("#overlay").hide();
            }
        });
    }
    /* colunm and line chart function for DAU,MAW and WAU */
    function colunmLineChart(DAU, WAU, MAU, daywisedau) {
        var data = [{ x: "DAU", value: DAU, displayValue: nFormatter(DAU), normal: { fill: "#55efc4", stroke: null, label: { enabled: true } }, hovered: { fill: "#00b894", stroke: null, label: { enabled: true } }, selected: { fill: "#00b894", stroke: null, label: { enabled: true } } }, { x: "WAU", value: WAU, displayValue: nFormatter(WAU), normal: { fill: "#74b9ff", stroke: null, label: { enabled: true } }, hovered: { fill: "#0984e3", stroke: null, label: { enabled: true } }, selected: { fill: "#0984e3", stroke: null, label: { enabled: true } } },
        { x: "MAU", value: MAU, displayValue: nFormatter(MAU), normal: { fill: "#a29bfe", stroke: null, label: { enabled: true } }, hovered: { fill: "#6c5ce7", stroke: null, label: { enabled: true } }, selected: { fill: "#6c5ce7", stroke: null, label: { enabled: true } } }];
        $("#column_chart").html("");
        // Put License Key
        anychart.licenseKey("semusi.com-df30754a-aa10847e");
        chart = anychart.column();
        // new text for credits
        // For appICE Value Change
        var credits = chart.credits();
        credits.url(semusiCommon.PANELURL + "/dashboard");
        credits.logoSrc(semusiCommon.PANELURL + "/assets/img/icon-title.png");
        credits.text("appICE");
        // create a column series and set the data
        var series = chart.column(data);
        series.name("Count :");
        series.labels().enabled(true).format("{%displayValue}");
        // set the container id
        chart.container("column_chart");
        // set axes titles
        var xAxis = chart.xAxis();
        xAxis.title("Users");
        var yAxis = chart.yAxis();
        yAxis.title("Active Users Counts");
        // initiate drawing the chart
        chart.draw();
        /* line chart start for DAU */
        $("#line_chart").html("");
        var lineChartData = daywisedau;
        chart = anychart.line();
        // new text for credits
        // For appICE Value Change
        var credits = chart.credits();
        credits.url(semusiCommon.PANELURL + "/dashboard");
        credits.logoSrc(semusiCommon.PANELURL + "/assets/img/icon-title.png");
        credits.text("appICE");
        var xAxis = chart.xAxis();
        xAxis.title("Date-Month ");
        var yAxis = chart.yAxis();
        yAxis.title("Daily Active Users Counts");
        // create a line series and set the data
        var series = chart.line(lineChartData);
        // format labels
        var xLabels = chart.xAxis().labels();
        xLabels.width(60);
        xLabels.wordWrap("break-word");
        xLabels.wordBreak("break-all"); // set the container id
        chart.container("line_chart");
        // initiate drawing the chart
        chart.draw();
    }
    /* Get events data and render pie chart for top 10 events */
    function eventPieChart(platform) {
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getEventsStats',
            data: {
                args: JSON.stringify({
                    startDate: semusiCommon.dateRange.currentStartDate,
                    endDate: semusiCommon.dateRange.currentEndDate,
                    startDateNew: semusiCommon.dateRange.currentStartDateNew,
                    endDateNew: semusiCommon.dateRange.currentEndDateNew
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            success: function (result) {
                $("#overlay").hide();
                if (result) {
                    /* find top 10 event and render chart function call */
                    createBarChartData(result, platform);
                }
            },
            error: function () {
                $("#overlay").hide();
            }
        });
    }


    //////////////////////////////////////////  
    //Demo Chart
    var chart = anychart.line();
    // set chart padding
    chart.padding([10, 20, 5, 20]);

    // turn on chart animation
    chart.animation(true);

    // turn on the crosshair
    chart.crosshair(true);

    // set chart title text settings
    chart.title('Cohort Analysis');

    // set y axis title
    chart.yAxis().title('User Count');

    // create logarithmic scale
    var logScale = anychart.scales.log();
    logScale.minimum(1).maximum(100);

    // set scale for the chart, this scale will be used in all scale dependent entries such axes, grids, etc
    chart.yScale(logScale);

    // create data set on our data,also we can pud data directly to series
    var dataSet = anychart.data.set([
        ['11/05/201', '12', '7'],
        ['12/05/201', '15', '9'],
        ['13/05/201', '19', '13'],
        ['14/05/201', '14', '7'],
        ['15/05/201', '22', '12'],
        ['16/05/201', '20', '13'],
        ['17/05/201', '8', '3']
    ]);

    // map data for the first series,take value from first column of data set
    var firstSeriesData = dataSet.mapAs({ x: 0, value: 1 });

    // map data for the second series,take value from second column of data set
    var secondSeriesData = dataSet.mapAs({ x: 0, value: 2 });

    // temp variable to store series instance
    var series;

    // setup first series
    series = chart.line(firstSeriesData);
    series.name('Browsed Home ');
    // enable series data labels
    series.labels().enabled(true).anchor('left-bottom').padding(5);
    // enable series markers
    series.markers(true);

    // setup second series
    series = chart.line(secondSeriesData);
    series.name('Browsed Home and Speeches');
    // enable series data labels
    series.labels().enabled(true).anchor('left-bottom').padding(5);
    // enable series markers
    series.markers(true);
    series.stroke("1 red");
    var credits = chart.credits();
    credits.url(semusiCommon.PANELURL + "/dashboard");
    credits.logoSrc(semusiCommon.PANELURL + "/assets/img/icon-title.png");
    credits.text("appICE");
    // turn the legend on
    chart.legend().enabled(true).fontSize(13).padding([0, 0, 20, 0]);

    // set container for the chart and define padding
    chart.container('container_cohart');
    // initiate chart drawing
    chart.draw();

    // set stage table chart for Campaign summery 
    var stage = anychart.graphics.create("table_summary");
    // create table
    var credits = stage.credits();
    credits.url(semusiCommon.PANELURL + "/dashboard");
    credits.logoSrc(semusiCommon.PANELURL + "/assets/img/icon-title.png");
    credits.text("appICE");
    var tableS = anychart.standalones.table();
    // set table content
    tableS.contents([
        [
            "Campaign Name",
            "Campaign Channel",
            "Users"
        ], [
            "FB All Audience ",
            "Facebook",
            "13"
        ], [
            "FB SIP target ",
            "Facebook",
            "77"
        ], [
            "TW Information ",
            "Twitter",
            "7"
        ], [
            "TW Loan campaign",
            "Twitter",
            "65"
        ]
    ]);
    // set colors for ever and odd rows
    tableS.getRow(0).height(40).fontWeight(500); // Set first row height 40px and bold the text
    tableS.getCol(0).width(200).fontWeight(500);  // Set first column width 200 px and bold the text
    // set colors for ever and odd rows
    tableS.rowOddFill("#F5F5F5");  // color for odd rows
    tableS.rowEvenFill("#FFFFFF"); // color for even rows
    // adjust table border and position text in each cell into center
    tableS.cellBorder("#FFFFFF").vAlign("middle").hAlign("left");
    // set table container and initiate draw
    tableS.container(stage).draw();

    // set stage table chart for Assets  
    var stage = anychart.graphics.create("table_assets");
    // create table
    var tableA = anychart.standalones.table();
    var credits = stage.credits();
    credits.url(semusiCommon.PANELURL + "/dashboard");
    credits.logoSrc(semusiCommon.PANELURL + "/assets/img/icon-title.png");
    credits.text("appICE");
    // set table content
    tableA.contents([[
        "Asset",
        "Clicks",
        "Downloads"
    ],
    [
        "Financial Sector in the New Decade (Address by Shri Shaktikanta Das, Governor, Reserve Bank of India - Thursday, March 25, 2021 - at the Times Network India Economic Conclave 2021 in New Delhi) ",
        "65",
        "56"
    ], [
        "Governor’s Statement - May 5, 2021  ",
        "58",
        "37"
    ], [
        "Open Banking in India - Remarks by Shri M. Rajeshwar Rao, Deputy Governor, Reserve Bank of India - Wednesday, April 14, 2021 ",
        "28",
        "17"
    ], [
        "Towards a Stable Financial System (Nani Palkhivala Memorial Lecture Delivered by Shri Shaktikanta Das, Governor, Reserve Bank of India on Saturday, January 16, 2021) ",
        "19",
        "11"
    ], [
        "Creating New Opportunities for Growth (Shri Shaktikanta Das, Governor, Reserve Bank of India - February 25, 2021 - at the Bombay Chamber of Commerce and Industry) ",
        "23",
        "9"
    ]
    ]);
    // set colors for ever and odd rows
    tableA.getRow(0).height(40).fontWeight(500); // Set first row height 40px and bold the text
    tableA.getCol(0).width(300).fontWeight(500);  // Set first column width 200 px and bold the text
    // set colors for ever and odd rows
    tableA.rowOddFill("#F5F5F5");  // color for odd rows
    tableA.rowEvenFill("#FFFFFF"); // color for even rows
    // adjust table border and position text in each cell into center
    tableA.cellBorder("#FFFFFF").vAlign("middle").hAlign("left");
    // set table container and initiate draw
    tableA.container(stage).draw();


    // create data
    var channelData = [
        { x: "Direct", value: 637166 },
        { x: "Organic Search", value: 721630 },
        { x: "Other", value: 658662 },
        { x: "Paid Search", value: 728662 },
        { x: "Referral", value: 400012 },
        { x: "Display", value: 320001 },
        { x: "Social", value: 430012 },
        { x: "Email", value: 700012 }
    ];

    anychart.licenseKey("semusi.com-df30754a-aa10847e");

    // create a chart and set the data
    var channelChart = anychart.pie(channelData);
    //Set credits
    var channelcredits = channelChart.credits();
    channelcredits.url(semusiCommon.PANELURL + "login");
    channelcredits.logoSrc(semusiCommon.PANELURL + "assets/img/icon-title.png");
    channelcredits.text("appICE");




    // set the chart title
    channelChart.title("Top Channels");
    let legend = channelChart.legend()
    channelChart.legend().paginator(false);
    // configure the format of legend items
    channelChart.legend().itemsFormat(
        "{%x}{%y}"
    );
    // enables legend
    legend.enabled(true);
    // set legend height
    legend.height(250);
    // set legend width
    legend.width(180);
    // set legend position
    legend.position("right");
    // set legend align
    legend.align("center");
    // legend items layout
    legend.itemsLayout("vertical");
    // set the container id
    channelChart.container("channel_container");
    // initiate drawing the chart
    channelChart.draw();

    //status 

    // create data
    var channelData1 = [
        { x: "404 Page Not Found", value: 160 },
        { x: "500 Server Error", value: 45 },
        { x: "200 Ok", value: 1662 },
    ];

    anychart.licenseKey("semusi.com-df30754a-aa10847e");

    // create a chart and set the data
    var channelChart1 = anychart.pie(channelData1);
    //Set credits
    var channelcredits1 = channelChart1.credits();
    channelcredits1.url(semusiCommon.PANELURL + "login");
    channelcredits1.logoSrc(semusiCommon.PANELURL + "assets/img/icon-title.png");

    channelcredits1.text("appICE");




    // set the chart title
    channelChart1.title("Status Codes");
    let legend1 = channelChart1.legend()
    channelChart1.legend().paginator(false);
    // configure the format of legend items
    channelChart1.legend().itemsFormat(
        "{%x}{%y}"
    );
    // enables legend
    legend1.enabled(true);
    // set legend height
    legend1.height(250);
    // set legend width
    legend1.width(180);
    // set legend position
    legend1.position("right");
    // set legend align
    legend1.align("center");
    // legend items layout
    legend1.itemsLayout("vertical");
    // set the container id
    channelChart1.container("status_container");
    // initiate drawing the chart
    channelChart1.draw();



    // Column chart
    var searchData = [
        ["recruitment", 830],
        ["Reverse Repo Rate", 799],
        ["NUE", 726],
        ["Exchange", 659],
        ["RBI Policy", 649],
        ["Repo Rate", 619],
        ["fsa", 576],
        ["vacancy", 555],
        ["https://www.rbi.org.in", 487],
        ["loans", 449],
    ];

    // create a chart
    searchChart = anychart.column();
    var searchcredits = searchChart.credits();
    searchcredits.url(semusiCommon.PANELURL + "login");
    searchcredits.logoSrc(semusiCommon.PANELURL + "assets/img/icon-title.png");

    searchcredits.text("appICE");

    searchChart.title("Top 10 Search Keywords");
    // create a column series and set the data
    var series = searchChart.column(searchData);

    // set the container id
    searchChart.container("search_container");

    // initiate drawing the chart
    searchChart.draw();

    // top 10 page view chart start

    // Column chart
    var searchDataP = [
        ["Home", 2.92],
        ["Speeches", 0.97],
        ["Research", 1.71],
        ["Museum Visit", 2.19]
    ];

    // create a chart
    searchChart = anychart.column();
    var searchcredits = searchChart.credits();
    searchcredits.url(semusiCommon.PANELURL + "login");
    searchcredits.logoSrc(semusiCommon.PANELURL + "assets/img/icon-title.png");

    searchcredits.text("appICE");

    searchChart.title("Page load time");

    var xAxis = searchChart.xAxis();
    xAxis.title("Pages Name");
    var yAxis = searchChart.yAxis();
    yAxis.title("Time (in seconds)");
    // create a column series and set the data
    var series = searchChart.column(searchDataP);
    series.name("seconds");
    // set the container id
    searchChart.container("time_on_page_container");

    // initiate drawing the chart
    searchChart.draw();

    // time on page full width


    // Column chart
    var searchDataP = [
        ["0-2 Sec", 292],
        ["2-4 Sec", 119],
        ["5-10 Sec", 53],
        ["10-20 Sec", 36],
        ["20-30 Sec", 16],
        ["30-60 Sec", 18],
        ["1 Min+ ", 7],
        ["5 Min+", 3]
    ];

    // create a chart
    searchChart = anychart.column();
    var searchcredits = searchChart.credits();
    searchcredits.url(semusiCommon.PANELURL + "login");
    searchcredits.logoSrc(semusiCommon.PANELURL + "assets/img/icon-title.png");
    searchcredits.text("appICE");

    searchChart.title("Time on Page");

    //var xAxis = searchChart.xAxis();
    // xAxis.title("No Of Pages");
    var yAxis = searchChart.yAxis();
    yAxis.title("Page Views");
    // create a column series and set the data
    var series = searchChart.column(searchDataP);
    series.name("Page Views");
    // set the container id
    searchChart.container("container_time");

    // initiate drawing the chart
    searchChart.draw();



    //Area Chert -- Outbound Chart

    // create data
    var outboundData = [
        ["5_08", 98],
        ["5_09", 90],
        ["5_10", 72],
        ["5_11", 93],
        ["5_12", 19],
        ["5_13", 43],
        ["5_14", 28],
        ["5_15", 38],
        ["5_16", 17],
        ["5_17", 10],
    ];

    // create a chart
    outboundDatachart = anychart.area();

    var outboundDatacredits = outboundDatachart.credits();
    outboundDatacredits.url(semusiCommon.PANELURL + "login");
    outboundDatacredits.logoSrc(semusiCommon.PANELURL + "assets/img/icon-title.png");
    outboundDatacredits.text("appICE");

    outboundDatachart.title("OutBound Links");

    // create an area series and set the data
    var series = outboundDatachart.area(outboundData);

    // set the container id
    outboundDatachart.container("outbound_container");

    // initiate drawing the chart
    outboundDatachart.draw();


    //Line Chart

    // create data
    var bounce_data = [
        ["5_08", 48],
        ["5_09", 30],
        ["5_10", 22],
        ["5_11", 43],
        ["5_12", 79],
        ["5_13", 13],
        ["5_14", 28],
        ["5_15", 18],
        ["5_16", 7],
        ["5_17", 8],
    ];

    // create a chart
    bounce_chart = anychart.line();
    var bouncecredits = bounce_chart.credits();
    bouncecredits.url(semusiCommon.PANELURL + "login");
    bouncecredits.logoSrc(semusiCommon.PANELURL + "assets/img/icon-title.png");
    bouncecredits.text("appICE");


    bounce_chart.title("Bounce Rate");

    // create a line series and set the data
    var series = bounce_chart.line(bounce_data);

    // set the container id
    bounce_chart.container("bounce_container");

    // initiate drawing the chart
    bounce_chart.draw();



    //////////////////////////////////////////  



    /* find top 10 event and render chart function defination */
    function createBarChartData(customEvents, platform) {
        /* Create data set in object eventsList (collect all events and event count for selected date selection) */
        if (customEvents != undefined && customEvents != '') {
            var eventsList = {};
            var totalEvents = 0;
            var platformArray = ['android', 'ios', 'web'];
            for (var e = 0; e < customEvents.length; e++) {  // loop for event mongo doc data[0]..
                platformArray.forEach((p) => {       // loop for every platform : data[0]['p']
                    if (customEvents[e][p] != undefined) {
                        if (platform == 'all' || platform == p) {
                            var key = Object.keys(customEvents[e][p]);
                            for (key in customEvents[e][p]) {
                                var innerKeys = Object.keys(customEvents[e][p][key]);
                                for (innerKeys in customEvents[e][p][key]) {
                                    if (!semusiCommon.SYSTEM_EVENTS.includes(innerKeys)) {
                                        if (eventsList.hasOwnProperty(innerKeys)) {
                                            eventsList[innerKeys] = eventsList[innerKeys] + customEvents[e][p][key][innerKeys];
                                        } else {
                                            eventsList[innerKeys] = customEvents[e][p][key][innerKeys];
                                        }
                                    }
                                }
                            }
                        }
                    }
                });
            }
            /* short event and slice top 10 events from all event set */
            array_last_five = sortObject(eventsList).slice(-10).reverse();
            var obj;
            for (obj in array_last_five) {
                totalEvents += array_last_five[obj].value;
            }
            // create a pie chart and set the data
            $("#container").html("");
            anychart.licenseKey("semusi.com-df30754a-aa10847e");
            chart = anychart.pie(array_last_five);
            // new text for credits
            // For appICE Value Change
            var credits = chart.credits();
            credits.url(semusiCommon.PANELURL + "/dashboard");
            credits.logoSrc(semusiCommon.PANELURL + "/assets/img/icon-title.png");
            credits.text("appICE");
            /* set the inner radius
            (to turn the pie chart into a doughnut chart)*/
            chart.innerRadius("50%");
            // set the container id
            chart.container("container");
            chart.labels().position("outside").format('{%displayValue}');;

            // disable the legend
            chart.legend(false);
            // set the chart title
            //let title = "Top 10 Events : " + platform;
            //chart.title(title);
            // create and configure a label
            var label = anychart.standalones.label();
            // new text for credits
            // For appICE Value Change
            var credits = chart.credits();
            credits.url(semusiCommon.PANELURL + "/dashboard");
            credits.logoSrc(semusiCommon.PANELURL + "/assets/img/icon-title.png");
            credits.text("appICE");
            label.text(nFormatter(totalEvents));
            label.width("100%");
            label.height("100%");
            label.fontColor("#60727b");
            label.hAlign("center");
            label.vAlign("middle");
            // set the label as the center content
            chart.center().content(label);
            // initiate drawing the chart
            chart.draw();
            /* table view chart for top 10 events  */
            // set stage
            $("#table_chart").html("");
            var stage = anychart.graphics.create("table_chart");
            var credits = stage.credits();
            credits.url(semusiCommon.PANELURL + "/dashboard");
            credits.logoSrc(semusiCommon.PANELURL + "/assets/img/icon-title.png");
            credits.text("appICE");
            // create table
            var table = anychart.standalones.table();
            // set table content
            var tableData = getTableData(array_last_five);
            table.contents(tableData);
            table.getRow(0).height(40).fontWeight(500); // Set first row height 40px and bold the text
            table.getCol(0).width(200).fontWeight(500);  // Set first column width 200 px and bold the text
            // set colors for ever and odd rows
            table.rowOddFill("#F5F5F5");  // color for odd rows
            table.rowEvenFill("#FFFFFF"); // color for even rows
            // adjust table border and position text in each cell into center
            table.cellBorder("#FFFFFF").vAlign("middle").hAlign("left");
            // set table container and initiate draw
            table.container(stage).draw();
        }
    }
    /* sort event list and create data set for pie chart */
    function sortObject(obj) {
        var arr = [];
        var prop;
        for (prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                let v = nFormatter(parseInt(obj[prop]));
                arr.push({
                    'x': prop,
                    'value': obj[prop],
                    'displayValue': v
                });
            }
        }
        arr.sort(function (a, b) {
            return a.value - b.value;
        });
        return arr; // returns array
    }
    /*  create data set for table chart */
    function getTableData(obj) {
        var arr = [];
        var prop;
        arr.push([
            "Event Name", "Number Of Events"
        ]);
        for (prop in obj) {
            if (obj.hasOwnProperty(prop)) {
                arr.push([
                    obj[prop]['x'], nFormatter(obj[prop]['value'])
                ]);
            }
        }
        return arr; // returns array
    }
    /*  number format function  like 10K, 5M etc ... */
    function nFormatter(num) {
        if (num >= 1000000000) {
            return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
        }
        if (num >= 1000000) {
            return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
        }
        if (num >= 1000) {
            return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
        }
        if (num == 0) {
            return 'NA';
        }
        return num;
    }

    function populateAvChart(data, filter) {
        //Av chart 
        $("#av_container").html("");
        var unique = [];
        let allPlatformDataAvList = [];
        let allPlatformData = [];
        if (filter == 'all') {
            allPlatformData = allPlatformData.concat(data.android, data.ios, data.web);
        }
        if (filter == 'android') {
            allPlatformData = data.android;
        }
        if (filter == 'ios') {
            allPlatformData = data.ios;
        }
        if (filter == 'web') {
            allPlatformData = data.web;
        }
        let updateData = allPlatformData.map(underscoreToDot);

        anychart.licenseKey("semusi.com-df30754a-aa10847e");
        // create a chart and set the data
        var channelChartAV = anychart.pie(updateData);
        //Set credits
        var channelcreditsAV = channelChartAV.credits();
        channelcreditsAV.url(semusiCommon.PANELURL + "login");
        channelcreditsAV.logoSrc(semusiCommon.PANELURL + "assets/img/icon-title.png");
        channelcreditsAV.text("appICE");
        // set the chart title
        channelChartAV.title("App Versions");
        let legendAV = channelChartAV.legend()
        channelChartAV.legend().paginator(false);
        // configure the format of legend items
        channelChartAV.legend().itemsFormat(
            "{%x}{%y}"
        );
        // enables legend
        legendAV.enabled(true);
        // set legend height
        legendAV.height(250);
        // set legend width
        legendAV.width(180);
        // set legend position
        legendAV.position("right");
        // set legend align
        legendAV.align("center");

        // legend items layout
        legendAV.itemsLayout("vertical");
        // set the container id
        channelChartAV.container("av_container");
        // initiate drawing the chart
        channelChartAV.draw();
    }
    function populateTimelySessionsUserActivityChunk(data, filter, totalCount) {
        $("#session_container").html("");
        var dataArray = [];
        data.forEach(function (keyObj) {
            var dayKeys = Object.keys(keyObj);
            if (dayKeys[0] == "evening") {
                dataArray.push(["Evening 4PM to 9PM ", ((keyObj.evening.other / totalCount) * 100).toFixed(2)]);
            }
            if (dayKeys[0] == "morning") {
                dataArray.push(["Morning 6AM to 11AM", ((keyObj.morning.other) / totalCount * 100).toFixed(2)]);
            }
            if (dayKeys[0] == "afternoon") {
                dataArray.push(["Afternoon 11AM to 4PM", ((keyObj.afternoon.other / totalCount) * 100).toFixed(2)]);
            }
            if (dayKeys[0] == "night") {
                dataArray.push(["Night 9PM to 12AM", ((keyObj.night.other / totalCount) * 100).toFixed(2)]);
            }
            if (dayKeys[0] == "midnight") {
                dataArray.push(["Mid Night 12AM to 6 AM", ((keyObj.midnight.other / totalCount) * 100).toFixed(2)]);
            }
        });

        searchChart = anychart.column();
        var searchcredits = searchChart.credits();
        searchcredits.url(semusiCommon.PANELURL + "login");
        searchcredits.logoSrc(semusiCommon.PANELURL + "assets/img/icon-title.png");
        searchcredits.text("appICE");

        searchChart.title("User Activity");
        // create a column series and set the data
        var series = searchChart.column(dataArray);
        series.name("Percentage ");
        // set the container id
        searchChart.container("session_container");

        // initiate drawing the chart
        searchChart.draw();
    }

    function populateDeviceData(data, filter, type) {
        // create a chart
        let allPlatformData = [];
        if (filter == 'all') {
            if (data.web != undefined) {
                data.web.forEach(function (keyObj) {
                    var exists = allPlatformData.filter(function (o) {
                        return (o.x == keyObj.x.replace("_", ".").replace("_", "."));
                    }).length > 0;

                    if (exists) {
                        var index = allPlatformData.findIndex(x => x.x === keyObj.x.replace("_", ".").replace("_", "."));
                        allPlatformData[index].value = parseInt(allPlatformData[index].value) + parseInt(keyObj.value);
                    } else {
                        allPlatformData.push({ "x": keyObj.x.replace("_", ".").replace("_", "."), "value": keyObj.value });
                    }
                });
            };
            if (data.IOS != undefined) {
                data.IOS.forEach(function (keyObj) {
                    var exists = allPlatformData.filter(function (o) {
                        return (o.x == keyObj.x.replace("_", ".").replace("_", "."));
                    }).length > 0;
                    if (exists) {
                        var index = allPlatformData.findIndex(x => x.x === keyObj.x.replace("_", ".").replace("_", "."));
                        allPlatformData[index].value = parseInt(allPlatformData[index].value) + parseInt(keyObj.value);
                    } else {
                        allPlatformData.push({ "x": keyObj.x.replace("_", ".").replace("_", "."), "value": keyObj.value });
                    }
                });
            };
            if (data.Android != undefined) {
                data.Android.forEach(function (keyObj) {
                    var exists = allPlatformData.filter(function (o) {
                        return (o.x == keyObj.x.replace("_", ".").replace("_", "."));
                    }).length > 0;

                    if (exists) {
                        var index = allPlatformData.findIndex(x => x.x === keyObj.x.replace("_", ".").replace("_", "."));
                        allPlatformData[index].value = parseInt(allPlatformData[index].value) + parseInt(keyObj.value);
                    } else {
                        allPlatformData.push({ "x": keyObj.x.replace("_", ".").replace("_", "."), "value": keyObj.value });
                    }
                });
            };
        }
        if (filter == 'android') {
            if (data.Android != undefined) {
                data.Android.forEach(function (keyObj) {
                    allPlatformData.push({ "x": keyObj.x.replace("_", ".").replace("_", "."), "value": keyObj.value });
                });
            };
        }
        if (filter == 'ios') {
            if (data.IOS != undefined) {
                data.IOS.forEach(function (keyObj) {
                    allPlatformData.push({ "x": keyObj.x.replace("_", ".").replace("_", "."), "value": keyObj.value });
                });
            };
        }
        if (filter == 'web') {
            if (data.web != undefined) {
                data.web.forEach(function (keyObj) {
                    allPlatformData.push({ "x": keyObj.x.replace("_", ".").replace("_", "."), "value": keyObj.value });
                });
            };
        }
        var channelChartAV = anychart.pie(allPlatformData);
        //Set credits
        var channelcreditsAV = channelChartAV.credits();
        searchcredits.url(semusiCommon.PANELURL + "login");
        searchcredits.logoSrc(semusiCommon.PANELURL + "assets/img/icon-title.png");
        channelcreditsAV.text("appICE");
        // set the chart title
        if (type == 'MAKE') {
            channelChartAV.title("Device Distribution");
        } else {
            channelChartAV.title("Version Distribution");
        }

        let legendAV = channelChartAV.legend()
        channelChartAV.legend().paginator(false);
        // configure the format of legend items
        channelChartAV.legend().itemsFormat(
            "{%x}{%y}"
        );
        // enables legend
        legendAV.enabled(true);
        // set legend height
        legendAV.height(250);
        // set legend width
        legendAV.width(180);
        // set legend position
        legendAV.position("right");
        // set legend align
        legendAV.align("center");
        // legend items layout
        legendAV.itemsLayout("vertical");
        // set the container id
        if (type == 'MAKE') {
            $("#make_container").html("");
            channelChartAV.container("make_container");
        } else {
            $("#av_container").html("");
            channelChartAV.container("av_container");
        }
        // initiate drawing the chart
        channelChartAV.draw();
    }

    semusiChart.getDeviceTotalStats = function (filter) {
        var filter = filter || 'all';
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/getDeviceTotalStats',
            data: {
                args: JSON.stringify({
                    startDate_C: semusiCommon.dateRange.currentStartDate,
                    endDate_C: semusiCommon.dateRange.currentEndDate,
                    startDate_P: semusiCommon.dateRange.previousStartDate,
                    endDate_P: semusiCommon.dateRange.previousEndDate,
                    startDate_CNew: semusiCommon.dateRange.currentStartDateNew,
                    endDate_CNew: semusiCommon.dateRange.currentEndDateNew,
                    startDate_PNew: semusiCommon.dateRange.previousStartDateNew,
                    endDate_PNew: semusiCommon.dateRange.previousEndDateNew
                }),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                uniqueNumber: semusiCommon.randomNumber(),
            },
            success: function (result) {
                $("#overlay").hide();
                populateDeviceData(result.devicedata, filter, 'MAKE');
                populateDeviceData(result.avdata, filter, 'AV');
            },
            error: function () {
                $("#overlay").hide();
            }
        });
    };
    function underscoreToDot(item) {
    // Optional chaining (?.) is used to check if 'item' is defined and 'x' property exists
    // If 'item' is undefined or 'x' is undefined, 'x' will be assigned undefined
        const x = item?.x?.replace(/_/g, '.');

    // Optional chaining (?.) is used to check if 'item' is defined and 'value' property exists
    // Nullish coalescing operator (??) is used to return 'undefined' if 'item' or 'item.value' is undefined

        const value = item?.value ?? undefined;

     // Return an object with 'x' and 'value' properties
        return { x, value };
    }
}(window.semusiChart = window.semusiChart || {}, jQuery));