<?php
class JElementItemId extends JElement
{
   var $_name = 'ItemId';
   var $options = array();
   var $menutype = '';
	// $parent is the parent of the children we want to see
	// $level is increased when we go deeper into the tree,
	//        used to display a nice indented tree
	function display_children($parent, $level ) {
		// retrieve all children of $parent
		$db =& JFactory::getDBO();

		$query = 'SELECT #__menu.id, #__menu.name as title, #__menu.parent, #__menu.menutype  
	            FROM #__menu, #__menu_types 
				WHERE parent='.$parent.' AND 
					  #__menu.menutype = #__menu_types.menutype AND 
					  #__menu.published=1 AND 
					  #__menu.componentid IN ( SELECT id 
												FROM #__components 
												WHERE published=1 ) 
												ORDER BY #__menu.menutype, #__menu_types.id, ordering, parent';
		
		$result = $db->setQuery( $query );
		$rows = $db->loadObjectList();

		// display each child
		foreach ($rows as $row) {
			if ($row->menutype != $this->menutype) {
				$this->options[] = JHTML::_('select.optgroup', $row->menutype);
				$this->menutype = $row->menutype;
			}
			
			$row->title = str_repeat('-',$level).$row->title;
			$this->options[] = JHTML::_('select.option', $row->id, $row->title);
			
			// call this function again to display this
			// child's children
			$this->display_children($row->id, $level+1);
	   }
	}    

   function fetchElement($name, $value, &$node, $control_name)
   {
	  $this->display_children(0, 0);

      $size = ( $node->attributes('size') ? $node->attributes('size') : 5 );
      return JHTML::_('select.genericlist',  $this->options, ''.$control_name.'['.$name.'][]',  ' multiple="multiple" size="' . $size . '" class="inputbox"', 'value', 'text', $value, $control_name.$name);
   }
}
?>