<?php namespace ProcessWire;

/**
 * /site/templates/_func.php
 * 
 * Example of shared functions used by template files
 *
 * This file is currently included by _init.php 
 *
 * For more information see README.txt
 *
 */

// We refer to our homepage a few times in our site, so we preload a copy 
// here in a $homepage variable for convenience. 
$homepage = $pages->get('/'); 
 

/**
* Builds a nested list (menu items) of a single menu.
* 
* A recursive function to display nested list of menu items.
*
* @access private
* @param Int $parent ID of menu item.
* @param Array $menu Object of menu items to display.
* @param Int $first Helper variable to designate first menu item.
* @return string $out.
*
*/
function buildMenuFromObject($parent = 0, $menu, $first = 0) {
  if(!is_object($menu)) return;

  $out = '';
  $has_child = false;

  foreach ($menu as $m) {
    $newtab = $m->newtab ? " target='_blank'" : '';            
    // if this menu item is a parent; create the sub-items/child-menu-items
    if ($m->parentID == $parent) {// if this menu item is a parent; create the inner-items/child-menu-items
        // if this is the first child
        if ($has_child === false) {                    
            $has_child = true;// This is a parent                        
            if ($first == 0){                            
              $out .= "<ul id=jetmenu class='jetmenu blue'>\n";                            
              $first = 1;
            }                        
            else $out .= "\n<ul class='dropdown'>\n";
        }

        $class = $m->isCurrent ? ' class="active"' : '';

        // a menu item
        $out .= '<li' . $class . '><a href="' . $m->url . '"' . $newtab . '>' . $m->title;                    
        // if menu item has children
        if ($m->isParent) {
          $out .= '</a>';
        }
        
        else $out .= '</a>';         

        // call function again to generate nested list for sub-menu items belonging to this menu item. 
        $out .= buildMenuFromObject($m->id, $menu, $first);
        $out .= "</li>\n";

    }// end if parent
  
  }// end foreach

  if ($has_child === true) $out .= "</ul>\n";    

  return $out;

}

// Returns a shorten string, parameter is max. characters
function shortText($description, $max_length = 240) {
  $the_description = strip_tags($description);
  if (strlen($the_description) > $max_length && preg_match('#^\s*(.{'. $max_length . ',}?)[,.\s]+.*$#s', $the_description, $matches)) {
    return $matches[1];
  } else {
    return $the_description;
  }
}

