<?php
/**
 * Project module
 *
 * Display projects list in back-office
 *
 * @package linea21\modules\project
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

//////////// Check Inclusion de pages ////////////
if (!class_exists('auth')) {
    include_once("../lib/lib_common.php");
    ReloadIndex('admin');
}
////////////

//////////// Check Droits utilisateur ////////////
if (!$l21auth->hasRight('project')) ReloadIndex('admin');
////////////
include_once(override('../level/display.php'));
include_once(override('../project/display.php'));
include_once('../class/class.tag.php');
include_once(override('../vote/display.php'));

// getting tags menu filter
$otag = new tag();
$tags =$otag->getTags('project', -1, false);
$finalities = $GLOBALS ['sql_object']->DBSelect ( SQL_getFinalities ( false ) );
$scales = $GLOBALS ['sql_object']->DBSelect ( SQL_getScales () );
$priorities = $GLOBALS ['sql_object']->DBSelect ( SQL_getPriorities() );
$managers = $sql_object->DBSelect(SQL_getProjectManagersList());
$filter_menu = getMenuFilter($tags, $finalities, $scales, $priorities, $managers);

if(!isset($_GET['statut'])) $statut='public';
else $statut=$_GET['statut'];
/**
// when all status were displayed / before update - @todo remove
if(!isset($_GET['statut']) || $_GET['statut']==-1) $statut=-1;
elseif($_GET['statut']!=-1) $statut=$_GET['statut'];
 * */


if(!isset($_GET['debut'])) $debut=0;
else $debut=$_GET['debut'];

$mask_statut_1='';
$mask_statut_2='';
$mask_statut_3='';
$mask_statut_4='';
if($statut=='public') $mask_statut_1=' selected="selected"';
if($statut=='draft') $mask_statut_2=' selected="selected"';
if($statut=='archives_p') $mask_statut_3=' selected="selected"';
if($statut=='archives_a') $mask_statut_4=' selected="selected"';

$link_statut=$rub_link."&amp;todo=list";
if(isset($_REQUEST['view'])) $link_statut.="&amp;view=".$_REQUEST['view'];
$current_list = $link_statut;
$link_statut.="&amp;statut=";
$link_self=$link_statut.'&amp;statut='.$statut;

// Nombre d'enregistrement total dans la bdd
$result_nb_req=$sql_object->DBSelect($req_count_projects);
$bdd_nb_projects=$result_nb_req[0]['num_rows'];
$bdd_nb_projects_display = $bdd_nb_projects." "._t('project','nb_total')."<br />\n";

$levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
$levels = getLevelChildren($levels, 0); // 0 is parentid

if($statut!=-1) {
    $link_back="<div class=\"filter\"><a href=\"".$current_list."&statut=-1\">"._t('project','all')."</a></div>";
    $req_count_projects=SQL_getCountProjectsList($statut);
    $result_nb_req=$sql_object->DBSelect($req_count_projects);
    $count_request=$result_nb_req[0]['num_rows'];
    //   $req_list_projects=SQL_getProjectsList($debut, 999, $statut);
    //   $projects=$sql_object->DBSelect($req_list_projects);
} else {
    $link_back='';
    $count_request=$bdd_nb_projects;
    //   $req_list_projects=SQL_getProjectsList($debut, 999, $statut);
    //   $projects=$sql_object->DBSelect($req_list_projects);
}

// get total completion by status
$r = $sql_object->DBSelect(SQL_getTotalProjectCompletion($statut));
if(is_array($r) && isset($r[0]['completion'])) $completion_display =  mb_ucfirst(_t('project', 'completion')). ' : ' . round($r[0]['completion'], 0) .' % ';
else $completion_display = '';

$comp = $GLOBALS['sql_object']->DBSelect(SQL_getTotalProjectCompletion('P'));
if(is_array($r) && isset($r[0]['completion'])) $completion_dynamic_display = sprintf('<div id="projects-percentage">'._t('project', 'completion-percentage').'</div>', '<span id="projects-percentage-value">'.round($comp[0]['completion'], 0).'</span>');
else $completion_dynamic_display = '';



if($count_request<=1) $count_request_display = _t('divers','query_result')." : <span id=\"total-count\">".$count_request."</span> "._t('divers','record')."<br />\n";
else $count_request_display = _t('divers','query_result')." : <span id=\"total-count\">".$count_request."</span> "._t('divers','records')."<br />\n";

// Liste des acteurs éditable pour les administrateurs

if ($l21auth->isSuperAdmin ()) {
    
    $actors_list = $sql_object->DBSelect(SQL_getActorsListWithOccurrences());
    
    $actors_content = '<div class="toggle_title" style="margin-top:3em;"><a href="#actors-container" id="modify-actors">' . _t('project','modify_actors') .'</a></div>'.PHP_EOL;
    $actors_content .= '<div id="actors-container" class="contboxwhite">'.PHP_EOL;
    $actors_content .= '<div class="info">' . _t('project','modify_actors_notice') .'</a></div>'.PHP_EOL;
    
    if(is_array($actors_list)) {
        foreach ($actors_list as $a) {
            $actors_content .=  '<div class="c-actors-inline"><div contenteditable="true" id="actor-'.$a['actor_id'].'">'.$a['actor_name'].'</div><span class="occurrences">('.$a['actor_occ'].')</span></div>';
        }
    }
    else {
        $actors_content .=  "<div class=\"info\">" . _t('divers','nodata') . "</div>".PHP_EOL;
    }
    $actors_content .=  "</div>".PHP_EOL;
    
    // we add code to allow inline edition
    $js = "$('#actors-container').hide();
            if (typeof CKEDITOR !== 'undefined') {
        
        				$(\"div[contenteditable='true']\").each(function( index ) {
        
                        var element_id = $(this).attr('id');
                        var arr = element_id.split('-');
                        var actor_id = arr[1];
                        // console.log('project : ' + element_id);
        
        				CKEDITOR.inline( element_id, {
        					 customConfig: 'l21_light_confignoimgur.js', // because imgur make multi-instance bug
                             enterMode : CKEDITOR.ENTER_BR,
        				      on: {
        				        blur: function( event ) {
        				          var data = event.editor.getData();
        				          // alert('Sending: ' + data.length + ' to ' + contrib_id );
        						  if(data.length < 2)  alertify.error('". addslashes(_t('msg', 'update_failed')) ."');
        						  else {
        							$.ajax({type:'POST', url: '".SITE_ROOT_URL."project/_ajax_edit.php', data: { name: data, id: actor_id }, dataType: 'json', success: function(data) {
        								if(data.status==1) {
        									alertify.success(data.msg);
        								} else {
        									alertify.error(data.msg);
        								}
        							}});
        						   }
        				        }
        				      }
        					});
						});
        			}";
    footerAddInlineJS($js, 'first');
}


// Liste des statuts disponibles
$select_statut="<select name=\"statut_filter\" id=\"statut_filter\">\n";
$select_statut.="<option value=\"-1\">"._t('project','statut_filter')."</option>\n";
$select_statut.="<option value=\"".$link_statut."public\"".$mask_statut_1.">".display_statut('P')."</option>\n";
$select_statut.="<option value=\"".$link_statut."draft\"".$mask_statut_2.">".display_statut('D')."</option>\n";
$select_statut.="<option value=\"".$link_statut."archives_p\"".$mask_statut_3.">".display_statut('PA')."</option>\n";
$select_statut.="<option value=\"".$link_statut."archives_a\"".$mask_statut_4.">".display_statut('AA')."</option>\n";
$select_statut.="</select>\n";

$js = "	$('#statut_filter').change(function() {
					if($(this).val() != -1) window.location = $(this).val();
				});";

footerAddInlineJS($js);

?>
<script>

function compute_values() {

	var total_progression = 0;
	var total_counter = 0;
	
	// compute total progression by finality
	$('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("td.project-progression span").each(function(index) {
			
			// only for visible elements
			if($(this).closest('tr').is(":visible")) {
				// console.log($(this).closest('tr').is(":visible"));
				var value = $(this).attr('data-progression');
				counter++;
				total_counter++;
			} else {
				var value = 0;
			}

			// add only if the value is number
			if(!isNaN(value) && value.length != 0) {
				sum += parseFloat(value);
				total_progression += 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', '<?php echo mb_ucfirst(_t('project', 'completion')); ?> : ' + mean + ' %');
		// @todo @simo the tooltip has been removed because code is not compatible with hint.css
		// tippy.js (https://atomiks.github.io/tippyjs/) is an option but to heavy 
		// just in case, tippy.js has to be included at the bottom of the page
		// tippy('#progressbar-' + currentId, {        content: '<?php echo mb_ucfirst(_t('project', 'completion')); ?> : ' + mean + ' %'});
		
	});
	// console.log('total_progression : ' + total_progression);
	// console.log('total_counter : ' + total_counter);
	$('#projects-percentage-value').html(Math.round(total_progression / total_counter)).hide().fadeIn('slow');

	// we iterate on levels. We can add more if needed
	var levels = {0:1, 1:2};
	for (i in levels) {
		$('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("td.project-progression span").each(function(index) {	
		
					// only for visible elements
					if($(this).closest('tr').is(":visible")) {
						var value = $(this).attr('data-progression');
						counter++;
					} else {
						var value = 0;
					}
					// 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('<?php echo mb_ucfirst(_t('project', 'completion')); ?> : ' + mean + ' %').hide().fadeIn('slow');
			
		});
	}

	// on the fly filter selection
	$( '#current-sel' ).html('<?php echo _t('divers', 'n_selected'); ?>'.replace("#", total_counter).replace("%", $('#total-count').text())).hide().fadeIn('slow');
}
</script>
<?php 


function get_list_by_finality($statut) {
	
	global $l21auth;
	global $sql_object;
	
	// begin with an empty html string
	$html = '';
	$rub_link = "index.php?rub=project";
	$link_sup=$rub_link."&amp;todo=sup&amp;id=";
	$link_mod=$rub_link."&amp;todo=mod&amp;id=";
	$link_det=$rub_link."&amp;todo=det&amp;id=";
	$link_statut=$rub_link."&amp;todo=list&amp;view=finality&amp;statut=";
	$link_self=$link_statut.$statut;
	
	
	if (! defined ( 'PROJECT_FINALITIES' ) || PROJECT_FINALITIES == 0) return false;
		// we get all values
	$finalities = $GLOBALS ['sql_object']->DBSelect ( SQL_getFinalities ( false ) );
	
	if (! isset ( $finalities [0] ['finality_id'] )) return false;
	
	
	foreach ( $finalities as $finality ) {
		
		$title = '<h2 class="byfinality mtl">' . $finality ['finality_name'] . '</h2>' . PHP_EOL;
		
		$html .= '<div class="row flex-container header-level-0">';
		$html .= '<div class="col w80 title-level-0" id="title-level-0-'.$finality ['finality_id'].'">' . $title . '</div>';
		$html .= '<div class="col w20 sum-level-0" id="sum-level-0-'.$finality ['finality_id'].'"></div>';
		$html .= '</div>';
		$html .='<div class="progressbar-finality" id="progressbar-level-0-'.$finality ['finality_id'].'"><div style="width:0%"><span data-progression=""></span></div></div>';		
		$html .= '<div class="level-0 mtl" id="level-0-'.$finality ['finality_id'].'">';

		
		$projects = $GLOBALS ['sql_object']->DBSelect ( SQL_getProjectsList ( 0, 999, $statut, 'FINALITY', $finality['finality_id'] ) );
		
		if (isset ( $projects [0] ['complete_project_name'] )) {
			
			$html .= "<table class=\"sortable multisort level-0\" id=\"sort-table-level-0\">\n";
			$html .= "<thead>\n";
			$html .= "<tr>\n";
			$html .= "<td>" . mb_ucfirst ( _t ( 'project', 'name' ) ) . "</td>\n";
			if(voteEnabled('project')) {
			    $html .= "<td>" . mb_ucfirst(_t('like', 'likes')) . "</td>\n";
			}
			$html .= "<td class=\"project-priority\">" . mb_ucfirst ( _t ( 'project', 'priority' ) ) . "</td>\n";
            $html .= "<td class=\"project-achievement\">".mb_ucfirst(_t('project','achievement'))."</td>\n";
			$html .= "<td>" . mb_ucfirst ( _t ( 'project', 'progression' ) ) . "</td>\n";
			$html .= "<td>" . mb_ucfirst ( _t ( 'divers', 'date_crea' ) ) . "</td>\n";
			// $html .= "<td>".cutText(mb_ucfirst(_t('divers','date_publi')), 13, 1, '')."</td>\n";
			$html .= "<td class=\"sorter-false\">&nbsp;<span class=\"visually-hidden\">" . mb_ucfirst ( _t ( 'divers', 'actions' ) ) . "</span></td>\n";
			$html .= "</tr>\n";
			$html .= "</thead>\n";
			
			$html .= "<tbody class=\"filter-items\">\n";
			
			for($i = 0; $i < count ( $projects ); $i ++) {
				$project_name = formatText ( cutText ( $projects [$i] ['complete_project_name'], 70 ), '2HTML' );
				$complete_project_name = $projects [$i] ['complete_project_name'];
				$project_owner = $projects [$i] ['project_posted_by'];
				$project_statut = $projects [$i] ['project_statut'];
				$project_published_date = $project_statut == 'D' ? _t ( 'statut', 'draft' ) : $projects [$i] ['project_published_date_display'];

                $project_achievement_badge = empty($projects[$i]['project_achievement']) ? empty_nc('') : '<span class="p-achievement-badge '.$projects[$i]['project_achievement'] .'">' .$GLOBALS['lang']['project']['achievementItems'][$projects[$i]['project_achievement']] .'</span>';
                $project_achievement_filter = empty($projects[$i]['project_achievement']) ? '0' : $projects[$i]['project_achievement'];
				
				// we get managers
				$manager = getAssociatedManagers($projects[$i]['project_id']);
				
				// getting votes number
				if(voteEnabled('project')) {
				    $nbVotes = getNbVotes(array('module' => 'project', 'module_id' => $projects [$i] ['project_id']));
				}
				
				// getting tags
				$otag = new tag ();
				$display_tags = $otag->getTags ( 'project', $projects [$i] ['project_id'], true, ';' );
				
				// getting finalities
				$display_finalities = get_finalities($projects[$i]['project_id'], true, ';');
				
				if($projects [$i] ['project_parent_id'] != 0)  {
				    $class='sub-project';
				    $parentName = '[' . mb_ucfirst(_t('project','parent')) . ' : ' . $projects [$i] ['parent_project_name'] . ']';
				} else {
				    $class = 'project';
				    $parentName = '';
				}
				
				if($l21auth->isProjectManager($l21auth->GetSessionElement( 'id' ), $sql_object, $projects[$i]['project_id'])) $pclass = 'is-mine'; else $pclass = 'is-not-mine';
				
				$html .= "<tr class=\"".$pclass."\" id=\"project-" . $projects [$i] ['project_id'] . "\" data-id=\"" . $projects [$i] ['project_id']. "\" data-manager=\"".getAssociatedManagers($projects [$i] ['project_id'], true)."\" data-completion=\"" . $projects [$i] ['project_completed'] . "\" data-priorities=\"" . $projects [$i] ['priority_name'] . "\" data-tags=\"" . $display_tags . "\" data-finalities=\"".$display_finalities."\" data-scales=\"".$projects[$i]['scale_denomination']."\" data-achievement=\"".$project_achievement_filter."\">\n";
				$html .= "<td class=\"project-name\">";
				$html .= "<a class=\"".$class."\" href=\"".$link_det.$projects[$i]['project_id']."\" title=\""._t('project','det')." ".formatText($complete_project_name, '2ATT'). ' ' . formatText($parentName, '2ATT') . ' // '  . mb_ucfirst(_t('project','manager')) . ' : ' . formatText(empty_nc($manager), '2ATT') ."\">".$project_name."</a>";
				if(!empty($display_tags)) $html .= "<i class=\"fa fa-tag\" aria-hidden=\"true\" style=\"opacity:0.3;margin:0\" title=\"" . formatText ( $display_tags, '2ATT' ) . "\"></i>\n";
				$html .= "</td>\n";
				if(voteEnabled('project')) {
				    $html .= "<td class=\"project-votes\">".$nbVotes."</td>";
				}
				$html .= "<td class=\"project-priority\">" . $projects [$i] ['priority_name'] . "</td>\n";
                $html .= "<td class=\"project-achievement\">".$project_achievement_badge."</td>\n";
				$html .= "<td class=\"project-progression\"><div class=\"progressbar\" 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></td>\n";
				$html .= "<td class=\"project-date\">" . $projects [$i] ['project_date_crea_display'] . "</td>\n";
				// $html .= "<td>".$project_published_date."</td>\n";
				$html .= "<td  class=\"project-actions\">\n";
				if ($l21auth->isProjectManager ( $l21auth->GetSessionElement ( 'id' ), $sql_object, $projects [$i] ['project_id'] ) || $l21auth->isSuperAdmin ()) {
					$html .= "<div class=\"iconetab\">\n";
					if ($l21auth->isSuperAdmin ()) {
						$html .= "<a href=\"" . $link_sup . $projects [$i] ['project_id'] . "\" class=\"ico_sup\" title=\"" . _t ( 'project', 'sup' ) . "\"><i class=\"fa fa-trash\"></i><span>" . _t ( 'project', 'sup' ) . "</span></a>\n";
					}
					$html .= "<a href=\"" . $link_mod . $projects [$i] ['project_id'] . "\" class=\"ico_mod\" title=\"" . _t ( 'project', 'mod' ) . "\"><i class=\"fa fa-pencil-square-o\"></i><span>" . _t ( 'project', 'mod' ) . "</span></a>\n";
					
					$html .= "</div>\n";
				}
				$html .= "</td>\n";
				$html .= "</tr>\n";
			}
			
			$html .= "</tbody>";
			$html .= "</table>";
		} else {
			$html .= "<div class=\"info\">"._t('project','noresult')."</div>";
		}
		
		$html .= '</div>';
		
		
	}
	return $html;
	
}
/**
 * get_flat_list()
 * return flat list of projects
 * @param array $result_projects_list
 */
function get_flat_list($status) {
	
	global $l21auth;
	global $sql_object;
	

	$projects=$sql_object->DBSelect(SQL_getProjectsList(0, 999, $status));
	
	$html = '';
	$rub_link = "index.php?rub=project";
	$link_sup=$rub_link."&amp;todo=sup&amp;id=";
	$link_mod=$rub_link."&amp;todo=mod&amp;id=";
	$link_det=$rub_link."&amp;todo=det&amp;id=";
	
	$finality ['finality_id'] = '1';
	
	$html .= '<div class="row flex-container header-level-0">';
	$html .= '<div class="col w80 title-level-0" id="title-level-0-all">&nbsp;</div>';
	$html .= '<div class="col w20 sum-level-0" id="sum-level-0-all"></div>';
	$html .= '</div>';
	$html .='<div class="progressbar-finality"  id="progressbar-level-0-all"><div style="width:0%"><span data-progression=""></span></div></div>';
	
	$html .= '<div class="level-0 mtl" id="level-0-all">';
	
	if(isset($projects[0]['project_posted_by'])) {
		
		$html .="<table class=\"sortable multisort\" id=\"sort-table\">\n";
		$html .="<thead>\n";
		$html .="<tr>\n";
		$html .="<td>".mb_ucfirst(_t('project','name'))."</td>\n";
		if(voteEnabled('project')) {
		    $html .= "<td>" . mb_ucfirst(_t('like', 'likes')) . "</td>\n";
		}
		$html .= "<td class=\"project-priority\">".mb_ucfirst(_t('project','priority'))."</td>\n";
        $html .= "<td class=\"project-achievement\">".mb_ucfirst(_t('project','achievement'))."</td>\n";
		$html .= "<td>".mb_ucfirst(_t('project','progression'))."</td>\n";
		$html .= "<td>".mb_ucfirst(_t('divers','date_crea'))."</td>\n";
		// $html .="<td>".cutText(mb_ucfirst(_t('divers','date_publi')), 13, 1, '')."</td>\n";
		$html .= "<td class=\"sorter-false\">&nbsp;<span class=\"visually-hidden\">".mb_ucfirst(_t('divers','actions'))."</span></td>\n";
		$html .= "</tr>\n";
		$html .= "</thead>\n";
	
		$html .="<tbody class=\"filter-items\">\n";
	
	
		for($i=0; $i<count($projects); $i++) {
			 
			$project_name=formatText(cutText($projects[$i]['complete_project_name'],70), '2HTML');
			$complete_project_name = $projects[$i]['complete_project_name'];
			$project_owner=$projects[$i]['project_posted_by'];
			$project_statut=$projects[$i]['project_statut'];
			$project_published_date = $project_statut=='D' ? _t('statut','draft') : $projects[$i]['project_published_date_display'];

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

			// we get managers
			$manager = getAssociatedManagers($projects [$i] ['project_id']);
			
			// getting votes number
			if(voteEnabled('project')) {
			    $nbVotes = getNbVotes(array('module' => 'project', 'module_id' => $projects [$i] ['project_id']));
			}
			
			if($projects [$i] ['project_parent_id'] != 0)  {
			    $class='sub-project';
			    $parentName = '[' . mb_ucfirst(_t('project','parent')) . ' : ' . $projects [$i] ['parent_project_name'] . ']';
			} else {
			    $class = 'project';
			    $parentName = '';
			}

			// we display only wanted status
			if($status == -1 || $project_statut == get_sql_status($status)) {
				// getting tags
				$otag = new tag();
				$display_tags =$otag->getTags('project',  $projects[$i]['project_id'], true, ';' );
				
				// getting finalities
				$display_finalities = get_finalities($projects[$i]['project_id'], true, ';');
				
				if($l21auth->isProjectManager($l21auth->GetSessionElement( 'id' ), $sql_object, $projects[$i]['project_id'])) $pclass = 'is-mine'; else $pclass = 'is-not-mine';
		
				$html .="<tr class=\"".$pclass."\" id=\"project-".$projects[$i]['project_id']."\" data-id=\"".$projects[$i]['project_id']. "\" data-completion=\"" . $projects [$i] ['project_completed'] . "\" data-manager=\"".getAssociatedManagers($projects [$i] ['project_id'], true)."\" data-priorities=\"" . $projects [$i] ['priority_name'] ."\" data-tags=\"".$display_tags."\" data-finalities=\"".$display_finalities."\" data-scales=\"".$projects[$i]['scale_denomination']."\" data-achievement=\"".$project_achievement_filter."\">\n";
				$html .="<td><a class=\"".$class."\" href=\"".$link_det.$projects[$i]['project_id']."\" title=\""._t('project','det')." ".formatText($complete_project_name, '2ATT'). ' ' . formatText($parentName, '2ATT') . ' // '  . mb_ucfirst(_t('project','manager')) . ' : ' . formatText(empty_nc($manager), '2ATT') ."\">".$project_name."</a>";
				if(!empty($display_tags))  $html .= "<i class=\"fa fa-tag\" aria-hidden=\"true\" style=\"opacity:0.3;margin:0\" title=\"".formatText($display_tags, '2ATT')."\"></i>";
				$html .= "</td>\n";
				if(voteEnabled('project')) {
				    $html .= "<td class=\"project-votes\">".$nbVotes."</td>";
				}
				$html .="<td class=\"project-priority\">".$projects[$i]['priority_name']."</td>\n";
                $html .= "<td class=\"project-achievement\">".$project_achievement_badge."</td>\n";
				$html .="<td class=\"project-progression\"><div class=\"progressbar\" 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></td>\n";
				
				$html .="<td>".$projects[$i]['project_date_crea_display']."</td>\n";
				//     $html .="<td>".$project_published_date."</td>\n";
				$html .="<td style=\"width:80px\">\n";
				if ($l21auth->isProjectManager($l21auth->GetSessionElement('id'), $sql_object, $projects[$i]['project_id']) || $l21auth->isSuperAdmin()) {
					$html .="<div class=\"iconetab\">\n";
					if ($l21auth->isSuperAdmin()) {
						$html .="<a href=\"".$link_sup.$projects[$i]['project_id']."\" class=\"ico_sup\" title=\""._t('project','sup')."\"><i class=\"fa fa-trash\"></i><span>" . _t('project','sup') . "</span></a>\n";
					}
					$html .="<a href=\"".$link_mod.$projects[$i]['project_id']."\" class=\"ico_mod\" title=\""._t('project','mod')."\"><i class=\"fa fa-pencil-square-o\"></i><span>" . _t('project','mod') . "</span></a>\n";
		
					$html .="</div>\n";
				} else $html .='';
				$html .="</td>\n";
				$html .="</tr>\n";
			}
		}
	
		$html .="</tbody>";
		$html .="</table>";
		
	} else {
		$html .="<div class=\"info\">"._t('project','noresult')."</div>";
	}
	$html .="</div>";
	
	return $html;
	
}


/**
 * 
 * @param array $data
 * @param string $statut
 * @param string $filter
 * @param integer $id_filter
 * @param integer $depth
 * @return string
 */
function generate_html_recursive($data, $statut, $filter, $id_filter, $depth)
{
	global $l21auth;
	global $sql_object;
	
	// begin with an empty html string
	$html = '';
	$rub_link = "index.php?rub=project";
	$link_sup=$rub_link."&amp;todo=sup&amp;id=";
	$link_mod=$rub_link."&amp;todo=mod&amp;id=";
	$link_det=$rub_link."&amp;todo=det&amp;id=";
	$link_statut=$rub_link."&amp;todo=list&amp;statut=";
	$link_self=$link_statut.$statut;

	// 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;
		}
		
		// we prepare timeline if needed only
		$timeline = get_timeline_info();
		
		if(is_array($timeline) && $depth == $timeline['depth']) {
		    $timelineLink = '<a href="../project/_ajax_timeline.php?id='. $item['level_id'].'" class="display-timeline"><span class="fa-stack fa-lg"><i class="fa fa-circle fa-stack-2x"></i><i class="fa fa-calendar fa-stack-1x fa-inverse"></i></span></a>';
		} else $timelineLink ='';
		
		
		echo '<script>
    		$(document).ready(function(){
    		    $(".display-timeline").colorbox({ 
					maxWidth: "90%", 
					maxHeight: "80%",
					innerWidth: "90%",
					innerHeight: "80%", 
					fixed: true,
					iframe: true, 
					href: function(){
						var url = $(this).attr("href");
						return url;
					}
				});
                var cboxOptions = { width: "80%", height: "80%", maxWidth: "960px", maxHeight: "800px" }
    		    jQuery(window).resize(function(){ $.colorbox.resize({ width: window.innerWidth > parseInt(cboxOptions.maxWidth) ? cboxOptions.maxWidth : cboxOptions.width, height: window.innerHeight > parseInt(cboxOptions.maxHeight) ? cboxOptions.maxHeight : cboxOptions.height }); });
    		});
    		    </script>';
    		    
  


		// we display link only on main levels
		$link_level = 'index.php?rub=level&amp;todo=det&amp;id='. $item['level_id'];
		
		if(!empty($item['level_code'])) $code = ' ['.$item['level_code'].'] '; else $code = '';
		$level_label = $item['level_name'] . $code;
		
		$title = '<h'.($depth+2).' class="bylevels" id="title-level-'.$item['level_id'].'"><a href="' . $link_level . '" title="' . formatText($item['level_name'], '2ATT') . '">' . formatText($level_label, '2HTML') . '</a></h'.($depth+2).'>' . PHP_EOL;
		
		$html .='<div class="row flex-container header-level-' . $depth .'">';
		if(!empty($timelineLink)) {
			$html .='<div class="col w50p timeline-link">'.$timelineLink.'</div>';
		}
		$html .='<div class="col item-fluid title-level-' . $depth .' title-level-'.$depth.'-'.$item['level_id'].'" id="title-level-'.$depth.'-'.$item['level_id'].'">'. $title.'</div>';
    	$html .='<div class="col w20 sum-level-' . $depth .' title-level-'.$depth.'-'.$item['level_id'].'" id="sum-level-'.$depth.'-'.$item['level_id'].'"></div>';
		$html .='</div>';
		
		if($item['level_parent'] == 0) {
			$html .='<div class="progressbar-finality"  id="progressbar-level-'.$depth.'-'.$item['level_id'].'"><div style="width:0%"><span data-progression=""></span></div></div>';
		}

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

		$projects = $GLOBALS['sql_object']->DBSelect(SQL_getProjectsList(0, 999, $statut, 'LEVEL', $item['level_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(isset($projects[0]['complete_project_name'])) {
		
		 $html .= "<table class=\"sortable multisort level-".$item['level_id']."\" id=\"sort-table-level-".$item['level_id']."\">\n";
		 $html .= "<thead>\n";
		 $html .= "<tr>\n";
		 $html .= "<td>".mb_ucfirst(_t('project','name'))."</td>\n";
		 if(voteEnabled('project')) {
		     $html .= "<td>" . mb_ucfirst(_t('like', 'likes')) . "</td>\n";
		 }
		 $html .= "<td class=\"project-priority\">".mb_ucfirst(_t('project','priority'))."</td>\n";
         $html .= "<td class=\"project-achievement\">".mb_ucfirst(_t('project','achievement'))."</td>\n";
		 $html .= "<td>".mb_ucfirst(_t('project','progression'))."</td>\n";
		 $html .= "<td>".mb_ucfirst(_t('divers','date_crea'))."</td>\n";
		  //$html .= "<td>".cutText(mb_ucfirst(_t('divers','date_publi')), 13, 1, '')."</td>\n";
		 $html .= "<td class=\"sorter-false\">&nbsp;<span class=\"visually-hidden\">".mb_ucfirst(_t('divers','actions'))."</span></td>\n";
		 $html .= "</tr>\n";
		 $html .= "</thead>\n";
		
		 $html .= "<tbody class=\"filter-items\">\n";
	
	
	  	for($i=0; $i<count($projects); $i++) {
		    $project_name=formatText(cutText($projects[$i]['complete_project_name'],70), '2HTML');
		    $complete_project_name = $projects[$i]['complete_project_name'];
		    $project_owner=$projects[$i]['project_posted_by'];
		    $project_statut=$projects[$i]['project_statut'];
		    $project_published_date = $project_statut=='D' ? _t('statut','draft') : $projects[$i]['project_published_date_display'];

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

		    // we get managers
		    $manager = getAssociatedManagers($projects [$i] ['project_id']);
		    
		    // getting votes number
		    if(voteEnabled('project')) {
		        $nbVotes = getNbVotes(array('module' => 'project', 'module_id' => $projects [$i] ['project_id']));
		    }
		    
		    // getting tags
		    $otag = new tag();
		    $display_tags = $otag->getTags('project',  $projects[$i]['project_id'], true, ';' );
		    
		    // getting finalities
		    $display_finalities = get_finalities($projects[$i]['project_id'], true, ';');
		    
		    if($projects [$i] ['project_parent_id'] != 0)  {
		      $class='sub-project'; 
		      $parentName = '[' . mb_ucfirst(_t('project','parent')) . ' : ' . $projects [$i] ['parent_project_name'] . ']';
		    } else { 
		      $class = 'project';
		      $parentName = '';
		    }
		    if($l21auth->isProjectManager($l21auth->GetSessionElement( 'id' ), $sql_object, $projects[$i]['project_id'])) $pclass = 'is-mine'; else $pclass = 'is-not-mine';
		    
		    $html .= "<tr class=\"".$pclass."\" id=\"project-".$projects[$i]['project_id']."\" data-id=\"".$projects[$i]['project_id']. "\" data-completion=\"" . $projects [$i] ['project_completed'] . "\" data-manager=\"".getAssociatedManagers($projects [$i] ['project_id'], true)."\" data-priorities=\"" . $projects [$i] ['priority_name'] ."\" data-tags=\"".$display_tags."\" data-finalities=\"".$display_finalities."\" data-scales=\"".$projects[$i]['scale_denomination']."\" data-achievement=\"".$project_achievement_filter."\">\n";
		    $html .= "<td class=\"project-name\"><a class=\"".$class."\" href=\"".$link_det.$projects[$i]['project_id']."\" title=\""._t('project','det')." ".formatText($complete_project_name, '2ATT'). ' ' . formatText($parentName, '2ATT') . ' // '  . mb_ucfirst(_t('project','manager')) . ' : ' . formatText(empty_nc($manager), '2ATT') ."\">".$project_name."</a>";
		    if(!empty($display_tags))  $html .= "<i class=\"fa fa-tag\" aria-hidden=\"true\" style=\"opacity:0.3;margin:0\" title=\"".formatText($display_tags, '2ATT')."\"></i>";
		    $html .= "</td>\n";
		   if(voteEnabled('project')) {
		       $html .= "<td class=\"project-votes\">".$nbVotes."</td>";
		   }
		   $html .= "<td class=\"project-priority\">".$projects[$i]['priority_name']."</td>\n";
           $html .= "<td class=\"project-achievement\">".$project_achievement_badge."</td>\n";
		   $html .= "<td class=\"project-progression\"><div class=\"progressbar\" 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></td>\n";
		   $html .= "<td class=\"project-date\">".$projects[$i]['project_date_crea_display']."</td>\n";
		//    $html .= "<td>".$project_published_date."</td>\n";
		   $html .= "<td  class=\"project-actions\">\n";
		    if ($l21auth->isProjectManager($l21auth->GetSessionElement('id'), $sql_object, $projects[$i]['project_id']) || $l21auth->isSuperAdmin()) {
		     $html .= "<div class=\"iconetab\">\n";
		      if ($l21auth->isSuperAdmin()) {
		      	$html .=  "<a href=\"".$link_sup.$projects[$i]['project_id']."\" class=\"ico_sup\" title=\""._t('project','sup')."\"><i class=\"fa fa-trash\"></i><span>" . _t('project','sup') . "</span></a>\n";
		      }
		     $html .= "<a href=\"".$link_mod.$projects[$i]['project_id']."\" class=\"ico_mod\" title=\""._t('project','mod')."\"><i class=\"fa fa-pencil-square-o\"></i><span>" . _t('project','mod') . "</span></a>\n";
		      
	      	$html .=  "</div>\n";
	    	}
	   		$html .= "</td>\n";
	    	$html .= "</tr>\n";
	  	}
	
		  $html .=  "</tbody>";
		  $html .=  "</table>";
		}
		
		// 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);
		
		$html .= '</div>';

	}

	// return the resulting html
	return $html;
}


?>
<div id="chemin">
<ul>
	<li><a href="index.php" class="chemin_home"><?php echo _t('way','home'); ?></a></li>
	<li><a href="<?php echo $rub_link; ?>" id="chemin_<?php echo $rub; ?>" class="chemin_rub"><?php echo _t('menu','project'); ?></a></li>
	<li><span><?php echo formatNavTitle(_t('project','list')); ?></span></li>
</ul>
</div>
<!--end barre haute -->

<div class="contentcontainer"><?php	include_once(override($dir.'/menurub.php', THEME_ADMIN_PATH));	?>
<div id="content"><?php

echo getInternalNav();

echo $link_back;
?>
<div class="filterselect"><?php echo $select_statut; ?>
</div>
<p>
<?php
echo $bdd_nb_projects_display;
echo $count_request_display;
echo $completion_display;
?></p>
<p><a href="#" id="my-projects"><i class="fa fa-archive" aria-hidden="true"></i> <span><?php echo mb_ucfirst(_t('project', 'mine')); ?></span></a></p>
<script>
	var mineFlag = false;
    $('#my-projects').on("click", function(){
		if(mineFlag == false) {
			$('tr.is-mine').show();
			$('tr.is-not-mine').fadeOut();
			setTimeout(function() { compute_values(); }, 1000);
			mineFlag = true;
			$('#my-projects span').html('<?php echo mb_ucfirst(_t('project', 'all')); ?>').parent().addClass('filtered');
			
		} else {
			$('tr.is-mine,tr.is-not-mine').fadeIn();
			setTimeout(function() { compute_values(); }, 1000);
			mineFlag = false;
			$('#my-projects span').html('<?php echo mb_ucfirst(_t('project', 'mine')); ?>').parent().removeClass('filtered');
		}
        
        return false;
    });
</script>
<?php echo $filter_menu; ?>
		
<?php

echo $completion_dynamic_display;
?>

<p id="current-sel"></p>

<?php
// which list to display ?
if(!isset($_REQUEST['view'])) echo generate_html_recursive($levels, $statut, 'LEVEL', 0, 0);
if(isset($_REQUEST['view']) && $_REQUEST['view'] == 'flat') echo get_flat_list($statut);

if(isset($_REQUEST['view']) && $_REQUEST['view'] == 'finality') echo get_list_by_finality($statut);

if ($l21auth->isSuperAdmin()) echo $actors_content;

// Ability to sort table
addDynamicCSS('../lib/js/jquery.tablesorter/theme.default.css');
footerAddJS('../lib/js/jquery.tablesorter/jquery.tablesorter.min.js');
$str = '$("table.multisort").tablesorter({	});';
footerAddInlineJS($str);
?>

<?php
// Animate progression bar
if(defined('ANIMATE_PROGRESS') && ANIMATE_PROGRESS == 1) {
footerAddJS('../lib/js/waypoints/lib/jquery.waypoints.min.js');
?>
<script>
		$(document).ready(function() {
			
			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 = $('table td.project-progression div.progressbar > 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));
			}
			
			// we compute progression values grouped by finalities
			// compute_values();
			
			/**
			* Animate anyway - Method B
			*/
// 			$('table td.project-progression div.progressbar > div').each(function(index) {
// 				animate_progress($(this));
// 			});



		});
		</script>
<?php } ?>



<?php

footerAddInlineJS('compute_values(); // we compute progression values grouped by finalities');
		
// Ability to drag'n drop items
if ($l21auth->isSuperAdmin()) {
	footerAddJS('../lib/js/TableDnD/dist/jquery.tablednd.1.0.5.min.js');
	dragTableSettings();
}
?>
</div> <!-- closing #content -->
</div> <!-- closing .contentcontainer -->