(function (semusiUnInstalls, $, undefined) {

    var dayWiseBarChart=document.getElementById('dayWiseBarchart');
    var timewiseBarChart=document.getElementById('timeWiseBarchart');
    var barChart1;
    var barChart2;

    var OSTableChart = false;
    var platformTableChart = false;
    var location_tableChart = true;

    var OS__allPieData = false;
    var worldmap_all = false;

    var dayWiseBarData = {
        labels: [],
        datasets: []
    };
    var timeWiseBarData = {
        labels: [],
        datasets: []
    };

    
    semusiCommon.dateRange.currentStartDate;
    semusiCommon.dateRange.currentEndDate;
    semusiCommon.dateRange.previousStartDate;
    semusiCommon.dateRange.previousEndDate;
    semusiUnInstalls.sourceWiseData;
    
    
    semusiUnInstalls.currentData;
    semusiUnInstalls.previousData;
    semusiUnInstalls.UnInstallData;
    semusiUnInstalls.cityWiseData ={currentData:[],previousData:[]};
    semusiUnInstalls.countryWiseData ={currentData:[],previousData:[]};
    semusiUnInstalls.appversionWiseData ={currentData:[],previousData:[]};
    semusiUnInstalls.timeWiseData = {newdata:[],repeatData:[]};
    semusiUnInstalls.dayWiseData = {newdata:[],repeatData:[]};

    semusiUnInstalls.Initialize = function(){
        
        semusiCommon.setDateRange(null,null);       
        initDateRange();
        initDayWiseRange();
        initTimeWiseRange();
        getReferalMappings();

        semusiUnInstalls.getUninstallData("all");
        //semusiUnInstalls.getInstallDataLocationWise('all');
        semusiUnInstalls.getRegainedUsers();    
        
        $('.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');

        /*$("#ddlLocation").change(function(){          
            if($(this).val()=="cty"){
                populateTopCityData();
            }
            else{
                populateTopCountryData();
            }
        });*/

        $('.swi-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());
        });
        $('#swiu').text('All');
        /*$("#ddlPlatform").change(function(){
            semusiCommonData.populateSourceWiseInstallsUninstalls($(this).val());
        });*/

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

        /*$("#ddlAppPlatform").change(function(){
            populateTopAppVersionData();
        })*/

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

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

        $('.time-wise-select').on('click',function(){
            var data = $(this).attr('data-attr');
            if(data == 'all'){
                $('#twu').text('All');
            }else if(data == 'android'){
                $('#twu').text('Android');
            }else if(data == 'ios'){
                $('#twu').text('iOS');
            }
            else if(data == 'web'){
                $('#twu').text('Web');
            }
            $("#ddlPlatform2").val(data)
            $("#ddlPlatform2").val();
            createTimeWiseUnInstallGraph(timeWiseBarData);
            handleTimeWiseGraph(true);
        });
        $('#twu').text('All');

        /*$("#ddlPlatform2").change(function(){
            createTimeWiseUnInstallGraph(timeWiseBarData);
            handleTimeWiseGraph(true);
        });*/

        $("#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+'&app_id='+ semusiCommon.ACTIVE_APP_ID+'&args='+args+'&filename='+filename);
        });
        $("#topappversions-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:"U",
                    downloadFlag:true,
                    downloadData:"appversions",
                    platform:$("#ddlAppPlatform").val() 
                });
            var filename = "app-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:"U",
                    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:"U",
                    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:"U",
                    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);
        });
    };



    semusiUnInstalls.getUninstallData =  function(filter){
        $.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:"U"
                }),
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID
            },
             
            success:function (data) {
                $("#overlay").hide();
                if(data){
                    InitializeAllChanks(data, filter);
                }
            },
            error:function(error){
                $("#overlay").hide();
            }
        });
    }   

    semusiUnInstalls.getRegainedUsers =  function(){
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.metrices.r + '/getRegainedUsers',
            data:{
                args:JSON.stringify({
                    startDate_C:semusiCommon.dateRange.currentStartDate,
                    endDate_C:semusiCommon.dateRange.currentEndDate,                   
                }),
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID
            },
             
            success:function (data) { 
                $("#overlay").hide(); 
                // check regained users records array
                if(data.regainedUsers.length > 0 ){
                    for(var i=0; i<data.regainedUsers.length; i++){
                        if( data.regainedUsers[i].p.toLowerCase() == "android" ){
                            $("#androidRegainedUsers").text(data.regainedUsers[i].total);
                        }
                        else if( data.regainedUsers[i].p.toLowerCase() == "ios" ){
                            $("#iosRegainedUsers").text(data.regainedUsers[i].total);
                        }
                        else if( data.regainedUsers[i].p.toLowerCase() == "web" ){
                            $("#webRegainedUsers").text(data.regainedUsers[i].total);
                        }
                    }
                }
            },
            error:function(error){
                $("#overlay").hide();
            }
        });
    }

    semusiUnInstalls.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:"BOTH"
                }),
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID
            },
             
            success:function (data) {
                $("#overlay").hide();
                if(data){
                    semusiCommonData.Dataset = data.installs;
                    semusiCommonData.populateSourceWiseInstallsUninstalls($("#ddlPlatform").val());
                }
            },
            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()));
            semusiUnInstalls.getUninstallData("topchunks");
           // semusiUnInstalls.getInstallDataLocationWise("topchunks");
            $('#locationTxt').text('City');
            $("#ddlLocation").val('cty');
            semusiUnInstalls.getRegainedUsers();
            semusiUnInstalls.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: 'right',
            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()));
            
            semusiUnInstalls.getUninstallData("daygraph");
        });
    }

    InitializeAllChanks = function(data, filter){
        if(filter=="all"){
            semusiUnInstalls.UnInstallData = data.populateUninstalls;
            populateUninstalls(data.populateUninstalls);
            // location variable
            semusiUnInstalls.cityWiseData.currentData=data.cityWiseData_currentData;
            semusiUnInstalls.cityWiseData.previousData=data.cityWiseData_previousData; 
            semusiUnInstalls.countryWiseData.currentData=data.countryWiseData_currentData;
            semusiUnInstalls.countryWiseData.previousData=data.countryWiseData_previousData; 
            // os version variables
            semusiUnInstalls.appversionWiseData.currentData=data.appversionWiseData_currentData;
            semusiUnInstalls.appversionWiseData.previousData=data.appversionWiseData_previousData;   
            // time variables
            semusiUnInstalls.timeWiseData.newData = data.timeWiseData_newData;       
            semusiUnInstalls.timeWiseData.repeatData = data.timeWiseData_repeatData;  
            // day variables
            semusiUnInstalls.dayWiseData.newData = data.dayWiseData_newData;       
            semusiUnInstalls.dayWiseData.repeatData = data.dayWiseData_repeatData;                 
            
            // populate city data
            populateTopCityData(); 
            // populate os version data
            populateTopAppVersionData();
            // generate time wise graph
            createTimeWiseUnInstallGraph(timeWiseBarData);
            handleTimeWiseGraph();
            // generate day wise graph
            createDayWiseUnInstallGraph(dayWiseBarData);
            handleDayWiseGraph(); 
        }
        else if(filter=="topchunks"){

            semusiUnInstalls.cityWiseData.currentData=data.cityWiseData_currentData;
            semusiUnInstalls.cityWiseData.previousData=data.cityWiseData_previousData; 
            semusiUnInstalls.countryWiseData.currentData=data.countryWiseData_currentData;
            semusiUnInstalls.countryWiseData.previousData=data.countryWiseData_previousData; 
            // os version variables
            semusiUnInstalls.appversionWiseData.currentData=data.appversionWiseData_currentData;
            semusiUnInstalls.appversionWiseData.previousData=data.appversionWiseData_previousData;   
            
            populateUninstalls(data.populateUninstalls);
            // populate city data
            populateTopCityData(); 
            // populate os version data
            populateTopAppVersionData();
        }
        else if(filter=="timegraph"){
            semusiUnInstalls.timeWiseData.newData = data.timeWiseData_newData;       
            semusiUnInstalls.timeWiseData.repeatData = data.timeWiseData_repeatData;  
            
            createTimeWiseUnInstallGraph(timeWiseBarData);
            handleTimeWiseGraph();          
        }
        else if(filter=="daygraph"){
            semusiUnInstalls.dayWiseData.newData = data.dayWiseData_newData;       
            semusiUnInstalls.dayWiseData.repeatData = data.dayWiseData_repeatData; 

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

    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()));

            semusiUnInstalls.getUninstallData("timegraph");
        });
    }

    //This method populates uninstalls chuck showing unique an dtotal uninstalls.
    populateUninstalls = function(data){
        if(platformTableChart){
            $("#platform_pieChart").hide();
            document.getElementById("platform_tableChart").style.display = 'block';
        }
        var androidTotalUninstalls  = data.androidTotalUninstalls;
        var androidUniqueUninstalls = data.androidUniqueUninstalls;
        var iosTotalUninstalls  = data.iosTotalUninstalls;
        var iosUniqueUninstalls = data.iosUniqueUninstalls;
        var webTotalUninstalls  = data.webTotalUninstalls;
        var webUniqueUninstalls = data.webUniqueUninstalls;
        
        $("#androidTotal").text(androidTotalUninstalls);
        $("#androidUnique").text(androidUniqueUninstalls); 
        $("#iosTotal").text(iosTotalUninstalls);
        $("#iosUnique").text(iosUniqueUninstalls);
        $("#webTotal").text(webTotalUninstalls);
        $("#webUnique").text(webUniqueUninstalls);   


        if(!platformTableChart){
            let pieData = [
                {
                    x:'android',
                    value: androidTotalUninstalls,
                    legendItem: {
                        iconType: "circle",
                      }

                },
                {
                    x:'ios',
                    value: iosTotalUninstalls,
                    legendItem: {
                        iconType: "circle",
                      }
                },
                {
                    x:'web',
                    value: webTotalUninstalls,
                    legendItem: {
                        iconType: "circle",
                      }
                }
            ];


            let platform_pieContainer =  document.querySelector("#platform_pieChart");
            let platformTableContainer = document.querySelector("#platform_tableChart");
            platformTableContainer.style.display = 'none';
            platform_pieContainer.style.display = 'block';

            //Removing previously rendered chart
            while (platform_pieContainer.firstChild) {
                platform_pieContainer.removeChild(platform_pieContainer.firstChild);
            }
            
            // create a chart and set the data
            let platformPieChart = anychart.pie(pieData);
            anychart.licenseKey("semusi.com-df30754a-aa10847e");
            var credits = platformPieChart.credits();
            credits.url("https://demo.appice.io/login");
            credits.logoSrc("https://demo.appice.io/assets/img/icon-title.png");
            credits.text("appICE");

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

            
             // configure the format of legend items
          
            // enables legend
            legend.enabled(true);
            // set legend height
            legend.height(250);
            // set legend width
            legend.width(120);
            // set legend position
            legend.position("right");
            // set legend align
            legend.align("center");
            // legend items layout
            legend.itemsLayout("vertical");
            // set the container id
            platformPieChart.container("platform_pieChart");

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

    //This method populates app version wise data on UI.
    populateTopAppVersionData = function(){

        if(OSTableChart){
            $("#os__pieChart").hide();
            document.getElementById("os__tableChart").style.display = 'block';
        }
        var currentData = semusiUnInstalls.appversionWiseData.currentData;
        var previousData = semusiUnInstalls.appversionWiseData.previousData;
        var platform = $("#ddlAppPlatform").val();
        var topAVdata=[];
        var tempArr = [];
         
        if(currentData && currentData.length>0){
            var result = _.groupBy(currentData, function(value){
                    return value.p + ' ' + value.av;
                });
            var keys = Object.keys(result)
            
            var i = 0;
            keys.forEach(function(item){
                var totalCc = 0;
                var st = item.split(' ');
                if(st[0] &&(st[0].toLowerCase()==platform || platform=="all")){
                    result[item].forEach(function(av){
                        totalCc += av.total;
                    })
                    topAVdata[i]=[];
                    topAVdata[i][0] = (st[0]) ? st[0]: "NA";
                    topAVdata[i][1] = (st[1]) ? st[1] : "NA";
                    topAVdata[i][2] = totalCc;
                    topAVdata[i][3] = 0;
                    i++;
                }
            });
            /*for(var i=0;i<currentData.length ;i++){
                if(currentData[i].p &&(currentData[i].p.toLowerCase()==platform || platform=="all")){
                    if(tempArr.indexOf(currentData[i].av) == '-1'){
                        tempArr.push(currentData[i].av)

                         
                        topAVdata[i] = [];
                        topAVdata[i][0]= (currentData[i].p) ? currentData[i].p : "";
                        topAVdata[i][1]= (currentData[i].av) ? currentData[i].av : "NA";
                        topAVdata[i][2]= currentData[i].total;
                        topAVdata[i][3] = 0; //This will be updated with previous year total.    
                    }else {
                        var index = tempArr.indexOf(currentData[i].av);
                        topAVdata = topAVdata.filter(function(n){ return n != undefined });
                        if(topAVdata[index] != undefined){
                            topAVdata[index][2] += currentData[i].total;
                        }
                    } 
                    
                    
                    //var p = (currentData[i].p) ? currentData[i].p : "";
                    //var av = (currentData[i].av) ? currentData[i].av : "NA";
                    //var t = currentData[i].total;
                    
                    //topAVdata.push([p,av,t,0]);
                }
                
            }*/
        }
         
        //topAVdata = topAVdata.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 < topAVdata.length; i++){
            for(var x=0;x<previousData.length; x++) {
                if(previousData[x].p &&(previousData[x].p.toLowerCase()==platform || platform=="all")){
                    if(previousData[x].p == topAVdata[i][0] && (previousData[x].av == topAVdata[i][1] || (previousData[x].av == undefined && topAVdata[i][1]=="NA") ) ){
                        topAVdata[i][3] += previousData[x].total; 
                    }
                }
            }
        };
        topAVdata.sort(function(a, b) {
            return b[2] - a[2];
        });

        var rows = 1;
        $('#tblOS > tbody >tr').remove();   
        topAVdata.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;"><i class="fa fa-2x fa-caret-down"></i></div>';
                strPercentChange = nFormatter(parseInt(percentChange)) +'%';
                optChange = '-';
            }
            else if(percentChange<0){
                percentChange=percentChange*-1;
                changeSign = '<div style="font-size:14px;"><i class="fa fa-2x fa-caret-up"></i></div>'
                strPercentChange = nFormatter(parseInt(percentChange)) +'%';
                optChange = '+';
            }
            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[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;

        });
        if(topAVdata.length>5){
            $('#tblOS > tbody').append('<tr "><td colspan="4" style="padding:3px;padding-right:8px; text-align:right;cursor:pointer" onclick="showAllPlatform();">+more</td></tr>');    
        }

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

         
    
    var data2 = topAVdata.map((ele)=>{
            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("https://demo.appice.io/login");
            credits.logoSrc("https://demo.appice.io/assets/img/icon-title.png");
            credits.text("appICE");

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

              // enable html for the legend

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

            // configure the format of legend items
            OS_pieChart.legend().itemsFormat(
            "{%x}{%y}"
            );
            
             // configure the format of legend items
          
            // enables legend
            legend.enabled(true);
            // set legend height
            legend.height(250);
            // set legend width
            legend.width(190);
            // 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("https://demo.appice.io/login");
        credits.logoSrc("https://demo.appice.io/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(220);
            // 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();
   }
}

}

    //This method populates UI with city data.
    populateTopCityData = function(){

        if(location_tableChart){
            $("#location__tablechart").show();
            $("#location__map").hide();
        
        var currentData = semusiUnInstalls.cityWiseData.currentData;
        var previousData = semusiUnInstalls.cityWiseData.previousData;
        var data=[];
        var ctyArr=[];
        if(currentData && currentData.length>0){
            var result=_.groupBy(currentData,"cty");
            var keys = Object.keys(result)
            var data=[];
            var i = 0;
            keys.forEach(function(item){
                var totalCity = 0;
                result[item].forEach(function(city){
                    totalCity += city.total;
                })
                data[i]=[];
                data[i][0] = (item) ? item : "NA";
                data[i][1] = totalCity;
                data[i][2] = 0
                i++;
            })
            /*for(var i=0;i<currentData.length;i++){
                if(ctyArr.indexOf(currentData[i].cty) == '-1'){
                    ctyArr.push(currentData[i].cty);
                    data[i]=[];
                    data[i][0] = (currentData[i].cty) ? currentData[i].cty : "NA";
                    data[i][1] = currentData[i].total;
                    data[i][2] = 0; //This will be updated with previous year total.
                }else if(ctyArr.indexOf(currentData[i].cty) != '-1'){
                    var cityIndex = ctyArr.indexOf(currentData[i].cty);
                    data = data.filter(function(n){ return n != undefined });
                    if(data[cityIndex] != undefined){
                        data[cityIndex][1] += currentData[i].total;
                    }
                }
            }*/
        }
        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].cty == data[i][0] || (previousData[x].cty == undefined && data[i][0]=="NA") ){
                    data[i][2] += previousData[x].total; 
                }
            }
        };

        data.sort(function(a, b) {
            return b[1] - a[1];
        });
        var rows = 1;
        $('#tblLocation > tbody >tr').remove(); 
        data.forEach(function(p){        
            var changeSign;
            var strPercentChange; 
            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-down"></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-up"></i></div>';
                strPercentChange = nFormatter(parseInt(percentChange)) +' %';
            }
            else if(percentChange==0){
                changeSign = '';
                strPercentChange = nFormatter(parseInt(percentChange)) +' %';
            }
            if(p[2]==0){
                changeSign = "";
                strPercentChange = 'NA';
            }
            if(p[0] != "?" ){  
                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 currentData = semusiUnInstalls.countryWiseData.currentData;
        var previousData = semusiUnInstalls.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++;
            })
            /*for(var i=0;i<currentData.length;i++){
                if(ccArr.indexOf(currentData[i].cc) == '-1'){
                    ccArr.push(currentData[i].cc);
                    data[i]=[];
                    data[i][0] = (currentData[i].cc) ? currentData[i].cc : "NA";
                    data[i][1] = currentData[i].total;
                    data[i][2] = 0; //This will be updated with previous year total.
                }else if(ccArr.indexOf(currentData[i].cc) != '-1'){
                    var ccIndex = ccArr.indexOf(currentData[i].cc);
                    data = data.filter(function(n){ return n != undefined });
                    if(data[ccIndex] != undefined){
                        data[ccIndex][1] += currentData[i].total;
                    }
                }      
            }*/
        }
        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];
        });
        var rows = 1;
        $('#tblLocation > tbody >tr').remove(); 
        data.forEach(function(p){        
            var changeSign;
            var strPercentChange; 
            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:8px;"><i class="fa fa-2x fa-arrow-down"></i></div>';
                strPercentChange = nFormatter(parseInt(percentChange)) +' %';
            }
            else if(percentChange<0){
                percentChange=percentChange*-1;
                changeSign = '<div style="font-size:8px;"><i class="fa fa-2x fa-arrow-up"></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">+more</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}]
               
        });
    }

    hideAndShow = function(){
        $(".row").hide();
        $("#divLocationInstalls").show();
        
    }

    showAllPlatform = function(){
        $(".row").hide();
        $("#divOSInstalls").show();
    }
    
    showAllSources = function(){
        $(".row").hide();
        $("#divAllSources").show();

    }

    $('.goToHomeNew').click(function() { 
        $(".row").show();
        $("#"+id).hide();
        $("#divOSInstalls").hide();
        $("#divLocationInstalls").hide();
        $("#divAllSources").hide();
        $("#divOSChurnPieData").hide();
        OS__allPieData = false;
        worldmap_all = false;
    })

    $('.uninstallclass').click(function() { 
        $(".row").hide();
        $("#divOSChurnPieData").show();
        OS__allPieData = true
        populateTopAppVersionData();
});

    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(); 
        }
        populateTopAppVersionData()
     }

     toggleplatformCharts = function(){
        platformTableChart = !platformTableChart;
        if(platformTableChart){
            $(".fa-pie-chart-platform").show();
            $(".fa-table-platform").hide();
        }else{
            $(".fa-pie-chart-platform").hide();
            $(".fa-table-platform").show(); 
        }
        populateUninstalls(semusiUnInstalls.UnInstallData);

     }

     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();
    }

    $('.uninstallclass').click(function() { 
            $(".row").hide();
            $("#world_chart").show();
            $(".world_all").show();
            worldmap_all = true
            initWorldLocationChart();
        })


    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) {
                semusiCommonData.referalMapping = data;
                semusiUnInstalls.getReferalWiseData();
            }
        });
    }
    

    createDayWiseUnInstallGraph = 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(semusiUnInstalls.dayWiseData.newData, chartLabels, true);
        getChartLabels(semusiUnInstalls.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<semusiUnInstalls.dayWiseData.repeatData.length;z++){
                var label=semusiUnInstalls.dayWiseData.repeatData[z].d;
                var cLabel=chartLabels[y];                
                if(semusiUnInstalls.dayWiseData.repeatData[z].p && (semusiUnInstalls.dayWiseData.repeatData[z].p.toLowerCase()==platform || platform=="all")){
                    if(label == cLabel ){
                        value = value + semusiUnInstalls.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<semusiUnInstalls.dayWiseData.newData.length;z++){
                var label=semusiUnInstalls.dayWiseData.newData[z].d;
                var cLabel=chartLabels[y];
                
                if(semusiUnInstalls.dayWiseData.newData[z].p && (semusiUnInstalls.dayWiseData.newData[z].p.toLowerCase()==platform || platform=="all")){
                    if(label == cLabel){
                        value = value + semusiUnInstalls.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.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);
        }   
    }

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

    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"];
            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);


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


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("https://demo.appice.io/login");
        credits.logoSrc("https://demo.appice.io/assets/img/icon-title.png");
        credits.text("appICE");
        if(worldmap_all){
            world_map.container('containerAll');
        }else{
            world_map.container('container');

        }

        world_map.draw();

}





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