<?php

/**
 * Cria os metodos do grafico
 */
function createChartMethods($file, $groupByName)
{
    // metodos para tratamento de informacoes da quebra
    fnChart_info_initializeChart($file);
    fnChart_info_initializeInfo($file);
    fnChart_info_initializeData($file);
    fnChart_info_loadMd5Info($file);
    fnChart_info_loadSessionInfo($file);
    fnChart_info_setSeriesMode($file);
    fnChart_info_setChartItemsLimit($file);
    fnChart_info_createFusionChartsData($file);
    fnChart_info_createFusionChartsData_license($file);
    fnChart_info_createFusionChartsData_javascript($file);
    fnChart_info_createFusionChartsData_json($file);
    fnChart_info_createFusionChartsData_json_chart($file);
    fnChart_info_createFusionChartsData_json_chart_subtitle($file);
    fnChart_info_createFusionChartsData_json_chart_theme($file);
    fnChart_info_createFusionChartsData_json_type_area($file);
    fnChart_info_createFusionChartsData_json_type_bar($file);
    fnChart_info_createFusionChartsData_json_type_funnel($file);
    fnChart_info_createFusionChartsData_json_type_gauge($file);
    fnChart_info_createFusionChartsData_json_type_line($file);
    fnChart_info_createFusionChartsData_json_type_pie($file);
    fnChart_info_createFusionChartsData_json_type_pyramid($file);
    fnChart_info_createFusionChartsData_json_type_radar($file);
    fnChart_info_createFusionChartsData_json_data_series($file);
    fnChart_info_createFusionChartsData_json_data_singleSeries($file);
    fnChart_info_createFusionChartsData_json_data_multiSeries($file);
    fnChart_info_createFusionChartsData_json_data_comparisonSeries($file);
    fnChart_info_createFusionChartsData_json_data_singleSerieCategorySeries($file);
    fnChart_info_createFusionChartsData_json_data_gaugeSeries($file);
    fnChart_info_createFusionChartsData_json_data_order($file);
    fnChart_info_saveFusionChartsJson($file);

    // metodos para exibicao de grafico
    fnChart_display_summaryChart_inline_startUp($file);
    fnChart_display_summaryChart_inline_initialAjaxCall($file);
    fnChart_display_summaryChart_inline_initialAjaxResponse($file);
    fnChart_display_summaryChart_inline_updateAjaxResponse($file);
    fnChart_display_summaryChart_newPage($file);
    fnChart_display_summaryChart_phantom($file);
    fnChart_display_summaryChart_phantom_md5($file);
    fnChart_display_chart_summaryBody($file);
    fnChart_display_chart_htmlHeader($file);
    fnChart_display_chart_htmlHeader_css($file);
    fnChart_display_chart_htmlHeader_javascript($file);
    fnChart_display_chart_htmlFooter($file);
    fnChart_display_chart_htmlFusionChartsLibrary($file);
    fnChart_display_chart_htmlFusionChartsConfigDiv($file);
    fnChart_display_chart_htmlFusionChartsDiv_inline($file);
    fnChart_display_chart_htmlFusionChartsDiv_newPage($file);
    fnChart_display_chart_htmlFusionChartsJavascript_function($file);
    fnChart_display_chart_htmlFusionChartsJavascript_phantom($file);
    fnChart_display_chart_htmlFusionChartsJavascript_onReady($file);
    fnChart_display_chart_htmlFusionChartsJavascript_setInlineChartMd5($file);

    // metodos auxiliares
    fnChart_aux_filterChartItems($file);
    fnChart_aux_getFusionChartsRenderer($file);
    fnChart_aux_getFusionChartsComparisonRenderer($file);
    fnChart_aux_isJsonChartCreated($file);
    fnChart_aux_isMobile($file);
    fnChart_aux_isMultiSeries($file);
    fnChart_aux_isResponsive($file);
    fnChart_aux_isUtf8($file);
    fnChart_aux_orderSerie($file);
    fnChart_aux_rearrangeOrderIndexes($file);
    fnChart_aux_rearrangeOrderMultiIndexes($file);
}

/**
 * Inicializa as estruturas internas do grafico
 */
function fnChart_info_initializeChart($file)
{
    $phpCode = <<<EOT
    function info_initializeChart(\$chartMd5, \$isExport = false)
    {
        \$this->info_initializeInfo(\$chartMd5);

        \$this->info_loadMd5Info(\$chartMd5);
        \$this->info_loadSessionInfo(\$chartMd5);
        \$this->info_setSeriesMode();
        \$this->info_setChartItemsLimit();
        \$this->info_createFusionChartsData(\$isExport);

        \$this->info_saveFusionChartsJson();
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_initializeChart

/**
 * Inicializa o array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo($file)
{
    $charset = str_replace(array('<?php echo ', ' ?>'), array('{', '}'), $_SESSION['nm_session'] ['charset']);

    $phpCode = <<<EOT
    function info_initializeInfo(\$chartMd5)
    {
        \$charset = <<<SCEOT
$charset
SCEOT;

        \$this->SC_APP_info = [

EOT;
    $phpCode .= fnChart_info_initializeInfo_chart();
    $phpCode .= fnChart_info_initializeInfo_types();
    $phpCode .= fnChart_info_initializeInfo_options();
    $phpCode .= fnChart_info_initializeInfo_css();
    $phpCode .= <<<EOT
        ];
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_initializeInfo

/**
 * Inicializa a secao chart do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_chart()
{
    global $summaryInfo;

    $availableTypes = [];
    foreach ($summaryInfo['chart'] ['available_types'] as $chartType) {
        $availableTypes[] = "'$chartType'";
    }
    $availableTypes = implode(', ', $availableTypes);

    $availableComparisonTypes = [];
    foreach ($summaryInfo['chart'] ['available_comparison_types'] as $chartType) {
        $availableComparisonTypes[] = "'$chartType'";
    }
    $availableComparisonTypes = implode(', ', $availableComparisonTypes);

    $availableModes = [];
    foreach ($summaryInfo['chart'] ['available_modes'] as $chartMode) {
        $availableModes[] = "'$chartMode'";
    }
    $availableModes = implode(', ', $availableModes);

    $phpCode = <<<EOT
            'chart' => [
                'page_title' => '',
                'available_types' => [$availableTypes],
                'available_comparison_types' => [$availableComparisonTypes],
                'default_type' => '{$summaryInfo['chart'] ['default_type']}',
                'available_modes' => [$availableModes],
                'default_mode' => '{$summaryInfo['chart'] ['default_mode']}',
                'json_filename' => "sc_fc_{$summaryInfo['general'] ['app_name_file']}_{\$chartMd5}.json",
                'json_base_dir' => \$this->Ini->root . \$this->Ini->path_imag_temp . '/',
                'json_base_url' => \$this->Ini->path_imag_temp . '/',
            ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_chart

/**
 * Inicializa a secao types do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_types()
{
    global $summaryInfo;

    $phpCode = <<<EOT
            'types' => [

EOT;
    $availableTypes = array_unique(array_merge($summaryInfo['chart'] ['available_types'], $summaryInfo['chart'] ['available_comparison_types']));
    foreach ($availableTypes as $chartType) {
        switch ($chartType) {
            case 'Area':
                $phpCode .= fnChart_info_initializeInfo_types_area();
                break;
            case 'Bar':
                $phpCode .= fnChart_info_initializeInfo_types_bar();
                break;
            case 'Funnel':
                $phpCode .= fnChart_info_initializeInfo_types_funnel();
                break;
            case 'Gauge':
                $phpCode .= fnChart_info_initializeInfo_types_gauge();
                break;
            case 'Line':
                $phpCode .= fnChart_info_initializeInfo_types_line();
                break;
            case 'Pie':
                $phpCode .= fnChart_info_initializeInfo_types_pie();
                break;
            case 'Pyramid':
                $phpCode .= fnChart_info_initializeInfo_types_pyramid();
                break;
            case 'Radar':
                $phpCode .= fnChart_info_initializeInfo_types_radar();
                break;
        }
    }
    $phpCode .= <<<EOT
            ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_types

/**
 * Inicializa a secao area dos tipos de graficos do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_types_area()
{
    global $summaryInfo;

    $phpCode = <<<EOT
                'area' => [
                    'format' => '{$summaryInfo['chart'] ['types'] ['area'] ['format']}',
                ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_types_area

/**
 * Inicializa a secao bar dos tipos de graficos do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_types_bar()
{
    global $summaryInfo;

    $stackingOption = $summaryInfo['chart'] ['types'] ['bar'] ['stacking'] ? 'true' : 'false';

    $phpCode = <<<EOT
                'bar' => [
                    'orientation' => '{$summaryInfo['chart'] ['types'] ['bar'] ['orientation']}',
                    'dimension' => '{$summaryInfo['chart'] ['types'] ['bar'] ['dimension']}',
                    'plotSpacePercent' => '{$summaryInfo['chart'] ['types'] ['bar'] ['plotSpacePercent']}',
                    'rotateValues' => '{$summaryInfo['chart'] ['types'] ['bar'] ['rotateValues']}',
                    'placeValuesInside' => '{$summaryInfo['chart'] ['types'] ['bar'] ['placeValuesInside']}',
                    'stacking' => $stackingOption,
                    'stack100Percent' => '{$summaryInfo['chart'] ['types'] ['bar'] ['stack100Percent']}',
                    'seriesMode' => '{$summaryInfo['chart'] ['types'] ['bar'] ['seriesMode']}',
                ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_types_bar

/**
 * Inicializa a secao funnel dos tipos de graficos do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_types_funnel()
{
    global $summaryInfo;

    $phpCode = <<<EOT
                'funnel' => [
                    'dimension' => '{$summaryInfo['chart'] ['types'] ['funnel'] ['dimension']}',
                    'streamlinedData' => '{$summaryInfo['chart'] ['types'] ['funnel'] ['streamlinedData']}',
                ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_types_funnel

/**
 * Inicializa a secao gauge dos tipos de graficos do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_types_gauge()
{
    global $summaryInfo;

    $phpCode = <<<EOT
                'gauge' => [
                    'format' => '{$summaryInfo['chart'] ['types'] ['gauge'] ['format']}',
                ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_types_gauge

/**
 * Inicializa a secao line dos tipos de graficos do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_types_line()
{
    global $summaryInfo;

    $phpCode = <<<EOT
                'line' => [
                    'format' => '{$summaryInfo['chart'] ['types'] ['line'] ['format']}',
                    'seriesMode' => '{$summaryInfo['chart'] ['types'] ['line'] ['seriesMode']}',
                ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_types_line

/**
 * Inicializa a secao pie dos tipos de graficos do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_types_pie()
{
    global $summaryInfo;

    $orderOption = strtolower($summaryInfo['chart'] ['types'] ['pie'] ['order']);
    $showPercentValuesOption = $summaryInfo['chart'] ['types'] ['pie'] ['showPercentValues'] ? 'true' : 'false';

    $phpCode = <<<EOT
                'pie' => [
                    'format' => '{$summaryInfo['chart'] ['types'] ['pie'] ['format']}',
                    'dimension' => '{$summaryInfo['chart'] ['types'] ['pie'] ['dimension']}',
                    'order' => '{$orderOption}',
                    'showPercentValues' => $showPercentValuesOption,
                ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_types_pie

/**
 * Inicializa a secao pyramid dos tipos de graficos do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_types_pyramid()
{
    global $summaryInfo;

    $showPercentValuesOption = $summaryInfo['chart'] ['types'] ['pyramid'] ['showPercentValues'] ? 'true' : 'false';
    $isSlicedOption = $summaryInfo['chart'] ['types'] ['pyramid'] ['isSliced'] ? 'true' : 'false';

    $phpCode = <<<EOT
                'pyramid' => [
                    'dimension' => '{$summaryInfo['chart'] ['types'] ['pyramid'] ['dimension']}',
                    'isSliced' => $isSlicedOption,
                ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_types_pyramid

/**
 * Inicializa a secao radar dos tipos de graficos do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_types_radar()
{
    $phpCode = <<<EOT
                'radar' => [
                ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_types_radar

/**
 * Inicializa a secao options do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_options()
{
    global $summaryInfo;

    $useFontawesomeOption = $summaryInfo['options'] ['use_fontawesome'] ? 'true' : 'false';
    $tooltipExpanderOption = $summaryInfo['chart'] ['tooltip_expanded'] ? 'true' : 'false';
    $formatNumberScaleOption = $summaryInfo['chart'] ['formatNumberScale'] ? 'true' : 'false';
    $setAdaptiveYMinOption = $summaryInfo['chart'] ['setAdaptiveYMin'] ? 'true' : 'false';

    $phpCode = <<<EOT
            'options' => [
                'charset' => \$charset,
                'favicon' => '{$summaryInfo['options'] ['favicon']}',
                'summary_css' => isset(\$_POST['summary_css']) && '' != \$_POST['summary_css'] ? \$_POST['summary_css'] : '',
                'use_fontawesome' => $useFontawesomeOption,
                'tooltip_expanded' => $tooltipExpanderOption,
                'formatNumberScale' => $formatNumberScaleOption,
                'legendPosition' => '{$summaryInfo['chart'] ['legendPosition']}',
                'setAdaptiveYMin' => $setAdaptiveYMinOption,
            ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_options

/**
 * Inicializa a secao css do array de informacoes a ser usado na geracao do grafico
 */
function fnChart_info_initializeInfo_css()
{
    $phpCode = <<<EOT
            'css' => [
                'chart_page' => 'scGridPage',
            ],

EOT;

    return $phpCode;
} // fnChart_info_initializeInfo_css

/**
 * Inicializa o array de dados calculados para geracao do grafico
 */
function fnChart_info_initializeData($file)
{
    global $summaryInfo;

    if ($summaryInfo['options'] ['display_inline_chart']) {
        $chartWidth = $summaryInfo['chart'] ['inline_width'];
        $chartHeight = $summaryInfo['chart'] ['inline_height'];
    } else {
        $chartWidth = $summaryInfo['chart'] ['width'];
        $chartHeight = $summaryInfo['chart'] ['height'];
    }

    $phpCode = <<<EOT
    function info_initializeData()
    {
        \$this->SC_APP_data = [
            'type' => '',
            'order' => '',
            'width' => '{$chartWidth}',
            'height' => '{$chartHeight}',
            'data_mode' => '',
            'series_mode' => '',
            'md5_data' => [],
            'chart_id' => 'id_chart_' . mt_rand(1, 1000),
            'chart_div' => 'id_div_' . mt_rand(1, 1000),
            'chart_dataFormat' => 'jsonurl',
            'license_key' => 'HA-8E3A-64coB5A2D4E1D4E4D3A11B11A5C3A1A1lC-7wA1B9xD-13lrgA2D3vbsC5E3D4A1E1I1B2B8D7A6E1F5C4I2D1A4juwE2B4G1C-7G1A7C8rqg1C4D1I4njyB5D6D3bzfG2C9A4C6A1B4A1C3D1J2B3yqsD1B1ZA33egvD8D5B4oC-8D3QA16A7jteE3A3H2E3A9C10C6C3C4E4A2H3F3C2B-16==',
            'license_creditLabel' => 'false',
            'limit_chart_items' => '',
            'filtered_chart_items' => [],
            'fusioncharts_license' => [],
            'fusioncharts_javascript' => [],
            'fusioncharts_json' => [],
        ];

        if (\$this->aux_isResponsive()) {
            \$this->SC_APP_data['width'] = '100%';
            \$this->SC_APP_data['height'] = '85%';
        } elseif (\$this->aux_isMobile()) {
            \$this->SC_APP_data['width'] = '100%';
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_initializeData

/**
 * Carrega informacoes do grafico a ser gerado
 */
function fnChart_info_loadMd5Info($file)
{
    global $summaryInfo;

    $phpCode = <<<EOT
    function info_loadMd5Info(\$chartMd5)
    {
        \$this->SC_APP_data['md5_data'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['chart_info'] [\$chartMd5];

        \$pageTitle = \$this->aux_isUtf8() ? \$this->SC_APP_data['md5_data'] ['metric'] ['label'] : sc_convert_encoding(\$this->SC_APP_data['md5_data'] ['metric'] ['label'], \$_SESSION['scriptcase'] ['charset'], 'UTF-8');

        \$this->SC_APP_info['chart'] ['page_title'] = \$pageTitle;
        \$this->SC_APP_data['type'] = \$this->SC_APP_info['chart'] ['default_type'];
        \$this->SC_APP_data['data_mode'] = \$this->SC_APP_info['chart'] ['default_mode'];
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_loadMd5Info

/**
 * Carrega configuracoes do grafico a ser gerado
 */
function fnChart_info_loadSessionInfo($file)
{
    global $summaryInfo;

    $phpCode = <<<EOT
    function info_loadSessionInfo(\$chartMd5)
    {
        \$this->SC_APP_data['type'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_tipo'];
        \$this->SC_APP_data['data_mode'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['graf_opc_atual'];

        \$this->SC_APP_data['width'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_larg'];
        \$this->SC_APP_data['height'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_alt'];

        \$this->SC_APP_data['order'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['graf_order'];

        \$this->SC_APP_info['types'] ['bar'] ['orientation'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_barra_orien'];
        \$this->SC_APP_info['types'] ['bar'] ['dimension'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_barra_dimen'];
        \$this->SC_APP_info['types'] ['bar'] ['stacking'] = 'Off' != \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_barra_empil'];
        \$this->SC_APP_info['types'] ['bar'] ['stack100Percent'] = 'Percent' == \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_barra_empil'] ? '1' : '0';
        \$this->SC_APP_info['types'] ['bar'] ['seriesMode'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_barra_agrup'];

        \$this->SC_APP_info['types'] ['funnel'] ['dimension'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_funil_dimen'];

        \$this->SC_APP_info['types'] ['gauge'] ['format'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_gauge_forma'];

        \$this->SC_APP_info['types'] ['line'] ['format'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_linha_forma'];
        \$this->SC_APP_info['types'] ['line'] ['seriesMode'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_linha_agrup'];

        \$this->SC_APP_info['types'] ['pie'] ['format'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_pizza_forma'];
        \$this->SC_APP_info['types'] ['pie'] ['dimension'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_pizza_dimen'];
        \$this->SC_APP_info['types'] ['pie'] ['order'] = strtolower(\$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_pizza_orden']);
        \$this->SC_APP_info['types'] ['pie'] ['showPercentValues'] = 'Percent' == \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_pizza_valor'];

        \$this->SC_APP_info['types'] ['pyramid'] ['dimension'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_pyram_dimen'];
        \$this->SC_APP_info['types'] ['pyramid'] ['showPercentValues'] = 'Percent' == \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_pyram_valor'];
        \$this->SC_APP_info['types'] ['pyramid'] ['isSliced'] = 'S' == \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['cfg_graf'] ['graf_pyram_forma'];
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_loadSessionInfo

/**
 * Define o modo de exibicao das series em graficos multi series
 */
function fnChart_info_setSeriesMode($file)
{
    $phpCode = <<<EOT
    function info_setSeriesMode()
    {
        switch (\$this->SC_APP_data['type']) {
            case 'Bar':
                if ('Series' == \$this->SC_APP_info['types'] ['bar'] ['seriesMode']) {
                    \$this->SC_APP_data['series_mode'] = 'serie';
                } else {
                    \$this->SC_APP_data['series_mode'] = 'set';
                }
                break;

            case 'Line':
                if ('Series' == \$this->SC_APP_info['types'] ['line'] ['seriesMode']) {
                    \$this->SC_APP_data['series_mode'] = 'serie';
                } else {
                    \$this->SC_APP_data['series_mode'] = 'set';
                }
                break;

            default:
                \$this->SC_APP_data['series_mode'] = 'set';
                break;
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_setSeriesMode

/**
 * Define o limite de itens para exibicao no grafico
 */
function fnChart_info_setChartItemsLimit($file)
{
    global $summaryInfo;

    $phpCode = <<<EOT
    function info_setChartItemsLimit()
    {
        if (\$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['has_limit_chart_items']) {
            if ('' != \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['limit_chart_items'] && '0' != \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['limit_chart_items']) {
                \$this->SC_APP_data['limit_chart_items'] = \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['limit_chart_items'];
            } elseif (isset(\$this->SC_APP_data['md5_data'] ['options'] ['limit_chart_items']) && '' != \$this->SC_APP_data['md5_data'] ['options'] ['limit_chart_items']) {
                \$this->SC_APP_data['limit_chart_items'] = \$this->SC_APP_data['md5_data'] ['options'] ['limit_chart_items'];
            }
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_setChartItemsLimit

/**
 * Cria as informacoes para geracao de um grafico do FusionCharts
 */
function fnChart_info_createFusionChartsData($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData(\$isExport)
    {
        \$this->info_createFusionChartsData_json(\$isExport);
        \$this->info_createFusionChartsData_javascript();
        \$this->info_createFusionChartsData_license();
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData

/**
 * Cria as informacoes da licensa do FusionCharts
 */
function fnChart_info_createFusionChartsData_license($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_license()
    {
        \$this->SC_APP_data['fusioncharts_license'] ['key'] = 'HA-8E3A-64coB5A2D4E1D4E4D3A11B11A5C3A1A1lC-7wA1B9xD-13lrgA2D3vbsC5E3D4A1E1I1B2B8D7A6E1F5C4I2D1A4juwE2B4G1C-7G1A7C8rqg1C4D1I4njyB5D6D3bzfG2C9A4C6A1B4A1C3D1J2B3yqsD1B1ZA33egvD8D5B4oC-8D3QA16A7jteE3A3H2E3A9C10C6C3C4E4A2H3F3C2B-16==';
        \$this->SC_APP_data['fusioncharts_license'] ['creditLabel'] = 'false';
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_license

/**
 * Cria as informacoes do codigo javascript do FusionCharts
 */
function fnChart_info_createFusionChartsData_javascript($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_javascript()
    {
        \$this->SC_APP_data['fusioncharts_javascript'] ['type'] = \$this->aux_getFusionChartsRenderer();
        \$this->SC_APP_data['fusioncharts_javascript'] ['width'] = \$this->SC_APP_data['width'];
        \$this->SC_APP_data['fusioncharts_javascript'] ['height'] = \$this->SC_APP_data['height'];
        \$this->SC_APP_data['fusioncharts_javascript'] ['dataFormat'] = 'jsonurl';
        \$this->SC_APP_data['fusioncharts_javascript'] ['dataSource'] = \$this->SC_APP_info['chart'] ['json_base_url'] . \$this->SC_APP_info['chart'] ['json_filename'];

        if (\$this->aux_isResponsive()) {
            \$this->SC_APP_data['fusioncharts_javascript'] ['width'] = '100%';
            \$this->SC_APP_data['fusioncharts_javascript'] ['height'] = '85%';
        } elseif (\$this->aux_isMobile()) {
            \$this->SC_APP_data['fusioncharts_javascript'] ['width'] = '100%';
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_javascript

/**
 * Cria as informacoes de configuracao json do FusionCharts
 */
function fnChart_info_createFusionChartsData_json($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json(\$isExport)
    {
        \$this->info_createFusionChartsData_json_chart(\$isExport);

        switch (\$this->SC_APP_data['type']) {
            case 'Area':
                \$this->info_createFusionChartsData_json_type_area();
                break;
            case 'Bar':
                \$this->info_createFusionChartsData_json_type_bar();
                break;
            case 'Funnel':
                \$this->info_createFusionChartsData_json_type_funnel();
                break;
            case 'Gauge':
                \$this->info_createFusionChartsData_json_type_gauge();
                break;
            case 'Line':
                \$this->info_createFusionChartsData_json_type_line();
                break;
            case 'Pie':
                \$this->info_createFusionChartsData_json_type_pie();
                break;
            case 'Pyramid':
                \$this->info_createFusionChartsData_json_type_pyramid();
                break;
            case 'Radar':
                \$this->info_createFusionChartsData_json_type_radar();
                break;
        }

        \$this->info_createFusionChartsData_json_data_series();

        \$this->info_createFusionChartsData_json_data_order();
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json

/**
 * Cria as informacoes de configuracao gerais json do FusionCharts
 */
function fnChart_info_createFusionChartsData_json_chart($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_chart(\$isExport)
    {
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] = [
            'caption' => \$this->SC_APP_data['md5_data'] ['metric'] ['label'],
            'subCaption' => \$this->info_createFusionChartsData_json_chart_subtitle(),
            'xAxisName' => \$this->SC_APP_data['md5_data'] ['dimension'] ['label'],
            'yAxisName' => \$this->SC_APP_data['md5_data'] ['metric'] ['label'],
            'chartLeftMargin' => '10',
            'chartTopMargin' => '10',
            'chartRightMargin' => '10',
            'chartBottomMargin' => '10',
        ];

        if (\$this->SC_APP_info['options'] ['formatNumberScale']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['formatNumberScale'] = '1';
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['numberScaleValue'] = '1000,1000,1000,1000';
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['numberScaleUnit']  = 'K,M,G,T';
        } else {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['formatNumberScale'] = '0';
        }

        if (\$this->SC_APP_info['options'] ['setAdaptiveYMin']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['setAdaptiveYMin'] = '1';
        }

        \$this->info_createFusionChartsData_json_chart_theme();

        if ('below' == \$this->SC_APP_info['options'] ['legendPosition']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['legendPosition'] = 'bottom';
        } elseif ('right' == \$this->SC_APP_info['options'] ['legendPosition']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['legendPosition'] = 'right';
        } elseif ('hide' == \$this->SC_APP_info['options'] ['legendPosition']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showLegend'] = '0';
        }

        if (\$isExport) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['animation'] = '0';
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_chart

/**
 * Cria o subtitulo do grafico
 */
function fnChart_info_createFusionChartsData_json_chart_subtitle($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_chart_subtitle()
    {
        \$parameters = [];

        foreach (\$this->SC_APP_data['md5_data'] ['parameters'] as \$parameterInfo) {
            \$parameters[] = "{\$parameterInfo['field_label']} = {\$parameterInfo['label']}";
        }

        return implode(' :: ', \$parameters);
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_chart_subtitle

/**
 * Cria a configuracao visual do grafico
 */
function fnChart_info_createFusionChartsData_json_chart_theme($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_chart_theme()
    {
        \$this->chartTheme = \$this->load_chart_theme();

        foreach (\$this->chartTheme as \$property => \$value) {
            if ('' != \$value) {
                \$this->SC_APP_data['fusioncharts_json'] ['chart'] [\$property] = \$value; 
            }
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_chart_theme

/**
 * Cria as informacoes de configuracao json do FusionCharts para graficos do tipo area
 */
function fnChart_info_createFusionChartsData_json_type_area($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_type_area()
    {
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_type_area

/**
 * Cria as informacoes de configuracao json do FusionCharts para graficos do tipo bar
 */
function fnChart_info_createFusionChartsData_json_type_bar($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_type_bar()
    {
        if ('' != \$this->SC_APP_info['types'] ['bar'] ['plotSpacePercent']) {
            if (20 > \$this->SC_APP_info['types'] ['bar'] ['plotSpacePercent']) {
                \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['plotSpacePercent'] = '20';
            } elseif (80 < \$this->SC_APP_info['types'] ['bar'] ['plotSpacePercent']) {
                \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['plotSpacePercent'] = '80';
            } else {
                \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['plotSpacePercent'] = \$this->SC_APP_info['types'] ['bar'] ['plotSpacePercent'];
            }
        }
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['rotateValues'] = \$this->SC_APP_info['types'] ['bar'] ['rotateValues'];
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['placeValuesInside'] = \$this->SC_APP_info['types'] ['bar'] ['placeValuesInside'];
        if (1 == \$this->SC_APP_info['types'] ['bar'] ['stack100Percent'] && \$this->aux_isMultiSeries()) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['stack100Percent'] = '1';
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showPercentValues'] = '0';
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_type_bar

/**
 * Cria as informacoes de configuracao json do FusionCharts para graficos do tipo funnel
 */
function fnChart_info_createFusionChartsData_json_type_funnel($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_type_funnel()
    {
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['useSameSlantAngle'] = '1';
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['isHollow'] = '0';
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showLegend'] = '1';
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showLabels'] = '0';
        if ('2d' == \$this->SC_APP_info['types'] ['funnel'] ['dimension']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['is2D'] = '1';
        }
        if ('0' == \$this->SC_APP_info['types'] ['funnel'] ['streamlinedData']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['streamlinedData'] = '0';
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_type_funnel

/**
 * Cria as informacoes de configuracao json do FusionCharts para graficos do tipo gauge
 */
function fnChart_info_createFusionChartsData_json_type_gauge($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_type_gauge()
    {
        if ('Circular' == \$this->SC_APP_info['types'] ['gauge'] ['format']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['gaugeStartAngle'] = '180';
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['gaugeEndAngle'] = '-180';
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['lowerLimitDisplay'] = ' ';
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_type_gauge

/**
 * Cria as informacoes de configuracao json do FusionCharts para graficos do tipo line
 */
function fnChart_info_createFusionChartsData_json_type_line($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_type_line()
    {
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showLegend'] = '0';
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_type_line

/**
 * Cria as informacoes de configuracao json do FusionCharts para graficos do tipo pie
 */
function fnChart_info_createFusionChartsData_json_type_pie($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_type_pie()
    {
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showLegend'] = '1';
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['use3DLighting'] = '0';
        if (\$this->SC_APP_info['types'] ['pie'] ['showPercentValues']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showPercentValues'] = '1';
        } else {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showPercentValues'] = '0';
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_type_pie

/**
 * Cria as informacoes de configuracao json do FusionCharts para graficos do tipo pyramid
 */
function fnChart_info_createFusionChartsData_json_type_pyramid($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_type_pyramid()
    {
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showLegend'] = '1';
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showLabels'] = '0';
        if ('2d' == \$this->SC_APP_info['types'] ['pyramid'] ['dimension']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['is2D'] = '1';
        }
        if (\$this->SC_APP_info['types'] ['pyramid'] ['showPercentValues']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showPercentValues'] = '1';
        } else {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showPercentValues'] = '0';
        }
        if (\$this->SC_APP_info['types'] ['pyramid'] ['isSliced']) {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['isSliced'] = '1';
        } else {
            \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['isSliced'] = '0';
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_type_pyramid

/**
 * Cria as informacoes de configuracao json do FusionCharts para graficos do tipo radar
 */
function fnChart_info_createFusionChartsData_json_type_radar($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_type_radar()
    {
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_type_radar

/**
 * Cria as informacoes de configuracao json das series de dados
 */
function fnChart_info_createFusionChartsData_json_data_series($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_data_series()
    {
        if (0 < \$this->SC_APP_data['limit_chart_items']) {
            \$this->aux_filterChartItems();
        }

        if (\$this->SC_APP_data['md5_data'] ['options'] ['is_comparison']) {
            \$this->info_createFusionChartsData_json_data_comparisonSeries();
        } elseif ('Line' == \$this->SC_APP_data['type'] && 'Step' == \$this->SC_APP_info['types'] ['line'] ['format'] && !\$this->aux_isMultiSeries()) {
            \$this->info_createFusionChartsData_json_data_singleSerieCategorySeries();
        } elseif ('Gauge' == \$this->SC_APP_data['type']) {
            \$this->info_createFusionChartsData_json_data_gaugeSeries();
        } elseif ('Radar' == \$this->SC_APP_data['type']) {
            if (self::CHART_MODE_SYNTHETIC == \$this->SC_APP_data['data_mode']) {
                \$this->info_createFusionChartsData_json_data_singleSerieCategorySeries();
            } else {
                \$this->info_createFusionChartsData_json_data_multiSeries();
            }
        } elseif (\$this->aux_isMultiSeries()) {
            \$this->info_createFusionChartsData_json_data_multiSeries();
        } else {
            \$this->info_createFusionChartsData_json_data_singleSeries();
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_data_series

/**
 * Cria as informacoes de configuracao json das series de dados para series simples
 */
function fnChart_info_createFusionChartsData_json_data_singleSeries($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_data_singleSeries()
    {
        \$this->SC_APP_data['fusioncharts_json'] ['data'] = [];

        foreach (\$this->SC_APP_data['md5_data'] ['data_synthetic'] [self::GROUPBY_ORIGINAL] as \$plotInfo) {
            \$addItem = true;

            if (!empty(\$this->SC_APP_data['filtered_chart_items']) && !in_array(\$plotInfo['label'], \$this->SC_APP_data['filtered_chart_items'])) {
                \$addItem = false;
            }

            if (\$addItem) {
                \$thisData = [
                    'label' => \$plotInfo['label'],
                    'value' => \$plotInfo['value'],
                ];

                if (\$this->SC_APP_info['options'] ['tooltip_expanded']) {
                    \$thisData['tooltext'] = "<b>{\$this->SC_APP_data['md5_data'] ['dimension'] ['label']}</b>";
                    \$thisData['tooltext'] .= "<br>";
                    \$thisData['tooltext'] .= "<b>{\$plotInfo['label']}</b>";
                    \$thisData['tooltext'] .= "<br><br>";
                    \$thisData['tooltext'] .= "<b>{\$this->SC_APP_data['md5_data'] ['metric'] ['label']}</b>: {\$plotInfo['value']}";
                }

                \$this->SC_APP_data['fusioncharts_json'] ['data'] [] = \$thisData;
            }
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_data_singleSeries

/**
 * Cria as informacoes de configuracao json das series de dados para series multiplas
 */
function fnChart_info_createFusionChartsData_json_data_multiSeries($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_data_multiSeries()
    {
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showLegend'] = '1';

        \$this->SC_APP_data['fusioncharts_json'] ['categories'] = [];
        \$this->SC_APP_data['fusioncharts_json'] ['dataset'] = [];

        \$category = [];
        foreach (\$this->SC_APP_data['md5_data'] ['data_analytic'] [ \$this->SC_APP_data['series_mode'] ] ['categories'] as \$categoryLabel) {
            \$addItem = true;

            if ('set' == \$this->SC_APP_data['series_mode'] && !empty(\$this->SC_APP_data['filtered_chart_items']) && !in_array(\$categoryLabel, \$this->SC_APP_data['filtered_chart_items'])) {
                \$addItem = false;
            }

            if (\$addItem) {
                \$category[] = [
                    'label' => \$categoryLabel,
                ];
            }
        }
        \$this->SC_APP_data['fusioncharts_json'] ['categories'] [] = [
            'category' => \$category,
        ];

        foreach (\$this->SC_APP_data['md5_data'] ['data_analytic'] [ \$this->SC_APP_data['series_mode'] ] ['dataset'] as \$seriesValue => \$seriesInfo) {
            \$data = [];

            foreach (\$seriesInfo['data'] as \$plotValue => \$plotInfo) {
                \$addItem = true;

                if ('set' == \$this->SC_APP_data['series_mode'] && !empty(\$this->SC_APP_data['filtered_chart_items']) && !in_array(\$plotInfo['label'], \$this->SC_APP_data['filtered_chart_items'])) {
                    \$addItem = false;
                } elseif ('serie' == \$this->SC_APP_data['series_mode'] && !empty(\$this->SC_APP_data['filtered_chart_items']) && !in_array(\$seriesInfo['label'], \$this->SC_APP_data['filtered_chart_items'])) {
                    \$addItem = false;
                }

                if (\$addItem) {
                    \$thisData = [
                        'value' => \$plotInfo['value'],
                    ];

                    if (\$this->SC_APP_info['options'] ['tooltip_expanded']) {
                        \$thisData['tooltext'] = "<b>{\$this->SC_APP_data['md5_data'] ['data_analytic'] [ \$this->SC_APP_data['series_mode'] ] ['field_name'] ['x_axys']}</b>";
                        \$thisData['tooltext'] .= "<br>";
                        \$thisData['tooltext'] .= "<b>{\$plotInfo['label']}</b>";
                        \$thisData['tooltext'] .= "<br><br>";
                        \$thisData['tooltext'] .= "<b>{\$this->SC_APP_data['md5_data'] ['data_analytic'] [ \$this->SC_APP_data['series_mode'] ] ['field_name'] ['legend']}</b>: {\$seriesInfo['label']}";
                        \$thisData['tooltext'] .= "<br>";
                        \$thisData['tooltext'] .= "<b>{\$this->SC_APP_data['md5_data'] ['metric'] ['label']}</b>: {\$plotInfo['value']}";
                    }

                    \$data[] = \$thisData;
                }
            }

            \$addItem = true;

            if ('serie' == \$this->SC_APP_data['series_mode'] && !empty(\$this->SC_APP_data['filtered_chart_items']) && !in_array(\$seriesInfo['label'], \$this->SC_APP_data['filtered_chart_items'])) {
                \$addItem = false;
            }

            if (\$addItem) {
                \$this->SC_APP_data['fusioncharts_json'] ['dataset'] [] = [
                    'seriesName' => \$seriesInfo['label'],
                    'data' => \$data,
                ];
            }
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_data_multiSeries

/**
 * Cria as informacoes de configuracao json das series de dados para series de comparacao
 */
function fnChart_info_createFusionChartsData_json_data_comparisonSeries($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_data_comparisonSeries()
    {
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showLegend'] = '1';

        \$this->SC_APP_data['fusioncharts_json'] ['categories'] = [];
        \$this->SC_APP_data['fusioncharts_json'] ['dataset'] = [];

        \$category = [];
        foreach (\$this->SC_APP_data['md5_data'] ['data_synthetic'] [self::GROUPBY_ORIGINAL] as \$plotInfo) {
            \$addItem = true;

            if (!empty(\$this->SC_APP_data['filtered_chart_items']) && !in_array(\$plotInfo['label'], \$this->SC_APP_data['filtered_chart_items'])) {
                \$addItem = false;
            }

            if (\$addItem) {
                \$category[] = [
                    'label' => \$plotInfo['label'],
                ];
            }
        }
        \$this->SC_APP_data['fusioncharts_json'] ['categories'] [] = [
            'category' => \$category,
        ];

        foreach (\$this->SC_APP_data['md5_data'] ['data_synthetic'] as \$seriesIndex => \$seriesInfo) {
            \$data = [];

            foreach (\$seriesInfo as \$plotInfo) {
                \$addItem = true;
    
                if (!empty(\$this->SC_APP_data['filtered_chart_items']) && !in_array(\$plotInfo['label'], \$this->SC_APP_data['filtered_chart_items'])) {
                    \$addItem = false;
                }
    
                if (\$addItem) {
                    \$thisData = [
                        'value' => \$plotInfo['value'],
                    ];
    
                    if (\$this->SC_APP_info['options'] ['tooltip_expanded']) {
                        \$thisData['tooltext'] = "<b>{\$this->SC_APP_data['md5_data'] ['dimension'] ['label']}</b>";
                        \$thisData['tooltext'] .= "<br>";
                        \$thisData['tooltext'] .= "<b>{\$plotInfo['label']}</b>";
                        \$thisData['tooltext'] .= "<br><br>";
                        \$thisData['tooltext'] .= "<b>{\$this->SC_APP_data['md5_data'] ['options'] ['comparison_field_label']}</b>: {\$this->SC_APP_data['md5_data'] ['options'] ['series_name'] [\$seriesIndex]}";
                        \$thisData['tooltext'] .= "<br>";
                        \$thisData['tooltext'] .= "<b>{\$this->SC_APP_data['md5_data'] ['metric'] ['label']}</b>: {\$plotInfo['value']}";
                    }
    
                    \$data[] = \$thisData;
                }
            }

            \$this->SC_APP_data['fusioncharts_json'] ['dataset'] [] = [
                'seriesName' => \$this->SC_APP_data['md5_data'] ['options'] ['series_name'] [\$seriesIndex],
                'data' => \$data,
            ];
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_data_comparisonSeries

/**
 * Cria as informacoes de configuracao json das series de dados para series de graficos com categorias mas com apenas uma serie
 */
function fnChart_info_createFusionChartsData_json_data_singleSerieCategorySeries($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_data_singleSerieCategorySeries()
    {
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['showLegend'] = '0';

        \$this->SC_APP_data['fusioncharts_json'] ['categories'] = [];
        \$this->SC_APP_data['fusioncharts_json'] ['dataset'] = [];

        \$category = [];
        foreach (\$this->SC_APP_data['md5_data'] ['data_synthetic'] [self::GROUPBY_ORIGINAL] as \$plotInfo) {
            \$addItem = true;

            if (!empty(\$this->SC_APP_data['filtered_chart_items']) && !in_array(\$plotInfo['label'], \$this->SC_APP_data['filtered_chart_items'])) {
                \$addItem = false;
            }

            if (\$addItem) {
                \$category[] = [
                    'label' => \$plotInfo['label'],
                ];
            }
        }
        \$this->SC_APP_data['fusioncharts_json'] ['categories'] [] = [
            'category' => \$category,
        ];

        \$data = [];
        foreach (\$this->SC_APP_data['md5_data'] ['data_synthetic'] [self::GROUPBY_ORIGINAL] as \$plotInfo) {
            \$addItem = true;

            if (!empty(\$this->SC_APP_data['filtered_chart_items']) && !in_array(\$plotInfo['label'], \$this->SC_APP_data['filtered_chart_items'])) {
                \$addItem = false;
            }

            if (\$addItem) {
                \$data[] = [
                    'value' => \$plotInfo['value'],
                ];
            }
        }
        \$this->SC_APP_data['fusioncharts_json'] ['dataset'] [] = [
            'seriesName' => '0',
            'data' => \$data,
        ];
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_data_singleSerieCategorySeries

/**
 * Cria as informacoes de configuracao json das series de dados para series de graficos gauge
 */
function fnChart_info_createFusionChartsData_json_data_gaugeSeries($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_data_gaugeSeries()
    {
        \$this->SC_APP_data['fusioncharts_json'] ['dials'] = [];

        \$gaugeMin = 0;
        \$gaugeMax = 0;

        \$dial = [];
        foreach (\$this->SC_APP_data['md5_data'] ['data_synthetic'] [self::GROUPBY_ORIGINAL] as \$plotInfo) {
            \$addItem = true;

            if (!empty(\$this->SC_APP_data['filtered_chart_items']) && !in_array(\$plotInfo['label'], \$this->SC_APP_data['filtered_chart_items'])) {
                \$addItem = false;
            }

            if (\$addItem) {
                \$gaugeMin = min(\$gaugeMin, \$plotInfo['value']);
                \$gaugeMax = max(\$gaugeMax, \$plotInfo['value']);
               
                \$dial[] = [
                    'value' => \$plotInfo['value'],
                    'tooltext' => "{\$plotInfo['label']}: {\$plotInfo['value']}",
                ];
            }
        }
        \$this->SC_APP_data['fusioncharts_json'] ['dials'] = [
            'dial' => \$dial,
        ];

        if (10 > \$gaugeMax) {
            \$gaugeMax = 10;
        }
        \$gaugeMax = ceil(\$gaugeMax * 1.1);

        if (isset(\$this->chart_theme['css_chart_background_pallete_color']) && '' != \$this->chart_theme['css_chart_background_pallete_color']) {
            \$chartPallete = explode(',', \$this->chart_theme['css_chart_background_pallete_color']);

            \$this->SC_APP_data['fusioncharts_json'] ['colorRange'] = [
                'color' => [[
                    'minValue' => '0',
                    'maxValue' => \$gaugeMax,
                    'code' => str_replace('#', '', \$chartPallete[0])
                ]]
            ];
        } else {
            \$this->SC_APP_data['fusioncharts_json'] ['colorRange'] = [
                'color' => [[
                    'minValue' => '0',
                    'maxValue' => \$gaugeMax,
                    'code' => '9bc8f2'
                ]]
            ];
        }

        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['lowerLimit'] = \$gaugeMin;
        \$this->SC_APP_data['fusioncharts_json'] ['chart'] ['upperLimit'] = \$gaugeMax;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_data_gaugeSeries

/**
 * Ordena as series do grafico
 */
function fnChart_info_createFusionChartsData_json_data_order($file)
{
    $phpCode = <<<EOT
    function info_createFusionChartsData_json_data_order()
    {
        if ('Pie' == \$this->SC_APP_data['type'] && 'off' != \$this->SC_APP_info['types'] ['pie'] ['order']) {
            \$this->aux_orderSerie(\$this->SC_APP_data['fusioncharts_json'] ['data'], \$this->SC_APP_info['types'] ['pie'] ['order']);
            \$this->aux_rearrangeOrderIndexes(\$this->SC_APP_data['fusioncharts_json'] ['data']);
        } elseif ('Line' == \$this->SC_APP_data['type'] && 'Step' == \$this->SC_APP_info['types'] ['line'] ['format'] && !\$this->aux_isMultiSeries()) {
            \$this->aux_orderSerie(\$this->SC_APP_data['fusioncharts_json'] ['dataset'] [0] ['data'], \$this->SC_APP_data['order']);
            \$this->aux_rearrangeOrderMultiIndexes(\$this->SC_APP_data['fusioncharts_json'] ['dataset'] [0] ['data'], \$this->SC_APP_data['fusioncharts_json'] ['categories'] [0] ['category']);
        } elseif ('Radar' == \$this->SC_APP_data['type'] && self::CHART_MODE_SYNTHETIC == \$this->SC_APP_data['data_mode']) {
            \$this->aux_orderSerie(\$this->SC_APP_data['fusioncharts_json'] ['dataset'] [0] ['data'], \$this->SC_APP_data['order']);
            \$this->aux_rearrangeOrderMultiIndexes(\$this->SC_APP_data['fusioncharts_json'] ['dataset'] [0] ['data'], \$this->SC_APP_data['fusioncharts_json'] ['categories'] [0] ['category']);
        } elseif (!\$this->aux_isMultiSeries() && !\$this->SC_APP_data['md5_data'] ['options'] ['is_comparison'] && '' != \$this->SC_APP_data['order'] && !in_array(\$this->SC_APP_data['type'], ['Gauge', 'Radar'])) {
            \$this->aux_orderSerie(\$this->SC_APP_data['fusioncharts_json'] ['data'], \$this->SC_APP_data['order']);
            \$this->aux_rearrangeOrderIndexes(\$this->SC_APP_data['fusioncharts_json'] ['data']);
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_createFusionChartsData_json_data_order

/**
 * Salva a configuracao json do grafico FusionCharts
 */
function fnChart_info_saveFusionChartsJson($file)
{
    $phpCode = <<<EOT
    function info_saveFusionChartsJson()
    {
        @file_put_contents(
            \$this->SC_APP_info['chart'] ['json_base_dir'] . \$this->SC_APP_info['chart'] ['json_filename'],
            json_encode(\$this->SC_APP_data['fusioncharts_json'])
        );
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_info_saveFusionChartsJson

/**
 * Exibe a inicializacao da estrutura onde sera exibido o grafico junto ao resumo
 */
function fnChart_display_summaryChart_inline_startUp($file)
{
    $phpCode = <<<EOT
    function display_summaryChart_inline_startUp()
    {
        \$htmlCode = \$this->display_chart_htmlFusionChartsLibrary();
        \$htmlCode .= \$this->display_chart_htmlFusionChartsDiv_inline();
        \$htmlCode .= \$this->display_chart_htmlFusionChartsJavascript_function();
        \$htmlCode .= <<<SCEOT
    <span id="sc-summary-fusioncharts-placeholder">
    </span>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_summaryChart_inline_startUp

/**
 * Exibe a inicializacao do grafico via ajax
 */
function fnChart_display_summaryChart_inline_initialAjaxCall($file)
{
    global $summaryInfo;

    $phpCode = <<<EOT
    function display_summaryChart_inline_initialAjaxCall(\$chartMd5)
    {
        \$this->info_initializeData();
        \$this->info_initializeChart(\$chartMd5);

        \$scPage = NM_encode_input(\$this->Ini->sc_page);
        \$ajaxUrl = "{\$this->Ini->path_link}{$summaryInfo['general'] ['app_dir']}/{$summaryInfo['general'] ['app_link_base_file']}";

        \$htmlCode = <<<SCEOT
    <script type="text/javascript">
        \$.ajax({
            type: "POST",
            url: "{\$ajaxUrl}",
            dataType: "json",
            data: {
                nmgp_opcao: "grafico",
                script_case_init: "{\$scPage}",
                chart_inline_create: "Y",
                chart_md5: "{\$chartMd5}",
            }
        }).done(function(data) {
            \$("#sc-summary-fusioncharts-placeholder").html(data.chartHtml);
            if ('' != data.chartType && '' != data.chartUrl) {
                scFusionCharts_create(data.chartType, data.chartUrl, data.chartWidth, data.chartHeight);
            }
        });
    </script>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_summaryChart_inline_initialAjaxCall

/**
 * Exibe a resposta para inicializacao do grafico via ajax
 */
function fnChart_display_summaryChart_inline_initialAjaxResponse($file)
{
    global $summaryInfo;

    $phpCode = <<<EOT
    function display_summaryChart_inline_initialAjaxResponse(\$chartMd5)
    {
        \$this->info_initializeData();
        \$this->info_initializeChart(\$chartMd5);

        \$ajaxResponse = [
            'status' => 'ok',
            'chartHtml' => '',
            'chartType' => '',
            'chartUrl' => '',
            'chartWidth' => \$this->SC_APP_data['width'],
            'chartHeight' => \$this->SC_APP_data['height'],
        ];

        if ('' != \$chartMd5 && isset(\$_SESSION['sc_session'][\$this->Ini->sc_page]['{$summaryInfo['general'] ['app_name_session_var']}']['chart_info'][\$chartMd5])) {
            \$ajaxResponse['chartHtml'] .= \$this->display_chart_htmlFusionChartsJavascript_setInlineChartMd5(\$chartMd5);
            \$ajaxResponse['chartType'] = \$this->SC_APP_data['fusioncharts_javascript'] ['type'];
            \$ajaxResponse['chartUrl'] = \$this->SC_APP_data['fusioncharts_javascript'] ['dataSource'];
        }

        echo json_encode(\$ajaxResponse);
        exit;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_summaryChart_inline_initialAjaxResponse

/**
 * Exibe a resposta para atualizacao do grafico via ajax
 */
function fnChart_display_summaryChart_inline_updateAjaxResponse($file)
{
    $phpCode = <<<EOT
    function display_summaryChart_inline_updateAjaxResponse(\$chartMd5)
    {
        \$this->info_initializeData();
        \$this->info_initializeChart(\$chartMd5);

        \$ajaxResponse = [
            'status' => 'ok',
            'chartType' => \$this->SC_APP_data['fusioncharts_javascript'] ['type'],
            'chartUrl' => \$this->SC_APP_data['fusioncharts_javascript'] ['dataSource'],
            'chartWidth' => \$this->SC_APP_data['width'],
            'chartHeight' => \$this->SC_APP_data['height'],
        ];


        echo json_encode(\$ajaxResponse);
        exit;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_summaryChart_inline_updateAjaxResponse

/**
 * Exibe o grafico do resumo em uma nova pagina
 */
function fnChart_display_summaryChart_newPage($file)
{
    $phpCode = <<<EOT
    function display_summaryChart_newPage(\$chartMd5)
    {
        global \$nm_saida;

        \$this->info_initializeData();
        \$this->info_initializeChart(\$chartMd5);

        \$htmlCode = \$this->display_chart_htmlHeader();
        \$htmlCode .= \$this->display_chart_summaryBody();
        \$htmlCode .= \$this->display_chart_htmlFooter();

        \$nm_saida->saida(\$htmlCode);
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_summaryChart_newPage

/**
 * Exibe o grafico do resumo para uso pelo Phantom
 */
function fnChart_display_summaryChart_phantom($file)
{
    $phpCode = <<<EOT
    function display_summaryChart_phantom()
    {
        \$htmlCode = \$this->display_chart_htmlFusionChartsDiv_newPage();
        \$htmlCode .= \$this->display_chart_htmlFusionChartsJavascript_phantom();

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_summaryChart_phantom

/**
 * Recupera as informacoes adicionais para criacao do MD5 para nomeacao da imagem do grafico
 */
function fnChart_display_summaryChart_phantom_md5($file)
{
    $phpCode = <<<EOT
    function display_summaryChart_phantom_md5()
    {
        return '__' . implode('X', [
            (\$this->SC_APP_data['md5_data'] ['options'] ['is_comparison'] ? 'comparison' : 'standard'),
            \$this->SC_APP_data['fusioncharts_javascript'] ['type'],
            \$this->SC_APP_data['fusioncharts_javascript'] ['width'],
            \$this->SC_APP_data['fusioncharts_javascript'] ['height'],
        ]);
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_summaryChart_phantom_md5

/**
 * Exibe o corpo html do grafico do resumo
 */
function fnChart_display_chart_summaryBody($file)
{
    $phpCode = <<<EOT
    function display_chart_summaryBody()
    {
        \$htmlCode = <<<SCEOT
<body class="{\$this->SC_APP_info['css'] ['chart_page']}">

SCEOT;
        \$htmlCode .= \$this->display_chart_htmlFusionChartsConfigDiv();
        \$htmlCode .= \$this->display_chart_htmlFusionChartsDiv_newPage();
        \$htmlCode .= \$this->display_chart_htmlFusionChartsJavascript_function();
        \$htmlCode .= \$this->display_chart_htmlFusionChartsJavascript_onReady();
        \$htmlCode .= <<<SCEOT
</body>


SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_summaryBody

/**
 * Exibe o cabecalho html
 */
function fnChart_display_chart_htmlHeader($file)
{
    $phpCode = <<<EOT
    function display_chart_htmlHeader()
    {
        \$htmlCode = <<<SCEOT
<html>

<head>
    {\$this->SC_APP_info['options'] ['charset']}

SCEOT;
        if ('' != \$this->SC_APP_info['options'] ['favicon']) {
            \$htmlCode .= <<<SCEOT
    <link rel="shortcut icon" href="../_lib/img/{\$this->SC_APP_info['options'] ['favicon']}" />

SCEOT;
        }
        if (\$this->aux_isMobile()) {
            \$htmlCode .= <<<SCEOT
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />

SCEOT;
        }
        \$htmlCode .= \$this->display_chart_htmlHeader_css();
        \$htmlCode .= \$this->display_chart_htmlHeader_javascript();
        \$htmlCode .= <<<SCEOT
    <title>{\$this->SC_APP_info['chart'] ['page_title']}</title>
</head>


SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlHeader

/**
 * Exibe a inclusao de estilos css do cabecalho html
 */
function fnChart_display_chart_htmlHeader_css($file)
{
    $phpCode = <<<EOT
    function display_chart_htmlHeader_css()
    {
        \$htmlCode = <<<SCEOT
    <style>
        #sc-id-chart-blockui {
            display: none;
            position: fixed;
            top: 0px;
            left: 0px;
            width: 100%;
            height: 100%;
            background-color: rgb(255, 255, 255);
            z-index: 99900;
            opacity: 0.7;
        }
        #sc-id-div-config {
            position: absolute;
            top: 50%;
            left: 50%;
            padding: 1.5rem;
            z-index: 99990;
            width: 700px;
            border: 1px solid #c2c2c2;
            display: none;
            flex-flow: column nowrap;
            row-gap: 2rem;
            justify-content: center;
            align-items: flex-start;
            box-sizing: border-box;
            transform: translate(-50%, -50%);
            box-shadow: 0 8px 16px rgba(0,0,0,.25);
        }
        #sc-id-div-config-input {
            width: 100%;
            display: flex;
            flex-flow: row wrap;
            row-gap: .875rem;
            column-gap: .875rem;
            justify-content: space-between;
            align-items: center;
        }
        #sc-id-div-config-button {
            width: 100%;
            display: flex;
            flex-flow: row nowrap;
            justify-content: end;
            column-gap: .75rem;
        }
        .input-group {
            flex-flow: column nowrap;
            justify-content: flex-start;
            align-items: flex-start;
            row-gap: .5rem;
            display: flex;
        }
        .input-group > label {
            font-weight: 700;
        }
    </style>

SCEOT;

        if (\$this->SC_APP_info['options'] ['use_fontawesome']) {
            \$htmlCode .= <<<SCEOT
    <link rel="stylesheet" href="{\$this->Ini->path_prod}/third/font-awesome/6/css/all.min.css" type="text/css" media="screen,print" />

SCEOT;
        }

        if ('' != \$this->SC_APP_info['options'] ['summary_css']) {
            \$summaryCss = NM_encode_input(\$this->SC_APP_info['options'] ['summary_css']);

            \$htmlCode .= <<<SCEOT
    <link rel="stylesheet" href="{\$summaryCss}" type="text/css" media="screen,print" />

SCEOT;
        }

        \$htmlCode .= <<<SCEOT
    <link rel="stylesheet" href="../_lib/buttons/{\$this->Ini->Str_btn_css}" type="text/css" media="screen,print" />

SCEOT;

        if (isset(\$this->Ini->str_google_fonts) && !empty(\$this->Ini->str_google_fonts)) {
            \$htmlCode .= <<<SCEOT
    <link rel="stylesheet" href="{\$this->Ini->str_google_fonts}" type="text/css" media="screen,print" />

SCEOT;
        }

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlHeader_css

/**
 * Exibe a inclusao de codigo javascript do cabecalho html
 */
function fnChart_display_chart_htmlHeader_javascript($file)
{
    global $summaryInfo;

    $phpCode = <<<EOT
    function display_chart_htmlHeader_javascript()
    {
        \$scPage = NM_encode_input(\$this->Ini->sc_page);
        \$ajaxUrl = "{\$this->Ini->path_link}{$summaryInfo['general'] ['app_dir']}/{$summaryInfo['general'] ['app_name_file']}_config_graf_flash.php?nome_apl={$summaryInfo['general'] ['app_name_var']}&campo_apl=nm_resumo_graf&sc_page=" . NM_encode_input(\$this->Ini->sc_page) . "&language={$summaryInfo['general'] ['app_language']}";

        \$htmlCode = <<<SCEOT
    <script type="text/javascript" src="{\$this->Ini->path_prod}/third/jquery/js/jquery.js"></script>
    <script type="text/javascript">
        function showChartConfig()
        {
            $("#sc-id-div-config").css("display", "flex").show();
            $("#sc-id-chart-blockui").show();
        }
        function hideChartConfig()
        {
            $("#sc-id-div-config").hide();
            $("#sc-id-chart-blockui").hide();
        }
        $(function() {
            $("#sc-id-button-submit").on("click", function() {
                $.ajax({
                    type: "POST",
                    url: "{\$ajaxUrl}",
                    data: {
                        bok_graf: "OK",
                        ajax: "OK",
                        nome_apl: "{$summaryInfo['general'] ['app_name_var']}",
                        campo_apl: "nm_resumo_graf",
                        sc_page: "{\$scPage}",
                        tipo: $("#sc-id-chart-type").val(),
                        opc_atual: $("#sc-id-chart-mode").val(),
                        largura: $("#sc-id-chart-width").val(),
                        altura: $("#sc-id-chart-height").val(),
                        order: $("#sc-id-chart-order").val()
                    }
                }).done(function(data, textStatus, jqXHR) {
                    document.refresh_chart.submit();
                });
            });
            $("#sc-id-button-cancel").on("click", function() {
                hideChartConfig();
            });
        });
    </script>

SCEOT;
        \$htmlCode .= \$this->display_chart_htmlFusionChartsLibrary();

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlHeader_javascript

/**
 * Exibe o rodape html
 */
function fnChart_display_chart_htmlFooter($file)
{
    $phpCode = <<<EOT
    function display_chart_htmlFooter()
    {
        \$htmlCode = <<<SCEOT
</html>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlFooter

/**
 * Exibe o codigo html para inclusao dos arquivos da bilbioteca FusionCharts
 */
function fnChart_display_chart_htmlFusionChartsLibrary($file)
{
    $phpCode = <<<EOT
    function display_chart_htmlFusionChartsLibrary(\$useServer = '')
    {
        \$jsServer = '';
        if ('pdf' == \$useServer) {
            \$jsServer = \$this->Ini->server_pdf;
        }

        \$htmlCode = <<<SCEOT
    <script type="text/javascript" src="{\$jsServer}{\$this->Ini->path_prod}/third/fusioncharts/js/fusioncharts.js"></script>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlFusionChartsLibrary

/**
 * Exibe o codigo html para criacao da div de configuracao do grafico
 */
function fnChart_display_chart_htmlFusionChartsConfigDiv($file)
{
    global $summaryInfo, $tbapl_toolbars_res;

    $configButtonParameters = [
        'id' => 'Rgraf',
        'click' => 'showChartConfig()',
        'align' => 'absmiddle',
        'value' => isset($tbapl_toolbars_res['labels'] ['sys_format_gra']) ? $tbapl_toolbars_res['labels'] ['sys_format_gra'] : '',
        'hint' => isset($tbapl_toolbars_res['hints'] ['sys_format_gra']) ? $tbapl_toolbars_res['hints'] ['sys_format_gra'] : '',
        'border' => "0",
    ];
    $configButtonCode = trim(new_gera_cod_botoes('bconf_graf', $configButtonParameters));
    if (';' == substr($configButtonCode, -1)) {
        $configButtonCode = substr($configButtonCode, 0, -1);
    }

    $okButtonParameters = [
        'id' => 'sc-id-button-submit',
        'click' => '',
        'align' => 'absmiddle',
        'border' => '0',
    ];
    $okButtonCode = trim(new_gera_cod_botoes('bok', $okButtonParameters));
    if (';' == substr($okButtonCode, -1)) {
        $okButtonCode = substr($okButtonCode, 0, -1);
    }

    $cancelButtonParameters = [
        'id' => 'sc-id-button-cancel',
        'click' => '',
        'align' => 'absmiddle',
        'border' => '0',
    ];
    $cancelButtonCode = trim(new_gera_cod_botoes('bcancelar', $cancelButtonParameters));
    if (';' == substr($cancelButtonCode, -1)) {
        $cancelButtonCode = substr($cancelButtonCode, 0, -1);
    }

    $phpCode = <<<EOT
    function display_chart_htmlFusionChartsConfigDiv()
    {
        \$translate = [];
        \$language = '{$summaryInfo['general'] ['app_language']}';
        if (isset(\$_SESSION['scriptcase'] ['sc_idioma_graf_flash'])) {
            \$translate = \$_SESSION['scriptcase'] ['sc_idioma_graf_flash'];
        }
        if (!isset(\$translate[\$language])) {
            foreach (\$translate as \$language => \$rest) {
                break;
            }
        }

        \$modeSyntheticSelected = self::CHART_MODE_SYNTHETIC == \$this->SC_APP_data['data_mode'] ? ' selected="selected"' : '';
        \$modeAnalyticSelected = self::CHART_MODE_ANALYTIC == \$this->SC_APP_data['data_mode'] ? ' selected="selected"' : '';
        \$modeSyntheticValue = self::CHART_MODE_SYNTHETIC;
        \$modeAnalyticValue = self::CHART_MODE_ANALYTIC;

        \$orderNoneSelected = '' == \$this->SC_APP_data['order'] ? ' selected="selected"' : '';
        \$orderAscSelected = 'asc' == \$this->SC_APP_data['order'] ? ' selected="selected"' : '';
        \$orderDescSelected = 'desc' == \$this->SC_APP_data['order'] ? ' selected="selected"' : '';

        \$configButtonCode = trim({$configButtonCode});
        \$okButtonCode = trim({$okButtonCode});
        \$cancelButtonCode = trim({$cancelButtonCode});
 
        \$htmlCode = <<<SCEOT
    {\$configButtonCode}
    <div id="sc-id-chart-blockui"></div>
    <div id="sc-id-div-config" class="scGridToolbar">
        <div id="sc-id-div-config-input" class="group">
            <div class="input-group">
                <label>{\$translate[\$language] ['tipo_g']}</label>
                <select id="sc-id-chart-type" class="css_toolbar_obj">

SCEOT;
        foreach (\$this->SC_APP_info['chart'] ['available_types'] as \$chartType) {
            \$typeSelected = \$chartType == \$this->SC_APP_data['type'] ? ' selected="selected"' : '';
             switch (\$chartType) {
                case 'Area':
                   \$chartTitle = 'tp_area';
                   break;
                case 'Bar':
                   \$chartTitle = 'tp_barra';
                   break;
                case 'Funnel':
                   \$chartTitle = 'tp_funil';
                   break;
                case 'Gauge':
                   \$chartTitle = 'tp_gauge';
                   break;
                case 'Line':
                   \$chartTitle = 'tp_linha';
                   break;
                case 'Mark':
                   \$chartTitle = 'tp_marcador';
                   break;
                case 'Pie':
                   \$chartTitle = 'tp_pizza';
                   break;
                case 'Pyramid':
                   \$chartTitle = 'tp_pyramid';
                   break;
                case 'Polar':
                   \$chartTitle = 'tp_polar';
                   break;
                case 'Radar':
                   \$chartTitle = 'tp_radar';
                   break;
             }

            \$htmlCode .= <<<SCEOT
                    <option value="{\$chartType}"{\$typeSelected}>{\$translate[\$language] [\$chartTitle]}</option>
            
SCEOT;
        }
        \$htmlCode .= <<<SCEOT
                </select>
            </div>
            <div class="input-group">
                <label>{\$translate[\$language] ['modo_gera']}</label>
                <select id="sc-id-chart-mode" class="css_toolbar_obj">
                    <option value="{\$modeSyntheticValue}"{\$modeSyntheticSelected}>{\$translate[\$language] ['sintetico']}</option>
                    <option value="{\$modeAnalyticValue}"{\$modeAnalyticSelected}>{\$translate[\$language] ['analitico']}</option>
                </select>
            </div>
            <div class="input-group">
                <label>{\$translate[\$language] ['largura']}</label>
                <input id="sc-id-chart-width" type="text" size="5" value="{\$this->SC_APP_data['width']}" class="css_toolbar_obj" style="text-align: right" />
            </div>
            <div class="input-group">
                <label>{\$translate[\$language] ['altura']}</label>
                <input id="sc-id-chart-height" type="text" size="5" value="{\$this->SC_APP_data['height']}" class="css_toolbar_obj" style="text-align: right" />
            </div>
            <div class="input-group">
                <label>{\$translate[\$language] ['order']}</label>
                <select id="sc-id-chart-order" class="css_toolbar_obj">
                    <option value=""{\$orderNoneSelected}>{\$translate[\$language] ['order_none']}</option>
                    <option value="asc"{\$orderAscSelected}>{\$translate[\$language] ['order_asc']}</option>
                    <option value="desc"{\$orderDescSelected}>{\$translate[\$language] ['order_desc']}</option>
                </select>
            </div>
        </div>
        <div id="sc-id-div-config-button" class="input-group">
            {\$okButtonCode}
            {\$cancelButtonCode}
        </div>
    </div>
    <form name="refresh_chart" action="./" method="POST">

SCEOT;
        foreach (\$_POST as \$postItem => \$postValue) {
            \$htmlCode .= <<<SCEOT
        <input type="hidden" name="{\$postItem}" value="{\$postValue}" />

SCEOT;
        }
        \$htmlCode .= <<<SCEOT
    </form>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlFusionChartsConfigDiv

/**
 * Exibe o codigo html para criacao da div onde sera renderizado o grafico FusionCharts em graficos inline
 */
function fnChart_display_chart_htmlFusionChartsDiv_inline($file)
{
    $phpCode = <<<EOT
    function display_chart_htmlFusionChartsDiv_inline()
    {
        \$htmlCode = <<<SCEOT
    <div id="{\$this->SC_APP_data['chart_div']}" style="display: inline-block; position: sticky; left: 0"></div>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlFusionChartsDiv_inline

/**
 * Exibe o codigo html para criacao da div onde sera renderizado o grafico FusionCharts em graficos em nova pagina
 */
function fnChart_display_chart_htmlFusionChartsDiv_newPage($file)
{
    $phpCode = <<<EOT
    function display_chart_htmlFusionChartsDiv_newPage()
    {
        \$htmlCode = <<<SCEOT
    <div id="{\$this->SC_APP_data['chart_div']}" style="width: 100%"></div>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlFusionChartsDiv_newPage

/**
 * Exibe o codigo html com funcao para instanciacao e renderizacao do grafico FusionCharts
 */
function fnChart_display_chart_htmlFusionChartsJavascript_function($file)
{
    $phpCode = <<<EOT
    function display_chart_htmlFusionChartsJavascript_function()
    {
        \$jsServer = '';
        if ('pdf' == \$useServer) {
            \$jsServer = \$this->Ini->server_pdf;
        }

        \$htmlCode = <<<SCEOT
    <script type="text/javascript">
        let scFusionCharts;
        let scFusionChartsType = "{\$this->SC_APP_data['fusioncharts_javascript'] ['type']}";
        let scFusionChartsDataSource = "{\$jsServer}{\$this->SC_APP_data['fusioncharts_javascript'] ['dataSource']}";
        let scFusionChartsWidth = "{\$this->SC_APP_data['width']}";
        let scFusionChartsHeight = "{\$this->SC_APP_data['height']}";
        function scFusionCharts_create(chartType, chartDataSource, chartWidth, chartHeight) {
            FusionCharts.options.license({
                key: "{\$this->SC_APP_data['license_key']}",
                creditLabel: {\$this->SC_APP_data['license_creditLabel']},
            });
            FusionCharts.ready(function() {
                scFusionCharts = new FusionCharts({
                    "renderAt": "{\$this->SC_APP_data['chart_div']}",
                    "id": "{\$this->SC_APP_data['chart_id']}",
                    "type": chartType,
                    "width": chartWidth,
                    "height": chartHeight,
                    "dataFormat": "{\$this->SC_APP_data['chart_dataFormat']}",
                    "dataSource": chartDataSource,
                }).render();
                scFusionCharts.configureLink({
                    overlayButton: {
                        message: "{\$this->Ini->Nm_lang['lang_btns_chart_back']}"
                    }
                });
            });
        }
    </script>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlFusionChartsJavascript_function

/**
 * Exibe o codigo html com funcao para instanciacao e renderizacao do grafico FusionCharts
 */
function fnChart_display_chart_htmlFusionChartsJavascript_phantom($file)
{
    $phpCode = <<<EOT
    function display_chart_htmlFusionChartsJavascript_phantom()
    {
        \$htmlCode = <<<SCEOT
    <script type="text/javascript">
        FusionCharts.options.license({
            key: "{\$this->SC_APP_data['license_key']}",
            creditLabel: {\$this->SC_APP_data['license_creditLabel']},
        });
        FusionCharts.ready(function() {
            var scFusionCharts = new FusionCharts({
                "creditLabel": {\$this->SC_APP_data['license_creditLabel']},
                "renderAt": "{\$this->SC_APP_data['chart_div']}",
                "id": "{\$this->SC_APP_data['chart_id']}",
                "type": "{\$this->SC_APP_data['fusioncharts_javascript'] ['type']}",
                "width": "{\$this->SC_APP_data['width']}",
                "height": "{\$this->SC_APP_data['height']}",
                "dataFormat": "{\$this->SC_APP_data['chart_dataFormat']}",
                "dataSource": "{\$this->Ini->server_pdf}{\$this->SC_APP_data['fusioncharts_javascript'] ['dataSource']}",
            }).render();
        });
    </script>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlFusionChartsJavascript_phantom

/**
 * Exibe o codigo html com chamada da funcao para instanciacao e renderizacao do grafico FusionCharts no evento onReady
 */
function fnChart_display_chart_htmlFusionChartsJavascript_onReady($file)
{
    $phpCode = <<<EOT
    function display_chart_htmlFusionChartsJavascript_onReady()
    {
        \$htmlCode = <<<SCEOT
    <script type="text/javascript">
        \$(function() {
            scFusionCharts_create(scFusionChartsType, scFusionChartsDataSource, scFusionChartsWidth, scFusionChartsHeight);
        });
    </script>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlFusionChartsJavascript_onReady

/**
 * Exibe o codigo html com chamada da funcao para atribuicao da chave MD5 inicial do grafico junto ao resumo
 */
function fnChart_display_chart_htmlFusionChartsJavascript_setInlineChartMd5($file)
{
    $phpCode = <<<EOT
    function display_chart_htmlFusionChartsJavascript_setInlineChartMd5(\$chartMd5)
    {
        \$htmlCode = <<<SCEOT
    <script type="text/javascript">
        \$(function() {
            scChartInlineMd5 = "{\$chartMd5}";
        });
    </script>

SCEOT;

        return \$htmlCode;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_display_chart_htmlFusionChartsJavascript_setInlineChartMd5

/**
 * Filtra items do grafico para satisfazer limite de items de exibicao
 */
function fnChart_aux_filterChartItems($file)
{
    $phpCode = <<<EOT
    function aux_filterChartItems()
    {
        \$itemCount = 0;
        \$itemValues = [];

        foreach (\$this->SC_APP_data['md5_data'] ['data_synthetic'] [self::GROUPBY_ORIGINAL] as \$dimensionValue => \$dimensionInfo) {
            \$itemValues[ \$dimensionInfo['label'] ] = \$dimensionInfo['value'];
        }

        arsort(\$itemValues);

        foreach (\$itemValues as \$dimensionLabel => \$dimensionValue) {
            \$this->SC_APP_data['filtered_chart_items'] [] = \$dimensionLabel;

            \$itemCount++;
            if (\$itemCount == \$this->SC_APP_data['limit_chart_items']) {
                break;
            }
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_filterChartItems

/**
 * Recupera o tipo de grafico para renderizacao
 */
function fnChart_aux_getFusionChartsRenderer($file)
{
    $phpCode = <<<EOT
    function aux_getFusionChartsRenderer()
    {
        if (\$this->SC_APP_data['md5_data'] ['options'] ['is_comparison']) {
            return \$this->aux_getFusionChartsComparisonRenderer();
        }

        \$multiSeriesSuffix = \$this->aux_isMultiSeries() ? 'ms' : '';

        switch (\$this->SC_APP_data['type']) {
            case 'Area':
                if ('Spline' == \$this->SC_APP_info['types'] ['area'] ['format']) {
                    return \$multiSeriesSuffix . 'splinearea';
                } elseif (\$this->aux_isMultiSeries()) {
                    return 'msarea';
                } else {
                    return 'area2d';
                }
                break;

            case 'Bar';
                if (\$this->aux_isMultiSeries() && \$this->SC_APP_info['types'] ['bar'] ['stacking']) {
                    \$multiSeriesSuffix = 'stacked';
                }
                if ('Horizontal' == \$this->SC_APP_info['types'] ['bar'] ['orientation']) {
                    if ('2d' == \$this->SC_APP_info['types'] ['bar'] ['dimension']) {
                        return \$multiSeriesSuffix . 'bar2d';
                    } else {
                        return \$multiSeriesSuffix . 'bar3d';
                    }
                } else {
                    if ('2d' == \$this->SC_APP_info['types'] ['bar'] ['dimension']) {
                        return \$multiSeriesSuffix . 'column2d';
                    } else {
                        return \$multiSeriesSuffix . 'column3d';
                    }
                }
                break;

            case 'Funnel';
                return 'funnel';
                break;

            case 'Gauge';
                return 'angulargauge';
                break;

            case 'Line':
                if ('Spline' == \$this->SC_APP_info['types'] ['line'] ['format']) {
                    return 'spline';
                } elseif ('Step' == \$this->SC_APP_info['types'] ['line'] ['format']) {
                    return 'msstepline';
                } else {
                    return \$multiSeriesSuffix . 'line';
                }
                break;

            case 'Pie':
                if ('Donut' == \$this->SC_APP_info['types'] ['pie'] ['format']) {
                    if ('2d' == \$this->SC_APP_info['types'] ['pie'] ['dimension']) {
                        return 'doughnut2d';
                    } else {
                        return 'doughnut3d';
                    }
                } else {
                    if ('2d' == \$this->SC_APP_info['types'] ['pie'] ['dimension']) {
                        return 'pie2d';
                    } else {
                        return 'pie3d';
                    }
                }
                break;

            case 'Pyramid';
                return 'pyramid';
                break;

            case 'Radar';
                return 'radar';
                break;
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_getFusionChartsRenderer

/**
 * Recupera o tipo de grafico para renderizacao em resumos de comparacao
 */
function fnChart_aux_getFusionChartsComparisonRenderer($file)
{
    $phpCode = <<<EOT
    function aux_getFusionChartsComparisonRenderer()
    {
        \$chartType = \$this->SC_APP_data['type'];
        if (!in_array(\$chartType, ['Area', 'Bar', 'Line', 'Radar'])) {
            \$chartType = \$this->SC_APP_info['chart'] ['available_comparison_types'] [0];
        }
 
        switch (\$chartType) {
            case 'Area':
                if ('Spline' == \$this->SC_APP_info['types'] ['area'] ['format']) {
                    return 'mssplinearea';
                } else {
                    return 'msarea';
                }
                break;

            case 'Bar';
                if ('Horizontal' == \$this->SC_APP_info['types'] ['bar'] ['orientation']) {
                    if ('2d' == \$this->SC_APP_info['types'] ['bar'] ['dimension']) {
                        return 'msbar2d';
                    } else {
                        return 'msbar3d';
                    }
                } else {
                    if ('2d' == \$this->SC_APP_info['types'] ['bar'] ['dimension']) {
                        return 'mscolumn2d';
                    } else {
                        return 'mscolumn3d';
                    }
                }
                break;

            case 'Line':
                if ('Step' == \$this->SC_APP_info['types'] ['line'] ['format']) {
                    return 'msstepline';
                } else {
                    return 'msline';
                }
                break;

            case 'Radar';
                return 'radar';
                break;
        }
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_getFusionChartsComparisonRenderer

/**
 * Verifica se aconfiguracao json do grafico carregado ja foi criado
 */
function fnChart_aux_isJsonChartCreated($file)
{
    $phpCode = <<<EOT
    function aux_isJsonChartCreated()
    {
        return @is_file(\$this->SC_APP_info['chart'] ['json_base_dir'] . \$this->SC_APP_info['chart'] ['json_filename']);
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_isJsonChartCreated

/**
 * Verifica se a exibicao da pagina e mobile
 */
function fnChart_aux_isMobile($file)
{
    $phpCode = <<<EOT
    function aux_isMobile()
    {
        return \$_SESSION['scriptcase'] ['proc_mobile'];
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_isMobile

/**
 * Verifica se o grafico tem mais de uma serie de dados
 */
function fnChart_aux_isMultiSeries($file)
{
    $phpCode = <<<EOT
    function aux_isMultiSeries()
    {
        if (self::CHART_MODE_ANALYTIC == \$this->SC_APP_data['data_mode'] && !empty(\$this->SC_APP_data['md5_data'] ['data_analytic'])) {
            switch (\$this->SC_APP_data['type']) {
                case 'Area':
                case 'Bar';
                case 'Line':
                    if ('Spline' != \$this->SC_APP_info['types'] ['line'] ['format']) {
                        return true;
                    }
            }
        }

        return false;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_isMultiSeries

/**
 * Verifica se a exibicao da pagina e responsiva
 */
function fnChart_aux_isResponsive($file)
{
    global $summaryInfo;

    $phpCode = <<<EOT
    function aux_isResponsive()
    {
        return \$_SESSION['sc_session'] [\$this->Ini->sc_page] ['{$summaryInfo['general'] ['app_name_session_var']}'] ['responsive_chart'] ['active'];
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_isResponsive

/**
 * Verifica se o conteudo da pagina esta no formato UTF-8
 */
function fnChart_aux_isUtf8($file)
{
    $phpCode = <<<EOT
    function aux_isUtf8()
    {
        return 'UTF-8' == \$_SESSION['scriptcase'] ['charset'];
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_isUtf8

/**
 * Ordena valores de series
 */
function fnChart_aux_orderSerie($file)
{
    $phpCode = <<<EOT
    function aux_orderSerie(&\$serie, \$direction)
    {
        \$this->tempSortRule = \$direction;

        uasort(\$serie, function(\$a, \$b) {
            if (\$a['value'] ==  \$b['value']) {
                if ('asc' == \$this->tempSortRule) {
                    return strnatcmp(\$a['label'], \$b['label']);
                } else {
                    return strnatcmp(\$b['label'], \$a['label']);
                }
            } else {
                if ('asc' == \$this->tempSortRule) {
                    return strnatcmp(\$a['value'], \$b['value']);
                } else {
                    return strnatcmp(\$b['value'], \$a['value']);
                }
            }
        });
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_orderSerie

/**
 * Reorganiza os indices do array de series
 */
function fnChart_aux_rearrangeOrderIndexes($file)
{
    $phpCode = <<<EOT
    function aux_rearrangeOrderIndexes(&\$serie)
    {
        \$newSerie = [];

        foreach (\$serie as \$itemIndex => \$itemInfo) {
            \$newSerie[] = \$itemInfo;
        }

        \$serie = \$newSerie;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_rearrangeOrderIndexes

/**
 * Reorganiza os indices do array de series e categorias
 */
function fnChart_aux_rearrangeOrderMultiIndexes($file)
{
    $phpCode = <<<EOT
    function aux_rearrangeOrderMultiIndexes(&\$serie, &\$category)
    {
        \$newSerie = [];
        \$newCategory = [];

        foreach (\$serie as \$itemIndex => \$itemInfo) {
            \$newSerie[] = \$itemInfo;
            \$newCategory[] = \$category[\$itemIndex];
        }

        \$serie = \$newSerie;
        \$category = \$newCategory;
    }


EOT;

    nm_imprime_2($file, $phpCode);
} // fnChart_aux_rearrangeOrderMultiIndexes
