<?php
defined('JPATH_BASE') or die;

jimport('joomla.html.html');
jimport('joomla.form.formfield');

class JFormFieldIcategory extends JFormField
{
	protected $type = 'Icategory';

	protected function getInput()
	{
		$option = JRequest::getVar('option');
		if($option == 'com_config')
		{
			$params =& JComponentHelper::getParams('com_igallery'); 
			$selected = $params->get('default_parent', 0);
			$where = '';
		}
		else if($option == 'com_menus')
		{
			$selected = $this->value;
			$where = '';
		}
		else if(strpos($option, 'module') )
		{
			$igparams = $this->form->getValue('params');
			$selected = isset($igparams->category_id) ? $igparams->category_id : 0;
			$where = '';
		}
		else
		{
			$selected = $this->form->getValue('parent');
			$current = JRequest::getInt('id',0);
			$where = 'WHERE id != '.(int)$current;
		} 
		
		$db =& JFactory::getDBO();
	    $query = 'SELECT * FROM #__igallery '.$where.' ORDER BY parent, ordering';
	    $db->setQuery($query);
	    $categories = $db->loadObjectList();
		
		for($i=0; $i<count($categories); $i++)
		{
			$categories[$i]->parent_id = $categories[$i]->parent;
			$categories[$i]->title = null;
		}
		
	    $children = array();
		if($categories )
	    {
	        foreach($categories as $v) 
	        {
	            $pt     = $v->parent;
	            $list   = @$children[$pt] ? $children[$pt] : array();
	            array_push($list,$v);
	            $children[$pt] = $list;
	        }
	    }
		$categoryTree = JHTML::_('menu.treerecurse', 0, '', array(), $children, 9999, 0, 0 );
		
	    $selectItems     = array();
	    
	    if($option != 'com_menus' && $option != 'com_modules' && JRequest::getVar('view') != 'editorbutton')
	    {
	    	$selectItems[]   = JHTML::_('select.option', '0', JText::_('JGLOBAL_TOP') );
	    }
		//print_r($categoryTree);die;
	    foreach ($categoryTree as $branch) 
	    {
	        $selectItems[] = JHTML::_('select.option', $branch->id, str_replace('&#160;&#160;', '-', str_replace('-', '', $branch->treename)).' '.$branch->name );
	    }
		
	    $selectHTML = JHTML::_("select.genericlist", $selectItems, $this->name, 'class="inputbox" size="5"', 
	    'value', 'text', $selected);
	   
	    return $selectHTML;
	}
}