<?php
/**
 * Project module
 * 
 * Provides basics methods called from public templates
 * These methods can be overriden. Discover logic and examples on :
 * @url http://dev.linea21.com/projects/linea21/wiki/Override
 * @url http://dev.linea21.com/projects/linea21/wiki/Personnalisation_de_l%27interface_publique
 * 
 * @package linea21\modules\project
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */
include_once (override('../project/' . SQL . '.inc.php'));
include_once (override('../project/common.php'));

/**
 * generate_html_recursive_with_progression()
 *
 * @see : http://stackoverflow.com/questions/7577396/php-walking-and-print-multi-dimensional-array
 * @param unknown $data
 * @return string
 */
/**
 *
 * @param array $data
 * @param unknown $statut
 * @param unknown $filter
 * @param unknown $id_filter
 * @param unknown $depth
 * @param unknown $display_first
 * @return string
 */
if (! function_exists('generate_html_recursive_with_progression')) {

    function generate_html_recursive_with_progression($data, $statut, $filter, $id_filter, $depth, $workshop_id = -1)
    {
        // begin with an empty html string
        $html = '';

        // loop through all items in this level
        foreach ($data as $key => &$item) {
            // echo "$key <br ><br>";
            // where only interested in numeric items
            // as those are the actual children
            if (! is_numeric($key)) {
                // otherwise continue
                continue;
            }

            // 'level_parent' attribute is not set when there is no children level
            if (isset($item['level_parent'])) {
                // we display link only on main levels
                $link_level = array(
                    'rub' => $GLOBALS['links'][U_L]['project']['linkvalue'],
                    'filter' => $GLOBALS['filters'][U_L]['level']['linkvalue'],
                    'id' => $item['level_id'],
                    'name' => $item['level_name']
                );

                if ($item['level_parent'] == 0) {
                    // $html .= '<h2><a href="' . HrefMaker($link_level) . '" title="' . formatText($item['level_name'], '2ATT') . '">' . $item['level_name'] . '</a></h2>' . PHP_EOL;

                    $html .= '<div class="grid-4 header-level-' . $depth . '">';
                    $html .= '<div class="col-3 title-level-' . $depth . ' title-level-' . $depth . '-' . $item['level_id'] . '" id="title-level-' . $depth . '-' . $item['level_id'] . '">';
                    $html .= '<h2><a href="' . HrefMaker($link_level) . '" title="' . formatText($item['level_name'], '2ATT') . '">' . $item['level_name'] . '</a></h2>' . PHP_EOL;
                    $html .= '</div>';
                    $html .= '<div class="col sum-level-' . $depth . ' title-level-' . $depth . '-' . $item['level_id'] . '" id="sum-level-' . $depth . '-' . $item['level_id'] . '"></div>';
                    $html .= '</div>';
                    $html .= '<div class="progressbar-finality"  id="progressbar-level-' . $depth . '-' . $item['level_id'] . '"><div style="width:0%"><span data-progression=""></span></div></div>';
                } else {

                    $html .= '<div class="grid-4 header-level-' . $depth . '">';
                    $html .= '<div class="col-3 title-level-' . $depth . ' title-level-' . $depth . '-' . $item['level_id'] . '" id="title-level-' . $depth . '-' . $item['level_id'] . '">';
                    $html .= '<h' . ($depth + 2) . '><a href="' . HrefMaker($link_level) . '" title="' . formatText($item['level_name'], '2ATT') . '">' . $item['level_name'] . '</a></h' . ($depth + 2) . '>' . PHP_EOL;
                    $html .= '</div>';
                    $html .= '<div class="col sum-level-' . $depth . ' title-level-' . $depth . '-' . $item['level_id'] . '" id="sum-level-' . $depth . '-' . $item['level_id'] . '"></div>';
                    $html .= '</div>';
                }

                $html .= '<div class="level-' . $depth . ' level-' . $depth . '-' . $item['level_id'] . '" id="level-' . $depth . '-' . $item['level_id'] . '">';
            }

            // echo "<br ><br>";

            // print_r($data[$j]);
            // echo "<br />";
            // we pass the level ID to the SQL query
            // Dirty but it works .....
            // PRIORITY and SCALE filters are handle later when choosing to displaying or not the project
            // See on the '$projects' loop
            if ($filter == 'TAG') {
                $projects = $GLOBALS['sql_object']->DBSelect(SQL_getProjectsList(0, 999, $statut, 'LEVEL_TAG', $item['level_id'], $id_filter, $workshop_id));
            } else {
                $projects = $GLOBALS['sql_object']->DBSelect(SQL_getProjectsList(0, 999, $statut, 'LEVEL', $item['level_id'], $workshop_id));
            }

            // // we sort values on level names
            // // Obtain a list of columns
            // foreach ($projects as $key => $row) {
            // $level[$key] = $row['level_name'];
            // }

            // // Sort the data with level descending
            // // Add $projects as the last parameter, to sort by the common key
            // array_multisort($level, SORT_DESC, $projects);

            if ($projects != 0) {

                $current_link = array(
                    'rub' => $GLOBALS['links'][U_L]['project']['linkvalue']
                );
                $current_level = '';

                $html .= '<div class="grid-6-small-3 has-gutter mbs project-header">' . PHP_EOL;
                $html .= '<div class="col-4-small-2 ">' . mb_ucfirst(_t('project', 'name')) . '</div>' . PHP_EOL;
                $html .= '<div>' . mb_ucfirst(_t('project', 'priority')) . '</div>' . PHP_EOL;
                $html .= '<div>' . mb_ucfirst(_t('project', 'progression')) . '</div>' . PHP_EOL;
                $html .= '</div>' . PHP_EOL;
                // <div class="level-0 level-0-5" id="level-0-5">
                // $html .= '<div id="level-'.$depth.'-'.$item['level_id'].'" class="projects-set level-'.$depth.' '. 'level-'.$depth.'-'.$item['level_id'].'">' . PHP_EOL;

                for ($i = 0; $i < count($projects); $i ++) {

                    $html .= '<div class="grid-6-small-3 has-gutter mbs">' . PHP_EOL;

                    $link_detail = array(
                        'rub' => $GLOBALS['links'][U_L]['project']['linkvalue'],
                        'id' => $projects[$i]['project_id'],
                        'name' => $projects[$i]['project_name']
                    );

                    $project_name = formatText($projects[$i]['complete_project_name'], '2HTML');
                    $project_description = formatText($projects[$i]['project_description'], '2HTML');

                    if ($projects[$i]['project_parent_id'] != 0)
                        $class = 'sub-project';
                    else
                        $class = 'project';

                    if ($filter == 'PRIORITY') {
                        if ($projects[$i]['priority_id'] == $id_filter) {
                            $html .= '<div class="col-4-small-2 project-name"><a href="' . HrefMaker($link_detail) . '" title="' . formatText($project_name, '2ATT') . '" class="' . $class . '">' . $project_name . '</a></div>' . PHP_EOL;
                            $html .= "<div class=\"project-priority\">" . $projects[$i]['priority_name'] . "</div>\n";
                            $html .= "<div class=\"project-progression\"><div class=\"pprogressbar\" title=\"" . mb_ucfirst(_t('project', 'completion')) . " : " . $projects[$i]['project_completed'] . " %\"><div style=\"width:" . $projects[$i]['project_completed'] . "%\"><span data-progression=\"" . $projects[$i]['project_completed'] . "\">" . $projects[$i]['project_completed'] . " % </span></div></div></div>\n";
                        }
                    } elseif ($filter == 'SCALE') {

                        if ($projects[$i]['project_scale_id'] == $id_filter) {
                            $html .= '<div class="col-4-small-2 project-name"><a href="' . HrefMaker($link_detail) . '" title="' . formatText($project_name, '2ATT') . '" class="' . $class . '">' . $project_name . '</a></div>' . PHP_EOL;
                            $html .= "<div class=\"project-priority\">" . $projects[$i]['priority_name'] . "</div>\n";
                            $html .= "<div class=\"project-progression\"><div class=\"pprogressbar\" title=\"" . mb_ucfirst(_t('project', 'completion')) . " : " . $projects[$i]['project_completed'] . " %\"><div style=\"width:" . $projects[$i]['project_completed'] . "%\"><span data-progression=\"" . $projects[$i]['project_completed'] . "\">" . $projects[$i]['project_completed'] . " % </span></div></div></div>\n";
                        }

                        // pas de filtre, on affiche tout !
                    } else {
                        $html .= '<div class="col-4-small-2 project-name"><a href="' . HrefMaker($link_detail) . '" title="' . formatText($project_name, '2ATT') . '" class="' . $class . '">' . $project_name . '</a></div>' . PHP_EOL;
                        $html .= "<div class=\"project-priority\">" . $projects[$i]['priority_name'] . "</div>\n";
                        $html .= "<div class=\"project-progression\"><div class=\"pprogressbar\" title=\"" . mb_ucfirst(_t('project', 'completion')) . " : " . $projects[$i]['project_completed'] . " %\"><div style=\"width:" . $projects[$i]['project_completed'] . "%\"><span data-progression=\"" . $projects[$i]['project_completed'] . "\">" . $projects[$i]['project_completed'] . " % </span></div></div></div>\n";
                    }

                    $html .= '</div>' . PHP_EOL; // ferme grid-6-small-3
                } // boucle projet
            } // test si projet

            // $html .= '</div>' . PHP_EOL;

            // call this funcion recursively
            // with the next level ($item)
            // it will figure out again whether that level has numeric children as well
            // returns a new complete set, if applicable, otherwise an empty string
            if (isset($item['children']))
                $html .= generate_html_recursive_with_progression($item['children'], $statut, $filter, $id_filter, $depth + 1);

            $html .= '</div>'; // on ferme le container des niveaux
        }

        // return the resulting html
        return $html;
    }
}

/**
 * DisplayListProjectByLevelsWithProgression()
 * Affichage de la liste des projets publics par niveaux
 *
 * @param string $statut
 * @param integer $filter
 * @param string $id_filter
 * @param integer $debut
 * @return string $content
 */

if (! function_exists('DisplayListProjectByLevelsWithProgression')) {

    function DisplayListProjectByLevelsWithProgression($statut, $filter, $id_filter)
    {
        echo "<script>
                $(document).ready(function() {
                function compute_values() {
            
                	// compute total progression by finality
                    // console.log($('div.level-0').attr('id'));
                	$('div.level-0').each(function(index) {
            
                		var currentId = $(this).attr('id');
                		// console.log(currentId);
            
                		var sum = 0;
                		var counter = 0;
                		// iterate through each td based on class and add the values
                		$(this).find('div.project-progression span').each(function(index) {
            
                			var value = $(this).attr('data-progression');
                			counter++;
            
                			// add only if the value is number
                			if(!isNaN(value) && value.length != 0) {
                				sum += parseFloat(value);
                			}
                		});
            
                		if(counter != 0) var mean = parseInt(sum / counter);
                		else var mean = 0;
            
                		$('#sum-' + currentId).html(mean + ' %').hide().fadeIn('slow');
                		$( '#progressbar-' + currentId + ' > ' ).animate({width : mean + '%'}, 3000);
                		$( '#progressbar-' + currentId).prop('title', '" . mb_ucfirst(_t('project', 'completion')) . "  : ' + mean + ' %');
                		    
                	});
               
                // we iterate on levels. We can add more if needed
            	var levels = {0:1, 1:2};
            	for (i in levels) {
                    // compute total progression by orientations
                	$('div.level-' + levels[i]).each(function(index) {
                		    
                		var currentId = $(this).attr('id');
                			var sum = 0;
                			var counter = 0;
                			// iterate through each td based on class and add the values
                			$(this).find('div.project-progression span').each(function(index) {
                		    
                            var value = $(this).attr('data-progression');
                			counter++;
                				// add only if the value is number
                				if(!isNaN(value) && value.length != 0) {
                					sum += parseFloat(value);
                				}
                			});
                		if(counter != 0) var mean = parseInt(sum / counter);
                		else var mean =0;
                        // console.log('#sum-' + currentId);
                		$('#sum-' + currentId).html('" . mb_ucfirst(_t('project', 'completion')) . " : ' + mean + ' %').hide().fadeIn('slow');
                		    
                	});
                }    

                		    
                }
    compute_values();
    });
                </script>";

        $data = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());

        // we retrieve main levels
        if ($filter != 'LEVEL') {
            $data = getLevelChildren($data, 0); // 0 is parentid
            $sublevels = $id_filter;
            $depth = 0;

            $comp = $GLOBALS['sql_object']->DBSelect(SQL_getTotalProjectCompletion('public'));
            if (isset($comp) && is_array($comp))
                $content = sprintf('<div id="projects-percentage">' . _t('project', 'completion-percentage') . '</div>', '<span id="projects-percentage-value">' . round($comp[0]['completion'] ?? 0, 0) . '</span>');
        } else {
            $current = $GLOBALS['sql_object']->DBSelect(SQL_getoneLevel($id_filter));

            $data = getLevelChildren($GLOBALS['sql_object']->DBSelect(SQL_getLevelsList()), $id_filter);
            $sublevels = array_extract($data, 'level_id', true, 'children');

            // if there is no sub-menu, we are working on last levels
            // we emulate a level by passing choosen level but 'level_parent' is not set
            if (count($sublevels) == 0) {
                $sublevels = array(
                    $id_filter
                );
                $data = $current;
            }

            $content = '<h2>' . $current[0]['level_name'] . '</h2>' . PHP_EOL;
            $content .= '<p class="description">' . $current[0]['level_desc_project'] . '</p>' . PHP_EOL;
            $depth = 1;
        }

        echo '<div class="bylevels">';
        if (isset($content))
            echo $content;
        echo generate_html_recursive_with_progression($data, $statut, $filter, $sublevels, $depth);
        echo '</div>';

        // Animate progression bar
        if (defined('ANIMATE_PROGRESS') && ANIMATE_PROGRESS == 1) {
            footerAddJS('../lib/js/waypoints/lib/jquery.waypoints.min.js');

            echo "<script>
            		$(document).ready(function() {
                
            			// $('.progressbar[title]' ).tooltip({ effect: 'slide', opacity: 0.8});
            			function animate_progress(object) {
            				var w = $(object).width() / $(object).parent().width() * 100 + '%'; // get width in percentage
            				$( object ).css('visibility', 'visible').css('width', '0%'); // set element visible and width to 0
            				$( object ).animate({width : w}, getRandomInt(2000,4000));
            			}
                
            			/**
            			* Waypoints animation - Method A
            			* animate when scrolled to object position
            			*/
            			var waypoints = $('div.project-progression div.pprogressbar > div').waypoint({
            				  handler: function(direction) {
            				    animate_progress($(this.element));
            				    this.destroy();
            				  },
            		      offset: 'bottom-in-view'
            			});
                
            			function animate_progress(object) {
            				var w = $(object).width() / $(object).parent().width() * 100 + '%'; // get width in percentage
            				$( object ).css('visibility', 'visible').css('width', '0%'); // set element visible and width to 0
            				$( object ).animate({width : w}, getRandomInt(2000,4000));
            			}
            		});
            		</script>";
        }
    }
}

/**
 * generate_html_recursive()
 *
 * @see : http://stackoverflow.com/questions/7577396/php-walking-and-print-multi-dimensional-array
 * @param unknown $data
 * @return string
 */
/**
 *
 * @param array $data
 * @param unknown $statut
 * @param unknown $filter
 * @param unknown $id_filter
 * @param unknown $depth
 * @param unknown $display_first
 * @return string
 */
if (! function_exists('generate_html_recursive')) {

    function generate_html_recursive($data, $statut, $filter, $id_filter, $depth, $workshop_id = -1)
    {
        // begin with an empty html string
        $html = '';

        // loop through all items in this level
        foreach ($data as $key => &$item) {
            // echo "$key <br ><br>";
            // where only interested in numeric items
            // as those are the actual children
            if (! is_numeric($key)) {
                // otherwise continue
                continue;
            }

            // 'level_parent' attribute is not set when there is no children level
            if (isset($item['level_parent'])) {
                // we display link only on main levels
                $link_level = array(
                    'rub' => $GLOBALS['links'][U_L]['project']['linkvalue'],
                    'filter' => $GLOBALS['filters'][U_L]['level']['linkvalue'],
                    'id' => $item['level_id'],
                    'name' => $item['level_name']
                );

                if ($item['level_parent'] == 0) {
                    $html .= '<h2><a href="' . HrefMaker($link_level) . '" title="' . formatText($item['level_name'], '2ATT') . '">' . $item['level_name'] . '</a></h2>' . PHP_EOL;
                } else {
                    $html .= '<h' . ($depth + 2) . '><a href="' . HrefMaker($link_level) . '" title="' . formatText($item['level_name'], '2ATT') . '">' . $item['level_name'] . '</a></h' . ($depth + 2) . '>' . PHP_EOL;
                }
            }

            // echo "<br ><br>";

            // print_r($data[$j]);
            // echo "<br />";
            // we pass the level ID to the SQL query
            // Dirty but it works .....
            // PRIORITY and SCALE filters are handle later when choosing to displaying or not the project
            // See on the '$projects' loop
            if ($filter == 'TAG') {
                $projects = $GLOBALS['sql_object']->DBSelect(SQL_getProjectsList(0, 999, $statut, 'LEVEL_TAG', $item['level_id'], $id_filter, $workshop_id));
            } else {
                $projects = $GLOBALS['sql_object']->DBSelect(SQL_getProjectsList(0, 999, $statut, 'LEVEL', $item['level_id'], $workshop_id));
            }

            // // we sort values on level names
            // // Obtain a list of columns
            // foreach ($projects as $key => $row) {
            // $level[$key] = $row['level_name'];
            // }

            // // Sort the data with level descending
            // // Add $projects as the last parameter, to sort by the common key
            // array_multisort($level, SORT_DESC, $projects);

            if ($projects != 0) {

                $current_link = array(
                    'rub' => $GLOBALS['links'][U_L]['project']['linkvalue']
                );
                $current_level = '';

                $html .= '<div class="projects-set">' . PHP_EOL;

                for ($i = 0; $i < count($projects); $i ++) {
                    $link_detail = array(
                        'rub' => $GLOBALS['links'][U_L]['project']['linkvalue'],
                        'id' => $projects[$i]['project_id'],
                        'name' => $projects[$i]['project_name']
                    );

                    $project_name = formatText($projects[$i]['complete_project_name'], '2HTML');
                    $project_description = formatText($projects[$i]['project_description'], '2HTML');

                    if ($projects[$i]['project_parent_id'] != 0)
                        $class = 'sub-project';
                    else
                        $class = 'project';

                    if ($filter == 'PRIORITY') {
                        if ($projects[$i]['priority_id'] == $id_filter) {
                            $html .= '<p>' . PHP_EOL;
                            $html .= '<a href="' . HrefMaker($link_detail) . '" title="' . formatText($project_name, '2ATT') . '" class="' . $class . '">' . $project_name . '</a>' . PHP_EOL;
                            $html .= '</p>' . PHP_EOL;
                        }
                    } elseif ($filter == 'SCALE') {
                        if ($projects[$i]['project_scale_id'] == $id_filter) {
                            $html .= '<p>' . PHP_EOL;
                            $html .= '<a href="' . HrefMaker($link_detail) . '" title="' . formatText($project_name, '2ATT') . '" class="' . $class . '">' . $project_name . '</a>' . PHP_EOL;
                            $html .= '</p>' . PHP_EOL;
                        }
                        // pas de filtre, on affiche tout !
                    } else {
                        $html .= '<p>' . PHP_EOL;
                        $html .= '<a href="' . HrefMaker($link_detail) . '" title="' . formatText($project_name, '2ATT') . '" class="' . $class . '">' . $project_name . '</a>' . PHP_EOL;
                        $html .= '</p>' . PHP_EOL;
                    }
                }
                $html .= '</div>' . PHP_EOL;
            }

            // call this funcion recursively
            // with the next level ($item)
            // it will figure out again whether that level has numeric children as well
            // returns a new complete set, if applicable, otherwise an empty string
            if (isset($item['children']))
                $html .= generate_html_recursive($item['children'], $statut, $filter, $id_filter, $depth + 1);
        }

        // return the resulting html
        return $html;
    }
}

/**
 * DisplayListProjectByLevels()
 * Affichage de la liste des projets publics par niveaux
 *
 * @param string $statut
 * @param integer $filter
 * @param string $id_filter
 * @param integer $debut
 * @return string $content
 */

if (! function_exists('DisplayListProjectByLevels')) {

    function DisplayListProjectByLevels($statut, $filter, $id_filter)
    {
        $data = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());

        // we retrieve main levels
        if ($filter != 'LEVEL') {
            $data = getLevelChildren($data, 0); // 0 is parentid
            $sublevels = $id_filter;
            $depth = 0;

            $comp = $GLOBALS['sql_object']->DBSelect(SQL_getTotalProjectCompletion('public'));
            if (isset($comp) && is_array($comp))
                $content = sprintf('<div id="projects-percentage">' . _t('project', 'completion-percentage') . '</div>', '<span id="projects-percentage-value">' . round($comp[0]['completion'], 0) . '</span>');
        } else {
            $current = $GLOBALS['sql_object']->DBSelect(SQL_getoneLevel($id_filter));

            $data = getLevelChildren($GLOBALS['sql_object']->DBSelect(SQL_getLevelsList()), $id_filter);
            $sublevels = array_extract($data, 'level_id', true, 'children');

            // if there is no sub-menu, we are working on last levels
            // we emulate a level by passing choosen level but 'level_parent' is not set
            if (count($sublevels) == 0) {
                $sublevels = array(
                    $id_filter
                );
                $data = $current;
            }

            $content = '<h2>' . $current[0]['level_name'] . '</h2>' . PHP_EOL;
            $content .= '<p class="description">' . $current[0]['level_desc_project'] . '</p>' . PHP_EOL;
            $depth = 1;
        }

        echo '<div class="bylevels">';
        if (isset($content))
            echo $content;
        echo generate_html_recursive($data, $statut, $filter, $sublevels, $depth);
        echo '</div>';
    }
}

/**
 * DisplayListProject()
 * Affichage de la liste des projets publics
 *
 * @param string $statut
 * @param integer $filter
 * @param string $id_filter
 * @param integer $debut
 * @return string $content
 */
if (! function_exists('DisplayListProject')) {

    function DisplayListProject($statut, $filter, $id_filter, $debut)
    {

        // getting tags
        include_once ('../class/class.tag.php');

        if ($statut == 'public') {
            $pas = 100;
            $suffix = '';
        } else
            $pas = SELECT_LIMIT;

        $sep = ' <span class="separator">/</span> ';

        if ($statut == 'archives_p')
            $suffix = ' "' . strtolower(_t('statut', 'PA')) . '"';
        $data = $GLOBALS['sql_object']->DBSelect(SQL_getProjectsList($debut, $pas, $statut, $filter, $id_filter));
        $datacount = $GLOBALS['sql_object']->DBSelect(SQL_getCountProjectsList($statut, $filter, $id_filter));
        $bdd_nb_com = $datacount[0]['num_rows'];
        $bdd_nb_com_display = '<p>' . $bdd_nb_com . ' ' . _t('project', 'name') . $suffix . '</p>' . PHP_EOL;
        $content = '';
        if (is_array($data) && count($data) > 0) {
            // echo $bdd_nb_com_display; // affichage du nombre d'enregistrements
            $current_link = array(
                'rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue']
            );
            $content .= get_linkin_page($current_link, $bdd_nb_com, $debut, $pas);

            for ($i = 0; $i < count($data); $i ++) {

                $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
                $level = getLevelParent($levels, $data[$i]['project_level_id'], 0);
                if (is_array($level)) {
                    $link_level = array(
                        'rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'],
                        'filter' => $GLOBALS['filters'][U_L]['level']['linkvalue'],
                        'id' => $level['id'],
                        'name' => $level['name']
                    );
                }

                $link_detail = array(
                    'rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'],
                    'id' => $data[$i]['project_id'],
                    'name' => $data[$i]['project_name']
                );
                $link_scale = array(
                    'rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'],
                    'filter' => $GLOBALS['filters'][U_L]['scale']['linkvalue'],
                    'id' => $data[$i]['project_scale_id'],
                    'name' => $data[$i]['scale_denomination']
                );
                $link_priority = array(
                    'rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'],
                    'filter' => $GLOBALS['filters'][U_L]['priority']['linkvalue'],
                    'id' => $data[$i]['priority_id'],
                    'name' => $data[$i]['priority_name']
                );
                $link_user = array(
                    'rub' => $GLOBALS['links'][U_L]['user-profile']['linkvalue'],
                    'id' => $data[$i]['project_posted_by'],
                    'name' => $data[$i]['user_login']
                );
                $link_tag = array(
                    'rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'],
                    'filter' => 'tag'
                );

                $project_name = formatText($data[$i]['complete_project_name'], '2HTML');
                $project_description = formatText($data[$i]['project_description'], '2HTML');
                $scale_denomination = formatText($data[$i]['scale_denomination'], '2HTML');
                $project_posted_on = formatText($data[$i]['project_published_date_display'], '2HTML');
                $project_posted_on_long = formatText($data[$i]['project_published_date_display_long'], '2ATT');
                $project_posted_by = formatText($data[$i]['user_login'], '2HTML');
                $project_priority = formatText($data[$i]['priority_name'], '2HTML');
                $project_level_id = $data[$i]['project_level_id'];

                $otag = new tag();
                $tags = $otag->getTags('project', $data[$i]['project_id'], false);

                $content .= '<h2>' . PHP_EOL;
                $content .= '<a href="' . HrefMaker($link_detail) . '" title="' . formatText($project_name, '2ATT') . '">' . $project_name . '</a>' . PHP_EOL;
                $content .= '</h2>' . PHP_EOL;
                $content .= '<p class="published_by">' . PHP_EOL;
                $content .= '<span class="published-on">' . _t('statut', 'published_on') . '</span> <span class="date" data-published-date="' . $project_posted_on_long . '">' . $project_posted_on . '</span> ';
                $content .= _t('divers', 'by') . ' <a href="' . HrefMaker($link_user) . '" title="' . $GLOBALS['links'][U_L]['user-profile']['desc'] . ' (' . $project_posted_by . ')">' . $project_posted_by . '</a>';
                $content .= '</p>' . PHP_EOL;

                $content .= '<div class="chapo clear">' . $project_description . '</div>' . PHP_EOL;
                $content .= '<a class="readmore" href="' . HrefMaker($link_detail) . '">' . _t('btn', 'read_more') . '</a>';
                $content .= '<div class="filter_info">';
                $content .= mb_ucfirst(_t('project', 'priority')) . ' : <a href="' . HrefMaker($link_priority) . '" title="' . $GLOBALS['filters'][U_L]['priority']['desc'] . ' : ' . formatText($project_priority, '2ATT') . '" class="filter_info_priority">' . mb_ucfirst($project_priority) . '</a>' . $sep . PHP_EOL;
                $content .= _t('divers', 'scale') . ' : <a href="' . HrefMaker($link_scale) . '" title="' . $GLOBALS['filters'][U_L]['scale']['desc'] . ' : ' . formatText($scale_denomination, '2ATT') . '" class="filter_info_scale">' . $scale_denomination . '</a>' . $sep . PHP_EOL;
                if (is_array($level))
                    $content .= ' ' . $level['label'] . ' : <a href="' . HrefMaker($link_level) . '" title="' . $GLOBALS['filters'][U_L]['level']['desc'] . ' : ' . formatText($level['name'], '2ATT') . '" class="filter_info_theme">' . $level['name'] . '</a>' . PHP_EOL;
                if (! empty($tags)) {
                    $content .= '<div class="tags">' . PHP_EOL;
                    $content .= mb_ucfirst(_t('tag', 'name')) . ' : ' . $otag->linkTags($tags, $link_tag) . PHP_EOL;
                    $content .= '</div>' . PHP_EOL;
                }
                $content .= '</div>' . PHP_EOL;
                if ($i < count($data) - 1)
                    $content .= '<hr />' . PHP_EOL;
            }
        } else {
            $content .= '<p class="info">' . _t('divers', 'nodata') . '</p>';
        }
        $content .= get_linkin_page($current_link, $bdd_nb_com, $debut, $pas);

        echo $content;
    }
}

/**
 * getProjectImpactsForm()
 * Affichage du formulaire de renseignement des impacts
 *
 * @param string $impactsField
 * @param string $title
 * @return string
 */
if (! function_exists('getProjectImpactsForm')) {

    function getProjectImpactsForm($impactsField = false)
    {

        // if not defined or not enabled we return empty string
        if (! defined('PROJECT_IMPACTS') || PROJECT_IMPACTS == 0)
            return '';

        $project_impacts = $GLOBALS['lang']['project']['impactsItems'];

        // print_r($impactsField);
        if ($impactsField)
            $impactsField = unserialize($impactsField);
        else {
            $default_values = array();
            foreach ($project_impacts as $k => $v) {
                $default_values[$k] = 0;
            }
            $impactsField = $default_values;
        }

        // no values, we return empty string
        if (! is_array($project_impacts))
            return '';

        // we initialise values for array
        $values = array();
        for ($i = 0; $i <= PROJECT_IMPACTS; $i ++) {
            array_push($values, $i);
        }

        $display_impacts = '';

        foreach ($project_impacts as $k => $v) {

            $display_impacts .= '<div class="txtcenter"><label for="project_impacts[' . $k . ']">' . mb_ucfirst($GLOBALS['lang']['project']['impactsItems'][$k]) . '</label><br />';
            // selectBox($data, $field_name, $current = 0, $default = null, $exclude = array(), $use_value = false, $class = 'textfield')
            $display_impacts .= selectBox($values, "project_impacts[$k]", $impactsField[$k], $default = null, $exclude = array(), $use_value = false, $class = 'shorttextfield');
            $display_impacts .= '</div>';
        }

        return '<div class="grid has-gutter-l mts">' . $display_impacts . '</div>';
    }
}

/**
 * getProjectImpacts()
 * Affichage des impacts d'un projet sous forme graphique
 *
 * @param string $impactsField
 * @param string $title
 * @return string
 */
if (! function_exists('getProjectImpacts')) {

    function getProjectImpacts($impactsField, $title = true)
    {
        // if not defined or not enabled we return empty string
        if (! defined('PROJECT_IMPACTS') || PROJECT_IMPACTS == 0)
            return '';

        $project_impacts = unserialize($impactsField);

        // no values, we return empty string
        if (empty($project_impacts) || ! is_array($project_impacts))
            return '';

        $display_impacts = '';

        foreach ($project_impacts as $k => $v) {

            $display_impacts .= '<div class="impacts-container"><div class="impacts-label">' . formatText($GLOBALS['lang']['project']['impactsItems'][$k], '2HTML') . '<span class="text-value">' . $v . '/' . PROJECT_IMPACTS . '</span></div><div class="impacts-value">';

            for ($i = 0; $i < PROJECT_IMPACTS; $i ++) {
                if ($v >= $i + 1)
                    $display_impacts .= '<span class="impacts-in-range">⬤</span>';
                else
                    $display_impacts .= '<span class="impacts-out-of-range">⬤</span>';
            }
            $display_impacts .= '</div></div>';
        }
        $title ? $t = '<h3>' . _t('project', 'impacts') . '</h3>' : $t = '';

        return '<div class="project-impacts">' . $t . '<div class="grid-' . count($project_impacts) . ' has-gutter">' . $display_impacts . '</div></div>';
    }
}

/**
 * DisplayOneProject()
 * Affichage d'un projet en détail
 *
 * @param integer $project_id
 * @return string $stat status name
 */
if (! function_exists('DisplayOneProject')) {

    function DisplayOneProject($project_id)
    {
        $data = $GLOBALS['sql_object']->DBSelect(SQL_getoneCompleteProject($project_id, array(
            'P',
            'PA'
        )));
        $content = '';

        if ($data == 0)
            error_redirect();

        // getting tags
        include_once ('../class/class.tag.php');
        $otag = new tag();
        $tags = $otag->getTags('project', $project_id, false);

        // getting projects tasks if defined
        if (defined('PROJECT_TASK') && PROJECT_TASK == 1) {
            include_once ('../class/class.project_task.php');
            $otask = new projectTask();
            $tasks = $otask->get_project_tasks($project_id, $GLOBALS['sql_object']);

            if (is_array($tasks)) {
                $pgtasks = get_task_progress_bar($project_id);
                $taskslist = format_tasks($tasks);
                $taskslist = sprintf('<div id="task-part"><h3>%s</h3><div id="task-container">%s%s</div></div>', mb_ucfirst(_t('project', 'tasks_title')), $pgtasks, $taskslist);
            }
        }

        $sep = ' <span class="separator">/</span> ';

        if (count($data) != 1)
            exit();
        else {
            $link_scale = array(
                'rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'],
                'filter' => $GLOBALS['filters'][U_L]['scale']['linkvalue'],
                'id' => $data[0]['project_scale_id'],
                'name' => $data[0]['scale_denomination']
            );
            $link_priority = array(
                'rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'],
                'filter' => $GLOBALS['filters'][U_L]['priority']['linkvalue'],
                'id' => $data[0]['project_priority_id'],
                'name' => $data[0]['project_priority']
            );
            $link_user = array(
                'rub' => $GLOBALS['links'][U_L]['user-profile']['linkvalue'],
                'id' => $data[0]['project_posted_by'],
                'name' => $data[0]['user_login']
            );
            $link_parent = array(
                'rub' => $GLOBALS['links'][U_L]['project']['linkvalue'],
                'id' => $data[0]['project_parent_id'],
                'name' => $data[0]['parent_name']
            );
            $link_self = array(
                'rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'],
                'id' => $project_id
            );
            $link_tag = array(
                'rub' => $GLOBALS['links'][U_L][ActiveItemKey($GLOBALS['activeitem'])]['linkvalue'],
                'filter' => 'tag'
            );

            $project_coordinator = empty_nc(getAssociatedActors($project_id, 'coordinator'));
            $project_partners = empty_nc(getAssociatedActors($project_id, 'partner'));
            $project_targets = getAssociatedActors($project_id, 'target');
            $project_managers = empty_nc(getAssociatedManagers($project_id));

            $project_name = formatText($data[0]['project_name'], '2HTML');
            $project_goal = formatText($data[0]['project_goal'], '2HTML');
            $project_opgoal = formatText($data[0]['project_opgoal'], '2HTML');
            $project_description = formatText($data[0]['project_description'], '2HTML');
            $project_body = formatText($data[0]['project_body'], '2HTML');
            $project_comment = formatText($data[0]['project_comment'], '2HTML');
            $project_budget = formatText(empty_nc(fnumber_format($data[0]['project_budget'], 0, false)), '2HTML');
            $project_budget_comment = formatText($data[0]['project_budget_comment'], '2HTML');
            $project_cal_comment = formatText($data[0]['project_cal_comment'], '2HTML');
            $project_team = formatText($data[0]['project_team'], '2HTML');
            $project_elected = formatText($data[0]['project_elected'], '2HTML');
            $project_parent = formatText($data[0]['parent_name'], '2HTML');
            $project_scale = formatText($data[0]['scale_denomination'], '2HTML');
            $project_priority = formatText($data[0]['project_priority'], '2HTML');
            $project_begin_date = formatText(empty_nc($data[0]['project_begin_date_display']), '2HTML');
            $project_estimated_date = formatText(empty_nc($data[0]['project_estimated_date_display']), '2HTML');
            $project_end_date = formatText(empty_nc($data[0]['project_end_date_display']), '2HTML');
            $project_progression = $data[0]['project_completed'];
            $workshop_id = formatText(empty_nc($data[0]['project_workshop_id']), '2HTML');
            $workshop_name = formatText(empty_nc($data[0]['workshop_denomination']), '2HTML');
            $scale_id = $data[0]['project_scale_id'];
            $project_level_id = $data[0]['project_level_id'];
            $project_indic_orders = $data[0]['project_indic_order'];

            $project_achievement_badge = empty($data[0]['project_achievement']) ? '': '<span class="p-achievement-badge '.$data[0]['project_achievement'] .'">' .$GLOBALS['lang']['project']['achievementItems'][$data[0]['project_achievement']] .'</span>';

            $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
            $level = getLevelParent($levels, $data[0]['project_level_id'], 0);
            if (is_array($level)) {
                $link_level = array(
                    'rub' => $GLOBALS['links'][U_L]['project']['linkvalue'],
                    'filter' => $GLOBALS['filters'][U_L]['level']['linkvalue'],
                    'id' => $level['id'],
                    'name' => $level['name']
                );
            }

            $schedule_table = getScheduleTable($data[0]['project_begin_date_display'], $data[0]['project_estimated_date_display'], $data[0]['project_end_date_display']);

            $project_posted_on = formatText($data[0]['project_published_date_display'], '2HTML');
            $project_posted_on_long = formatText($data[0]['project_published_date_display_long'], '2ATT');
            $project_modify_on = formatText($data[0]['project_last_modify_display'], '2HTML');
            $project_posted_by = formatText($data[0]['user_login'], '2HTML');
            $project_status = $data[0]['project_statut'];

            if (commentEnabled('project')) {
                postCommentAction(array(
                    'module' => ActiveItemKey($GLOBALS['activeitem']),
                    'module_id' => $project_id
                ));
                $content .= '<div id="anchor-comments">' . PHP_EOL;
                $content .= getCommentsAnchor(array(
                    'module' => ActiveItemKey($GLOBALS['activeitem']),
                    'module_id' => $project_id
                ));
                if ($project_status == 'P')
                    $content .= getPostCommentAnchor();
                $content .= '</div>' . PHP_EOL;
            }

            $content .= '<h1>' . $project_name . '</h1>' . PHP_EOL;
            $content .= '<p class="published_by">' . PHP_EOL;
            $content .= $project_achievement_badge;
            $content .= '<span class="published-on">' . _t('statut', 'published_on') . '</span> <span class="date" data-published-date="' . $project_posted_on_long . '">' . $project_posted_on . '</span> ';
            $content .= _t('divers', 'by') . ' <a href="' . HrefMaker($link_user) . '" title="' . $GLOBALS['links'][U_L]['user-profile']['desc'] . ' (' . $project_posted_by . ')">' . $project_posted_by . '</a>';
            if ($project_status == 'PA') {
                $content .= ' (' . _t('statut', 'archived_on') . ' ' . $project_modify_on . ')';
            }
            $content .= formatted_permalink($link_self);
            $content .= '</p>' . PHP_EOL;
            if ($data[0]['project_parent_id'] != 0) {
                $content .= '<div id="parent_project">' . PHP_EOL;
                $content .= mb_ucfirst(_t('project', 'parent')) . ' : ';
                $content .= '<a href="' . HrefMaker($link_parent) . '" title="' . _t('project', 'parent') . ' : ' . formatText($project_parent, '2ATT') . '" class="filter_info_parent">
 ' . $project_parent . '</a> ';
                $content .= '</div>' . PHP_EOL;
            }


            if (! empty($project_targets))
                $content .= '<div class="project-target"><span class="project-item-l">' . mb_ucfirst(_t('project', 'target')) . ' : </span>' . $project_targets . '</div>' . PHP_EOL;

            if (! empty($project_goal))
                $content .= '<div class="project-goal"><span class="project-item-l">' . mb_ucfirst(_t('project', 'goal')) . '</span>' . $project_goal . '</div>' . PHP_EOL;
            if (! empty($project_opgoal))
                $content .= '<div class="project-opgoal"><span class="project-item-l">' . mb_ucfirst(_t('project', 'opgoal')) . '</span>' . $project_opgoal . '</div>' . PHP_EOL;

            $content .= '<div class="grid project-calendar">' . PHP_EOL;
            $content .= '<div class="grid3-1 grid has-gutter-xl">' . PHP_EOL;
            $content .= '<div class="schedule two-thirds">' . $schedule_table . '</div>' . PHP_EOL;
            $content .= '<div class="progression one-third">' . mb_ucfirst(_t('project', 'progression')) . '<br />' . getDynamicProgressbar($project_progression, 80) . '</div>' . PHP_EOL;
            $content .= '</div>' . PHP_EOL;
            $content .= '</div>' . PHP_EOL;
            if (! empty($project_cal_comment))
                $content .= '<div class="project-cal-comment">' . $project_cal_comment . '</div>' . PHP_EOL;

            if (defined('PROJECT_FINALITIES') && PROJECT_FINALITIES == 1) {
                $content .= '<div class="finalities"><h3>' . _t('project', 'finalities') . '</h3>';
                $content .= getFinalities($project_id, 'read');
                $content .= '</div>';
            }

            $content .= '<div class="chapo clear"><span class="project-item-l">' . mb_ucfirst(_t('project', 'description')) . '</span>' . $project_description . '</div>' . PHP_EOL;

            if (! empty($project_body))
                $content .= '<div class="body"><span class="project-item-l">' . _t('project', 'body') . '</span>' . $project_body . '</div>' . PHP_EOL;

            if (isset($taskslist))
                $content .= $taskslist . PHP_EOL;

            $content .= getProjectImpacts($data[0]['project_impact']);

            // including easyTabs
            footerAddJS('../lib/js/jQuery-EasyTabs/vendor/jquery.hashchange.min.js');
            footerAddJS('../lib/js/jQuery-EasyTabs/lib/jquery.easytabs.min.js');
            footerAddInlineJS("$('#tabs').easytabs({animate:false});");

            $content .= '<div id="tabs" class="mtl">';
            $content .= "<ul class=\"internal-nav\" id=\"action-navigation\">" . PHP_EOL;
            $content .= "<li class=\"tab\">" . PHP_EOL;
            $content .= '<a href="#steering">' . mb_ucfirst(_t('project', 'steering_title')) . '</a>' . PHP_EOL;
            $content .= "</li><li class=\"tab\">" . PHP_EOL;
            $content .= '<a href="#budget">' . mb_ucfirst(_t('project', 'budget_title')) . '</a>' . PHP_EOL;
            $content .= "</li>" . PHP_EOL;
            $content .= "</ul>" . PHP_EOL;

            $content .= '<div class="tab-content current internal-content steering" id="steering">';
            // $content .= '<h3>' . _t('project','steering_title') . '</h3>';
            $content .= '<div class="p-elected"><span class="project-item-l">' . mb_ucfirst(_t('project', 'elected')) . ' : </span><span>' . empty_nc($project_elected) . '</span></div>';
            $content .= '<div class="p-coordinator"><span class="project-item-l">' . mb_ucfirst(_t('project', 'coordinator')) . ' : </span><span>' . $project_coordinator . '</span></div>';
            $content .= '<div class="p-partner"><span class="project-item-l">' . mb_ucfirst(_t('project', 'partners')) . ' : </span><span>' . $project_partners . '</span></div>';
            $content .= '<div class="p-manager"><span class="project-item-l">' . mb_ucfirst(_t('project', 'manager')) . ' : </span><span>' . $project_managers . '</span></div>';
            if (! empty($project_team))
                $content .= '<div class="p-team"><span class="project-item-l">' . mb_ucfirst(_t('project', 'team')) . ' : </span>' . $project_team . '</div>';
            $content .= '</div>';

            $content .= '<div class="tab-content internal-content budget" id="budget">';
            // $content .= '<h3>' . _t('project','budget_title') . '</h3>';
            $content .= '<div class="p-budget"><span class="project-item-l">' . mb_ucfirst(_t('project', 'budget')) . ' : </span><span>' . $project_budget . '</span></div>';
            if (! empty($project_budget_comment))
                $content .= '<div class="p-budget-comment">' . $project_budget_comment . '</div>';
            $content .= '</div>';

            $content .= '</div>'; // on ferme lde div#tabs

            // // older layout for steering and budget - without tabs navigation
            // $content .= '<div class="management grid">';
            // $content .= '<div class="grid2 grid has-gutter-xl">';

            // $content .= '<div class="steering">';
            // $content .= '<h3>' . _t('project','steering_title') . '</h3>';
            // $content .= '<div><span class="project-item-l">' . mb_ucfirst(_t('project','elected')) . ' : </span><span>' . empty_nc($project_elected) . '</span></div>';
            // $content .= '<div><span class="project-item-l">' . mb_ucfirst(_t('project','coordinator')) . ' : </span><span>' . $project_coordinator . '</span></div>';
            // $content .= '<div><span class="project-item-l">' . mb_ucfirst(_t('project','partners')) . ' : </span><span>' . $project_partners .'</span></div>';
            // $content .= '<div><span class="project-item-l">' . mb_ucfirst(_t('project','manager')) . ' : </span><span>' . $project_managers . '</span></div>';
            // if(!empty($project_team)) $content .= '<div><span class="project-item-l">' . mb_ucfirst(_t('project','team')) . ' : </span>' . $project_team . '</div>';
            // $content .= '</div>';

            // $content .= '<div class="budget">';
            // $content .= '<h3>' . _t('project','budget_title') . '</h3>';
            // $content .= '<div><span class="project-item-l">' . mb_ucfirst(_t('project','budget')). ' : </span><span>' . $project_budget . '</span></div>';
            // if(!empty($project_budget_comment)) $content .= '<div>' . $project_budget_comment . '</div>';
            // $content .= '</div>';

            // $content .= '</div>' . PHP_EOL;
            // $content .= '</div>' . PHP_EOL;

            // if(!empty($project_comment)) $content .= '<div class="project-comment">' . $project_comment . '</div>' . PHP_EOL;

            $content .= getProjectChildren($project_id);
            // $content .= getAssociatedIndicators($project_id, $scale_id);
            $content .= getAssociatedIndicatorsValues($project_id, $project_indic_orders);
            $content .= getAssociatedWorkshop($workshop_id, $workshop_name);

            $content .= '<div class="filter_info">' . PHP_EOL;
            $content .= mb_ucfirst(_t('project', 'priority')) . ' : ';
            $content .= '<a href="' . HrefMaker($link_priority) . '" title="' . $GLOBALS['filters'][U_L]['priority']['desc'] . ' : ' . formatText($project_priority, '2ATT') . '" class="filter_info_priority">' . mb_ucfirst($project_priority) . '</a>' . $sep . PHP_EOL;
            $content .= ' ' . _t('divers', 'scale') . ' : <a href="' . HrefMaker($link_scale) . '" title="' . $GLOBALS['filters'][U_L]['scale']['desc'] . ' : ' . formatText($project_scale, '2ATT') . '" class="filter_info_scale">' . $project_scale . '</a>' . $sep . PHP_EOL;
            if (is_array($level))
                $content .= ' ' . $level['label'] . ' : <a href="' . HrefMaker($link_level) . '" title="' . $GLOBALS['filters'][U_L]['level']['desc'] . ' : ' . formatText($level['name'], '2ATT') . '" class="filter_info_theme">' . $level['name'] . '</a>' . $sep . PHP_EOL;
            if (! empty($tags)) {
                $content .= '<div class="tags">' . PHP_EOL;
                $content .= ' ' . mb_ucfirst(_t('tag', 'name')) . ' : ' . $otag->linkTags($tags, $link_tag) . PHP_EOL;
                $content .= '</div>' . PHP_EOL;
            }
            $content .= '</div>' . PHP_EOL;

            if (voteEnabled('project')) {
                echo getAjaxVotesFunction(array(
                    'module' => 'project'
                ));
                $likes_number = getNbVotes(array(
                    'module' => 'project',
                    'module_id' => $project_id
                ));
                $likes_number > 1 ? $likes_title = _t('like', 'like_plural') : $likes_title = _t('like', 'like_singular');
                $content .= '<div class="votes flex-container">' . PHP_EOL;
                $content .= '<div class="votes-number txtcenter"><span class="cnt-votes" id="cnt-votes-' . $project_id . '">' . $likes_number . '</span> ' . $likes_title . '</div>' . PHP_EOL;
                $content .= '<div class="i-like-it item-fluid"><a href="' . SITE_ROOT_URL . 'vote/_vote.php" data-id="' . $project_id . '">' . mb_ucfirst(_t('like', 'i_like_project')) . '</a>';
                $content .= '<p class="vote-msg" id="vote-msg-' . $project_id . '">&nbsp;</p>' . PHP_EOL;
                $content .= '</div>' . PHP_EOL;
                $content .= '</div>' . PHP_EOL;
            }
        }

        // including sparkline code based on peity
        footerAddJS('../lib/js/peity-3.3.0/jquery.peity.min.js');
        footerAddInlineJS("$('.dashboard-indicator-sparkline .inlinebar').peity( 'bar', { fill: ['#5EA7AC']});"); // previous color '#8DA8CB'

        echo $content;
        return GetStatusName($project_status);
    }
}

/**
 * GetProjectChildren()
 *
 * @param
 *            $id
 * @return string
 */
if (! function_exists('getProjectChildren')) {

    function getProjectChildren($id)
    {
        $data = $GLOBALS['sql_object']->DBSelect(SQL_getProjectChildren($id));

        $content = '';

        if (is_array($data) && $data[0] != 0) {

            $content .= '<div id="project_children">' . PHP_EOL;
            $content .= '<p>' . mb_ucfirst(_t('project', 'sub-projects')) . ' : </p><ul>' . PHP_EOL;
            for ($i = 0; $i < count($data); $i ++) {
                $link = array(
                    'rub' => $GLOBALS['links'][U_L]['project']['linkvalue'],
                    'id' => $data[$i]['project_id'],
                    'name' => $data[$i]['project_name']
                );
                $name = formatText($data[$i]['project_name'], '2HTML');

                $content .= '<li><a href="' . HrefMaker($link) . '" title="' . _t('project', 'parent') . ' : ' . formatText($name, '2ATT') . '" class="filter_info_parent">' . $name . '</a></li>' . PHP_EOL;
            }
            $content .= '</ul></div>' . PHP_EOL;
        }

        return $content;
    }
}

/**
 * GetStatusName()
 *
 * @param
 *            $status
 * @return $stat Status name
 */
if (! function_exists('GetStatusName')) {

    function GetStatusName($status)
    {
        switch ($status) {
            case 'P':
                $stat = 'public';
                break;
            case 'PA':
                $stat = 'archives_p';
                break;
            case 'AA':
                $stat = 'archives_a';
                break;
            default:
                $stat = 'public';
        }
        return $stat;
    }
}

/**
 * getScheduleTable()
 *
 * @param string $s_date
 * @param string $es_date
 * @param string $e_date
 * @return string $content
 */
if (! function_exists('getScheduleTable')) {

    function getScheduleTable($s_date, $es_date, $e_date)
    {
        $es_date_class = 'nothing';
        $e_date_class = 'nothing';

        if (! isNullDate($es_date)) {
            if (! isNullDate($e_date))
                $es_date_class = date_compare($e_date, $es_date, '>') ? 'warn' : 'good';
            else
                $es_date_class = date_compare(date("Y-m-d"), $es_date, '>') ? 'bad' : 'good';
        }
        if (! isNullDate($e_date)) {
            if (! isNullDate($es_date))
                $e_date_class = date_compare($e_date, $es_date, '>') ? 'bad' : 'good';
            else
                $e_date_class = 'good';
        } else {
            if (! isNullDate($es_date)) {
                $e_date_class = date_compare(date("Y-m-d"), $es_date, '>') ? 'warn' : 'nothing';
            }
        }

        $content = '<table class="project">' . PHP_EOL;
        $content .= '<thead>' . PHP_EOL;
        $content .= '<tr>' . PHP_EOL;
        $content .= '<td>' . mb_ucfirst(_t('project', 'begin_date')) . '</td>' . PHP_EOL;
        $content .= '<td>' . mb_ucfirst(_t('project', 'estimated_date')) . '</td>' . PHP_EOL;
        $content .= '<td>' . mb_ucfirst(_t('project', 'end_date')) . '</td>' . PHP_EOL;
        $content .= '</tr>' . PHP_EOL;
        $content .= '</thead>' . PHP_EOL;
        $content .= '<tbody>' . PHP_EOL;
        $content .= '<tr>' . PHP_EOL;
        $content .= '<td>' . formatText(empty_nc($s_date)) . '</td>' . PHP_EOL;
        $content .= '<td class="' . $es_date_class . '">' . formatText(empty_nc($es_date)) . '</td>' . PHP_EOL;
        $content .= '<td class="' . $e_date_class . '">' . formatText(empty_nc($e_date)) . '</td>' . PHP_EOL;
        $content .= '</tr>' . PHP_EOL;
        $content .= '</tbody>' . PHP_EOL;
        $content .= '</table>' . PHP_EOL;
        return $content;
    }
}

/**
 * getAssociatedWorkshop()
 *
 * @param
 *            $id
 * @return string
 */
if (! function_exists('getAssociatedWorkshop')) {

    function getAssociatedWorkshop($wid, $wname)
    {

		if(!is_numeric($wid)) return '';
		
        $content = '';
        if ($wid != 0) {
            $link = array(
                'rub' => $GLOBALS['links'][U_L]['workgroup']['linkvalue'],
                'id' => $wid,
                'name' => $wname
            );
            $content .= '<div id="project_workshop">' . PHP_EOL;
            $content .= '<h3>' . ucfirst(_t('project', 'workshop')) . '</h3>' . PHP_EOL;
            $content .= '<p><a href="' . HrefMaker($link) . '" title="' . _t('project', 'workshop') . ' : ' . formatText($wname, '2ATT') . '">' . $wname . '</a></p>' . PHP_EOL;
            $content .= '</div>' . PHP_EOL;
        }

        return $content;
    }
}

/**
 * getFinalities()
 *
 * @param $id (optionnal)
 * @param $mode (optionnal)
 *            : take value 'read' or 'write' or 'array'
 * @param $selected (optionnal)
 *            : array with selected values - useful when adding / changing current values
 * @return array
 */
if (! function_exists('getFinalities')) {

    function getFinalities($id = false, $mode = 'read', $selected = array())
    {
        // we get all values
        $init = $GLOBALS['sql_object']->DBSelect(SQL_getFinalities(false));

        // we get finalities for the given project if needed
        // and we merge all selected values in $selected array
        if (is_numeric($id)) {
            $data = $GLOBALS['sql_object']->DBSelect(SQL_getFinalities($id));
            if (isset($data[0]['finality_id'])) {
                foreach ($data as $item) {
                    if (! in_array($item['finality_id'], $selected))
                        array_push($selected, $item['finality_id']);
                }
            }
        }

        $content = '';

        if (isset($init[0]['finality_id'])) {

            $array = array();

            if ($mode == 'read' || $mode == 'array') {
                $content .= '<div><ul class="finalities">';
                for ($i = 0; $i < count($init); $i ++) {

                    $tmp = array();
                    $name = formatText($init[$i]['finality_name'], '2HTML');
                    $tmp['name'] = $name;

                    if (in_array($init[$i]['finality_id'], $selected)) {
                        $box = '<span class="finality-active">☑ </span>';
                        $tmp['state'] = 'active';
                        $tmp['state_utf8'] = '☑';
                    } else {
                        $box = '<span class="finality-inactive">☐ </span>';
                        $tmp['state'] = 'inactive';
                        $tmp['state_utf8'] = '☐';
                    }

                    $content .= '<li id="finality-' . $init[$i]['finality_id'] . '">' . $box . $name . '</li>';

                    $array[$i] = $tmp;
                }
                $content .= '</ul></div>';
            }

            if ($mode == 'write')
                $content = get_checkbox($init, 'finalities[]', 'finality_name', 'finality_id', $selected);

            if ($mode == 'array')
                $content = $array;
        }

        return $content;
    }
}

/**
 * getAssociatedActors()
 *
 * @param
 *            $id
 * @param
 *            $type
 * @return string
 */
if (! function_exists('getAssociatedActors')) {

    function getAssociatedActors($id, $type)
    {
        $data = $GLOBALS['sql_object']->DBSelect(SQL_getAssociatedActors($id, $type));

        $content = '';
        $sep = '';
        if (is_array($data) && $data[0] != 0) {

            for ($i = 0; $i < count($data); $i ++) {
                $name = formatText($data[$i]['actor_name'], '2HTML');

                $content .= $sep . $name;
                $sep = ', ';
            }
        }

        return $content;
    }
}

/**
 * getAssociatedManagers()
 *
 * @param
 *            $id
 * @return string
 */
if (! function_exists('getAssociatedManagers')) {

    function getAssociatedManagers($id, $raw = false)
    {
        $data = $GLOBALS['sql_object']->DBSelect(SQL_getAssociatedManagers($id));

        $content = '';
        $sep = '';

        if (is_array($data) && $data[0] != 0) {

            for ($i = 0; $i < count($data); $i ++) {

                if ($raw == true) {

                    $name = formatText($data[$i]['user_login'], '2HTML');
                } else {

                    if (! empty($data[$i]['profile_firstname']) && ! empty($data[$i]['profile_lastname'])) {
                        $name = formatText($data[$i]['profile_firstname'] . ' ' . $data[$i]['profile_lastname'] . ' (' . $data[$i]['user_login'] . ')', '2HTML');
                    } elseif (! empty($data[$i]['profile_firstname']) || $data[$i]['profile_lastname']) {
                        $name = formatText($data[$i]['user_login'] . ' - ' . $data[$i]['profile_firstname'] . ' ' . $data[$i]['profile_lastname'], '2HTML');
                    } else {
                        $name = formatText($data[$i]['user_login'], '2HTML');
                    }
                }

                $content .= $sep . $name;
                $sep = ', ';
            }
        }

        return $content;
    }
}

/**
 * getAssociatedWorkshop()
 *
 * @param
 *            $id
 * @return string
 */
if (! function_exists('getAssociatedIndicators')) {

    function getAssociatedIndicators($id, $scale_id, $linkto = true)
    {
        $data = $GLOBALS['sql_object']->DBSelect(SQL_getProjectSdi($id));

        $content = '';
        if (count($data) != 0 && $data[0] != 0) {

            $content .= '<div id="project_indicators" class="listed">' . PHP_EOL;
            $content .= '<h3>' . ucfirst(_t('project', 'sdi')) . '</h3>' . PHP_EOL;
            $content .= '<ul>' . PHP_EOL;
            for ($i = 0; $i < count($data); $i ++) {
                $link = array(
                    'rub' => $GLOBALS['links'][U_L]['dashboard']['linkvalue'],
                    'id' => $data[$i]['sdii_id'],
                    'parentid' => $scale_id,
                    'name' => $data[$i]['sdii_name']
                );
                $name = formatText($data[$i]['sdii_name'], '2HTML');
                if ($linkto) {
                    $content .= '<li><a href="' . HrefMaker($link) . '" title="' . _t('project', 'sdi') . ' : ' . formatText($name, '2ATT') . '">' . $name . '</a></li>' . PHP_EOL;
                } else {
                    $content .= '<li>' . $name . '</li>' . PHP_EOL;
                }
            }
            $content .= '</ul></div>' . PHP_EOL;
        }

        return $content;
    }
}

/**
 * getAssociatedIndicatorsValues()
 *
 * @param integer $id
 * @return string
 */
if (! function_exists('getAssociatedIndicatorsValues')) {

    function getAssociatedIndicatorsValues($id, $orderedIndicators = null, $extraclass = '', $cursorcssposition = 0, $addvalues = false)
    {
        global $l21auth;
        global $sql_object;

        include_once ('../dashboard/display.php');
        include_once ('../dashboard/mysql.inc.php');


        $result_sdi = $GLOBALS['sql_object']->DBSelect(SQL_getProjectSdiValues($id));

        $content = '';
        $id_filter = 1; // scale id value

        if (CURRENT_APP == 'admin' && ($l21auth->isProjectManager($l21auth->GetSessionElement('id'), $sql_object, $id) || $l21auth->isSuperAdmin())) {
            $displayLink = true;
            // we add script for sorting indicators
            footerAddJS('../lib/js/TableDnD/dist/jquery.tablednd.1.0.5.min.js');
            dragTableSettings(array('id' => $id, 'order' => 'indic'));
        } else {
            $displayLink = false;
        }

        if (is_array($result_sdi) && $result_sdi[0] != 0) {
            
            $ordered_indics = array();
            // we prepare ordered data if given
            // 1 - first data stored in $orderedIndicators, then all data
            if(!is_null($orderedIndicators))  $tmp = unserialize($orderedIndicators);
            if(isset($tmp) && is_array($tmp)) {
                foreach($tmp as $k => $v) {
                    if(is_integer($k)) array_push($ordered_indics, $k); // to be sure it is not empty 
                }
            }
            // 2 - then, we iterate on all indicators thare are not already in $ordered_indics
            foreach($result_sdi as $sdi) {
                if($sdi['sdii_statut'] == 'P' && !in_array($sdi['sdii_id'], $ordered_indics)) array_push($ordered_indics, $sdi['sdii_id']); // to be sure it is not empty 
            }
            
            $content .= '<div class="project-dashboard ' . $extraclass . '" id="project-' . $id . '-dashboard">' . PHP_EOL;
            $content .= '<h3>' . ucfirst(_t('project', 'sdi')) . '</h3>' . PHP_EOL;

            // table header
            $content .= '<table id="sort-table" class="table_dashboard sortable">' . PHP_EOL;
            $content .= '<thead class="invisible">' . PHP_EOL;
            $content .= '<tr>' . PHP_EOL;
            $content .= '<td class="graphic-values pt2">' . mb_ucfirst(_t('dashboard', 'graphic_value')) . '</td>' . PHP_EOL;
            // $content .= '<td>'.mb_ucfirst(_t('dashboard','numeric_value')).'</td>' . PHP_EOL;
            $content .= '<td>' . mb_ucfirst(_t('dashboard', 'label_value')) . '</td>' . PHP_EOL;
            if ($displayLink === true)
                $content .= '<td>' . mb_ucfirst(_t('divers', 'actions')) . '</td>' . PHP_EOL;
            $content .= '</tr>' . PHP_EOL;
            $content .= '</thead>' . PHP_EOL;
            $content .= '<tbody>' . PHP_EOL;
            
            $indics_array = [];
            foreach($ordered_indics as $k => $v) {
                
                // we search for the key of searched element : $j
                // then we display the full record
                $j = array_search($v, array_column($result_sdi, 'sdii_id')); 

                // we display values only if indicator is public
                if ($result_sdi[$j]['sdii_statut'] == 'P' && !in_array($j, $indics_array)) {
                    // setting $threshold_value
                    // By default initial value
                    $threshold_value = $result_sdi[$j]['sdii_threshold_value'];
                    // if set, we get the latest for the given scale
                    $r = $GLOBALS['sql_object']->DBSelect(SQL_getlastInsertByPublicationDate($result_sdi[$j]['sdii_id'], 1));
                    if (isset($r[0]['sdiv_value']) && ! is_null($r[0]['sdiv_threshold'])) {
                        $threshold_value = $r[0]['sdiv_threshold'];
                    }

                    if ($displayLink === true) {
                        $link_add_values = './index.php?rub=dashboard&todo=add&id=' . $result_sdi[$j]['sdii_id'] . '&scale_id=' . $id_filter.'&project-referer='.$id;
                        $addvalues_link = "<div class=\"iconetab\">\n";
                        $addvalues_link .= "<a href=\"" . $link_add_values . "\" class=\"ico_add\" title=\"" . mb_ucfirst(_t('project', 'add_indicator_value')) . "\"><i class=\"fa fa-plus-circle\" aria-hidden=\"true\"></i><span>" . mb_ucfirst(_t('project', 'add_indicator_value')) . "</span></a>\n";
                        $addvalues_link .= "</div>\n";
                    } else
                        $addvalues_link = '';

                    if ($result_sdi[$j]['sdii_type'] != 'not-set')
                        $typecontent = '<span class="indic-type ' . $result_sdi[$j]['sdii_type'] . '">' . formatText(mb_ucfirst($GLOBALS['lang']['sdi']['select_type'][$result_sdi[$j]['sdii_type']]), '2HTML') . '</span>';
                    else
                        $typecontent = '';
                    if (CURRENT_APP == 'admin') {
                        $link_det_sdi = './index.php?rub=dashboard&todo=det&id=' . $result_sdi[$j]['sdii_id'] . '&scale_id=' . $id_filter;
                    } else {
                        $link_det_sdi = HrefMaker(array(
                            'rub' => $GLOBALS['links'][U_L]['dashboard']['linkvalue'],
                            'id' => $result_sdi[$j]['sdii_id'],
                            'parentid' => $id_filter,
                            'name' => $result_sdi[$j]['sdii_name']
                        ));
                    }
                    $content .= "<tr  id=\"indic-".$result_sdi[$j]['sdii_id']."\" >" . PHP_EOL;
                    $content .= "<td class=\"graphic-values indicator-" . $result_sdi[$j]['sdii_type'] . "\">";
                    $content .= getViz($GLOBALS['sql_object'], $id_filter, $result_sdi[$j], $threshold_value, null, $cursorcssposition);
                    $content .= "</td>";

                    if ($displayLink === true || CURRENT_APP != 'admin')
                        $content .= "<td><a href=\"" . $link_det_sdi . "\" title=\"" . formatText($result_sdi[$j]['sdii_name'], '2ATT') . "\">" . formatText(Stringy\Stringy::create($result_sdi[$j]['sdii_name'], CHARSET)->safeTruncate(90, ' ...'), '2HTML') . "</a>" . $typecontent . "</td>" . PHP_EOL;
                    else
                        $content .= "<td>" . formatText(cutText($result_sdi[$j]['sdii_name'], 53), '2HTML') . $typecontent . "</td>" . PHP_EOL;
                    if ($displayLink === true)
                        $content .= "<td>" . $addvalues_link . "</td>" . PHP_EOL;
                    $content .= "</tr>" . PHP_EOL;
                }
                array_push($indics_array, $j);
            }

            $content .= "</tbody>" . PHP_EOL;
            $content .= "</table>" . PHP_EOL;
            $content .= "</div>" . PHP_EOL;
        }

        $js = '<script>
							$(document).ready(function() {
								$(".dashboard-indicator-gauge .cursor").removeAttr("title");
								$(".infobox").hover(
									function() {
										$(this).next().fadeIn("fast");
									},
									function() {
										$(this).next().hide();
									}
								);
								});
						</script>';
        footerAddInlineJS($js, 'default', false);

        return $content;
    }
}

?>