/**
*
*  Generate a chart for a question
*  @param int $iQuestionID      ID of the question
*  @param int $iSurveyID        ID of the survey
*  @param mixed $type           Type of the chart to be created - null produces bar chart, any other value produces pie chart
*  @param array $lbl            An array containing the labels for the chart items
*  @param mixed $gdata          An array containing the percentages for the chart items
*  @param mixed $grawdata       An array containing the raw count for the chart items
*  @param mixed $cache          An object containing [Hashkey] and [CacheFolder]
*  @param string $sQuestionType The question type
*  @return                Name
*/
function createChart($iQuestionID, $iSurveyID, $type = null, $lbl, $gdata, $grawdata, $cache, $oLanguage, $sQuestionType)
{
    /* This is a lazy solution to bug #6389. A better solution would be to find out how
       the "T" gets passed to this function from the statistics.js file in the first place! */
    if (substr($iSurveyID, 0, 1) == "T") {
        $iSurveyID = substr($iSurveyID, 1);
    }
    static $bErrorGenerate = false;
    if ($bErrorGenerate) {
        return false;
    }
    $rootdir = Yii::app()->getConfig("rootdir");
    $homedir = Yii::app()->getConfig("homedir");
    $homeurl = Yii::app()->getConfig("homeurl");
    $admintheme = Yii::app()->getConfig("admintheme");
    $scriptname = Yii::app()->getConfig("scriptname");
    $chartfontfile = Yii::app()->getConfig("chartfontfile");
    $chartfontsize = Yii::app()->getConfig("chartfontsize");
    $alternatechartfontfile = Yii::app()->getConfig("alternatechartfontfile");
    $language = $oLanguage->langcode;
    $cachefilename = "";
    /* Set the fonts for the chart */
    if ($chartfontfile == 'auto') {
        // Tested with ar,be,el,fa,hu,he,is,lt,mt,sr, and en (english)
        // Not working for hi, si, zh, th, ko, ja : see $config['alternatechartfontfile'] to add some specific language font
        $chartfontfile = 'DejaVuSans.ttf';
        if (array_key_exists($language, $alternatechartfontfile)) {
            $neededfontfile = $alternatechartfontfile[$language];
            if (is_file($rootdir . "/fonts/" . $neededfontfile)) {
                $chartfontfile = $neededfontfile;
            } else {
                Yii::app()->setFlashMessage(sprintf(gT('The fonts file %s was not found in <limesurvey root folder>/fonts directory. Please, see the txt file for your language in fonts directory to generate the charts.'), $neededfontfile), 'error');
                $bErrorGenerate = true;
                // Don't do a graph again.
                return false;
            }
        }
    }
    if (count($lbl) > 72) {
        $DataSet = array(1 => array(1 => 1));
        if ($cache->IsInCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet) && Yii::app()->getConfig('debug') < 2) {
            $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet));
        } else {
            $graph = new pChart(690, 200);
            $graph->loadColorPalette($homedir . DIRECTORY_SEPARATOR . 'styles' . DIRECTORY_SEPARATOR . $admintheme . DIRECTORY_SEPARATOR . 'limesurvey.pal');
            $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
            $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
            $graph->drawTitle(0, 0, gT('Sorry, but this question has too many answer options to be shown properly in a graph.', 'unescaped'), 30, 30, 30, 690, 200);
            $cache->WriteToCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet, $graph);
            $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet));
            unset($graph);
        }
        return $cachefilename;
    }
    if (array_sum($gdata) == 0) {
        $DataSet = array(1 => array(1 => 1));
        if ($cache->IsInCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet) && Yii::app()->getConfig('debug') < 2) {
            $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet));
        } else {
            $graph = new pChart(690, 200);
            $graph->loadColorPalette($homedir . DIRECTORY_SEPARATOR . 'styles' . DIRECTORY_SEPARATOR . $admintheme . DIRECTORY_SEPARATOR . 'limesurvey.pal');
            $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
            $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
            $graph->drawTitle(0, 0, gT('Sorry, but this question has no responses yet so a graph cannot be shown.', 'unescaped'), 30, 30, 30, 690, 200);
            $cache->WriteToCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet, $graph);
            $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet));
            unset($graph);
        }
        return $cachefilename;
    }
    if (array_sum($gdata) > 0) {
        $graph = "";
        $p1 = "";
        $i = 0;
        foreach ($gdata as $data) {
            if ($data != 0) {
                $i++;
            }
        }
        /* Totatllines is the number of entries to show in the key and we need to reduce the font
           and increase the size of the chart if there are lots of them (ie more than 15) */
        $totallines = $i;
        if ($totallines > 15) {
            $gheight = 320 + 6.7 * ($totallines - 15);
            $fontsize = 7;
            $legendtop = 0.01;
            $setcentrey = 0.5 / ($gheight / 320);
        } else {
            $gheight = 320;
            $fontsize = 8;
            $legendtop = 0.07000000000000001;
            $setcentrey = 0.5;
        }
        if (!$type) {
            $DataSet = new pData();
            $counter = 0;
            $maxyvalue = 0;
            foreach ($grawdata as $datapoint) {
                $DataSet->AddPoint(array($datapoint), "Serie{$counter}");
                $DataSet->AddSerie("Serie{$counter}");
                $counter++;
                if ($datapoint > $maxyvalue) {
                    $maxyvalue = $datapoint;
                }
            }
            if ($maxyvalue < 10) {
                ++$maxyvalue;
            }
            if ($language == 'ar') {
                if (!class_exists('I18N_Arabic_Glyphs', false)) {
                    $Arabic = new I18N_Arabic('Glyphs');
                } else {
                    $Arabic = new I18N_Arabic_Glyphs();
                }
                foreach ($lbl as $kkey => $kval) {
                    if (preg_match("^[A-Za-z]^", $kkey)) {
                        //auto detect if english
                        $lblout[] = $kkey . ' (' . $kval . ')';
                    } else {
                        $lblout[] = $Arabic->utf8Glyphs($kkey . ' )' . $kval . '(');
                    }
                }
            } elseif (getLanguageRTL($language)) {
                foreach ($lbl as $kkey => $kval) {
                    $lblout[] = UTF8Strrev($kkey . ' )' . $kval . '(');
                }
            } else {
                foreach ($lbl as $kkey => $kval) {
                    $lblout[] = $kkey . ' (' . $kval . ')';
                }
            }
            $counter = 0;
            foreach ($lblout as $sLabelName) {
                $DataSet->SetSerieName(html_entity_decode($sLabelName, null, 'UTF-8'), "Serie{$counter}");
                $counter++;
            }
            if ($cache->IsInCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData()) && Yii::app()->getConfig('debug') < 2) {
                $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData()));
            } else {
                $graph = new pChart(1, 1);
                $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
                $legendsize = $graph->getLegendBoxSize($DataSet->GetDataDescription());
                if ($legendsize[1] < 320) {
                    $gheight = 420;
                } else {
                    $gheight = $legendsize[1] + 100;
                }
                $graph = new pChart(690 + $legendsize[0], $gheight);
                $graph->drawFilledRectangle(0, 0, 690 + $legendsize[0], $gheight, 254, 254, 254, false);
                $graph->loadColorPalette($homedir . DIRECTORY_SEPARATOR . 'styles' . DIRECTORY_SEPARATOR . $admintheme . DIRECTORY_SEPARATOR . 'limesurvey.pal');
                $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
                $graph->setGraphArea(50, 30, 500, $gheight - 60);
                $graph->drawFilledRoundedRectangle(7, 7, 523 + $legendsize[0], $gheight - 7, 5, 254, 255, 254);
                $graph->drawRoundedRectangle(5, 5, 525 + $legendsize[0], $gheight - 5, 5, 230, 230, 230);
                $graph->drawGraphArea(254, 254, 254, TRUE);
                $graph->drawScale($DataSet->GetData(), $DataSet->GetDataDescription(), SCALE_START0, 150, 150, 150, TRUE, 90, 0, TRUE, 5, false);
                $graph->drawGrid(4, TRUE, 230, 230, 230, 50);
                // Draw the 0 line
                $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
                $graph->drawTreshold(0, 143, 55, 72, TRUE, TRUE);
                // Draw the bar graph
                $graph->drawBarGraph($DataSet->GetData(), $DataSet->GetDataDescription(), FALSE);
                //$Test->setLabel($DataSet->GetData(),$DataSet->GetDataDescription(),"Serie4","1","Important point!");
                // Finish the graph
                $graph->setFontProperties($rootdir . DIRECTORY_SEPARATOR . 'fonts' . DIRECTORY_SEPARATOR . $chartfontfile, $chartfontsize);
                $graph->drawLegend(510, 30, $DataSet->GetDataDescription(), 250, 250, 250);
                $cache->WriteToCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData(), $graph);
                $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData()));
                unset($graph);
            }
        } else {
            // this block is to remove the items with value == 0
            // and an inelegant way to remove comments from List with Comments questions
            $i = 0;
            $j = 0;
            $labelTmp = array();
            while (isset($gdata[$i])) {
                $aHelperArray = array_keys($lbl);
                if ($gdata[$i] == 0 || $sQuestionType == "O" && substr($aHelperArray[$i], 0, strlen($oLanguage->gT("Comments"))) == $oLanguage->gT("Comments")) {
                    array_splice($gdata, $i, 1);
                } else {
                    $i++;
                    $labelTmp = $labelTmp + array_slice($lbl, $j, 1, true);
                    // Preserve numeric keys for the labels!
                }
                $j++;
            }
            $lbl = $labelTmp;
            if ($language == 'ar') {
                if (!class_exists('I18N_Arabic_Glyphs', false)) {
                    $Arabic = new I18N_Arabic('Glyphs');
                } else {
                    $Arabic = new I18N_Arabic_Glyphs();
                }
                foreach ($lbl as $kkey => $kval) {
                    if (preg_match("^[A-Za-z]^", $kkey)) {
                        //auto detect if english
                        $lblout[] = $kkey . ' (' . $kval . ')';
                    } else {
                        $lblout[] = $Arabic->utf8Glyphs($kkey . ' )' . $kval . '(');
                    }
                }
            } elseif (getLanguageRTL($language)) {
                foreach ($lbl as $kkey => $kval) {
                    $lblout[] = UTF8Strrev(html_entity_decode($kkey, null, 'UTF-8') . ' )' . $kval . '(');
                }
            } else {
                foreach ($lbl as $kkey => $kval) {
                    $lblout[] = html_entity_decode($kkey, null, 'UTF-8') . ' (' . $kval . ')';
                }
            }
            //create new 3D pie chart
            $DataSet = new pData();
            $DataSet->AddPoint($gdata, "Serie1");
            $DataSet->AddPoint($lblout, "Serie2");
            $DataSet->AddAllSeries();
            $DataSet->SetAbsciseLabelSerie("Serie2");
            if ($cache->IsInCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData()) && Yii::app()->getConfig('debug') < 2) {
                $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData()));
            } else {
                $gheight = ceil($gheight);
                $graph = new pChart(690, $gheight);
                $graph->drawFilledRectangle(0, 0, 690, $gheight, 254, 254, 254, false);
                $graph->loadColorPalette($homedir . '/styles/' . $admintheme . '/limesurvey.pal');
                $graph->drawFilledRoundedRectangle(7, 7, 687, $gheight - 3, 5, 254, 255, 254);
                $graph->drawRoundedRectangle(5, 5, 689, $gheight - 1, 5, 230, 230, 230);
                // Draw the pie chart
                $graph->setFontProperties($rootdir . "/fonts/" . $chartfontfile, $chartfontsize);
                $graph->drawPieGraph($DataSet->GetData(), $DataSet->GetDataDescription(), 225, round($gheight / 2), 170, PIE_PERCENTAGE, TRUE, 50, 20, 5);
                $graph->setFontProperties($rootdir . "/fonts/" . $chartfontfile, $chartfontsize);
                $graph->drawPieLegend(430, 12, $DataSet->GetData(), $DataSet->GetDataDescription(), 250, 250, 250);
                $cache->WriteToCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData(), $graph);
                $cachefilename = basename($cache->GetFileFromCache("graph" . $iSurveyID . $language . $iQuestionID, $DataSet->GetData()));
                unset($graph);
            }
        }
        //end else -> pie charts
    }
    return $cachefilename;
}
/**
* displayResults builds html output to display the actual results from a survey
*
* @param mixed $outputs
* @param INT $results The number of results being displayed overall
* @param mixed $rt
* @param mixed $outputType
* @param mixed $surveyid
* @param mixed $sql
* @param mixed $usegraph
*/
function displayResults($outputs, $results, $rt, $outputType, $surveyid, $sql, $usegraph, $browse, $pdf, $oLanguage)
{
    /* Set up required variables */
    $TotalCompleted = 0;
    //Count of actually completed answers
    $statlang = $oLanguage;
    $statisticsoutput = "";
    $sDatabaseType = Yii::app()->db->getDriverName();
    $tempdir = Yii::app()->getConfig("tempdir");
    $tempurl = Yii::app()->getConfig("tempurl");
    $firstletter = substr($rt, 0, 1);
    $astatdata = array();
    if ($usegraph == 1) {
        //for creating graphs we need some more scripts which are included here
        require_once APPPATH . '/third_party/pchart/pchart/pChart.class';
        require_once APPPATH . '/third_party/pchart/pchart/pData.class';
        require_once APPPATH . '/third_party/pchart/pchart/pCache.class';
        $MyCache = new pCache($tempdir . '/');
    }
    switch ($outputType) {
        case 'xls':
            $xlsTitle = sprintf($statlang->gT("Field summary for %s"), html_entity_decode($outputs['qtitle'], ENT_QUOTES, 'UTF-8'));
            $xlsDesc = html_entity_decode($outputs['qquestion'], ENT_QUOTES, 'UTF-8');
            ++$xlsRow;
            ++$xlsRow;
            ++$xlsRow;
            $sheet->write($xlsRow, 0, $xlsTitle);
            ++$xlsRow;
            $sheet->write($xlsRow, 0, $xlsDesc);
            $tableXLS = array();
            $footXLS = array();
            break;
        case 'pdf':
            $sPDFQuestion = flattenText($outputs['qquestion'], false, true);
            $pdfTitle = $pdf->delete_html(sprintf($statlang->gT("Field summary for %s"), html_entity_decode($outputs['qtitle'], ENT_QUOTES, 'UTF-8')));
            $titleDesc = $sPDFQuestion;
            $pdf->addPage('P', 'A4');
            $pdf->Bookmark($sPDFQuestion, 1, 0);
            $pdf->titleintopdf($pdfTitle, $sPDFQuestion);
            $tablePDF = array();
            $footPDF = array();
            break;
        case 'html':
            //output
            $statisticsoutput .= "<table class='statisticstable'>\n" . "\t<thead><tr><th colspan='4' align='center'><strong>" . sprintf($statlang->gT("Field summary for %s"), $outputs['qtitle']) . "</strong>" . "</th></tr>\n" . "\t<tr><th colspan='4' align='center'><strong>" . $outputs['qquestion'] . "</strong></th></tr>\n" . "\t<tr>\n\t\t<th width='50%' align='center' >";
            break;
        default:
            break;
    }
    echo '';
    //loop thorugh the array which contains all answer data
    foreach ($outputs['alist'] as $al) {
        //picks out answer list ($outputs['alist']/$al)) that come from the multiple list above
        if (isset($al[2]) && $al[2]) {
            //handling for "other" option
            if ($al[0] == $statlang->gT("Other")) {
                if ($outputs['qtype'] == '!' || $outputs['qtype'] == 'L') {
                    // It is better for single choice question types to filter on the number of '-oth-' entries, than to
                    // just count the number of 'other' values - that way with failing Javascript the statistics don't get messed up
                    $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName(substr($al[2], 0, strlen($al[2]) - 5)) . "='-oth-'";
                } else {
                    //get data
                    $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ";
                    $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " != ''" : "NOT (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE '')";
                }
            } elseif ($outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "S" || $outputs['qtype'] == "Q" || $outputs['qtype'] == ";") {
                $sDatabaseType = Yii::app()->db->getDriverName();
                //free text answers
                if ($al[0] == "Answers") {
                    $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ";
                    $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " != ''" : "NOT (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE '')";
                } elseif ($al[0] == "NoAnswer") {
                    $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( ";
                    $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " = '')" : " (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE ''))";
                }
            } elseif ($outputs['qtype'] == "O") {
                $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( ";
                $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " <> '')" : " (" . Yii::app()->db->quoteColumnName($al[2]) . " NOT LIKE ''))";
                // all other question types
            } else {
                $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($al[2]) . " =";
                //ranking question?
                if (substr($rt, 0, 1) == "R") {
                    $query .= " '{$al['0']}'";
                } else {
                    $query .= " 'Y'";
                }
            }
        } else {
            if ($al[0] != "") {
                //get more data
                $sDatabaseType = Yii::app()->db->getDriverName();
                if ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv') {
                    // mssql cannot compare text blobs so we have to cast here
                    $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar)= '{$al['0']}'";
                } else {
                    $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($rt) . " = '{$al['0']}'";
                }
            } else {
                // This is for the 'NoAnswer' case
                // We need to take into account several possibilities
                // * NoAnswer cause the participant clicked the NoAnswer radio
                //  ==> in this case value is '' or ' '
                // * NoAnswer in text field
                //  ==> value is ''
                // * NoAnswer due to conditions, or a page not displayed
                //  ==> value is NULL
                if ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv') {
                    // mssql cannot compare text blobs so we have to cast here
                    //$query = "SELECT count(*) FROM {{survey_$surveyid}} WHERE (".sanitize_int($rt)." IS NULL "
                    $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( " . "cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar) = '' " . "OR cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar) = ' ' )";
                } else {
                    //                $query = "SELECT count(*) FROM {{survey_$surveyid}} WHERE (".sanitize_int($rt)." IS NULL "
                    $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( " . " " . Yii::app()->db->quoteColumnName($rt) . " = '' " . "OR " . Yii::app()->db->quoteColumnName($rt) . " = ' ') ";
                }
            }
        }
        //check filter option
        if (incompleteAnsFilterState() == "inc") {
            $query .= " AND submitdate is null";
        } elseif (incompleteAnsFilterState() == "filter") {
            $query .= " AND submitdate is not null";
        }
        //check for any "sql" that has been passed from another script
        if ($sql != "NULL") {
            $query .= " AND {$sql}";
        }
        //get data
        $result = Yii::app()->db->createCommand($query)->query();
        // $statisticsoutput .= "\n<!-- ($sql): $query -->\n\n";
        // this just extracts the data, after we present
        foreach ($result->readAll() as $row) {
            $row = array_values($row);
            //store temporarily value of answer count of question type '5' and 'A'.
            $tempcount = -1;
            //count can't be less han zero
            //increase counter
            $TotalCompleted += $row[0];
            //"no answer" handling
            if ($al[0] === "") {
                $fname = $statlang->gT("No answer");
            } elseif ($al[0] === $statlang->gT("Other") || $al[0] === "Answers" || $outputs['qtype'] === "O" && $al[0] === $statlang->gT("Comments") || $outputs['qtype'] === "P") {
                if ($outputs['qtype'] == "P") {
                    $ColumnName_RM = $al[2] . "comment";
                } else {
                    $ColumnName_RM = $al[2];
                }
                if ($outputs['qtype'] == 'O') {
                    $TotalCompleted -= $row[0];
                }
                $fname = "{$al['1']}";
                if ($browse === true) {
                    $fname .= " <input type='button' class='statisticsbrowsebutton' value='" . $statlang->gT("Browse") . "' id='{$ColumnName_RM}' />";
                }
            } elseif ($outputs['qtype'] == "S" || $outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "Q") {
                $headPDF = array();
                $headPDF[] = array($statlang->gT("Answer"), $statlang->gT("Count"), $statlang->gT("Percentage"));
                //show free text answers
                if ($al[0] == "Answers") {
                    $fname = "{$al['1']}";
                    if ($browse === true) {
                        $fname .= " <input type='button'  class='statisticsbrowsebutton' value='" . $statlang->gT("Browse") . "' id='{$ColumnName_RM}' />";
                    }
                } elseif ($al[0] == "NoAnswer") {
                    $fname = "{$al['1']}";
                }
                $statisticsoutput .= "</th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . $statlang->gT("Count") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . $statlang->gT("Percentage") . "</strong></th>\n" . "\t</tr></thead>\n";
            } elseif (Yii::app()->getConfig('showaggregateddata') == 1) {
                if (!isset($showheadline) || $showheadline != false) {
                    if ($outputs['qtype'] == "5" || $outputs['qtype'] == "A") {
                        switch ($outputType) {
                            case 'xls':
                                $headXLS = array();
                                $headXLS[] = array($statlang->gT("Answer"), $statlang->gT("Count"), $statlang->gT("Percentage"), $statlang->gT("Sum"));
                                ++$xlsRow;
                                $sheet->write($xlsRow, 0, $statlang->gT("Answer"));
                                $sheet->write($xlsRow, 1, $statlang->gT("Count"));
                                $sheet->write($xlsRow, 2, $statlang->gT("Percentage"));
                                $sheet->write($xlsRow, 3, $statlang->gT("Sum"));
                                break;
                            case 'pdf':
                                $headPDF = array();
                                $headPDF[] = array($statlang->gT("Answer"), $statlang->gT("Count"), $statlang->gT("Percentage"), $statlang->gT("Sum"));
                                break;
                            case 'html':
                                //four columns
                                $statisticsoutput .= "<strong>" . $statlang->gT("Answer") . "</strong></th>\n" . "\t\t<th width='15%' align='center' >" . "<strong>" . $statlang->gT("Count") . "</strong></th>\n" . "\t\t<th width='20%' align='center' >" . "<strong>" . $statlang->gT("Percentage") . "</strong></th>\n" . "\t\t<th width='15%' align='center' >" . "<strong>" . $statlang->gT("Sum") . "</strong></th>\n" . "\t</tr></thead>\n";
                                break;
                            default:
                                break;
                        }
                        $showheadline = false;
                    } else {
                        switch ($outputType) {
                            case 'xls':
                                $headXLS = array();
                                $headXLS[] = array($statlang->gT("Answer"), $statlang->gT("Count"), $statlang->gT("Percentage"));
                                ++$xlsRow;
                                $sheet->write($xlsRow, 0, $statlang->gT("Answer"));
                                $sheet->write($xlsRow, 1, $statlang->gT("Count"));
                                $sheet->write($xlsRow, 2, $statlang->gT("Percentage"));
                                break;
                            case 'pdf':
                                $headPDF = array();
                                $headPDF[] = array($statlang->gT("Answer"), $statlang->gT("Count"), $statlang->gT("Percentage"));
                                break;
                            case 'html':
                                //three columns
                                $statisticsoutput .= "<strong>" . $statlang->gT("Answer") . "</strong></td>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . $statlang->gT("Count") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . $statlang->gT("Percentage") . "</strong></th>\n" . "\t</tr></thead>\n";
                                break;
                            default:
                                break;
                        }
                        $showheadline = false;
                    }
                }
                //text for answer column is always needed
                $fname = "{$al['1']} ({$al['0']})";
                //these question types get special treatment by Yii::app()->getConfig('showaggregateddata')
                if ($outputs['qtype'] == "5" || $outputs['qtype'] == "A") {
                    //put non-edited data in here because $row will be edited later
                    $grawdata[] = $row[0];
                    $showaggregated_indice = count($grawdata) - 1;
                    $showaggregated_indice_table[$showaggregated_indice] = "aggregated";
                    $showaggregated_indice = -1;
                    //keep in mind that we already added data (will be checked later)
                    $justadded = true;
                    //we need a counter because we want to sum up certain values
                    //reset counter if 5 items have passed
                    if (!isset($testcounter) || $testcounter >= 4) {
                        $testcounter = 0;
                    } else {
                        $testcounter++;
                    }
                    //beside the known percentage value a new aggregated value should be shown
                    //therefore this item is marked in a certain way
                    if ($testcounter == 0) {
                        //store the original value!
                        $tempcount = $row[0];
                        //HACK: add three times the total number of results to the value
                        //This way we get a 300 + X percentage which can be checked later
                        $row[0] += 3 * $results;
                    }
                    //the third value should be shown twice later -> mark it
                    if ($testcounter == 2) {
                        //store the original value!
                        $tempcount = $row[0];
                        //HACK: add four times the total number of results to the value
                        //This way there should be a 400 + X percentage which can be checked later
                        $row[0] += 4 * $results;
                    }
                    //the last value aggregates the data of item 4 + item 5 later
                    if ($testcounter == 4) {
                        //store the original value!
                        $tempcount = $row[0];
                        //HACK: add two times the total number of results to the value
                        //This way there should be a 200 + X percentage which can be checked later
                        $row[0] += 2 * $results;
                    }
                }
                //end if -> question type = "5"/"A"
            } else {
                if (!isset($showheadline) || $showheadline != false) {
                    switch ($outputType) {
                        case 'xls':
                            $headXLS = array();
                            $headXLS[] = array($statlang->gT("Answer"), $statlang->gT("Count"), $statlang->gT("Percentage"));
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0, $statlang->gT("Answer"));
                            $sheet->write($xlsRow, 1, $statlang->gT("Count"));
                            $sheet->write($xlsRow, 2, $statlang->gT("Percentage"));
                            break;
                        case 'pdf':
                            $headPDF = array();
                            $headPDF[] = array($statlang->gT("Answer"), $statlang->gT("Count"), $statlang->gT("Percentage"));
                            break;
                        case 'html':
                            //three columns
                            $statisticsoutput .= "<strong>" . $statlang->gT("Answer") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . $statlang->gT("Count") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . $statlang->gT("Percentage") . "</strong></th>\n" . "\t</tr></thead>\n";
                            break;
                        default:
                            break;
                    }
                    $showheadline = false;
                }
                //answer text
                $fname = "{$al['1']} ({$al['0']})";
            }
            //are there some results to play with?
            if ($results > 0) {
                //calculate percentage
                $gdata[] = $row[0] / $results * 100;
            } else {
                //no data!
                $gdata[] = "N/A";
            }
            //only add this if we don't handle question type "5"/"A"
            if (!isset($justadded)) {
                //put absolute data into array
                $grawdata[] = $row[0];
            } else {
                //unset to handle "no answer" data correctly
                unset($justadded);
            }
            //put question title and code into array
            $label[] = $fname;
            //put only the code into the array
            $justcode[] = $al[0];
            //edit labels and put them into antoher array
            //first check if $tempcount is > 0. If yes, $row[0] has been modified and $tempcount has the original count.
            if ($tempcount > 0) {
                $lbl[] = wordwrap(FlattenText("{$al['1']} ({$tempcount})"), 25, "\n");
                // NMO 2009-03-24
                $lblrtl[] = UTF8Strrev(wordwrap(FlattenText("{$al['1']} ){$tempcount}("), 25, "\n"));
                // NMO 2009-03-24
            } else {
                $lbl[] = wordwrap(FlattenText("{$al['1']} ({$row['0']})"), 25, "\n");
                // NMO 2009-03-24
                $lblrtl[] = UTF8Strrev(wordwrap(FlattenText("{$al['1']} ){$row['0']}("), 25, "\n"));
                // NMO 2009-03-24
            }
        }
        //end while -> loop through results
    }
    //end foreach -> loop through answer data
    //no filtering of incomplete answers and NO multiple option questions
    //if ((incompleteAnsFilterState() != "filter") and ($outputs['qtype'] != "M") and ($outputs['qtype'] != "P"))
    //error_log("TIBO ".print_r($showaggregated_indice_table,true));
    if ($outputs['qtype'] != "M" and $outputs['qtype'] != "P") {
        //is the checkbox "Don't consider NON completed responses (only works when Filter incomplete answers is Disable)" checked?
        //if (isset($_POST[''noncompleted']) and ($_POST['noncompleted'] == "on") && (isset(Yii::app()->getConfig('showaggregateddata')) && Yii::app()->getConfig('showaggregateddata') == 0))
        // TIBO: TODO WE MUST SKIP THE FOLLOWING SECTION FOR TYPE A and 5 when
        // showaggreagated data is set and set to 1
        if (isset($_POST['noncompleted']) and $_POST['noncompleted'] == "on") {
            //counter
            $i = 0;
            while (isset($gdata[$i])) {
                if (isset($showaggregated_indice_table[$i]) && $showaggregated_indice_table[$i] == "aggregated") {
                    // do nothing, we don't rewrite aggregated results
                    // or at least I don't know how !!! (lemeur)
                } else {
                    //we want to have some "real" data here
                    if ($gdata[$i] != "N/A") {
                        //calculate percentage
                        $gdata[$i] = $grawdata[$i] / $TotalCompleted * 100;
                    }
                }
                //increase counter
                $i++;
            }
            //end while (data available)
        } else {
            //calculate total number of incompleted records
            $TotalIncomplete = $results - $TotalCompleted;
            //output
            if (incompleteAnsFilterState() != "filter") {
                $fname = $statlang->gT("Not completed or Not displayed");
            } else {
                $fname = $statlang->gT("Not displayed");
            }
            //we need some data
            if ($results > 0) {
                //calculate percentage
                $gdata[] = $TotalIncomplete / $results * 100;
            } else {
                $gdata[] = "N/A";
            }
            //put data of incompleted records into array
            $grawdata[] = $TotalIncomplete;
            //put question title ("Not completed") into array
            $label[] = $fname;
            //put the code ("Not completed") into the array
            $justcode[] = $fname;
            //edit labels and put them into antoher array
            if (incompleteAnsFilterState() != "filter") {
                $lbl[] = wordwrap(flattenText($statlang->gT("Not completed or Not displayed") . " ({$TotalIncomplete})"), 20, "\n");
                // NMO 2009-03-24
            } else {
                $lbl[] = wordwrap(flattenText($statlang->gT("Not displayed") . " ({$TotalIncomplete})"), 20, "\n");
                // NMO 2009-03-24
            }
        }
        //end else -> noncompleted NOT checked
    }
    //end if -> no filtering of incomplete answers and no multiple option questions
    //counter
    $i = 0;
    //we need to know which item we are editing
    $itemcounter = 1;
    //array to store items 1 - 5 of question types "5" and "A"
    $stddevarray = array();
    //loop through all available answers
    while (isset($gdata[$i])) {
        //repeat header (answer, count, ...) for each new question
        unset($showheadline);
        /*
         * there are 3 colums:
         *
         * 1 (50%) = answer (title and code in brackets)
         * 2 (25%) = count (absolute)
         * 3 (25%) = percentage
         */
        $statisticsoutput .= "\t<tr>\n\t\t<td align='center' >" . $label[$i] . "\n" . "\t\t</td>\n";
        /*
         * If there is a "browse" button in this label, let's make sure there's an extra row afterwards
         * to store the columnlist
         *
         * */
        if (strpos($label[$i], "class='statisticsbrowsebutton'")) {
            $extraline = "<tr><td class='statisticsbrowsecolumn' colspan='3' style='display: none'>\n            <div class='statisticsbrowsecolumn' id='columnlist_{$ColumnName_RM}'></div></td></tr>\n";
        }
        //output absolute number of records
        $statisticsoutput .= "\t\t<td align='center' >" . $grawdata[$i] . "\n</td>";
        //no data
        if ($gdata[$i] == "N/A") {
            switch ($outputType) {
                case 'xls':
                    $label[$i] = flattenText($label[$i]);
                    $tableXLS[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $gdata[$i]) . "%");
                    ++$xlsRow;
                    $sheet->write($xlsRow, 0, $label[$i]);
                    $sheet->write($xlsRow, 1, $grawdata[$i]);
                    $sheet->write($xlsRow, 2, sprintf("%01.2f", $gdata[$i]) . "%");
                    break;
                case 'pdf':
                    $tablePDF[] = array(flattenText($label[$i]), $grawdata[$i], sprintf("%01.2f", $gdata[$i]) . "%", "");
                    break;
                case 'html':
                    //output when having no data
                    $statisticsoutput .= "\t\t<td  align='center' >";
                    //percentage = 0
                    $statisticsoutput .= sprintf("%01.2f", $gdata[$i]) . "%";
                    $gdata[$i] = 0;
                    //check if we have to adjust ouput due to Yii::app()->getConfig('showaggregateddata') setting
                    if (Yii::app()->getConfig('showaggregateddata') == 1 && ($outputs['qtype'] == "5" || $outputs['qtype'] == "A")) {
                        $statisticsoutput .= "\t\t</td>";
                    } elseif ($outputs['qtype'] == "S" || $outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "Q") {
                        $statisticsoutput .= "</td>\n\t";
                    }
                    $statisticsoutput .= "</tr>\n";
                    //Close the row
                    if (isset($extraline)) {
                        $statisticsoutput .= $extraline;
                    }
                    break;
                default:
                    break;
            }
        } else {
            //check if data should be aggregated
            if (Yii::app()->getConfig('showaggregateddata') == 1 && ($outputs['qtype'] == "5" || $outputs['qtype'] == "A")) {
                //mark that we have done soemthing special here
                $aggregated = true;
                //just calculate everything once. the data is there in the array
                if ($itemcounter == 1) {
                    //there are always 5 answers
                    for ($x = 0; $x < 5; $x++) {
                        //put 5 items into array for further calculations
                        array_push($stddevarray, $grawdata[$x]);
                    }
                }
                //"no answer" & items 2 / 4 - nothing special to do here, just adjust output
                if ($gdata[$i] <= 100) {
                    if ($itemcounter == 2 && $label[$i + 4] == $statlang->gT("No answer")) {
                        //prevent division by zero
                        if ($results - $grawdata[$i + 4] > 0) {
                            //re-calculate percentage
                            $percentage = $grawdata[$i] / ($results - $grawdata[$i + 4]) * 100;
                        } else {
                            $percentage = 0;
                        }
                    } elseif ($itemcounter == 4 && $label[$i + 2] == $statlang->gT("No answer")) {
                        //prevent division by zero
                        if ($results - $grawdata[$i + 2] > 0) {
                            //re-calculate percentage
                            $percentage = $grawdata[$i] / ($results - $grawdata[$i + 2]) * 100;
                        } else {
                            $percentage = 0;
                        }
                    } else {
                        $percentage = $gdata[$i];
                    }
                    switch ($outputType) {
                        case 'xls':
                            $label[$i] = flattenText($label[$i]);
                            $tableXLS[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%");
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0, $label[$i]);
                            $sheet->write($xlsRow, 1, $grawdata[$i]);
                            $sheet->write($xlsRow, 2, sprintf("%01.2f", $percentage) . "%");
                            break;
                        case 'pdf':
                            $label[$i] = flattenText($label[$i]);
                            $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", "");
                            break;
                        case 'html':
                            //output
                            $statisticsoutput .= "\t\t<td align='center'>";
                            //output percentage
                            $statisticsoutput .= sprintf("%01.2f", $percentage) . "%";
                            //adjust output
                            $statisticsoutput .= "\t\t</td>";
                            break;
                        default:
                            break;
                    }
                }
                //item 3 - just show results twice
                //old: if($gdata[$i] >= 400)
                //trying to fix bug #2583:
                if ($gdata[$i] >= 400 && $i != 0) {
                    //remove "400" which was added before
                    $gdata[$i] -= 400;
                    if ($itemcounter == 3 && $label[$i + 3] == $statlang->gT("No answer")) {
                        //prevent division by zero
                        if ($results - $grawdata[$i + 3] > 0) {
                            //re-calculate percentage
                            $percentage = $grawdata[$i] / ($results - $grawdata[$i + 3]) * 100;
                        } else {
                            $percentage = 0;
                        }
                    } else {
                        //get the original percentage
                        $percentage = $gdata[$i];
                    }
                    switch ($outputType) {
                        case 'xls':
                            $label[$i] = flattenText($label[$i]);
                            $tableXLS[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", sprintf("%01.2f", $percentage) . "%");
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0, $label[$i]);
                            $sheet->write($xlsRow, 1, $grawdata[$i]);
                            $sheet->write($xlsRow, 2, sprintf("%01.2f", $percentage) . "%");
                            $sheet->write($xlsRow, 3, sprintf("%01.2f", $percentage) . "%");
                            break;
                        case 'pdf':
                            $label[$i] = flattenText($label[$i]);
                            $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", sprintf("%01.2f", $percentage) . "%");
                            break;
                        case 'html':
                            //output percentage
                            $statisticsoutput .= "\t\t<td align='center' >";
                            $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>";
                            //output again (no real aggregation here)
                            $statisticsoutput .= "\t\t<td align='center' >";
                            $statisticsoutput .= sprintf("%01.2f", $percentage) . "%";
                            $statisticsoutput .= "</td>\t\t";
                            break;
                        default:
                            break;
                    }
                }
                //FIRST value -> add percentage of item 1 + item 2
                //old: if($gdata[$i] >= 300 && $gdata[$i] < 400)
                //trying to fix bug #2583:
                if ($gdata[$i] >= 300 && $gdata[$i] < 400 || $i == 0 && $gdata[$i] <= 400) {
                    //remove "300" which was added before
                    $gdata[$i] -= 300;
                    if ($itemcounter == 1 && $label[$i + 5] == $statlang->gT("No answer")) {
                        //prevent division by zero
                        if ($results - $grawdata[$i + 5] > 0) {
                            //re-calculate percentage
                            $percentage = $grawdata[$i] / ($results - $grawdata[$i + 5]) * 100;
                            $percentage2 = $grawdata[$i + 1] / ($results - $grawdata[$i + 5]) * 100;
                        } else {
                            $percentage = 0;
                            $percentage2 = 0;
                        }
                    } else {
                        $percentage = $gdata[$i];
                        $percentage2 = $gdata[$i + 1];
                    }
                    //percentage of item 1 + item 2
                    $aggregatedgdata = $percentage + $percentage2;
                    switch ($outputType) {
                        case 'xls':
                            $label[$i] = flattenText($label[$i]);
                            $tableXLS[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", sprintf("%01.2f", $aggregatedgdata) . "%");
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0, $label[$i]);
                            $sheet->write($xlsRow, 1, $grawdata[$i]);
                            $sheet->write($xlsRow, 2, sprintf("%01.2f", $percentage) . "%");
                            $sheet->write($xlsRow, 3, sprintf("%01.2f", $aggregatedgdata) . "%");
                            break;
                        case 'pdf':
                            $label[$i] = flattenText($label[$i]);
                            $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", sprintf("%01.2f", $aggregatedgdata) . "%");
                            break;
                        case 'html':
                            //output percentage
                            $statisticsoutput .= "\t\t<td align='center' >";
                            $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>";
                            //output aggregated data
                            $statisticsoutput .= "\t\t<td align='center' >";
                            $statisticsoutput .= sprintf("%01.2f", $aggregatedgdata) . "%";
                            $statisticsoutput .= "</td>\t\t";
                            break;
                        default:
                            break;
                    }
                }
                //LAST value -> add item 4 + item 5
                if ($gdata[$i] > 100 && $gdata[$i] < 300) {
                    //remove "200" which was added before
                    $gdata[$i] -= 200;
                    if ($itemcounter == 5 && $label[$i + 1] == $statlang->gT("No answer")) {
                        //prevent division by zero
                        if ($results - $grawdata[$i + 1] > 0) {
                            //re-calculate percentage
                            $percentage = $grawdata[$i] / ($results - $grawdata[$i + 1]) * 100;
                            $percentage2 = $grawdata[$i - 1] / ($results - $grawdata[$i + 1]) * 100;
                        } else {
                            $percentage = 0;
                            $percentage2 = 0;
                        }
                    } else {
                        $percentage = $gdata[$i];
                        $percentage2 = $gdata[$i - 1];
                    }
                    //item 4 + item 5
                    $aggregatedgdata = $percentage + $percentage2;
                    switch ($outputType) {
                        case 'xls':
                            $label[$i] = flattenText($label[$i]);
                            $tableXLS[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", sprintf("%01.2f", $aggregatedgdata) . "%");
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0, $label[$i]);
                            $sheet->write($xlsRow, 1, $grawdata[$i]);
                            $sheet->write($xlsRow, 2, sprintf("%01.2f", $percentage) . "%");
                            $sheet->write($xlsRow, 3, sprintf("%01.2f", $aggregatedgdata) . "%");
                            break;
                        case 'pdf':
                            $label[$i] = flattenText($label[$i]);
                            $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", sprintf("%01.2f", $aggregatedgdata) . "%");
                            break;
                        case 'html':
                            //output percentage
                            $statisticsoutput .= "\t\t<td align='center' >";
                            $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>";
                            //output aggregated data
                            $statisticsoutput .= "\t\t<td align='center' >";
                            $statisticsoutput .= sprintf("%01.2f", $aggregatedgdata) . "%";
                            $statisticsoutput .= "</td>\t\t";
                            break;
                        default:
                            break;
                    }
                    // create new row "sum"
                    //calculate sum of items 1-5
                    $sumitems = $grawdata[$i] + $grawdata[$i - 1] + $grawdata[$i - 2] + $grawdata[$i - 3] + $grawdata[$i - 4];
                    //special treatment for zero values
                    if ($sumitems > 0) {
                        $sumpercentage = "100.00";
                    } else {
                        $sumpercentage = "0";
                    }
                    //special treatment for zero values
                    if ($TotalCompleted > 0) {
                        $casepercentage = "100.00";
                    } else {
                        $casepercentage = "0";
                    }
                    switch ($outputType) {
                        case 'xls':
                            $footXLS[] = array($statlang->gT("Sum") . " (" . $statlang->gT("Answers") . ")", $sumitems, $sumpercentage . "%", $sumpercentage . "%");
                            $footXLS[] = array($statlang->gT("Number of cases"), $TotalCompleted, $casepercentage . "%", "");
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0, $statlang->gT("Sum") . " (" . $statlang->gT("Answers") . ")");
                            $sheet->write($xlsRow, 1, $sumitems);
                            $sheet->write($xlsRow, 2, $sumpercentage . "%");
                            $sheet->write($xlsRow, 3, $sumpercentage . "%");
                            ++$xlsRow;
                            $sheet->write($xlsRow, 0, $statlang->gT("Number of cases"));
                            $sheet->write($xlsRow, 1, $TotalCompleted);
                            $sheet->write($xlsRow, 2, $casepercentage . "%");
                            break;
                        case 'pdf':
                            $footPDF[] = array($statlang->gT("Sum") . " (" . $statlang->gT("Answers") . ")", $sumitems, $sumpercentage . "%", $sumpercentage . "%");
                            $footPDF[] = array($statlang->gT("Number of cases"), $TotalCompleted, $casepercentage . "%", "");
                            break;
                        case 'html':
                            $statisticsoutput .= "\t\t&nbsp;\n\t</tr>\n";
                            $statisticsoutput .= "<tr><td align='center'><strong>" . $statlang->gT("Sum") . " (" . $statlang->gT("Answers") . ")</strong></td>";
                            $statisticsoutput .= "<td align='center' ><strong>" . $sumitems . "</strong></td>";
                            $statisticsoutput .= "<td align='center' ><strong>{$sumpercentage}%</strong></td>";
                            $statisticsoutput .= "<td align='center' ><strong>{$sumpercentage}%</strong></td>";
                            $statisticsoutput .= "\t\t&nbsp;\n\t</tr>\n";
                            $statisticsoutput .= "<tr><td align='center'>" . $statlang->gT("Number of cases") . "</td>";
                            //German: "Fallzahl"
                            $statisticsoutput .= "<td align='center' >" . $TotalCompleted . "</td>";
                            $statisticsoutput .= "<td align='center' >{$casepercentage}%</td>";
                            //there has to be a whitespace within the table cell to display correctly
                            $statisticsoutput .= "<td align='center' >&nbsp;</td></tr>";
                            break;
                        default:
                            break;
                    }
                }
            } else {
                switch ($outputType) {
                    case 'xls':
                        $label[$i] = flattenText($label[$i]);
                        $tableXLS[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $gdata[$i]) . "%", "");
                        ++$xlsRow;
                        $sheet->write($xlsRow, 0, $label[$i]);
                        $sheet->write($xlsRow, 1, $grawdata[$i]);
                        $sheet->write($xlsRow, 2, sprintf("%01.2f", $gdata[$i]) . "%");
                        break;
                    case 'pdf':
                        $label[$i] = flattenText($label[$i]);
                        $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $gdata[$i]) . "%", "");
                        break;
                    case 'html':
                        //output percentage
                        $statisticsoutput .= "\t\t<td align='center' >";
                        $statisticsoutput .= sprintf("%01.2f", $gdata[$i]) . "%";
                        $statisticsoutput .= "\t\t";
                        //end output per line. there has to be a whitespace within the table cell to display correctly
                        $statisticsoutput .= "\t\t&nbsp;</td>\n\t</tr>\n";
                        if (isset($extraline)) {
                            $statisticsoutput .= $extraline;
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        //end else -> $gdata[$i] != "N/A"
        //increase counter
        $i++;
        $itemcounter++;
        //Clear extraline
        unset($extraline);
    }
    //end while
    //only show additional values when this setting is enabled
    if (Yii::app()->getConfig('showaggregateddata') == 1) {
        //it's only useful to calculate standard deviation and arithmetic means for question types
        //5 = 5 Point Scale
        //A = Array (5 Point Choice)
        if ($outputs['qtype'] == "5" || $outputs['qtype'] == "A") {
            $stddev = 0;
            $am = 0;
            //calculate arithmetic mean
            if (isset($sumitems) && $sumitems > 0) {
                //calculate and round results
                //there are always 5 items
                for ($x = 0; $x < 5; $x++) {
                    //create product of item * value
                    $am += ($x + 1) * $stddevarray[$x];
                }
                //prevent division by zero
                if (isset($stddevarray) && array_sum($stddevarray) > 0) {
                    $am = round($am / array_sum($stddevarray), 2);
                } else {
                    $am = 0;
                }
                //calculate standard deviation -> loop through all data
                /*
                 * four steps to calculate the standard deviation
                 * 1 = calculate difference between item and arithmetic mean and multiply with the number of elements
                 * 2 = create sqaure value of difference
                 * 3 = sum up square values
                 * 4 = multiply result with 1 / (number of items)
                 * 5 = get root
                 */
                for ($j = 0; $j < 5; $j++) {
                    //1 = calculate difference between item and arithmetic mean
                    $diff = $j + 1 - $am;
                    //2 = create square value of difference
                    $squarevalue = square($diff);
                    //3 = sum up square values and multiply them with the occurence
                    //prevent divison by zero
                    if ($squarevalue != 0 && $stddevarray[$j] != 0) {
                        $stddev += $squarevalue * $stddevarray[$j];
                    }
                }
                //4 = multiply result with 1 / (number of items (=5))
                //There are two different formulas to calculate standard derivation
                //$stddev = $stddev / array_sum($stddevarray);        //formula source: http://de.wikipedia.org/wiki/Standardabweichung
                //prevent division by zero
                if (array_sum($stddevarray) - 1 != 0 && $stddev != 0) {
                    $stddev = $stddev / (array_sum($stddevarray) - 1);
                    //formula source: http://de.wikipedia.org/wiki/Empirische_Varianz
                } else {
                    $stddev = 0;
                }
                //5 = get root
                $stddev = sqrt($stddev);
                $stddev = round($stddev, 2);
            }
            switch ($outputType) {
                case 'xls':
                    $tableXLS[] = array($statlang->gT("Arithmetic mean"), $am, '', '');
                    $tableXLS[] = array($statlang->gT("Standard deviation"), $stddev, '', '');
                    ++$xlsRow;
                    $sheet->write($xlsRow, 0, $statlang->gT("Arithmetic mean"));
                    $sheet->write($xlsRow, 1, $am);
                    ++$xlsRow;
                    $sheet->write($xlsRow, 0, $statlang->gT("Standard deviation"));
                    $sheet->write($xlsRow, 1, $stddev);
                    break;
                case 'pdf':
                    $tablePDF[] = array($statlang->gT("Arithmetic mean"), $am, '', '');
                    $tablePDF[] = array($statlang->gT("Standard deviation"), $stddev, '', '');
                    break;
                case 'html':
                    //calculate standard deviation
                    $statisticsoutput .= "<tr><td align='center'>" . $statlang->gT("Arithmetic mean") . "</td>";
                    //German: "Fallzahl"
                    $statisticsoutput .= "<td>&nbsp;</td><td align='center'> {$am}</td><td>&nbsp;</td></tr>";
                    $statisticsoutput .= "<tr><td align='center'>" . $statlang->gT("Standard deviation") . "</td>";
                    //German: "Fallzahl"
                    $statisticsoutput .= "<td>&nbsp;</td><td align='center'>{$stddev}</td><td>&nbsp;</td></tr>";
                    break;
                default:
                    break;
            }
        }
    }
    if ($outputType == 'pdf') {
        //$tablePDF = array();
        $tablePDF = array_merge_recursive($tablePDF, $footPDF);
        $pdf->headTable($headPDF, $tablePDF);
        //$pdf->tableintopdf($tablePDF);
        //                if(isset($footPDF))
        //                foreach($footPDF as $foot)
        //                {
        //                    $footA = array($foot);
        //                    $pdf->tablehead($footA);
        //                }
    }
    if ($outputType == 'html') {
        $statisticsoutput .= "<tr><td colspan='4' style=\"text-align:center\" id='statzone_{$rt}'>";
    }
    //-------------------------- PCHART OUTPUT ----------------------------
    list($qsid, $qgid, $qqid) = explode("X", $rt, 3);
    $qsid = $surveyid;
    $aattr = getQuestionAttributeValues($qqid, substr($rt, 0, 1));
    //PCHART has to be enabled and we need some data
    if ($usegraph == 1) {
        $bShowGraph = $aattr["statistics_showgraph"] == "1";
        $bAllowPieChart = $outputs['qtype'] != "M" && $outputs['qtype'] != "P";
        $bAllowMap = isset($aattr["location_mapservice"]) && $aattr["location_mapservice"] == "1";
        $bShowMap = $bAllowMap && $aattr["statistics_showmap"] == "1";
        $bShowPieChart = $bAllowPieChart && (isset($aattr["statistics_graphtype"]) && $aattr["statistics_graphtype"] == "1");
        $astatdata[$rt] = array('id' => $rt, 'sg' => $bShowGraph, 'ap' => $bAllowPieChart, 'am' => $bAllowMap, 'sm' => $bShowMap, 'sp' => $bShowPieChart);
        $stats = Yii::app()->session['stats'];
        $stats[$rt] = array('lbl' => $lbl, 'gdata' => $gdata, 'grawdata' => $grawdata);
        Yii::app()->session['stats'] = $stats;
        if (array_sum($gdata) > 0 && $bShowGraph == true) {
            $cachefilename = createChart($qqid, $qsid, $bShowPieChart, $lbl, $gdata, $grawdata, $MyCache, $statlang);
            //introduce new counter
            if (!isset($ci)) {
                $ci = 0;
            }
            //increase counter, start value -> 1
            $ci++;
            switch ($outputType) {
                case 'xls':
                    /**
                     * No Image for Excel...
                     */
                    break;
                case 'pdf':
                    $pdf->AddPage('P', 'A4');
                    $pdf->titleintopdf($pdfTitle, $titleDesc);
                    $pdf->Image($tempdir . "/" . $cachefilename, 0, 70, 180, 0, '', Yii::app()->getController()->createUrl("admin/survey/view/surveyid/" . $surveyid), 'B', true, 150, 'C', false, false, 0, true);
                    break;
                case 'html':
                    $statisticsoutput .= "<img src=\"{$tempurl}/" . $cachefilename . "\" border='1' />";
                    $aattr = getQuestionAttributeValues($qqid, $firstletter);
                    if ($bShowMap) {
                        $statisticsoutput .= "<div id=\"statisticsmap_{$rt}\" class=\"statisticsmap\"></div>";
                        $agmapdata[$rt] = array("coord" => getQuestionMapData(substr($rt, 1), $qsid), "zoom" => $aattr['location_mapzoom'], "width" => $aattr['location_mapwidth'], "height" => $aattr['location_mapheight']);
                    }
                    break;
                default:
                    break;
            }
        }
    }
    //close table/output
    if ($outputType == 'html') {
        if ($usegraph == 1) {
            $sImgUrl = Yii::app()->getConfig('adminimageurl');
            $statisticsoutput .= "</td></tr><tr><td colspan='4'><div id='stats_{$rt}' class='graphdisplay' style=\"text-align:center\">" . "<img class='stats-hidegraph' src='{$sImgUrl}/chart_disabled.png' title='" . $statlang->gT("Disable chart") . "' />" . "<img class='stats-showgraph' src='{$sImgUrl}/chart.png' title='" . $statlang->gT("Enable chart") . "' />" . "<img class='stats-showbar' src='{$sImgUrl}/chart_bar.png' title='" . $statlang->gT("Display as bar chart") . "' />" . "<img class='stats-showpie' src='{$sImgUrl}/chart_pie.png' title='" . $statlang->gT("Display as pie chart") . "' />" . "<img class='stats-showmap' src='{$sImgUrl}/map_disabled.png' title='" . $statlang->gT("Disable map display") . "' />" . "<img class='stats-hidemap' src='{$sImgUrl}/map.png' title='" . $statlang->gT("Enable map display") . "' />" . "</div></td></tr>";
        }
        $statisticsoutput .= "</td></tr></table><br /> \n";
    }
    return array("statisticsoutput" => $statisticsoutput, "pdf" => $pdf, "astatdata" => $astatdata);
}