(function (semusiInstalls, $, undefined) {

    var dayWiseBarChart=document.getElementById('dayWiseBarchart');
    var timewiseBarChart=document.getElementById('timeWiseBarchart');
    var barChart1;
    var barChart2;
    var OS__allPieData = false;
    var OSTableChart = false;
    var worldmap_all = false;

    var SourceTableChart = false;
    var location_tableChart = true;
    var dayWiseBarData = {
        labels: [],
        datasets: []
    };
    var timeWiseBarData = {
        labels: [],
        datasets: []
    };

    semusiInstalls.referalMapping;
    semusiInstalls.sourceWiseData;
    semusiInstalls.cityWiseData ={currentData:[]};
    semusiInstalls.countryWiseData ={currentData:[]};
    semusiInstalls.osversionWiseData ={currentData:[],previousData:[]};
    semusiInstalls.timeWiseData = {newdata:[],repeatData:[]};
    semusiInstalls.dayWiseData = {newdata:[],repeatData:[]};

    semusiInstalls.Initialize = function(){
        //This will set default daterange as last 30 days.
        semusiCommon.setDateRange(null,null);
        initDateRange();
        initDayWiseRange();
        initTimeWiseRange();
        getReferalMappings();
        getInstallDataNew("S","all");
        semusiInstalls.getInstallData("all");

        $('.location-select').on('click',function(){
            var data = $(this).attr('data-attr');
            if(data == "cty"){
                $('#locationTxt').text('City')
                $("#ddlLocation").val('cty');
                populateTopCityData();
            }else{
                $('#locationTxt').text('Country')
                $("#ddlLocation").val('cc');
                populateTopCountryData();
            }
        });
        $('#locationTxt').text('City')

        $('.install-select').on('click',function(){
            var data = $(this).attr('data-attr');
            if(data == 'all'){
                $('#Acquisitionource').text('All');
            }else if(data == 'android'){
                $('#Acquisitionource').text('Android');
            }else if(data == 'ios'){
                $('#Acquisitionource').text('iOS');
            }
            else if(data == 'web'){
                $('#Acquisitionource').text('Web');
            }
            $("#ddlPlatform").val(data)
            $("#ddlPlatform").val();
            populateSourceWiseTable();
        });
        $('#Acquisitionource').text('All');
        /*$(".install-select").change(function(){
            populateSourceWiseTable();
        });*/

         $('.daywise-select').on('click',function(){
            var data = $(this).attr('data-attr');
            if(data == 'all'){
                $('#dwi').text('All');
            }else if(data == 'android'){
                $('#dwi').text('Android');
            }else if(data == 'ios'){
                $('#dwi').text('iOS');
            }
            else if(data == 'web'){
                $('#dwi').text('Web');
            }
            $("#ddlPlatform1").val(data)
            $("#ddlPlatform1").val();
            createDayWiseInstallGraph(dayWiseBarData);
            handleDayWiseGraph(true);
        });
         $('#dwi').text('All');

        /*$("#ddlPlatform1").change(function(){
            createDayWiseInstallGraph(dayWiseBarData);
            handleDayWiseGraph(true);
        });*/


        $('.timewise-select').on('click',function(){
            var data = $(this).attr('data-attr');
            if(data == 'all'){
                $('#twi').text('All');
            }else if(data == 'android'){
                $('#twi').text('Android');
            }else if(data == 'ios'){
                $('#twi').text('iOS');
            }
            else if(data == 'web'){
                $('#twi').text('Web');
            }
            $("#ddlPlatform2").val(data)
            $("#ddlPlatform2").val();
            createTimeWiseInstallGraph(timeWiseBarData);
            handleTimeWiseGraph(true);
        });
        $('#twi').text('All');
        /*$("#ddlPlatform2").change(function(){
            createTimeWiseInstallGraph(timeWiseBarData);
            handleTimeWiseGraph(true);
        });*/

        $('.os-select').on('click',function(){
          
            var data = $(this).attr('data-attr');
            if(data == 'all'){
                $('#osSelect').text('All');
            }else if(data == 'android'){
                $('#osSelect').text('Android');
            }else if(data == 'ios'){
                $('#osSelect').text('iOS');
            }
            else if(data == 'web'){
                $('#osSelect').text('Web');
            }
            $("#ddlAppPlatform").val(data)
            $("#ddlAppPlatform").val();
            populateTopOSVersionData();
        });
        $('#osSelect').text('All');


        /*$('#ddlAppPlatform').on('change',function(){
           populateTopOSVersionData()
        });*/

        $("#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:"I",
                    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+'&app_id='+ semusiCommon.ACTIVE_APP_ID+'&uniqueNumber='+semusiCommon.randomNumber()+'&args='+args+'&filename='+filename);
        });
        $("#topos-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:"I",
                    downloadFlag:true,
                    downloadData:"versions",
                    platform:$('#ddlAppPlatform').val()
                });
            var filename = "os-version-wise.csv";
            window.location = appiceEncode.encodePayload(semusiCommon.API_PARTS.metrices.r + '/getInstallUnistallStatsByParam?api_key='+ semusiCommon.getActiveUser.api_key+'&app_id='+ semusiCommon.ACTIVE_APP_ID+'&uniqueNumber='+semusiCommon.randomNumber()+'&args='+args+'&filename='+filename);
        });
        $("#toplocations-downloadLink").click(function(){
            var location = $("#ddlLocation").val(); 

            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:"I",
                    downloadFlag:true,
                    downloadData:(location=="cty")?"cities":"countries"
                });
            var filename =  location+"-wise.csv";
            window.location = appiceEncode.encodePayload(semusiCommon.API_PARTS.metrices.r + '/getInstallUnistallStatsByParam?api_key='+ semusiCommon.getActiveUser.api_key+'&app_id='+ semusiCommon.ACTIVE_APP_ID+'&uniqueNumber='+semusiCommon.randomNumber()+'&args='+args+'&filename='+filename);
        });

        $("#daywise-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:"I",
                    downloadFlag:true,
                    downloadData:"days",
                    platform:$("#ddlPlatform1").val()
                });
            var filename = "day-wise.csv";
            window.location = appiceEncode.encodePayload(semusiCommon.API_PARTS.metrices.r + '/getInstallUnistallStatsByParam?api_key='+ semusiCommon.getActiveUser.api_key+'&app_id='+ semusiCommon.ACTIVE_APP_ID+'&uniqueNumber='+semusiCommon.randomNumber()+'&args='+args+'&filename='+filename);
        });
        $("#hourwise-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:"I",
                    downloadFlag:true,
                    downloadData:"hours",
                    platform:$("#ddlPlatform2").val()
                });
            var filename = "hour-wise.csv";
            window.location = appiceEncode.encodePayload(semusiCommon.API_PARTS.metrices.r + '/getInstallUnistallStatsByParam?api_key='+ semusiCommon.getActiveUser.api_key+'&app_id='+ semusiCommon.ACTIVE_APP_ID+'&uniqueNumber='+semusiCommon.randomNumber()+'&args='+args+'&filename='+filename);
        });
    };

    semusiInstalls.getInstallData =  function(filter){
        $(".daywisegraph").show();
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.metrices.r + '/getInstallUnistallStatsByParam',
            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,
                    type:"I"
                }),
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID
            },
             
            success:function (data) {
                $('#overlay').hide();
                $(".daywisegraph").hide();
                if(data){
                    localStorage.setItem('fulldata', JSON.stringify(data));
                    populateAvChart(data.appversion,'all');
                    InitializeAllChanks(data, filter);
                }
            },
            error:function(error){
                $('#overlay').hide();
            }
        });
    }

    semusiInstalls.getReferalWiseData =  function(){

        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.metrices.r + '/getInstallUnistallStatsBySource',
            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,
                    type:"I"
                }),
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID
            },
             
            success:function (data) {
                $('#overlay').hide();
                if(data){
                    semusiInstalls.sourceWiseData = data.installs;
                    populateSourceWiseTable();
                }
            },
            error:function(error){
                $('#overlay').hide();
            }
        });
    }


    //private functions
    initDateRange = function(){
        $('#advance-daterange span').html(moment().subtract('days', 29).format(semusiCommon.getDateFormatt()) + ' - ' + moment().format(semusiCommon.getDateFormatt()));


        $('#advance-daterange').daterangepicker({
            format: semusiCommon.getDateFormatt(),
            startDate: moment().subtract(29, 'days'),
            endDate: moment(),
            minDate: '01/01/2012',
            maxDate: new Date(),
            dateLimit: { days: 365 },
            showDropdowns: true,
            showWeekNumbers: false,
            timePicker: false,
            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) {

            semusiCommon.setDateRange(start,end);
            $('#advance-daterange span').html(start.format(semusiCommon.getDateFormatt()) + ' - ' + end.format(semusiCommon.getDateFormatt()));
            $('#locationTxt').text('City');
            $("#ddlLocation").val('cty');
            semusiInstalls.getInstallData("topchunks");
            semusiInstalls.getReferalWiseData();

        });
    }

    initDayWiseRange = function(){

        $('#daywise-daterange span').html(moment().subtract('days', 29).format(semusiCommon.getDateFormatt()) + ' - ' + moment().format(semusiCommon.getDateFormatt()));


        $('#daywise-daterange').daterangepicker({
            format: semusiCommon.getDateFormatt(),
            startDate: moment().subtract(29, 'days'),
            endDate: moment(),
            minDate: '01/01/2012',
            maxDate: new Date(),
            dateLimit: { days: 365 },
            showDropdowns: true,
            showWeekNumbers: false,
            timePicker: false,
            timePickerIncrement: 1,
            timePicker12Hour: true,
            ranges: {
               'Last 7 Days': [moment().subtract(6, 'days'), moment()],
               'Last 30 Days': [moment().subtract(29, 'days'), moment()],
               'This Month': [moment().startOf('month'), moment().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) {
            semusiCommon.setDateRange(start,end);
            $('#daywise-daterange span').html(start.format(semusiCommon.getDateFormatt()) + ' - ' + end.format(semusiCommon.getDateFormatt()));

            semusiInstalls.getInstallData("daygraph");
        });
    }

    initTimeWiseRange = function(){
        $('#timewise-daterange span').html(moment().subtract('days', 29).format(semusiCommon.getDateFormatt()) + ' - ' + moment().format(semusiCommon.getDateFormatt()));

        $('#timewise-daterange').daterangepicker({
            format: semusiCommon.getDateFormatt(),
            startDate: moment().subtract(29, 'days'),
            endDate: moment(),
            minDate: '01/01/2012',
            maxDate: new Date(),
            dateLimit: { days: 365 },
            showDropdowns: true,
            showWeekNumbers: false,
            timePicker: false,
            timePickerIncrement: 1,
            timePicker12Hour: true,
            ranges: {
               'Last 7 Days': [moment().subtract(6, 'days'), moment()],
               'Last 30 Days': [moment().subtract(29, 'days'), moment()],
               'This Month': [moment().startOf('month'), moment().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) {

            semusiCommon.setDateRange(start,end);
            $('#timewise-daterange span').html(start.format(semusiCommon.getDateFormatt()) + ' - ' + end.format(semusiCommon.getDateFormatt()));
            semusiInstalls.getInstallData("timegraph")
        });
    }

    //This method populates app version wise data on UI.
    populateTopOSVersionData = function(currentData,previousData){
         
        if(OSTableChart){
            $("#os__pieChart").hide();
            var OS__tableContainer = document.getElementById("os__tableChart").style.display = 'block';
        }
        var currentData = semusiInstalls.osversionWiseData.currentData;
        var previousData = semusiInstalls.osversionWiseData.previousData;
      
        var topOSdata=[];
        var platform = $('#ddlAppPlatform').val();
        var tempArr = [];
             
            var keys = Object.keys(currentData);

            var i = 0;
            keys.forEach(function(item){
                var totalCc = 0;
                var st = item.split(' ');
                if(st[0] &&(st[0].toLowerCase()==platform || platform=="all")){
                    currentData[item].forEach(function(city){
                        totalCc += city.total;
                    })
                    topOSdata[i]=[];
                    topOSdata[i][0] = (st[0]) ? st[0] : "NA";
                    topOSdata[i][1] = (st[1]) ? st[1] : "NA";
                    topOSdata[i][2] = totalCc;
                    topOSdata[i][3] = 0;
                    i++;
                }
            });

        // }
        topOSdata = topOSdata.filter(function(n){ return n != undefined });
        //If we have current period data, then calculate previous period data for the same
        for(var i = 0; i < topOSdata.length; i++){
            if(topOSdata[i] != undefined){
                for(var x=0;x<previousData.length; x++) {
                //if(previousData[x].p &&(previousData[x].p.toLowerCase()==platform || platform=="all")){
                    if(semusiCommon.toFirstUpper(previousData[x].p) == topOSdata[i][0] && (previousData[x].pv == topOSdata[i][1] || (previousData[x].pv == undefined && topOSdata[i][1]=="NA") ) ){
                        topOSdata[i][3] += previousData[x].total;
                    }
                //}
                }
            }
        }
        topOSdata.sort(function(a, b) {
            return b[2] - a[2];
        });
        var rows = 1;
        $('#tblOS > tbody >tr').remove();

        topOSdata.forEach(function(p){
            var changeSign;
            var strPercentChange;
            var optchange;
            changedTotal = p[2]-p[3];

            percentChange =(p[3]==0) ? 100: parseFloat(changedTotal/p[3]*100).toFixed(2);
            if(percentChange>0){
                changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-up"></i></div>'
                optchange = '+';
                strPercentChange = nFormatter(parseInt(percentChange)) +'%';
            }
            else if(percentChange<0){
                percentChange=percentChange*-1;
                changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-down"></i></div>';
                optchange = '-';
                strPercentChange = nFormatter(parseInt(percentChange)) +'%';
            }
            else if(percentChange==0){
                changeSign = '';
                optchange = '';
                strPercentChange = nFormatter(parseInt(percentChange)) +'%';
            }
            if(p[3]==0){
                changeSign = "";
                optchange = '';
                strPercentChange = 'NA';
            }
           
            //Replace a/i and : from mongo formated version
            p[1] = p[1].replace(/a/g,"").replace(/i/g,"").replace(/:/g,".");


            if(rows<6){
                $('#tblOS > tbody').append('<tr ><td style="padding:3px;">' + p[0]+' '+ nFormatter(p[1]) +'</td><td style="padding:3px;">'+ nFormatter(p[2])  +'</td><td style="padding:3px;padding-right: 0px;text-align:right;">'+ changeSign +'</td><td style="padding:3px;padding-right: 0px;">'+ strPercentChange + '</td></tr>');
            }
            rows++;
            p[3] = changeSign +""+strPercentChange;
            p[4] = optchange

        });

        topOSdata=topOSdata.filter(Boolean);
      
        if(topOSdata.length>5){
            $('#tblOS > tbody').append('<tr ><td colspan="4" style="padding:3px;padding-right:8px; text-align:right;cursor:pointer"  onclick="showAllPlatform();"><a>View Detail <i class="fa fa-arrow-circle-o-right"></i></a></td></tr>');
        }


        //Bind data to tables which show all data
        $('#tblOsAll').dataTable({
                "bPaginate": true,
                "bFilter": false ,
                 bDestroy:true,
                "aaData": topOSdata,
                "aaSorting": [[ 2, "desc" ]],
                "aoColumnDefs": [ {"bSortable": false}]

        });
      

        var data2 = topOSdata.map((ele)=>{
            ele[3] = nFormatter(ele[3]);
            return { 
                x:  ele[0]+' '+ele[1],
                y: ' ('+ele[4]+ele[3]+')',
                value: ele[2],
                legendItem: {
                    iconType: "circle",
                  }
             }        
    });



   
     if(!OSTableChart){   

        var OS__tableContainer = document.getElementById("os__tableChart");
        var OS__pieContainer = document.getElementById("os__pieChart");
        var OS__pieContent = document.getElementById("os__pie-content");

       
        if(!OS__allPieData){
            let data3 = []
                for(let i=0; i<data2.length;i++){
                    data3.push(data2[i]);
                    if(i==4){
                        break;
                    }
                }
            
             

            OS__tableContainer.style.display = 'none';
            OS__pieContainer.style.display = 'block';
            
            //Removing previously rendered chart
            while (OS__pieContent.firstChild) {
                OS__pieContent.removeChild(OS__pieContent.firstChild);
            }
            
            // create a chart and set the data
            let OS_pieChart = anychart.pie(data3);
            anychart.licenseKey("semusi.com-df30754a-aa10847e");
            var credits = OS_pieChart.credits();
            credits.url("login");
            credits.logoSrc(window.location.origin+"/assets/img/icon-title.png");
            credits.text("appICE");

            let legend = OS_pieChart.legend()
             OS_pieChart.legend().paginator(false);

                // enable html for the legend
                OS_pieChart.legend().useHtml(true);

            // configure the format of legend items
            OS_pieChart.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
            OS_pieChart.container("os__pie-content");
            // initiate drawing the chart
            OS_pieChart.draw();
   }
   else{

       let OS__pieContent = document.getElementById("os__pie-content-all");
        while (OS__pieContent.firstChild) {
            OS__pieContent.removeChild(OS__pieContent.firstChild);
        }
        
        // create a chart and set the s
        let OS_pieChart = anychart.pie(data2);
        anychart.licenseKey("semusi.com-df30754a-aa10847e");
        var credits = OS_pieChart.credits();
        credits.url(window.location.origin+"/login");
        credits.logoSrc(window.location.origin+"/assets/img/icon-title.png");
        credits.text("appICE");
        let legend = OS_pieChart.legend()
        let paginator =   OS_pieChart.legend().paginator();

         
       
            // enables legend
            legend.enabled(true);
            // set legend height
            legend.height(400);
            // set legend width
            legend.width(240);
            // set legend position
            legend.position("right");
            // set legend align
            legend.align("center");
            // legend items layout
            legend.itemsLayout("vertical");
            // paginator settings

            // enable html for the legend
            OS_pieChart.legend().useHtml(true);

            // configure the format of legend items
            OS_pieChart.legend().itemsFormat(
            "{%x}{%y}"
            );
            // set padding for paginator
            paginator.padding(3);
            // set paginator layout
            paginator.layout("vertical");
            // place paginator at the left of a legend
            paginator.orientation("left");


        // set the container id
        OS_pieChart.container("os__pie-content-all");

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

}

function deepCopy(obj) {
    if (typeof obj == 'object') {
      if (Array.isArray(obj)) {
        var l = obj.length;
        var r = new Array(l);
        for (var i = 0; i < l; i++) {
          r[i] = deepCopy(obj[i]);
        }
        return r;
      } else {
        var r = {};
        r.prototype = obj.prototype;
        for (var k in obj) {
          r[k] = deepCopy(obj[k]);
        }
        return r;
      }
    }
    return obj;
  }

  /*  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;
    }



    //This method populates UI with city data.
    populateTopCityData = function(){
        if(location_tableChart){
                $("#location__tablechart").show();
                $("#location__map").hide();
                var data = [];

                data = deepCopy(semusiInstalls.cityWiseData.currentData);

                $('#tblLocation > tbody >tr').remove();
        
            var rows = 1;
            data.forEach(function(p){

                var changeSign;
                var strPercentChange;
                if(p[0] != "?" ){   
                var changedTotal = p[1]-p[2];
                var percentChange = (p[2]==0) ? 100: parseFloat(changedTotal/p[2]*100).toFixed(2);
                if(percentChange>0){
                    changeSign = '<div style="font-size:14px;"><i class="fa fa-2x fa-caret-up"></i></div>'
                    strPercentChange = nFormatter(parseInt(percentChange)) +' %';
                }
                else if(percentChange<0){
                    percentChange=percentChange*-1;
                    changeSign = '<div style="font-size:14px;"><i class="fa fa-2x fa-caret-down"></i></div>';
                    strPercentChange = nFormatter(parseInt(percentChange)) +' %';
                }
                else if(percentChange==0){
                    changeSign = '';
                    strPercentChange = nFormatter(parseInt(percentChange)) +' %';
                }
                if(p[2]==0){
                    changeSign = "";
                    strPercentChange = 'NA';
                }
                    if(rows<6){
                        $('#tblLocation > tbody').append('<tr><td style="padding:3px;">' + semusiCommon.toFirstUpper(p[0]) +'</td><td style="padding:3px;">'+ nFormatter(p[1])  +'</td><td style="padding:3px;padding-right: 0px;text-align:right;">'+ changeSign +'</td><td style="padding:3px;padding-right: 0px;">'+ strPercentChange + '</td></tr>');
                    }
                
                rows++;
                p[2]= changeSign +"  "+strPercentChange;
            } 
            });
            if(data.length>5){
                $('#tblLocation > tbody').append('<tr><td colspan="4" style="padding:3px;padding-right:8px; text-align:right;cursor:pointer"  class="showAllLocations"><a>View Detail <i class="fa fa-arrow-circle-o-right"></i></a></td></tr>');
                $('.showAllLocations').click(function() { 
                    hideAndShow();
                });
            }

            //Bind data to tables which show all data
            $('#tblLocationAll').dataTable({
                    "bPaginate": true,
                    "bFilter": false ,
                    bDestroy:true,
                    "aaData": data,
                    "aaSorting": [[ 1, "desc" ]],
                    "aoColumnDefs": [ {"bSortable": false}]

            });

        }
        else{
            initWorldLocationChart();
        }
    }

    //This method populates UI with country data.
    populateTopCountryData = function(){
        var data = semusiInstalls.countryWiseData.currentData;
        // var previousData = semusiInstalls.countryWiseData.previousData;
        // var data=[];
        // var ccArr = [];
        // if(currentData && currentData.length>0){
        //     var result=_.groupBy(currentData,"cc");
        //     var keys = Object.keys(result)
        //     var data=[];
        //     var i = 0;
        //     keys.forEach(function(item){
        //         var totalCc = 0;
        //         result[item].forEach(function(city){
        //             totalCc += city.total;
        //         })
        //         data[i]=[];
        //         data[i][0] = (item) ? item : "NA";
        //         data[i][1] = totalCc;
        //         data[i][2] = 0
        //         i++;
        //     })
     
        // }
        // data = data.filter(function(n){ return n != undefined });
        // //If we have current period data, then calculate previous period data for the same
        // for(var i = 0; i < data.length; i++){
        //     for(var x=0;x<previousData.length; x++) {
        //         if(previousData[x].cc == data[i][0] || (previousData[x].cc == undefined && data[i][0]=="NA") ){
        //             data[i][2] += previousData[x].total;
        //         }
        //     }
        // };
        // data.sort(function(a, b) {
        //     return b[1] - a[1];
        // });


        //till here
        var rows = 1;
        $('#tblLocation > tbody >tr').remove();
        data.forEach(function(p){
            var changeSign;
            var strPercentChange;
        if(p[0] != "?" ){   
            changedTotal = p[1]-p[2];
            percentChange =(p[2]==0) ? 100: parseFloat(changedTotal/p[2]*100).toFixed(2);
            if(percentChange>0){
                changeSign = '<div style="font-size:14px;"><i class="fa fa-2x fa-caret-up"></i></div>'
                strPercentChange = nFormatter(parseInt(percentChange)) +' %';
            }
            else if(percentChange<0){
                percentChange=percentChange*-1;
                changeSign = '<div style="font-size:14px;"><i class="fa fa-2x fa-caret-down"></i></div>';
                strPercentChange = nFormatter(parseInt(percentChange)) +' %';
            }
            else if(percentChange==0){
                changeSign = '';
                strPercentChange = nFormatter(parseInt(percentChange)) +' %';
            }
            if(p[2]==0){
                changeSign = "";
                strPercentChange = 'NA';
            }
              if(rows<6){
                $('#tblLocation > tbody').append('<tr><td style="padding:3px;">' + semusiCommon.toFirstUpper(p[0]) +'</td><td style="padding:3px;">'+ nFormatter(p[1])  +'</td><td style="padding:3px;padding-right: 0px;text-align:right;">'+ changeSign +'</td><td style="padding:3px;padding-right: 0px;">'+ strPercentChange + '</td></tr>');
              }
            rows++;
            p[2]= changeSign +"  "+strPercentChange;
          }
        });
        if(data.length>5){
            $('#tblLocation > tbody').append('<tr><td colspan="4" style="padding:3px;padding-right:8px; text-align:right;cursor:pointer" class="showAllLocations"><a>View Detail <i class="fa fa-arrow-circle-o-right"></i></a></td></tr>');
            $('.showAllLocations').click(function() { 
                hideAndShow();
            });
        }

        //Bind data to tables which show all data
        $('#tblLocationAll').dataTable({
                "bPaginate": true,
                "bFilter": false ,
                 bDestroy:true,
                "aaData": data,
                "aaSorting": [[ 1, "desc" ]],
                "aoColumnDefs": [ {"bSortable": false}]

        });

        
    }

    InitializeAllChanks = function(data, filter){
    
        if(filter=="all"){
            // location variable
            populateSourceWiseTable();

            semusiInstalls.cityWiseData.currentData= data.cityWiseData;
            // semusiInstalls.cityWiseData.previousData= data.cityWiseData_previousData;
            semusiInstalls.countryWiseData.currentData=data.countryWiseData;
            // semusiInstalls.countryWiseData.previousData=data.countryWiseData_previousData;
            // os version variables
            semusiInstalls.osversionWiseData.currentData=data.osversionWiseData.OScurrentData;
            semusiInstalls.osversionWiseData.previousData=data.osversionWiseData.OSpreviousData;
            // time variables
            semusiInstalls.timeWiseData.newData=data.timeWiseData.newData;
            semusiInstalls.timeWiseData.repeatData=data.timeWiseData.repeatData;
            // day variables
            semusiInstalls.dayWiseData.newData=data.dayWiseData.newData;
            semusiInstalls.dayWiseData.repeatData=data.dayWiseData.repeatData;

            // populate os version data
            populateTopOSVersionData();
            // generate time wise graph
            createTimeWiseInstallGraph(timeWiseBarData);
            handleTimeWiseGraph();
            // generate day wise graph
            createDayWiseInstallGraph(dayWiseBarData);
            handleDayWiseGraph();
            // populate city data
            populateTopCityData();
            
        }
        else if(filter=="topchunks"){
           
            // // location variable
            // semusiInstalls.cityWiseData.currentData= data.cityWiseData_currentData;
            // semusiInstalls.cityWiseData.previousData= data.cityWiseData_previousData;
            // semusiInstalls.countryWiseData.currentData=data.countryWiseData_currentData;
            // semusiInstalls.countryWiseData.previousData=data.countryWiseData_previousData;
            // // os version variables
            // semusiInstalls.osversionWiseData.currentData=data.osversionWiseData_currentData;
            // semusiInstalls.osversionWiseData.previousData=data.osversionWiseData_previousData;

            semusiInstalls.cityWiseData.currentData= data.cityWiseData;
            semusiInstalls.countryWiseData.currentData=data.countryWiseData;
            // os version variables
            semusiInstalls.osversionWiseData.currentData=data.osversionWiseData.OScurrentData;
            semusiInstalls.osversionWiseData.previousData=data.osversionWiseData.OSpreviousData;

            // populate city data
            populateTopCityData();
            // populate os version data
            populateTopOSVersionData();
        }
        else if(filter=="timegraph"){
           
            // time variables
            // semusiInstalls.timeWiseData.newData=data.timeWiseData_newData;
            // semusiInstalls.timeWiseData.repeatData=data.timeWiseData_repeatData;

            semusiInstalls.timeWiseData.newData=data.timeWiseData.newData;
            semusiInstalls.timeWiseData.repeatData=data.timeWiseData.repeatData;

            // generate time wise graph
            createTimeWiseInstallGraph(timeWiseBarData);
            handleTimeWiseGraph();
        }
        else if(filter=="daygraph"){
          
            // day variables
            // semusiInstalls.dayWiseData.newData=data.dayWiseData_newData;
            // semusiInstalls.dayWiseData.repeatData=data.dayWiseData_repeatData;

            semusiInstalls.dayWiseData.newData=data.dayWiseData.newData;
            semusiInstalls.dayWiseData.repeatData=data.dayWiseData.repeatData;

            // generate day wise graph
            createDayWiseInstallGraph(dayWiseBarData);
            handleDayWiseGraph();
        }
    }

    hideAndShow = function(){
        $("#divMainHeader").hide();
        $("#divMain").hide();
        $("#divOSAcquisition").hide();
        $("#divLocationAcquisition").show();
        $("#divSources").hide();
        $("#divGraphs").hide();
    }

    showAllPlatform = function(){
        $("#divMainHeader").hide();
        $("#divMain").hide();
        $("#divOSAcquisition").show();
        $("#divLocationAcquisition").hide();
        $("#divSources").hide();
        $("#divGraphs").hide();
    }

    $('#installclass').click(function() { 
        $("#divMainHeader").hide();
        $("#divMain").hide();
        $("#divOSAcquisitionPieData").show();
        $("#divLocationAcquisition").hide();
        $("#divSources").hide();
        $("#divGraphs").hide();
        OS__allPieData = true
        populateTopOSVersionData();


    });

    showAllSources = function(){
        $("#divMainHeader").hide();
        $("#divMain").hide();
        $("#divOSAcquisition").hide();
        $("#divLocationAcquisition").hide();
        $("#divSources").show();
        $("#divGraphs").hide();
    }

    $('.goToHomeNew').click(function() { 
        $("#divMainHeader").show();
        $("#divMain").show();
        $("#divGraphs").show();
        $("#divOSAcquisition").hide();
        $("#divLocationAcquisition").hide();
        $("#divSources").hide();
        $("#divOSAcquisitionPieData").hide();
        $("#world_chart").hide();
        $("#location__map").show();

        OS__allPieData = false;
        worldmap_all = false;
        
    });

    toggleOsCharts = function(){
       OSTableChart = !OSTableChart;
       if(OSTableChart){
           $(".fa-pie-chart-os").show();
           $(".fa-table-os").hide();
       }
       else{
        $(".fa-pie-chart-os").hide();
        $(".fa-table-os").show(); 
       }
        populateTopOSVersionData();
    }

    toggleSourceChats = function(){
        SourceTableChart = !SourceTableChart;
        if(SourceTableChart){
            $(".fa-pie-chart-source").show();
            $(".fa-table-source").hide();
        }
        else{
         $(".fa-pie-chart-source").hide();
         $(".fa-table-source").show(); 
        }

        populateSourceWiseTable();
        
    }

    $('.showLocationChartsAll').click(function() { 
        $("#divMainHeader").hide();
        $("#divMain").hide();
        $("#divOSAcquisitionPieData").hide();
        $("#divLocationAcquisition").hide();
        $("#divSources").hide();
        $("#divGraphs").hide();
        $("#location__map").hide();
        $("#world_chart").show();
        worldmap_all = true
        initWorldLocationChart();
    });


    toggleLocationCharts = function(){
        location_tableChart = !location_tableChart;
         
        if(location_tableChart){
            $("#location__map").hide();
            $(".fa-map-marker-location").show();
            $(".fa-table-location").hide();
            $("#location__tablechart").show();

        }
        else{
            $("#location__tablechart").hide();
            $("#location__map").show();
            $(".fa-map-marker-location").hide();
            $(".fa-table-location").show();
           
        }

        populateTopCityData(); 
      
    }

    populateSourceWiseTable = function(){

        if(SourceTableChart){
            $("#source__pieChart").hide();
            document.getElementById("source__tableChart").style.display = 'block';
        }
        var platform =  $("#ddlPlatform").val();
        var sources = getUniqueSources(semusiInstalls.sourceWiseData,platform);
        var tableData = [];

        var platforms = ['android','ios', 'web'];
        var data = semusiInstalls.sourceWiseData;
        for(var y=0;y<sources.length;y++){
            var row = {};
            var i_new=0;
            var i_repeat=0;
            var avgcpi =0;

   

            for(var x=0; x<platforms.length; x++){
               
                if(platforms[x].toLowerCase() == platform || platform == 'all'){
                    if(data[platforms[x]]){
                    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 == 'ri'){
                                        i_repeat += rec[value];
                                    }
                                    if(value == 'in'){
                                        i_new += rec[value];
                                    }

                                    if(value == 'cpi'){
                                        avgcpi =  rec[value];
                                    }
                                }
                            });
                        }
                    }
                }
                }
            }
            row.source=sources[y];
            row.avg_cpi= parseFloat(avgcpi).toFixed(2);
            row.new = i_new;
            row.repeat = i_repeat;
            row.total = i_new + i_repeat;
            if(row.total > 0){
                tableData.push(row);
            }
        }

        var rows=1;
        $('#tblSourceData > tbody >tr').remove();
        tableData.forEach(function(item){
            if(item.source == 'Self' || item.source == 'self'){
                item.source = 'Organic';
            }

            if(rows<6){
                $('#tblSourceData > tbody').append('<tr ><td style="padding:3px;">' + semusiCommon.toFirstUpper(item.source)+'</td><td style="padding:3px;text-align:right;">'+ nFormatter(item.new) +'</td><td style="padding:3px;text-align:right;">'+ nFormatter(item.repeat) + '</td><td style="padding:3px;text-align:right;">'+ nFormatter(item.total) + '</td></tr>');
            }
            rows++;
        });
     
        if(tableData.length>5){
            $('#tblSourceData > tbody').append('<tr ><td colspan="5" style="padding:3px;padding-right:8px; text-align:right;cursor:pointer" onclick="showAllSources();"><a>View Detail <i class="fa fa-arrow-circle-o-right"></i></a></td></tr>');
        }

        //Bind data to tables which show all data
        $('#tblAllSources').dataTable({
                "bPaginate": true,
                "bFilter": false ,
                 bDestroy:true,
                "aaData": tableData,
                "aaSorting": [[ 3, "desc" ]],
                "aoColumns": [
                        { "mData": 'source' },
                        // { "mData": 'avg_cpi' },
                        { "mData": 'new' },
                        { "mData": 'repeat' },
                        { "mData": 'total' }
                    ],

        });

        //code for sorce wise pie chart 

        if(!SourceTableChart){

            // prepare data for pie chart

            var newInstall=0;
            var repeatInstall = 0;
            var pieData = [];
            
            for(let i=0;i<tableData.length;i++){
                newInstall+=tableData[i].new;
                repeatInstall+=tableData[i].repeat;
            }

            pieData.push({
                x:'NewAcquisition',
                value: newInstall,
                legendItem: {
                    iconType: "circle",
                  }
               }
            )
            pieData.push({
                x:'RepeatAcquisition',
                value: repeatInstall,
                legendItem: {
                    iconType: "circle",
                  }
            })            

            var source__tableContainer = document.getElementById("source__tableChart");
            var source__pieContainer = document.getElementById("source__pieChart");
            var source__pieContent = document.getElementById("source__pieContent");
    
    
            source__tableContainer.style.display = 'none';
            source__pieContainer.style.display = 'block';
    
                
                //Removing previously rendered chart
                while (source__pieContent.firstChild) {
                    source__pieContent.removeChild(source__pieContent.firstChild);
                }
                
                // create a chart and set the data
                let source_pieChart = anychart.pie(pieData);
                anychart.licenseKey("semusi.com-df30754a-aa10847e");
                var credits = source_pieChart.credits();
                credits.url(window.location.origin+"/login");
                credits.logoSrc(window.location.origin+"/assets/img/icon-title.png");
                credits.text("appICE");
                let legend = source_pieChart.legend()
                source_pieChart.legend().paginator(false);
    
                  // enable html for the legend
    
             
                    // enable html for the legend
                    source_pieChart.legend().useHtml(true);
    
                // configure the format of legend items
              
                
                 // configure the format of legend items
              
                // enables legend
                legend.enabled(true);
                // set legend height
                legend.height(250);
                // set legend width
                legend.width(155);
                // set legend position
                legend.position("right");
                // set legend align
                legend.align("center");
                // legend items layout
                legend.itemsLayout("vertical");
    
    
                // set the container id
                source_pieChart.container("source__pieContent");
    
                // initiate drawing the chart
                source_pieChart.draw();

        }

    }

    


    getUniqueSources = function(data,platform){
        var sources = [];
        if(data){
            var platformsArray = Object.keys(data);
            for(var x=0; x<platformsArray.length; x++){
                if(platformsArray[x].toLowerCase() == platform || platform == 'all'){
                    var obj = data[platformsArray[x]];
                    obj.forEach(function(objVal){
                        if(objVal){
                            var s = Object.keys(objVal);
                            if(sources.indexOf(s[0]) == '-1'){
                              sources.push(s[0]);
                            }
                        }
                    });
                }
            }
        }

        return sources;
    }

    getReferalMappings =function (){
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.metrices.r + '/getReferalMappings',
            data:{
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID
            },
             
            success:function (data) {
                //$('#overlay').hide();
                if(data){
                    semusiInstalls.referalMapping = data;
                    semusiInstalls.getReferalWiseData();
                }
            },
            error:function(error){
                //$('#overlay').hide();
            }
        });
    }

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

    createDayWiseInstallGraph = function(barData){
        /*Sample BAR chart data structure, below data is constructed in this format.
        var sampleData = {
            labels: ['Italy', 'UK', 'USA', 'Germany', 'France', 'Japan','India'],
            datasets: [
                {
                    fillColor: '#382765',
                    data: [2500, 1902, 1041, 610, 1245, 952,550]
                },
                {
                    fillColor: '#7BC225',
                    data: [3104, 1689, 1318, 589, 1199, 1436,800]
                }
            ]
        };
        */
        barData.labels=[];
        barData.datasets=[];
        var platform = $("#ddlPlatform1").val();
        var chartLabels = [];
        var chartMetrics = [];
        getChartLabels(semusiInstalls.dayWiseData.newData, chartLabels, true);
        getChartLabels(semusiInstalls.dayWiseData.repeatData, chartLabels, true);
        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<semusiInstalls.dayWiseData.repeatData.length;z++){
                var label=semusiInstalls.dayWiseData.repeatData[z].d;
                var cLabel=chartLabels[y];
                if(semusiInstalls.dayWiseData.repeatData[z].p && (semusiInstalls.dayWiseData.repeatData[z].p.toLowerCase()==platform || platform=="all")){
                    if(label == cLabel ){
                        value = value + semusiInstalls.dayWiseData.repeatData[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<semusiInstalls.dayWiseData.newData.length;z++){
                var label=semusiInstalls.dayWiseData.newData[z].d;
                var cLabel=chartLabels[y];

                if(semusiInstalls.dayWiseData.newData[z].p && (semusiInstalls.dayWiseData.newData[z].p.toLowerCase()==platform || platform=="all")){
                    if(label == cLabel){
                        value = value + semusiInstalls.dayWiseData.newData[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.backgroundColor= semusiCommon.basicColors[x];
            }
            else{
                bar.backgroundColor= '#'+Math.floor(appiceFloat.generateRandomFloat()*16777215).toString(16);
            }
            bar.data=yxis[x];
            bar.label = chartMetrics[x];
            barData.datasets.push(bar);
        }
    }

    createTimeWiseInstallGraph = function(barData){
        /*Sample BAR chart data structure, below data is constructed in this format.
        var sampleData = {
            labels: ['Italy', 'UK', 'USA', 'Germany', 'France', 'Japan','India'],
            datasets: [
                {
                    fillColor: '#382765',
                    data: [2500, 1902, 1041, 610, 1245, 952,550]
                },
                {

                    fillColor: '#7BC225',
                    data: [3104, 1689, 1318, 589, 1199, 1436,800]
                }
            ]
        };
        */
        barData.labels=[];
        barData.datasets=[];

        var platform = $("#ddlPlatform2").val();
        var chartLabels = [];
        var chartMetrics = [];
        getChartLabels(semusiInstalls.timeWiseData.newData, chartLabels, false);
        getChartLabels(semusiInstalls.timeWiseData.repeatData, chartLabels, false);
        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<semusiInstalls.timeWiseData.repeatData.length;z++){
                var label=semusiInstalls.timeWiseData.repeatData[z].h;
                var cLabel=chartLabels[y];

                if(semusiInstalls.timeWiseData.repeatData[z].p && (semusiInstalls.timeWiseData.repeatData[z].p.toLowerCase()==platform || platform=="all")){
                    if(label == cLabel ){
                        value = value + semusiInstalls.timeWiseData.repeatData[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<semusiInstalls.timeWiseData.newData.length;z++){
                var label=semusiInstalls.timeWiseData.newData[z].h;
                var cLabel=chartLabels[y];

                if(semusiInstalls.timeWiseData.newData[z].p && (semusiInstalls.timeWiseData.newData[z].p.toLowerCase()==platform || platform=="all")){
                    if(label == cLabel){
                        value = value + semusiInstalls.timeWiseData.newData[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.backgroundColor= semusiCommon.basicColors[x];
            }
            else{
                bar.backgroundColor= '#'+Math.floor(appiceFloat.generateRandomFloat()*16777215).toString(16);
            }
            bar.data=yxis[x];
            bar.label = chartMetrics[x];
            barData.datasets.push(bar);
        }
    }

    getChartLabels = function(data,chartLabels,daywise){
        for(var x=0;x< data.length;x++){
            var label;
            if(daywise && data[x].d){
                label = data[x].d;
            }
            else if(!daywise ){
                label = data[x].h;
            }
            if ($.inArray(label, chartLabels) == -1 ) {
                chartLabels.push(label);
            }
        }
        chartLabels.sort(function(a, b){return a-b});
    }

    handleChartJs = function () {
        $(window).load(function() {
            handleTimeWiseGraph(true);
            handleDayWiseGraph(true);
        });

        $(window).resize( function() {
            handleDayWiseGraph();
            handleTimeWiseGraph();
        });
    };


    var handleDayWiseGraph = function(animationOption) {
        var animationOption = (animationOption) ? animationOption : false;
        if (dayWiseBarChart) {
            if (barChart1 !== undefined) {
                barChart1.destroy();
            }
            var ctx1 = dayWiseBarChart.getContext('2d');
            barChart1 = new Chart(ctx1, {
                type: 'bar',
                data: dayWiseBarData,
                options: {
                    animation: animationOption,
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.dataset.label + ' - ' + context.parsed.y;
                                }
                            }
                        },
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        x: {
                            stacked: true
                        },
                        y: {
                            stacked: true
                        }
                    }
                }
            });
    
            $('#legend1').html(barChart1.generateLegend());
        }
    }
    
    
    
  
    var handleTimeWiseGraph = function(animationOption) {
      var animationOption = (animationOption) ? animationOption : false;
      if (timeWiseBarchart) {
          if (barChart2 !== undefined) {
              barChart2.destroy();
          }
          var ctx2 = timeWiseBarchart.getContext('2d');
          barChart2 = new Chart(ctx2, {
              type: 'bar',
              data: timeWiseBarData,
              options: {
                  animation: animationOption,
                  plugins: {
                      tooltip: {
                          callbacks: {
                              label: function(context) {
                                  return context.dataset.label + ' - ' + context.parsed.y;
                              }
                          }
                      },
                      legend: {
                          display: false
                      }
                  },
                  scales: {
                      x: {
                          stacked: true
                      },
                      y: {
                          stacked: true
                      }
                  }
              }
          });
  
          $('#legend2').html(barChart2.generateLegend());
      }
  }
  


//World map code starts

function reduceToTwoDigits(n)   {
  
    let x = n;
    while(x.length >= 3){
        x = x.split("").reverse().join("");
        let len = x.length;
        let ans = 0;
        for(let j = 0; j < len - 1 ; j++) {
            ans = (ans * 10) + Math.abs( parseInt(x[j]) - parseInt(x[j + 1]) );
        }
        x = ans.toString();
    }
    return x;
}


    function updateProgress()   {
        if(worldmap_all){
            var progress = document.getElementById("progressContentAll");
        }else{
            var progress = document.getElementById("progressContent");
        }
        progress.innerHTML = "";
        if(sessionStorage.getItem('data') !== "undefined"){
            let dataSet = JSON.parse(sessionStorage.getItem('data'));
             
            let background = ["#d54062","#318fb5","#ffcb8e","#fbd46d","#7fdbda","#363636","#fa1616"];
            if(dataSet!= null){
            for(let i = 0 ; i < dataSet.length; i++) {
            let data = dataSet[i];
            // console.info("data =>",data);
            let valPercentage = reduceToTwoDigits(data.size.toString());
            // progress.innerHTML += `
            // <div class="d-flex flex-column w-100 py-3 align-self-center">
            //         <div class="d-flex flex-row justify-content-between py-2">
            //             <h6 class="text-dark align-self-center">${data.id}</h6>
            //             <h6 class="text-dark align-self-center">${data.size}</h6>
            //         </div>
            //         <div class="progress" style="height:10px;">
            //             <div class="progress-bar" role="progressbar" style="width: ${valPercentage}%; background-color: ${background[i]};" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
            //         </div>
            //     </div>  
            // `;
            }
        }
        sessionStorage.clear();
        }
        else{
            progress.innerHTML = "No data available";
        }
    }
    window.onload = setTimeout(() => { updateProgress(); },1000);


    var initWorldLocationChart = function(){
 
        if(!worldmap_all) {
            $("#location__tablechart").hide();
            $("#location__map").show();
            let chartContainer = document.querySelector("#container");
            let progress = document.getElementById("progressContent");
            while (progress.firstChild) {
                progress.removeChild(progress.firstChild);
            }
            while (chartContainer.firstChild) {
                chartContainer.removeChild(chartContainer.firstChild);
            }
        }else{
            let chartContainer = document.querySelector("#containerAll");
            let progress = document.getElementById("progressContentAll");
            while (progress.firstChild) {
                progress.removeChild(progress.firstChild);
            }
            while (chartContainer.firstChild) {
                chartContainer.removeChild(chartContainer.firstChild);
            }
        }
        
        window.onload = setTimeout(() => { updateProgress(); },1000);
     
       
            function retrieve() {
                let x = {
                    "world":[
                        {"id":"India", "lat":25.6585001, "lon":80.0133649, "size":8000 },
                        {"id":"Australia", "lat":-23.6993532, "lon":133.8713752, "size":5000 },
                        {"id":"Russia", "lat":66.2222222, "lon":96.7986413, "size":9000 }
                    ],
                    "India":[
                        {"id":"Maharashtra", "lat":18.802007, "lon":74.5307288, "size":8000 },
                        {"id":"Delhi",  "lat":28.5272803,"lon":77.0688992, "size":3000 }
                    ],
                    "Maharashtra":[
                        {"id":"Mumbai", "lat":19.0821978, "lon":72.7410994, "size":100 },
                        {"id":"Nagpur", "lat":21.1610714, "lon":79.0024696, "size":700 },
                        {"id":"Solapur","lat":17.6614569, "lon":75.8485767,"size":400}
                    ],
                    "Delhi":[
                        {"id":"Karol Bagh", "lat":28.6517981, "lon":77.1845669, "size":300 },
                        {"id":"Alipur", "lat":28.7993988, "lon":77.1185301, "size":100 },
                        {"id":"Dwarka", "lat":28.5733056, "lon":77.0109150, "size":500 }
                    ]
                };
                return x;
            }
    
    
            function addValue(ar)    {
                let sum = 0;
                for(let i = 0 ; i<ar.length; i++)   {
                    sum += ar[i].size;
                }
                return sum;
            }
            var palette = anychart.palettes.distinctColors(); 
            palette.items(["#d54062","#318fb5","#ffcb8e","#fbd46d","#7fdbda","#363636","#fa1616"]);
            var ind_dl_map = anychart.map();//IND-DL
            var ind_dl_data = retrieve().Delhi;
            anychart.data.loadJsonFile("https://raw.githubusercontent.com/shklnrj/IndiaStateTopojsonFiles/master/Delhi.geojson",function (geoData){
                ind_dl_map.geoData(geoData);
                // ind_dl_map.title().useHtml(true).hAlign('center');
                // ind_dl_map.title('<span style="font-size: 18px;">Semusi <br> Delhi Map');
                ind_dl_map.listen("click",function(e){ind_dl_map.drillUp();})
                ind_dl_map.maxBubbleSize('5%');
                ind_dl_map.minBubbleSize('2%');          
                var ind_dl_series = ind_dl_map.bubble(ind_dl_data);
                ind_dl_series.tooltip().titleFormat("{%id}");
                ind_dl_series.tooltip().format("{%size}");
                ind_dl_series.labels().format("{%id} \n {%size}");
                ind_dl_series.labels().fontSize(17);
                ind_dl_series.labels().fontColor("#fffff");
                ind_dl_series.labels().fontWeight(500);
                ind_dl_series.labels().fontFamily("Open Sans");
                ind_dl_series.labels(false);
                ind_dl_series.stroke('#ffffff');
                ind_dl_series.fill(function(){
                    let index = this.index;
                    let color = palette.itemAt(index);
                    return color;
                });
                // ind_dl_series.colorScale(scale);
            });
    
            var ind_mh_map = anychart.map();//IND-MH
                // var ind_mh_data = [
                //     {'id':'Aurangabad','size':500, 'name':'Aurangabad', fill: background[0]},
                //     {'id':'Pune','size':400 , 'name':'Pune', fill: background[1]},
                //     {'id':'Thane','size':600 , 'name':'Thane', fill: background[2]},
                //     {'id':'Nagpur','size':800, 'name':'Nagpur', fill: background[3]}
                // ];
                var ind_mh_data = retrieve().Maharashtra;
                anychart.data.loadJsonFile("https://raw.githubusercontent.com/shklnrj/IndiaStateTopojsonFiles/master/Maharashtra.geojson",function(geoData){
                    ind_mh_map.geoData(geoData);
                    // ind_mh_map.title().useHtml(true).hAlign('center');
                    // ind_mh_map.title('<span style="font-size: 18px;">Semusi <br> Maharashrta Map');
                    ind_mh_map.listen("click",function(e){ind_mh_map.drillUp();})
                    ind_mh_map.maxBubbleSize('5%');
                    ind_mh_map.minBubbleSize('2%');
                    var ind_mh_series = ind_mh_map.bubble(ind_mh_data);
                    ind_mh_series.tooltip().titleFormat("{%id}");
                    ind_mh_series.tooltip().format("{%size}");
                    ind_mh_series.labels().format("{%id} \n {%size}");
                    ind_mh_series.labels().fontSize(17);
                    ind_mh_series.labels().fontColor("#fffff");
                    ind_mh_series.labels().fontWeight(500);
                    ind_mh_series.labels().fontFamily("Open Sans");
                    ind_mh_series.labels(false);
                    ind_mh_series.stroke('#ffffff');
                    ind_mh_series.fill(function(){
                    let index = this.index;
                    let color = palette.itemAt(index);
                    return color;
                    });
                    // ind_mh_series.colorScale(scale);
                });
           
            var ind_map = anychart.map();//IND
              
                var ind_data = retrieve().India;
                ind_map.geoData(anychart.maps.india);
                
                ind_map.listen("click",function(e){ind_map.drillUp();})
                ind_map.maxBubbleSize('5%');
                ind_map.minBubbleSize('2%');
                var ind_series = ind_map.bubble(ind_data);
                // ind_series.colorScale(scale);
                ind_series.tooltip().titleFormat("{%id}");
                ind_series.tooltip().format("{%size}");
                ind_series.labels().format("{%code} \n {%size}");
                ind_series.labels().fontSize(17);
                ind_series.labels().fontColor("#fffff");
                ind_series.labels().fontWeight(500);
                ind_series.labels().fontFamily("Open Sans");
                ind_series.labels(false);
                ind_series.stroke('#ffffff');
                ind_series.fill(function(){
                    var index = this.index;
                    var color = palette.itemAt(index);
                    return color;
                });
    
    
            var world_map = anychart.map();
            world_map.geoData(anychart.maps.world);
          
            var world_data = retrieve().world;
            sessionStorage.setItem("data",JSON.stringify(world_data));
            var world_series = world_map.bubble(world_data);
            world_series.selected().fill('#5588ff');
            // world_series.colorScale(scale);
            world_series.tooltip().titleFormat("{%id}");
            world_series.tooltip().format("{%size}");
            world_series.labels().format("{%code} \n {%size}");
            world_series.labels().fontSize(17);
            world_series.labels().fontColor("#fffff");
            world_series.labels().fontWeight(500);
            world_series.labels().fontFamily("Open Sans");
            world_series.labels(false);
            world_series.stroke('#ffffff');
            world_series.fill(function(){
                    var index = this.index;
                    var color = palette.itemAt(index);
                    return color;
            });
            world_map.maxBubbleSize('5%');
            world_map.minBubbleSize('2%');
            world_map.drillDownMap({
                // "AU":aus_map.drillDownMap({}),
                "India":ind_map.drillDownMap({
                    "Delhi":ind_dl_map,
                    "Maharashtra":ind_mh_map,
                }),
               
            })
            world_map.listen('drillChange',function(e) {
                switch(e.current.id){
                    case "AE":
                        sessionStorage.setItem("data",JSON.stringify(uae_data));
                        break;
                    case "AU":
                        sessionStorage.setItem("data",JSON.stringify(aus_data));
                        break;
                    case "India": 
                        sessionStorage.setItem("data",JSON.stringify(ind_data));
                        break;
                    case "RU":
                        sessionStorage.setItem("data",JSON.stringify(rus_data));    
                        break;
                    case "US": 
                        sessionStorage.setItem("data",JSON.stringify(usa_data));
                        break;
                    
                    case "Delhi": 
                        sessionStorage.setItem("data",JSON.stringify(ind_dl_data));
                        break;
                    case "IN.WB": 
                        sessionStorage.setItem("data",JSON.stringify(ind_wb_data));
                        break;
                    case "IN.TG": 
                        sessionStorage.setItem("data",JSON.stringify(ind_tg_data));
                        break;
                    case "Maharashtra": 
                        sessionStorage.setItem("data",JSON.stringify(ind_mh_data));    
                        break;
                    case "IN.KA": 
                        sessionStorage.setItem("data",JSON.stringify(ind_ka_data));
                        break;
                    case "IN.TN": 
                        sessionStorage.setItem("data",JSON.stringify(ind_tn_data));
                        break;
                    case "IN.GJ": 
                        sessionStorage.setItem("data",JSON.stringify(ind_gj_data));
                        break;
    
                    case "AE.AZ": 
                        sessionStorage.setItem("data",JSON.stringify(uae_az_data));
                        break;
                    case "AE.DU": 
                        sessionStorage.setItem("data",JSON.stringify(uae_du_data));
                        break;
                    case "AE.UQ": 
                        sessionStorage.setItem("data",JSON.stringify(uae_uq_data));
                        break;
                    case "US.TX": 
                        sessionStorage.setItem("data",JSON.stringify(usa_tx_data));
                        break;
                    default:
                        sessionStorage.setItem("data",JSON.stringify(world_data));
                }
                updateProgress();
            });
            
            world_map.interactivity({selectionMode: "drill-down"});
            var zoomControls = anychart.ui.zoom();
            zoomControls.target(world_map);
            zoomControls.render();
            anychart.licenseKey("semusi.com-df30754a-aa10847e");
    
            var credits = world_map.credits();
            credits.url(window.location.origin+"login");
            credits.logoSrc(window.location.origin+"/assets/img/icon-title.png");
            credits.text("appICE");
            if(worldmap_all){
                world_map.container('containerAll');
            }else{
                world_map.container('container');
    
            }
    
            world_map.draw();
    
    }

submitInstallData = function(){
    let appID = document.getElementById("appID_install").value;
    let date = document.getElementById("date").value;
    let campaign = document.getElementById("campaign").value;
    let source = document.getElementById("source").value;
    let acquisitions = document.getElementById("acquisitions").value;
    let churn = document.getElementById("churn").value;
    let spend = document.getElementById("spend").value;
    
    $.ajax({
        type:"GET",
        url:semusiCommon.API_PARTS.metrices.r + '/saveInstallData',
        data:{
            args:JSON.stringify({
                appID:appID,
                date:date,
                campaign:campaign,
                source:source,
                acquisitions:acquisitions,
                churn:churn,
                spend:spend
            }),
            api_key: semusiCommon.getActiveUser.api_key,
            app_id: semusiCommon.ACTIVE_APP_ID
        },
         
        success:function (data) {
            $('#overlay').hide();
            if(data){
                alert("data submit successfully");
                document.getElementById("appID_install").value = "";
                document.getElementById("date").value = "";
                document.getElementById("campaign").value = "";
                document.getElementById("source").value = "";
                document.getElementById("acquisitions").value = "";
                document.getElementById("churn").value = "";
                document.getElementById("spend").value = "";
                //semusiInstalls.sourceWiseData = data.installs;
                //populateSourceWiseTable();
            }
        },
        error:function(error){
            $('#overlay').hide();
        }
    });
}
getInstallDataNew = function(type,platform){

    $.ajax({
        type:"GET",
        url:semusiCommon.API_PARTS.metrices.r + '/getInstallData',
        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,
                    type:type,
                    platform:platform
            }),
            uniqueNumber : semusiCommon.randomNumber(),
            api_key: semusiCommon.getActiveUser.api_key,
            app_id: semusiCommon.ACTIVE_APP_ID
        },
         
        success:function (data) {
            $('#overlay').hide();
            if(data){
                //alert("data",data);

                var output = [];
                data.forEach(function(item,i) {
                if(i == 0){
                        output.push(item);
                }else{
                    let resIndex = search(item.cmp, output);
                        if(resIndex != "no"){
                            let temp = {"cmp":item.cmp,"in": parseInt(output[resIndex].in) + parseInt(item.in),"un": parseInt(output[resIndex].un) + parseInt(item.un),"sp": parseInt(output[resIndex].sp) + parseInt(item.sp) }
                            output.splice(resIndex, 1);
                            output.push(temp);
                    
                        }
                        else{
                            output.push(item);
                        } 
                } 
                });

                function search(nameKey, myArray){
                    for (var i=0; i < myArray.length; i++) {
                        if (myArray[i].cmp == nameKey) {
                            return i;
                        }else{
                        return "no";
                        }
                    }
                }
                $("#campaignSourceData").html("");
                if(output.length == 0){
                    $("#campaignSourceData").html('<div class="progress-col-row" style="text-align: center;">DATA NOT FOUND</div>');
                }
                output.forEach(function (res) {
                    let cpi = 0; 
                    if(res.in != 0){ cpi = (parseInt(res.sp)/parseInt(res.in)).toFixed(2);
                    }else{ cpi = parseInt(res.sp).toFixed(2); }
                    let install   = (res.in == 0) ? 0 : nFormatter(parseInt(res.in));
                    let uninstall = (res.un == 0) ? 0 : parseInt(res.un);
                    let sp = (res.sp == 0) ? 0 : '&#x20B9;'+nFormatter(parseInt(res.sp));
                    $("#campaignSourceData").append('<div class="progress-col-row"><div class="prog-info-col one">'+ res.cmp +'</div><div class="prog-info-col two"><div class="prog-bar blue" title="'+res.in+'"> '+install+' </div><div class="prog-bar red" title="'+res.un+'">  </span> </div></div><div class="prog-info-col three">'+cpi+'</div><div class="prog-info-col four red">'+sp+'</div></div>');
                })
            }
        },
        error:function(error){
            $('#overlay').hide();
        }
    });
}
cmpSourceFilter = function(val){
    let sc = document.getElementById("cmpSource").value;
    val = document.getElementById("cmpSourceByPlatform").value;
    getInstallDataNew(sc,val);
}
cmpSourceFilterByPlatform = function(val){
    val = document.getElementById("cmpSourceByPlatform").value;
    let sc = document.getElementById("cmpSource").value;
    getInstallDataNew(sc,val);
}
// World map code ends
function populateAvChart(data, filter){
    filter = document.getElementById("avByPlatform").value;
    //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;
    }
     
    anychart.licenseKey("semusi.com-df30754a-aa10847e");
     
    // create a chart and set the data
    var channelChartAV = anychart.pie(allPlatformData);
    //Set credits
    var channelcreditsAV = channelChartAV.credits();
    channelcreditsAV.url(window.location.origin+"/login");
    channelcreditsAV.logoSrc(window.location.origin+"/assets/img/icon-title.png");
    channelcreditsAV.text("appICE");
    // set the chart title
    channelChartAV.title("");
    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();
    populateMakeChart("all");
}

function populateMakeChart( filter){
    //filter = document.getElementById("avByPlatform").value;
    allPlatformData = [{"x":"Mi A1",value:1},{"x":"M2006C3MI",value:1},{"M2101K7BI":"",value:2},{"x":"Redmi Note 7S",value:2},{"x":"POCO M2 Pro",value:2},{"x":"Redmi Note 9 Pro",value:2}]
    anychart.licenseKey("semusi.com-df30754a-aa10847e");
     
    // create a chart and set the data
    var channelChartAV = anychart.pie(allPlatformData);
    //Set credits
    var channelcreditsAV = channelChartAV.credits();
    channelcreditsAV.url(window.location.origin+"/login");
    channelcreditsAV.logoSrc(window.location.origin+"/assets/img/icon-title.png");
    channelcreditsAV.text("appICE");
    // set the chart title
    channelChartAV.title("");
    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("make_container");
    // initiate drawing the chart
    channelChartAV.draw();
}

avFilterByPlatform = function(){
    semusiInstalls.getInstallData("topchunks");
}

}(window.semusiInstalls = window.semusiInstalls || {}, jQuery));