// (function( $ ) {

function forRadioType( item, thisAysSurveyPublicChartData ){
    var questionId = item.question_id;
    var dataTypes = [[ aysSurveyPublicChartLangObj.answers ,  aysSurveyPublicChartLangObj.percent ]];
    for (var key in item.answers) {
        dataTypes.push([
            item.answerTitles[key] + '', +item.answers[key]
        ]);
    }
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    
    function drawChart() {

        var data = google.visualization.arrayToDataTable(dataTypes);
        var options = {
            height: 250,
            fontSize: 14,
            chartArea: { 
                width: '80%',
                height: '80%'
            }
        };

        var chart = new google.visualization.PieChart( document.getElementById( 'survey_answer_chart_' + questionId ) );

        chart.draw(data, options);

        //create trigger to resizeEnd event     
        jQuery(window).resize(function() {
            if(this.resizeTO) clearTimeout(this.resizeTO);
            this.resizeTO = setTimeout(function() {
                jQuery(this).trigger('resizeEnd');
            }, 500);
        });

        //redraw graph when window resize is completed  
        jQuery(window).on('resizeEnd', function() {
            chart.draw(data, options);
        });
    }
}

function forCheckboxType( item, thisAysSurveyPublicChartData ){
    var questionId = item.question_id;
    var dataTypes = [[ aysSurveyPublicChartLangObj.answers ,  aysSurveyPublicChartLangObj.count ]];
    var sum_of_answers_count = item.sum_of_answers_count;

    if( ! jQuery.isEmptyObject( item.answers ) ){
        for (var key in item.answers) {
            dataTypes.push([
                item.answerTitles[key] + '', item.answers[key]
            ]);
        }
    }else{
        dataTypes.push([
            '', 0
        ]);
    }

    google.charts.load('current', {packages: ['corechart', 'bar']});
    google.charts.setOnLoadCallback(drawBasic);

    function drawBasic() {

        var data = google.visualization.arrayToDataTable(dataTypes);
        var groupData = google.visualization.data.group(
            data,
            [{column: 0, modifier: function () {return 'total'}, type:'string'}],
            [{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
        );
        
        var formatPercent = new google.visualization.NumberFormat({
            pattern: '#%'
        });
    
        var formatShort = new google.visualization.NumberFormat({
            pattern: 'short'
        });
    
        var view = new google.visualization.DataView(data);
        view.setColumns([0, 1, {
            calc: function (dt, row) {
                if( jQuery.isEmptyObject( item.answers ) ){
                    return amount;
                }
                var amount =  formatShort.formatValue(dt.getValue(row, 1));
                if( sum_of_answers_count == 0 ){
                    var percent = 0;
                } else {
                    var percent = formatPercent.formatValue(dt.getValue(row, 1) / sum_of_answers_count);
                }
                return amount + ' (' + percent + ')';
            },
            type: 'string',
            role: 'annotation'
        }]);
    
        var options = {
            height: 300,
            fontSize: 14,
            chartArea: { 
                width: '50%',
                height: '80%'
            },
            annotations: {
                alwaysOutside: true
            },
            bars: 'horizontal',
            bar: { groupWidth: "50%" },
            colors: [ aysSurveyRgba2hex( thisAysSurveyPublicChartData.surveyColor ) ]
        };

        var chart = new google.visualization.BarChart( document.getElementById( 'survey_answer_chart_' + questionId ) );

        chart.draw(view, options);

        //create trigger to resizeEnd event     
        jQuery(window).resize(function() {
            if(this.resizeTO) clearTimeout(this.resizeTO);
            this.resizeTO = setTimeout(function() {
                jQuery(this).trigger('resizeEnd');
            }, 500);
        });

        //redraw graph when window resize is completed  
        jQuery(window).on('resizeEnd', function() {
            chart.draw(view, options);
        });
    }
}

function forLinearScaleType( item, thisAysSurveyPublicChartData ){

    var questionId = item.question_id;
    var dataTypes = [[ aysSurveyPublicChartLangObj.answers ,  aysSurveyPublicChartLangObj.count , { role: 'style' }]];

    var xAxesFrom = "";
    var xAxesTo = "";
    var xAxesLengthMin = "1";
    var xAxesLengthMax = "";
    var likertScale = false;
    if(typeof item.labels != "undefined"){
        xAxesFrom =  typeof item.labels.from != "undefined" && item.labels.from != "" ? item.labels.from  : "";
        xAxesTo   =  typeof item.labels.to != "undefined" && item.labels.to != "" ? item.labels.to : "";
        xAxesLengthMax  =  typeof item.labels.length != "undefined" && item.labels.length != "" ? item.labels.length : "";
        likertScale     =  typeof item.labels.likertScale != "undefined" && item.labels.likertScale ? true : false;
    }
    
    var xAxesLength = 5;
    if ( xAxesLengthMax !== "" ) {
        xAxesLength = parseInt(xAxesLengthMax);
    }

    var dataValues = {};
    var eachAnswer = [];

    for (var i=1; i <= xAxesLength; i++) {
        dataValues[i] = 0;
    }

    for (var key in item.answers[questionId]) {
        dataValues[ item.answers[questionId][key] ]++;
        eachAnswer.push(+item.answers[questionId][key]);
    }

    var sumOfAnswers = 0;    
    var maxCountForMode = 0;
    for (var key in dataValues) {
        dataTypes.push([
            key + '', parseInt( dataValues[key] ), thisAysSurveyPublicChartData.surveyColor
        ]);
        sumOfAnswers += key * dataValues[key];
        if(likertScale){
            if(dataValues[key] > maxCountForMode){
                maxCountForMode = dataValues[key];
            }
        }
    }

    var avgOfAnswers = ( sumOfAnswers > 0 && (item.sum_of_answers_count && item.sum_of_answers_count > 0) ) ? sumOfAnswers / item.sum_of_answers_count : 0;
    avgOfAnswers = avgOfAnswers.toFixed(2);
    var likertBoxHTML = '';
    var labelsCount  = item.labels.length && item.labels.length > 0 ? item.labels.length : 0;

    /* LIKERT SCALE START  */ 
    if(likertScale){
        // Standard Deviation calculation start (var SD);
            var SDArr = [];
            var SDcalc1;
            var SDcalc2;
            for (var SDKey in dataValues) {
                // STEP 1
                SDcalc1 = +((SDKey - avgOfAnswers)**2).toFixed(2);
                // STEP 2
                SDcalc2 = (SDcalc1 * dataValues[SDKey]);
                SDArr.push(SDcalc2);
            }
            // STEP 3
            var SDSum = SDArr.reduce(function(a, b){return a + b;});                  
            // STEP 4
            var SDAvg = SDSum / item.sum_of_answers_count;
            // STEP 5
            var SDSqrt = +Math.sqrt(SDAvg).toFixed(2);
            
            likertBoxHTML += `<div class="ays-survey-submission-linear-likert-calculation ays-survey-submission-linear-likert-standart-deviation" >
                                <div class="ays-survey-submission-linear-likert-calculation-text-option">Standard Deviation: </div>
                                <div class="ays-survey-submission-linear-likert-calculation-value-option" > ${SDSqrt} </div>
                              </div>`;
        // Standard Deviation calculation end

        // Median start
            var medianArr = eachAnswer.sort(function(a,b){ return a - b });
            var isEven = (medianArr.length % 2 == 0) ? true : false;
            var linearMedian = 0;
            
            if(isEven){
                var medianArrCount =  medianArr.length / 2;
                var linearMedian1 =  medianArr[medianArrCount - 1];
                var linearMedian2 =  medianArr[medianArrCount];
                linearMedian = (linearMedian1 + linearMedian2)/2;
            }
            else{
                linearMedian = medianArr[Math.floor(medianArr.length / 2)];
            }

            likertBoxHTML += `<div class="ays-survey-submission-linear-likert-calculation ays-survey-submission-linear-likert-median" >
                                <div class="ays-survey-submission-linear-likert-calculation-text-option">Median: </div>
                                <div class="ays-survey-submission-linear-likert-calculation-value-option" > ${linearMedian} </div>
                              </div>`;
        // Median end

        // Mode start            
            var modeArr = [];
            for (var modeKey in dataValues) {
                if (dataValues[modeKey] == maxCountForMode) {
                    modeArr.push(modeKey);
                }
            }
            likertBoxHTML += `<div class="ays-survey-submission-linear-likert-calculation ays-survey-submission-linear-likert-mode" >
                                <div class="ays-survey-submission-linear-likert-calculation-text-option">Mode: </div>
                                <div class="ays-survey-submission-linear-likert-calculation-value-option"> ${modeArr.join(',')} </div>
                              </div>`;
        // Mode end
    }
    /* LIKERT SCALE START  */ 

    google.charts.load("current", {packages:['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
        var data = google.visualization.arrayToDataTable( dataTypes );
        var view = new google.visualization.DataView(data);
        
        var groupData = google.visualization.data.group(
            data,
            [{column: 0, modifier: function () {return 'total'}, type:'string'}],
            [{column: 1, aggregation: google.visualization.data.sum, type: 'number'}]
        );

        var formatPercent = new google.visualization.NumberFormat({
            pattern: '#%'
        });
    
        var formatShort = new google.visualization.NumberFormat({
            pattern: 'short'
        });
        
        view.setColumns([0, 1, {
            calc: function (dt, row) {
                if( jQuery.isEmptyObject( item.answers[questionId] ) ){
                    return amount;
                }
                var amount =  formatShort.formatValue(dt.getValue(row, 1));
                var percent = formatPercent.formatValue(dt.getValue(row, 1) / groupData.getValue(0, 1));

                if( percent == NaN || ( typeof percent == 'string' && percent == 'NaN' ) ){
                    percent = '0%';
                }

                return amount + ' (' + percent + ')';
            },
            sourceColumn: 1,
            type: "string",
            role: "annotation" 
        } ]);
        var chartTitle = xAxesFrom != "" && xAxesTo != "" ? xAxesLengthMin + " = " + xAxesFrom + " , " + xAxesLengthMax + " = " + xAxesTo : "";
        var options = {
            height: 300,
            fontSize: 14,
            title: chartTitle,
            titleTextStyle: {
                fontSize: 13,
                bold: false,
                italic: true
            },
            chartArea: { 
                width: '80%',
                height: '80%'
            },
            legend: {
                position: "none"
            },
            annotations: {
                alwaysOutside: true
            },
            bar: {
                groupWidth: "80%"
            },
            colors: [ aysSurveyRgba2hex( thisAysSurveyPublicChartData.surveyColor ) ]
        };

        var chartBox = document.getElementById( 'survey_answer_chart_' + questionId );
        var chart = new google.visualization.ColumnChart( chartBox );
        chart.draw(view, options);
        
        if(avgOfAnswers > 0){
                
            var likertBox  = '<div class="ays-survey-submission-linear-likert-calc-box">';
                        likertBox += `<div class="ays-survey-submission-linear-likert-calculation ays-survey-submission-linear-likert-mean-calc" >
                                        <div class="ays-survey-submission-linear-likert-calculation-text-option">AVG (Mean):</div>
                                        <div class="ays-survey-submission-linear-likert-calculation-value-option" > ${avgOfAnswers} </div>
                                      </div>`;
                        likertBox += likertBoxHTML;
                likertBox += '</div>';                
            jQuery(chartBox).prepend(likertBox);
        }

        
        //create trigger to resizeEnd event     
        jQuery(window).resize(function() {
            if(this.resizeTO) clearTimeout(this.resizeTO);
            this.resizeTO = setTimeout(function() {
                jQuery(this).trigger('resizeEnd');
            }, 500);
        });

        //redraw graph when window resize is completed  
        jQuery(window).on('resizeEnd', function() {
            chart.draw(view, options);
        });
    }
}

function forMatrixScaleType( item, thisAysSurveyPublicChartData ){
    var questionId = item.question_id;
    var results    = item.matrix_data;
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    
    function drawChart() {

        var data = google.visualization.arrayToDataTable(results);
  
        var options = {
            isStacked: false,
            height: 300,
            fontSize: 14,
            chartArea: { 
                width: '90%',
                height: '80%'
            },
            legend: {
                position: 'top'
            }
        };
        var chart = new google.visualization.ColumnChart(document.getElementById( 'survey_answer_chart_' + questionId ));
        chart.draw(data, options);
        
        //create trigger to resizeEnd event     
        jQuery(window).resize(function() {
            if(this.resizeTO) clearTimeout(this.resizeTO);
            this.resizeTO = setTimeout(function() {
                jQuery(this).trigger('resizeEnd');
            }, 500);
        });

        //redraw graph when window resize is completed  
        jQuery(window).on('resizeEnd', function() {
            chart.draw(data, options);
        });
    }
}

function forMatrixScaleTypeCustom( item, thisAysSurveyPublicChartData ){
    var questionId = item.question_id;
    var martixDataColumns = new Array();
    var martixDataAnswers = item.allAnswers;

    var matrixlikertScale =  typeof item.question_options.likertScale != "undefined" && item.question_options.likertScale ? true : false;
    var columnPoints = typeof item.question_options.likertScaleMatrixPoints != "undefined" && item.question_options.likertScaleMatrixPoints ? item.question_options.likertScaleMatrixPoints : [];
    var matrixScaleIsFullReady = matrixlikertScale && columnPoints.length > 0 ? true : false;
    var matrixMean = 0;      
    var matrixEachMean;   
    var matrixSDValues = [];
    var pointsArrByAnswers = [];
    
    if(item.matrix_data){
        martixDataColumns = item.matrix_data[0].length > 0 ? item.matrix_data[0] : martixDataColumns;
    }
    var martixDataColumnsForRows = item.matrix_data;
    martixDataColumnsForRows.shift();
    var content = '<div class="ays_questions_answers">';
            content += '<div class="ays-survey-answer-matrix-scale-main ays-survey-answer-matrix-scale-main-chart">';
                content += '<div class="ays-survey-answer-matrix-scale-container">';
                    content += '<div class="ays-survey-answer-matrix-scale-row ays-survey-answer-matrix-scale-row-chart-columns">';
                    for(var columnKey in martixDataColumns){
                        content += '<div class="ays-survey-answer-matrix-scale-column" title="'+martixDataColumns[columnKey]+'">' + aysSurveyRestrictionString(martixDataColumns[columnKey], 3) + '</div>';
                    }
                    if(matrixScaleIsFullReady){
                        content += '<div class="ays-survey-answer-matrix-scale-column">Mean</div>';
                        content += '<div class="ays-survey-answer-matrix-scale-column">Total</div>';
                        content += '<div class="ays-survey-answer-matrix-scale-column"></div>';
                    }
                    content += '</div>';
                    content += '<div class="ays-survey-answer-matrix-scale-row-spacer"></div>';
                    
                    martixDataColumns.shift();
                    for(var rowKey in martixDataColumnsForRows){
                        content += '<div class="ays-survey-answer-matrix-scale-row ays-survey-answer-matrix-scale-row-chart">';
                            content += '<div class="ays-survey-answer-matrix-scale-row-content">';
                                content += '<div class="ays-survey-answer-matrix-scale-column ays-survey-answer-matrix-scale-column-row-header ays-survey-answer-matrix-scale-column-row-header-chart" title="'+martixDataColumnsForRows[rowKey][0]+'">'+ aysSurveyRestrictionString( martixDataColumnsForRows[rowKey][0], 5 ) +'</div>';
                                var answerTitle = martixDataColumnsForRows[rowKey][0];
                                martixDataColumnsForRows[rowKey].shift();

                                matrixEachMean = 0;
                                var SDMeanCounter = 0;
                                var columnAnswerSum = 0;              
                                var eachRowSD = 0;
                                var eachColumnAnswerCount = [];
                                // var eachAnswerAllCount = martixDataAnswers[rowKey];
                                var maxPointCountArr = [];
                                var columnAnswerForLikertChart = [];

                                var eachAnswerAllCount = martixDataAnswers[rowKey];
                                for(var rowInnerKey in martixDataColumnsForRows[rowKey]){
                                    var percent = 0;
                                    if(martixDataColumnsForRows[rowKey][rowInnerKey] > 0 && eachAnswerAllCount > 0){
                                        percent = ((martixDataColumnsForRows[rowKey][rowInnerKey] * 100) / eachAnswerAllCount);
                                        if( aysSurveyIsFloat( percent ) ){
                                            percent = percent.toFixed(1);
                                        }
                                    }
                                    
                                    if(matrixScaleIsFullReady){
                                        // Mean
                                        matrixEachMean += (columnPoints[rowInnerKey] * martixDataColumnsForRows[rowKey][rowInnerKey]);
                                        eachColumnAnswerCount.push(martixDataColumnsForRows[rowKey][rowInnerKey]);

                                        columnAnswerSum += +(martixDataColumnsForRows[rowKey][rowInnerKey]);

                                        // Median
                                        for(var ci = 0; ci < martixDataColumnsForRows[rowKey][rowInnerKey]; ci++){
                                            pointsArrByAnswers.push(columnPoints[rowInnerKey]);
                                            maxPointCountArr.push(columnPoints[rowInnerKey]);
                                        }

                                        columnAnswerForLikertChart.push([martixDataColumns[rowInnerKey] , +martixDataColumnsForRows[rowKey][rowInnerKey]]);
                                    }

                                    content +=  '<div class="ays-survey-answer-matrix-scale-column ays-survey-answer-matrix-scale-column-chart" style="background-color:rgb(255, 87, 34, '+percent+'%);" title="'+percent+'%">'+martixDataColumnsForRows[rowKey][rowInnerKey]+'</div>';
                                }

                                if(matrixScaleIsFullReady){
                                    // Mean calculation each row
                                    var matrixEachMeanCalc = matrixEachMean / eachAnswerAllCount;
                                    var matrixEachMeanReady = !isNaN(matrixEachMeanCalc) ? matrixEachMeanCalc : 0;
                                    matrixMean += matrixEachMeanReady;
                    
                                    // Standard Deviation calculation each row
                                    columnPoints.forEach( function(element, key){
                                        SDMeanCounter += (+(((element - matrixEachMeanReady)**2) * eachColumnAnswerCount[key]));
                                    });
                                    var prepareEachRowSD = (SDMeanCounter / columnAnswerSum);
                                    eachRowSD = !isNaN(prepareEachRowSD) ? Math.sqrt(prepareEachRowSD) : 0;
                                    matrixSDValues.push(eachRowSD);
                    
                                    // Mode calculation
                                    var eachRowMode = modeCalculator(maxPointCountArr);
                                    
                                }
                                columnAnswerForLikertChart = btoa(JSON.stringify(columnAnswerForLikertChart));
                                if(matrixScaleIsFullReady){
                                    content += '<div class="ays-survey-answer-matrix-scale-column ays-survey-answer-matrix-scale-column-chart">'+matrixEachMeanReady.toFixed(2)+'</div>';
                                    content += '<div class="ays-survey-answer-matrix-scale-column ays-survey-answer-matrix-scale-column-chart">'+columnAnswerSum+'</div>';
                                    content += '<div data-row-sum="'+columnAnswerSum+'" data-global-values="'+columnAnswerForLikertChart+'" data-row-title="'+answerTitle+'" data-likert-mean="'+matrixEachMeanReady.toFixed(2)+'" data-likert-sd="'+ ((eachRowSD > 0) ? eachRowSD.toFixed(2) : 0) +'" data-likert-median="'+maxPointCountArr.join(',')+'" data-likert-mode="'+eachRowMode.join(',')+'" class="ays-survey-answer-matrix-scale-column ays-survey-answer-matrix-scale-column-chart ays-survey-answer-matrix-scale-column-open-details">'+aysSurveyPublicChartLangObj.openSettingsImg+'</div>';
                                }

                            content += '</div>';
                        content += '</div>';
                        content += '<div class="ays-survey-answer-matrix-scale-row-spacer"></div>';
                    }
                content += '</div>';
            content += '</div>';
       content += '</div>';

       /* LIKERT SCALE START  */ 
       if(matrixScaleIsFullReady){
        var likertBoxHTML = '';
        // Mean
        var prepareMean = matrixMean / martixDataAnswers.length; 
        matrixMean = !isNaN(prepareMean) ? (prepareMean).toFixed(2) : 0;
        likertBoxHTML += `<div class="ays-survey-submission-linear-likert-calculation ays-survey-submission-linear-likert-mean-calc" >
                            <div class="ays-survey-submission-linear-likert-calculation-text-option">AVG (Mean):</div>
                            <div class="ays-survey-submission-linear-likert-calculation-value-option" > ${matrixMean} </div>
                        </div>`;            
        // Standard Deviation
        var prepareSD = SDCalculatorForMatrix(matrixSDValues);
        var readySDForMatrix = !isNaN(prepareSD) ? prepareSD.toFixed(2) : 0;
        likertBoxHTML += `<div class="ays-survey-submission-linear-likert-calculation ays-survey-submission-linear-likert-standart-deviation" >
                            <div class="ays-survey-submission-linear-likert-calculation-text-option">Standard Deviation: </div>
                            <div class="ays-survey-submission-linear-likert-calculation-value-option" > ${readySDForMatrix} </div>
                        </div>`;

        // Median start
        var prepareMedian = medianCalculator(pointsArrByAnswers);
        var linearMatrixMedian = !isNaN(prepareMedian) ? prepareMedian.toFixed(2) : 0;
        likertBoxHTML += `<div class="ays-survey-submission-linear-likert-calculation ays-survey-submission-linear-likert-median" >
                            <div class="ays-survey-submission-linear-likert-calculation-text-option">Median: </div>
                            <div class="ays-survey-submission-linear-likert-calculation-value-option" > ${linearMatrixMedian} </div>
                        </div>`;
        // Median end

        // Mode start
        var eachRowMode = modeCalculator(pointsArrByAnswers);

        likertBoxHTML += `<div class="ays-survey-submission-linear-likert-calculation ays-survey-submission-linear-likert-mode" >
                            <div class="ays-survey-submission-linear-likert-calculation-text-option">Mode: </div>
                            <div class="ays-survey-submission-linear-likert-calculation-value-option"> ${eachRowMode.join(',')} </div>
                        </div>`;
        // Mode end
    }

    var likertBox = '';
    if(matrixScaleIsFullReady){
            
        likertBox  = '<div class="ays-survey-submission-linear-likert-calc-box">';
                    likertBox += likertBoxHTML;
            likertBox += '</div>'; 
    }

       jQuery(document).find( '#survey_answer_chart_' + questionId ).html(content);
       jQuery(document).find( '#survey_answer_chart_' + questionId ).prepend(likertBox);
}

function forStarListTypeCustom( item ){
    var questionId = item.question_id;
    var StarListAllAnswers = item.answerTitles;
    var StarListChangeableAnswers = typeof item.star_list_data != "undefined" ? item.star_list_data[questionId] : "undefined";

    if(typeof StarListChangeableAnswers != "undefined"){
        var starsLength = parseInt(item.question_options);
        var content = '<div class="ays_questions_answers">';
                content += '<div class="ays-survey-answer-star-list-main ays-survey-answer-star-list-main-chart">';
                    content += '<div class="ays-survey-answer-star-list-container">';
                        content += '<div class="ays-survey-answer-star-list-row ays-survey-answer-star-list-row-chart-columns">';
                        
                            content += '<div class="ays-survey-answer-star-list-column" title=""></div>';
                            content += '<div class="ays-survey-answer-star-list-column" title="" style="color: #000">Rating</div>';
                            content += '<div class="ays-survey-answer-star-list-column" title="" style="color: #000">Stars count</div>';
                        
                        content += '</div>';
                        content += '<div class="ays-survey-answer-star-list-row-spacer"></div>';
                        for(var rowKey in StarListAllAnswers){
                            var averageSum = 0;
                                var currentAnswer = typeof StarListChangeableAnswers[rowKey] != "undefined" ? StarListChangeableAnswers[rowKey] : [];
                                if(currentAnswer == ""){
                                    currentAnswer['answered_sum'] = 0;
                                    currentAnswer['answered_count'] = 0;
                                }
                                if(currentAnswer.answered_sum > 0 && currentAnswer.answered_count > 0){
                                    averageSum = (currentAnswer.answered_sum/currentAnswer.answered_count).toFixed(1);
                                }
                                    content += '<div class="ays-survey-answer-star-list-row ays-survey-answer-star-list-row-chart">';
                                        content += '<div class="ays-survey-answer-star-list-row-content">';
                                            content += '<div class="ays-survey-answer-star-list-column ays-survey-answer-star-list-column-row-header ays-survey-answer-star-list-column-row-header-chart" style="color: #000" title="'+StarListAllAnswers[rowKey]+'">'+aysSurveyRestrictionString(StarListAllAnswers[rowKey], 5)+'</div>';                                                
                                                content +=  '<div class="ays-survey-answer-star-list-column ays-survey-answer-star-list-column-chart" style="box-shadow:inset 0px 0px 7px 0 #e9e4e4;font-weight: 600; font-size: 17px; color: #000;" >'+averageSum+'</div>';
                                                content +=  '<div class="ays-survey-answer-star-list-column ays-survey-answer-star-list-column-chart" style="box-shadow:inset 0px 0px 7px 0 #e9e4e4;position:relative;width:15%;text-align:initial;padding: 0 18px; color: #000;">';
                                                    var starsAverageSum = (averageSum*100)/starsLength;
                                                    content += getStars(starsLength,starsAverageSum);
                                                content += '</div>';
                                        content += '</div>';
                                    content += '</div>';
                                    content += '<div class="ays-survey-answer-star-list-row-spacer"></div>';
                            
                        }
                    content += '</div>';
                content += '</div>';
        content += '</div>';

        jQuery(document).find( '#survey_answer_chart_' + questionId ).html(content);
    }
}

function forSliderListTypeCustom( item ){
    var questionId = item.question_id;
    var sliderListAllAnswers = item.answerTitles;
    var sliderListChangeableAnswers = item.slider_list_data[questionId];
    
    if(typeof sliderListChangeableAnswers != "undefined"){
        var content = '<div class="ays_questions_answers">';
                content += '<div class="ays-survey-answer-slider-list-main ays-survey-answer-slider-list-main-chart">';
                    content += '<div class="ays-survey-answer-slider-list-container">';
                        content += '<div class="ays-survey-answer-slider-list-row ays-survey-answer-slider-list-row-chart-columns">';
                        
                            content += '<div class="ays-survey-answer-slider-list-column" title=""></div>';
                            content += '<div class="ays-survey-answer-slider-list-column" title="" style="color: #000">Average</div>';
                        
                        content += '</div>';
                        content += '<div class="ays-survey-answer-slider-list-row-spacer"></div>';
                        for(var rowKey in sliderListAllAnswers){
                            var averageSum = 0;
                                var currentAnswer = typeof sliderListChangeableAnswers[rowKey] != "undefined" ? sliderListChangeableAnswers[rowKey] : [];
                                if(currentAnswer == ""){
                                    currentAnswer['answered_sum'] = 0;
                                    currentAnswer['answered_count'] = 0;
                                }
                                if(currentAnswer.answered_sum > 0 && currentAnswer.answered_count > 0){
                                    averageSum = (currentAnswer.answered_sum/currentAnswer.answered_count).toFixed(1);
                                }
                                    content += '<div class="ays-survey-answer-slider-list-row ays-survey-answer-slider-list-row-chart">';
                                        content += '<div class="ays-survey-answer-slider-list-row-content">';
                                            content += '<div class="ays-survey-answer-slider-list-column ays-survey-answer-slider-list-column-row-header ays-survey-answer-star-list-column-row-header-chart" style="color: #000" title="'+sliderListAllAnswers[rowKey]+'">'+aysSurveyRestrictionString(sliderListAllAnswers[rowKey], 5)+'</div>';                                                
                                                content +=  '<div class="ays-survey-answer-slider-list-column ays-survey-answer-slider-list-column-chart" style="box-shadow:inset 0px 0px 7px 0 #e9e4e4;font-weight: 600; font-size: 17px; color: #000;" >'+averageSum+'</div>';
                                        content += '</div>';
                                    content += '</div>';
                                    content += '<div class="ays-survey-answer-slider-list-row-spacer"></div>';
                            
                        }
                    content += '</div>';
                content += '</div>';
        content += '</div>';

        jQuery(document).find( '#survey_answer_chart_' + questionId ).html(content);
    }
}


function getStars(lenght,averagePercent){


    var content = "";
        content += '<div class="ays-survey-star-list-chart-star-box">';
            content += '<div class="ays-survey-star-list-chart-star-box-wrap">';
                content += '<span class="ays-survey-star-list-chart-stars-active" style="width:'+averagePercent+'%">';
                for (var i = 1; i <= lenght; i++) {
                    content += '<i class="ays-fa ays-fa-star" aria-hidden="true"></i>';
                }
                content += '</span>';
        
                content += '<span class="ays-survey-star-list-chart-stars-inactive">';
                for (var i = 1; i <= lenght; i++) {
                    content += '<i class="ays-fa ays-fa-star-o"></i>';
                }
                content += '</span>';
            content += '</div>';
        content += '</div>';
        return content;
}

function forRangeType( item, thisAysSurveyPublicChartData ){
    var questionId = item.question_id;
    var results = item.answers[questionId] ? item.answers[questionId] : new Array();
    var readyRes = new Array();
    for(var i = 0; i < results.length; i++){
        readyRes.push([(i + 1) , parseInt(results[i])]);
    }
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    
    function drawChart() {

        var data = new google.visualization.DataTable();
        data.addColumn('number' , 'X' );
        data.addColumn('number' , 'Answer' );
        data.addRows(readyRes);
        var options = {
            height: 300,
            fontSize: 14,
            chartArea: { 
                width: '90%',
                height: '80%'
            },
            legend: {
                position: "none"
            },
            annotations: {
                alwaysOutside: true
            },
            bar: {
                groupWidth: "80%"
            },
            colors: [ '#FF5722' ]
        };
        var chart = new google.visualization.LineChart(document.getElementById( 'survey_answer_chart_' + questionId ));
        chart.draw(data, options);
        
        //create trigger to resizeEnd event     
        jQuery(window).resize(function() {
            if(this.resizeTO) clearTimeout(this.resizeTO);
            this.resizeTO = setTimeout(function() {
                jQuery(this).trigger('resizeEnd');
            }, 500);
        });

        //redraw graph when window resize is completed  
        jQuery(window).on('resizeEnd', function() {
            chart.draw(data, options);
        });
    }
}

function aysSurveyRestrictionString(word, length){
    var output = "";
    var res = word.split(" ");
    if(res.length <= length){
        output = res.join(" ");
    } else {
        res = res.slice(0,length);
        output = res.join(" ") + '...';
    }
    return output;
}

function aysSurveyIsFloat(n){
    return Number(n) === n && n % 1 !== 0;
}

function aysSurveyRgba2hex(orig) {
    if( orig.indexOf('#') !== -1 ){
        return orig;
    }

    var a, isPercent,
      rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
      alpha = (rgb && rgb[4] || "").trim(),
      hex = rgb ?
      (rgb[1] | 1 << 8).toString(16).slice(1) +
      (rgb[2] | 1 << 8).toString(16).slice(1) +
      (rgb[3] | 1 << 8).toString(16).slice(1) : orig;
  
    if (alpha !== "") {
      a = alpha;
    } else {
      a = 0o1;
    }

    // multiply before convert to HEX
    a = ''; //((a * 255) | 1 << 8).toString(16).slice(1)

    if( hex == '000000' || hex == '000' ){
        hex = '3366cc';
    }

    hex = '#' + hex + a;
  
    return hex;
}

function avgCalculator (answers, answersCount){
    var avgAnswer = 0;
    answers.forEach(function(eachAnswer, key){
        avgAnswer += eachAnswer * (key + 1);
    });
    var readyAvg = avgAnswer > 0 ? (avgAnswer / answersCount).toFixed(2) : 0;
    return readyAvg;
} 


function modeCalculator (numArr){
    var countMap = new Map();

    // Count the occurrences of each element in the array
    for (var element of numArr) {
        if (countMap.has(element)) {
        countMap.set(element, countMap.get(element) + 1);
        } else {
        countMap.set(element, 1);
        }
    }

    // Find the maximum count
    let maxCount = 0;
    countMap.forEach((count) => {
        if (count > maxCount) {
        maxCount = count;
        }
    });

    // Find the elements with the maximum count (the mode)
    var mode = [];
    countMap.forEach((count, element) => {
        if (count === maxCount) {
        mode.push(element);
        }
    });

    return mode;

}

function medianCalculator (countable){
    var medianArr = countable.sort(function(a,b){ return a - b });
    var isEven = (medianArr.length % 2 == 0) ? true : false;
    var linearMatrixMedian = 0;
    
    if(isEven){
        var medianArrCount =  medianArr.length / 2;
        var linearMedian1 =  +medianArr[medianArrCount - 1];
        var linearMedian2 =  +medianArr[medianArrCount];
        linearMatrixMedian = (linearMedian1 + linearMedian2)/2;
    }
    else{
        linearMatrixMedian = medianArr[Math.floor(medianArr.length / 2)];
    }
    return linearMatrixMedian;

}

function SDCalculatorForMatrix(numArr){
    // Calculate the sum of squares
    var squareArr = numArr.reduce(function(a, b) {
        return (a ** 2) + (b ** 2);
    });
    // Calculate the result for the entire array
    var result = Math.sqrt(squareArr / 2);

    return result;

}

function renderEachRowData (element){
    var modalBox = jQuery('#ays-survey-matrix-scale-likert-detailed-calc-modal-box');
    
    modalBox.aysModal('show');
        
    modalBox.find('.ays-survey-matrix-scale-likert-detailed-calc-chart').html('');
    modalBox.find('.ays-survey-matrix-scale-likert-detailed-calc-analytics').html('');

    // Row Title
    var titleBox = modalBox.find('.ays-modal-header');
    var titleBoxValue = titleBox.find('.ays-survey-matrix-scale-likert-detailed-calc-modal-row-title');

    // Row Mean
    var meanBox = modalBox.find('.ays-survey-submission-linear-likert-mean-calc');
    var meanBoxValue = meanBox.find('.ays-survey-submission-linear-likert-calculation-value-option');

    // Row SD
    var sdBox = modalBox.find('.ays-survey-submission-linear-likert-standart-deviation');
    var sdBoxValue = sdBox.find('.ays-survey-submission-linear-likert-calculation-value-option');

    // Row Median
    var medianBox = modalBox.find('.ays-survey-submission-linear-likert-median');
    var medianBoxValue = medianBox.find('.ays-survey-submission-linear-likert-calculation-value-option');

    // Row Mode
    var modeBox = modalBox.find('.ays-survey-submission-linear-likert-mode');
    var modeBoxValue = modeBox.find('.ays-survey-submission-linear-likert-calculation-value-option');
    
    var rowTitle   = element.attr('data-row-title');

    var rowMean   = +element.attr('data-likert-mean');
    var rowSD     = +element.attr('data-likert-sd');
    var rowMedianStr = element.attr('data-likert-median');
    var rowMode   = element.attr('data-likert-mode');

    var rowAnswers = element.attr('data-global-values');
    var rowAnswersSum = +element.attr('data-row-sum');
    
    var rowMedianArr = rowMedianStr.split(',');
    var rowMedian = medianCalculator(rowMedianArr);
    
    // Render Row title
    titleBoxValue.text(rowTitle);

    // Render Likert values
    meanBoxValue.text(rowMean);
    sdBoxValue.text(rowSD);
    medianBoxValue.text(rowMedian);
    modeBoxValue.text(rowMode);

    // Render Likert chart
    var chartData = [['Answers', 'Percent']];
    var rowAnswersArr = JSON.parse(atob(rowAnswers));
    for(var eachDataArr of rowAnswersArr){
        chartData.push(eachDataArr);
    }
    var options = {
        height: 250,
        fontSize: 14,
        chartArea: {
            width: '80%',
            height: '80%'
        }
    };

    if(rowAnswersSum > 0){
        surveyPieChartDrawer(chartData, options, '.ays-survey-matrix-scale-likert-detailed-calc-chart');

        // Render Likert Data table
        var tableHTML = matrixEachRowDataTable(chartData, rowAnswersSum);
        modalBox.find('.ays-survey-matrix-scale-likert-detailed-calc-analytics').html(tableHTML);
    }
    
}

function surveyPieChartDrawer (cdata, options, element){
    
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    
    function drawChart() {

        var data = google.visualization.arrayToDataTable(cdata);

        var chart = new google.visualization.PieChart( document.querySelector( element ) );
        chart.draw(data, options);
        resizeChart(chart, data, options);
    }

}

function matrixEachRowDataTable (tdata, answersSum){
    var tableData = tdata.slice();
    tableData.shift();
    var tableHTML = '<table class="ays-survey-matrix-scale-likert-detailed-calc-analytics-box" cellpadding="10" border="1">';
            tableHTML += '<tr class="ays-survey-matrix-scale-likert-detailed-calc-analytics-box-header-row">';
                tableHTML += '<th class="ays-survey-matrix-scale-likert-detailed-calc-analytics-box-header-columns">Answer</th>';
                tableHTML += '<th class="ays-survey-matrix-scale-likert-detailed-calc-analytics-box-header-columns">Count</th>';
                tableHTML += '<th class="ays-survey-matrix-scale-likert-detailed-calc-analytics-box-header-columns">Percent</th>';
            tableHTML += '</tr>';
            
    tableData.forEach(function(eachColumn){
        tableHTML += '<tr class="ays-survey-matrix-scale-likert-detailed-calc-analytics-box-data-row" >';
                var columnTitle         = (eachColumn[0] && eachColumn[0].length > 0) ? eachColumn[0] : '';
                var columnAnswerCount   = (eachColumn[1] && eachColumn[1] > 0) ? +(eachColumn[1]) : 0;
                
                var columnAnswerPercent = (columnAnswerCount > 0) ? Math.floor(((columnAnswerCount * 100) / answersSum)) : 0;

                var columnAnswerTextPercent = (columnAnswerPercent > 0) ? columnAnswerPercent + "%" : 0;

                tableHTML += '<td class="ays-survey-matrix-scale-likert-detailed-calc-analytics-box-data-columns">'+columnTitle+'</td>';
                tableHTML += '<td class="ays-survey-matrix-scale-likert-detailed-calc-analytics-box-data-columns">'+columnAnswerCount+'</td>';
                tableHTML += '<td class="ays-survey-matrix-scale-likert-detailed-calc-analytics-box-data-columns">'+columnAnswerTextPercent+'</td>';
        tableHTML += '</tr>';
    });
            tableHTML += '<tr class="ays-survey-matrix-scale-likert-detailed-calc-analytics-box-total-row">';
                tableHTML += '<td>Total</td>';
                tableHTML += '<td colspan="2">'+answersSum+'</td>';
            tableHTML += '</tr>';
    tableHTML += '</table>';
    return tableHTML;
}

function resizeChart(chart, data, options){
    
    //create trigger to resizeEnd event     
    jQuery(window).resize(function() {
        if(this.resizeTO) clearTimeout(this.resizeTO);
        this.resizeTO = setTimeout(function() {
            jQuery(this).trigger('resizeEnd');
        }, 100);
    });

    //redraw graph when window resize is completed  
    jQuery(window).on('resizeEnd', function() {
        chart.draw(data, options);
    });
    
}

// Function to set a cookie
function setPopupCookie(name, value, daysToExpire) {
    const date = new Date();
    date.setTime(date.getTime() + (daysToExpire * 24 * 60 * 60 * 1000));
    const expires = "expires=" + date.toUTCString();
    document.cookie = name + "=" + value + "; " + expires + "; path=/";
}

jQuery.fn.aysModal = function(action){
    var $this = jQuery(this);
    switch(action){
        case 'hide':
            jQuery(this).find('.ays-modal-content').css('animation-name', 'zoomOut');
            setTimeout(function(){
                jQuery(document.body).removeClass('modal-open');
                jQuery(document).find('.ays-modal-backdrop').remove();
                $this.hide();
            }, 250);
            break;
        case 'show':
        default:
            $this.show();
            jQuery(this).find('.ays-modal-content').css('animation-name', 'zoomIn');
            jQuery(document).find('.modal-backdrop').remove();
            jQuery(document.body).append('<div class="ays-modal-backdrop"></div>');
            jQuery(document.body).addClass('modal-open');
            break;
    }
}
// })( jQuery );
