<?php if (!defined('PmWiki')) exit();
/*  
 	Copyright 2007 Jens Schiffler, (jens dot schiffler ÃĪt gmx dÃķt de)
	based on work by Patrick R. Michaud (pmichaud@pobox.com) 
    This file is jjs_trailmenu_3.php;  you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published
    by the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.  See pmwiki.php for full details.
*/

SDV($FPLFunctions['trailmenu'], 'FPLTrailMenu');

function get_match_index(&$pagename, &$matches)
{
	foreach($matches as $idx => $page)
	{
		if ($page['pagename'] == $pagename)
		{
			return $idx;
		}
	}
	return false;
}

function &get_parent_indices($pidx, &$matches)
{	
	$a_idx = array(); 
		
	while (!(NULL == $pidx))
	{
		if (@isset($matches[$pidx]['parent'])) 
		{
			$pidx = $matches[$pidx]['parent'];			
			$a_idx[] = $pidx;
		}
		else
		{
			$pidx = NULL;			
		}
	}
	
	return $a_idx;
}

function FPLTrailMenu($pagename, &$matches, $opt) 
{
  global $FPLTrailMenuOpt;
  SDVA($FPLTrailMenuOpt, array('readf' => 0));
  $matches = MakePageList($pagename, array_merge($FPLTrailMenuOpt,(array)$opt));
  // mark path to selected item
  $selidx = get_match_index($pagename, $matches);
  $pl = array($selidx);  
  while (count($pl)>0) 
  {
    $p = array_shift($pl);
    @$ancestors[$p]++;
    $pns = get_parent_indices($p, $matches);
        
    foreach($pns as $pa)
    {
      if (!$ancestors[$pa]) $pl[] = $pa;
             
    }  
  }
   
  @$topparent = array_pop($pns); # last element of any parent list is root node
  
  // return top level elements plus marked path
  foreach($matches as $pidx => $pc) 
  {
	if ($ancestors[$pc['parent']] || (1 == $pc['depth']))
	{
		if ($pidx == $topparent)
		{
			$hl = ' %item highlight%';
		}
		else
		{
			$hl = '';
		}
		if (stristr($pc['markup'], 'Main.MenuSpacer'))
		{
			$out[] = str_repeat('*', $pc['depth']) . " %item space% " . chr(160) . "\n";
		}
		else
		{
			$out[] = str_repeat('*', $pc['depth']) . $hl . " {$pc['markup']}\n";
		}
	}
  }
  
  return implode('', $out);
}