(function (semusiMetrics, $, undefined) {

    var installDonoughChart=document.getElementById('installDoughnutChart');
    var unInstallDonoughChart=document.getElementById('unInstallDoughnutChart');
    var feedbackResponseChart=document.getElementById('feedbackResponseChart');
    var idonoughnutChart;
    var udonoughnutChart;
    var responseChart;
    var filterObject={
        currentPeriod : moment.utc().month()+1,
        previousPeriod : moment.utc().month(),
        periodtype : "m"
    }; 
    var installDoughnutData=[];
    var unInstallDoughnutData=[];
    var doughnutData;
    var responseChartData;
    var maxInstallValue=0;
    

    semusiMetrics.switchState = true;
    semusiMetrics.referalMapping = [];
    // semusiMetrics.InitInstalls = function(){
    //     if(semusiCommon.ACTIVE_APP_ID ==undefined || semusiCommon.ACTIVE_APP_ID==""){
    //         showMessage("You need to select an app before going to installs.");
    //         $("#divUploadReferalData").hide();
    //     }
    
    //     if(installDonoughChart){
    //         $('#chkDoughnutSwitch').bootstrapSwitch('state', true);
    //         $('.bootstrap-switch-label').css("background","#f5f5f5");

    //         $('#chkDoughnutSwitch').on('switchChange.bootstrapSwitch', function (event, state) {
    //             if(state){
    //                 var text=$('#chkDoughnutSwitch').bootstrapSwitch('offText');
    //                 $('#chkDoughnutSwitch').bootstrapSwitch('labelText',text);
                    
    //             }
    //             else{
    //                 var text=$('#chkDoughnutSwitch').bootstrapSwitch('onText');
    //                 $('#chkDoughnutSwitch').bootstrapSwitch('labelText',text);
    //             }
                
    //             semusiMetrics.switchState = state;
    //             var filter=$('#ddlDonoughnutFilter').val();
    //             semusiMetrics.getInstallDoughnutChartData(filter);
    //         });
    //         $('#ddlDonoughnutFilter').change(function() {
    //             maxInstallValue=0;
    //             filterObject=semusiCommon.getFilterObject($(this).val());
    //             semusiMetrics.getInstallDoughnutChartData($(this).val());
    //         });
    //         getReferalMappings();

    //     }

    //     $('.fileObject').live('change',function(evt) {
    //         uploadCSVFile(evt);
    //     });
    // };
    // semusiMetrics.InitUninstalls = function(){

    //     $('#chkDoughnutSwitch-u').bootstrapSwitch('state', true);
    //     $('.bootstrap-switch-label').css("background","#f5f5f5");

    //     $('#chkDoughnutSwitch-u').on('switchChange.bootstrapSwitch', function (event, state) {
    //         if(state){
    //             var text=$('#chkDoughnutSwitch-u').bootstrapSwitch('offText');
    //             $('#chkDoughnutSwitch-u').bootstrapSwitch('labelText',text);
                
    //         }
    //         else{
    //             var text=$('#chkDoughnutSwitch-u').bootstrapSwitch('onText');
    //             $('#chkDoughnutSwitch-u').bootstrapSwitch('labelText',text);
    //         }
    //         semusiMetrics.switchState  = state;
    //         var filter=$('#ddlUninstallFilter').val();
    //         semusiMetrics.getUnInstallDoughnutChartData(filter);
    //     });
    //     $('#ddlUninstallFilter').change(function() {
    //         var filter=$(this).val();
    //         filterObject=semusiCommon.getFilterObject(filter);
    //         semusiMetrics.getUninstallData(filter);
    //         semusiMetrics.getUsersAtRisk(filter);
    //         semusiMetrics.getFeedbackResponses(filter);
    //     });
        
    //     $('#ddlCampaigns').change(function() {
    //         semusiMetrics.getFeedbackResponses($("#ddlUninstallFilter").val());
    //     });
    //     var filter= $('#ddlUninstallFilter').val();
    //     getReferalMappings();
    //     semusiMetrics.getUsersAtRisk(filter);
        
    //     bindCampaignsDropDown();
    // };



    semusiMetrics.getUninstallData = function(filter){
        var dateRange = semusiCommon.getFilterDateRange(filter);
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.metrices.r + '/getReferralCounts',
            data:{
                args:JSON.stringify({
                    startDate:dateRange[0],
                    endDate:dateRange[1],
                    type:"U",
                    metric:"p",
                    periodtype:filterObject.periodtype
                }),
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID
            },
             
            success:function (data) {
                populateCurrentUninstallWidgets(data);
                createDoughnutChartData(data);
            }
        });
    };

    semusiMetrics.getInstallDoughnutChartData = function(filter){
        var dateRange = semusiCommon.getFilterDateRange(filter,false);
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.metrices.r + '/getReferralCounts',
            data:{
                args:JSON.stringify({
                    startDate:dateRange[0],
                    endDate:dateRange[1],
                    type:"I",
                    metric:"p",
                    periodtype:filterObject.periodtype
                }),
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID
            },
             
            success:function (data) {
                createDoughnutChartData(data);
            }
        }); 
    };
    semusiMetrics.getUnInstallDoughnutChartData = function(filter){
        var dateRange = semusiCommon.getFilterDateRange(filter,false);
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.metrices.r + '/getReferralCounts',
            data:{
                args:JSON.stringify({
                    startDate:dateRange[0],
                    endDate:dateRange[1],
                    type:"U",
                    metric:"p",
                    periodtype:filterObject.periodtype
                }),
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID
            },
             
            success:function (data) {
                createDoughnutChartData(data);
            }
        }); 
    };
    semusiMetrics.getUsersAtRisk = function(filter){
        var dateRange = semusiCommon.getFilterDateRange(filter);
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.metrices.r + '/getUsersAtRisk',
            data:{
                args:JSON.stringify({
                    startDate:dateRange[0],
                    endDate:dateRange[1],
                    period:semusiCommon.USER_RISK_TIME
                }),
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID
            },
             
            success:function (data) {
                populateUsersRiskWidget(data);
            }
        });
    };

    semusiMetrics.getFeedbackResponses = function(filter){
        var dateRange = semusiCommon.getFilterDateRange(filter,false);
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.templates.r + '/getCampaignFeedbackById',
            data:{
                args:JSON.stringify({
                    sd:dateRange[0],
                    ed:dateRange[1],
                    t:"y",
                    cid:$("#ddlCampaigns").val(),
                }),
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
            },
             
            success:function (data) {
                createBarChartData(data);
            }
        }); 
    };
    semusiMetrics.getCSVLogs = function (){
        $.ajax({
        type:"GET",
        url:semusiCommon.API_PARTS.metrices.r + '/getCSVLogs',
        data:{
            uniqueNumber : semusiCommon.randomNumber(),
            api_key: semusiCommon.getActiveUser.api_key,
            app_id:semusiCommon.ACTIVE_APP_ID
        },
         
        success:function (data) {
            var oTable =     $('#tblDataUploads').dataTable({
                "bProcessing": true,
                 "dom":' <"search"f><"top"l>rt<"bottom"ip><"clear">', // Allign Search
                 stateSave: true,
                "aaData": data,// <-- Data source
                "aoColumns": [
                        { "mData": 'referal_name' },
                        { "mData": 'file_name'  },
                        { "mData": 'createdOn' } ,
                        { "mData": 'status' } ,
                        { "mData": 'records' } ,
                    ]

            });
        }});
    };

    $('#btnUploadCSV').click(function(){
        var platform = $("input[type='radio'][name='optionsDataType']:checked").val();
        var referal = $('#txtReferal').val();
        var csvData = $('#csvFile').get(0).files;    
        if(confirm("Note: If any of the record from the uploaded data exists in our system, then system will check and find its last state which can be either install or uninstall and an entry will be recorded if the state found is uninstall. Click ok to continue.")){
            if(csvData.length >= 1 )  
            {
                $("#loadingDiv").show();
                $("#statusMessageDiv").hide();
                var fd = new FormData();
                fd.append('csvFile', csvData[0]);                              
                fd.append('fileName',csvData[0].name);                         
                fd.append('platform',platform);
                fd.append('referal',referal);
                fd.append('app_id',semusiCommon.ACTIVE_APP_ID);
                fd.append('api_key',semusiCommon.getActiveUser.api_key);
              $.ajax({
                        url: '/data/upload',
                        data: fd,
                        cache: false,
                        contentType: false,
                        processData: false,
                        type: 'POST',
                        success: function(data){
                            $("#statusMessageDiv").show();
                            $("#statusMessageDiv").html("<strong>"+data.message+"</strong>");
                            $("#loadingDiv").hide();

                            //Refresh donough chart.
                            var filter=$('#ddlDonoughnutFilter').val();
                            //semusiMetrics.getInstallDoughnutChartData(filter);
                        }
                });
            }
        }
    });

    semusiMetrics.setReferal = function (value){
        $('#txtReferal').val(value);
        switch (value){
            case "APPSFLYER":
                $("#rdbAll").attr('disabled', true);
                $("#rdbAndroid").attr('checked', 'checked');
                $('#divDataFormats').show();
            break;
            case "APPSALAR" :
                $("#rdbAll").attr('checked', 'checked');
                $('#divDataFormats').hide();
            break;
        }
    };


    function getCurrentDate(){
        var m_names = new Array("January", "February", "March","April", "May", "June", "July", "August", "September","October", "November", "December");
        var d = new Date();
        var curr_date = d.getDate();
        var curr_month = d.getMonth();
        var curr_year = d.getFullYear();
        return (curr_date + "-" + m_names[curr_month]+ "-" + curr_year);
    }

    function populateCurrentUninstallWidgets(data){
        var currentTotal=0;
        var previousTotal=0;
        var changedTotal=0;
        var percentChange=0;
        var platforms=[];
        var platformData=[];

        for(var i=0;i<data.length;i++){
            if(data[i].oEntry==filterObject.currentPeriod){
                currentTotal = currentTotal + data[i].subTotals;
            }
            if(data[i].oEntry == filterObject.previousPeriod){
                previousTotal = previousTotal + data[i].subTotals;
            }
            var platform = data[i].metric.toLowerCase();
            if ($.inArray(platform, platforms) == -1) {
                platforms.push(platform);
            }

        }

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

        //Calculate platform wise total
        for(var x=0;x<platforms.length;x++){
            platformData[x]=[platforms[x],0,0];
            var ctotal = 0;
            var ptotal = 0;
            for(var i=0;i<data.length;i++){
                if(data[i].metric.toLowerCase() == platforms[x] && data[i].oEntry== filterObject.currentPeriod){
                    ctotal = ctotal + data[i].subTotals;
                }
                else if(data[i].metric.toLowerCase() == platforms[x] && data[i].oEntry== filterObject.previousPeriod){
                    ptotal = ptotal + data[i].subTotals;
                }
            }
            platformData[x][1]=ctotal;
            platformData[x][2]=ptotal;
        }

        $('#tblPlatformUninstalls tr').remove();
        platformData.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:10px;"><i class="fa fa-2x fa-arrow-down"></i></div>'
                strPercentChange = parseInt(percentChange)+' %';
            }
            else if(percentChange<0){
                percentChange=percentChange*-1;
                changeSign = '<div style="font-size:10px;"><i class="fa fa-2x fa-arrow-up"></i></div>'
                strPercentChange = parseInt(percentChange)+' %';
            }
            if(p[2]==0){
                changeSign="";
                strPercentChange = "NA";
            }
            $('#tblPlatformUninstalls > tbody:last').append('<tr ><td style="padding:3px;">' + semusiCommon.toFirstUpper(p[0]) +'</td><td style="padding:3px;">'+ p[1]  +'</td><td style="padding:3px;">'+ changeSign +'</td><td style="padding:3px;">'+ strPercentChange + '</td></tr>');
        });
    }

    function populateUsersRiskWidget(data){
        if(data.length>0){
            var currentTotal=data[0].D2;
            var previousTotal=data[0].D1;
            var changedTotal=currentTotal-previousTotal;
            var percentChange =(previousTotal==0) ? 100: parseFloat(changedTotal/previousTotal*100).toFixed(2);
            if(percentChange>0){
                $("#r-downarrow").show();
                $("#r-uparrow").hide();
                $('#changeRiskTotal').text(parseInt(percentChange)+'%');
            }   
            else if(percentChange<0){
                percentChange=percentChange*-1;
                $("#r-downarrow").hide();
                $("#r-uparrow").show();
                $('#changeRiskTotal').text(parseInt(percentChange)+'%');
            }
            else{
                $("#r-downarrow").hide();
                $("#r-uparrow").hide();
                $('#changeRiskTotal').text('NA');
            }
            if(previousTotal==0){
                $("#r-downarrow").hide();
                $("#r-uparrow").hide();
                $('#changeRiskTotal').text('NA');   
            }
            $('#currentRiskTotal').text(currentTotal);
        }
        else{
            $('#currentRiskTotal').text('NA');
            $('#changeRiskTotal').text('NA');
        }
    }

     function createDoughnutChartData(data){
        /*var doughnutData = [
            {
                value: 300,
                color: fillGrey,
                highlight: highlightFillGrey,
                label: 'Grey'
            }
        ];*/
        doughnutData=[];
        var chartLabels = [];
        var chartMetrics = [];
        fillLabelAndMetrices(data,chartLabels,chartMetrics);
        if(semusiMetrics.switchState){
            chartLabels.forEach(function(label){
                for(var i=0;i<data.length;i++){
                    var doughnutItem={};
                    if(getReferalMapping(data[i].refName.toLowerCase())== label && data[i].oEntry== filterObject.currentPeriod){
                        var value=data[i].subTotals;
                        var color;
                        if(i<semusiCommon.basicColors.length) {
                            color = semusiCommon.basicColors[i] ;
                        }
                        else{
                            color = '#'+Math.floor(appiceFloat.generateRandomFloat()*16777215).toString(16);
                        }
                        updateExistingDoughnutItem(label,value,color);
                    }
                }
            });
        }
        else{
            chartMetrics.forEach(function(metric){
                for(var i=0;i<data.length;i++){
                    var doughnutItem={};
                    //var label = getReferalMapping(data[i].refName.toLowerCase());
                    if(data[i].metric.toLowerCase() == metric && data[i].oEntry == filterObject.currentPeriod){
                        var value=data[i].subTotals;
                        if(i<semusiCommon.basicColors.length) {
                            color = semusiCommon.basicColors[i] ;
                        }
                        else{
                            color = '#'+Math.floor(appiceFloat.generateRandomFloat()*16777215).toString(16);
                        }
                        updateExistingDoughnutItem(metric,value,color);
                    }
                }
            });
        }
        handleGenerateGraph(true);
    }

    function updateExistingDoughnutItem(label,value,color){
        var dItem;
        doughnutData.forEach(function(item){
            if(item.label==label){
                dItem=item;
                item.value= item.value+value;
            }
        });
        if(dItem===undefined)
        {
            dItem={};
            dItem.value=value;
            dItem.color=color;
            dItem.label=label;
            doughnutData.push(dItem);

        }
    }

    function formatDoughnutDisplay(doughnutData){
        var formattedData = [];//JSON.parse(JSON.stringify(doughnutData));
        var otherLabel="Others";
        var otherValue=0;

        var peakValue = (maxInstallValue * semusiCommon.OTHERGROUP_NUMBER)/100;
        if(doughnutData==undefined){return;}
        for(var i=0;i<doughnutData.length;i++){
           
            if(doughnutData[i].value<peakValue){
                otherValue = otherValue + doughnutData[i].value;
            }
            else{
                formattedData.push(doughnutData[i]);
            }
        }
        if(otherValue>0){
            var newitem={};
            newitem.color="#ff5b57";
            newitem.label=otherLabel;
            newitem.value=otherValue;
            formattedData.push(newitem);
        }
        for(var x=0;x<formattedData.length;x++){
             if(x< semusiCommon.basicColors.length) {
                formattedData[x].color = semusiCommon.basicColors[x] ;
            }
            else{
                formattedData[x].color = '#'+Math.floor(appiceFloat.generateRandomFloat()*16777215).toString(16);
            }
        }
        return formattedData;
    }

    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) {
                semusiMetrics.referalMapping = data;
                if(unInstallDonoughChart){
                    semusiMetrics.getUninstallData("MONTH");
                }
                if(installDonoughChart){
                    semusiMetrics.switchState = true;
                    semusiMetrics.getInstallDoughnutChartData("MONTH");
                }
                
            }
        });
    }

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

    function fillLabelAndMetrices(data,chartLabels,chartMetrics){
        for(var x=0;x< data.length;x++){
            var label = getReferalMapping(data[x].refName.toLowerCase());
            var metric = data[x].metric.toLowerCase();
            if ($.inArray(label, chartLabels) == -1 && data[x].oEntry==filterObject.currentPeriod) {
                chartLabels.push(label);
            }
            if ($.inArray(metric, chartMetrics) == -1 && data[x].oEntry==filterObject.currentPeriod) {
                chartMetrics.push(metric);
            }
            if((data[x].oEntry==filterObject.currentPeriod) && data[x].subTotals > maxInstallValue){
                maxInstallValue=data[x].subTotals;
            }
        }
    }

    createBarChartData = function(chartdata){
        responseChartData = {
            labels : [],
            datasets : []
        };
        var labels=[];
        var data=[];
        for(var i=0;i< chartdata.length;i++){
            if(chartdata[i].value<= 5 ){continue;}
            labels.push(chartdata[i].value);
            data.push(chartdata[i].totalSum);
        }
        var bar={};
        bar.data=data;
        bar.fillColor = semusiCommon.basicColors[0];
        responseChartData.datasets.push(bar);
        responseChartData.labels=labels;
        handleGenerateGraphForResponses();
         
    };
    updateExistingResponsetItem = function(label,value,color){
        var dItem;
        doughnutData.forEach(function(item){
            if(item.label==label){
                dItem=item;
                item.value= item.value+value;
            }
        });
        if(dItem===undefined)
        {
            dItem={};
            dItem.value=value;
            dItem.color=color;
            dItem.label=label;
            doughnutData.push(dItem);

        }
    };

    bindCampaignsDropDown = function(){
        var app_id = semusiCommon.ACTIVE_APP_ID;
        $.ajax({
            type:"GET",
            url:semusiCommon.API_PARTS.templates.r + '/getPastAndActiveCampaigns',
            data:{
                uniqueNumber : semusiCommon.randomNumber(),
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: app_id,
            },
             
            success:function (data) {
                $('#ddlCampaigns').empty();
                data.forEach(function(item){
                    $('#ddlCampaigns').append($('<option>').text(item.nm).attr('value', item._id));
                });
                semusiMetrics.getFeedbackResponses($("#ddlUninstallFilter").val());
            }
        });
    };

    // Chart.defaults.global = {
    //     animation: true,
    //     animationSteps: 60,
    //     animationEasing: 'easeOutQuart',
    //     showScale: true,
    //     scaleOverride: false,
    //     scaleSteps: null,
    //     scaleStepWidth: null,
    //     scaleStartValue: null,
    //     scaleLineColor: 'rgba(0,0,0,.1)',
    //     scaleLineWidth: 1,
    //     scaleShowLabels: true,
    //     scaleLabel: '<%=value%>',
    //     scaleIntegersOnly: true,
    //     scaleBeginAtZero: false,
    //     scaleFontFamily: '"Open Sans", "Helvetica Neue", "Helvetica", "Arial", sans-serif',
    //     scaleFontSize: 12,
    //     scaleFontStyle: 'normal',
    //     scaleFontColor: '#707478',
    //     responsive: true,
    //     maintainAspectRatio: true,
    //     showTooltips: true,
    //     customTooltips: false,
    //     tooltipEvents: ['mousemove', 'touchstart', 'touchmove'],
    //     tooltipFillColor: 'rgba(0,0,0,0.8)',
    //     tooltipFontFamily: '"Open Sans", "Helvetica Neue", "Helvetica", "Arial", sans-serif',
    //     tooltipFontSize: 12,
    //     tooltipFontStyle: 'normal',
    //     tooltipFontColor: '#ccc',
    //     tooltipTitleFontFamily: '"Open Sans", "Helvetica Neue", "Helvetica", "Arial", sans-serif',
    //     tooltipTitleFontSize: 12,
    //     tooltipTitleFontStyle: 'bold',
    //     tooltipTitleFontColor: '#fff',
    //     tooltipYPadding: 10,
    //     tooltipXPadding: 10,
    //     tooltipCaretSize: 8,
    //     tooltipCornerRadius: 3,
    //     tooltipXOffset: 10,
    //     tooltipTemplate: '<%if (label){%><%=label%>: <%}%><%= value %>',
    //     multiTooltipTemplate: '<%= value %>',
    //     onAnimationProgress: function(){},
    //     onAnimationComplete: function(){}
    // }
    // function handleChartJs() {
    //     $(window).load(function() {
    //         handleGenerateGraph();
    //         handleGenerateGraphForResponses();
    //     });
        
    //     $(window).resize( function() {
    //         handleGenerateGraph();
    //         handleGenerateGraphForResponses();
    //     });
    // };
    // var handleGenerateGraph = function(){
    //    if(installDonoughChart){
    //         if(idonoughnutChart!== undefined){
    //             idonoughnutChart.clear();
    //             idonoughnutChart.destroy();    
    //         }
    //         var ctx3 = installDonoughChart.getContext('2d');
    //         idonoughnutChart = new Chart(ctx3).Doughnut(formatDoughnutDisplay(doughnutData), {
    //         }); 
    //         $('#legend3').html(idonoughnutChart.generateLegend());    

    //     }
    //     if(unInstallDonoughChart){
    //         if(udonoughnutChart!== undefined){
    //             udonoughnutChart.clear();
    //             udonoughnutChart.destroy();    
    //         }
    //         var ctx4 = unInstallDonoughChart.getContext('2d');
    //         udonoughnutChart = new Chart(ctx4).Doughnut(formatDoughnutDisplay(doughnutData), {
    //         }); 
    //         $('#legend4').html(udonoughnutChart.generateLegend());    

    //     }
    // };
    // var handleGenerateGraphForResponses = function(){
    //     if(feedbackResponseChart){
    //         if(responseChart!== undefined){
    //             responseChart.clear();
    //             responseChart.destroy();    
    //         }
    //         var ctx5 = feedbackResponseChart.getContext("2d");
    //             responseChart = new Chart(ctx5).HorizontalBar(responseChartData, {
    //             responsive: true,
    //             barShowStroke: false
    //         });
    //         if(responseChart.datasets.length>0){
    //             for(var i=0;i<responseChart.datasets[0].bars.length;i++){
    //                 responseChart.datasets[0].bars[i].fillColor = semusiCommon.basicColors[i];
    //             }
    //             responseChart.update();
    //         }
    //     }
    // }
}(window.semusiMetrics = window.semusiMetrics || {}, jQuery));

