<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

function igalleryBuildRoute(&$query)
{
    $segments = array();
    
    if( isset($query['view']) && isset($query['igid']) )
    {
        if($query['view'] == 'category')
        {
            $db =& JFactory::getDBO();
            $dbQuery = 'SELECT name, alias, parent FROM #__igallery WHERE id = '.(int)$query['igid'];
            $db->setQuery($dbQuery);
            $row = $db->loadObject();
            $segments[] = $row->alias;
            
            $Itemid = JRequest::getInt('Itemid', null);
            if( !empty($Itemid) )
            {
                $app	= JFactory::getApplication();
				$menu	= $app->getMenu();
                $active = $menu->getActive();
                if( isset($active->query['igid']) )
                {
                	$itemIdCatId = $active->query['igid'];
                }
                else
                {
                	$itemIdCatId = 0;
                }
            }
            else
    		{
    		    $itemIdCatId = 0;
    		}
            
            while($row->parent != 0 && $row->parent != $itemIdCatId)
            {
            	$dbQuery = 'SELECT name, alias, parent FROM #__igallery WHERE id = '.(int)$row->parent;
            	$db->setQuery($dbQuery);
            	$row = $db->loadObject();
            	array_unshift($segments, $row->alias);
            }
        
        unset($query['view']);
        unset($query['igid']);
    }
}

return $segments;
}

function igalleryParseRoute($segments)
{
    $vars = array();
    $count = count($segments);
    $lastSegment = $segments[$count - 1];
    
    $lastSegment = str_replace(':', '-', $lastSegment);
    
    $db =& JFactory::getDBO();
    $dbQuery = 'SELECT id FROM #__igallery WHERE alias = "'.$db->getEscaped($lastSegment).'"';
    $db->setQuery($dbQuery);
    $row = $db->loadObject();
    $vars['igid'] = $row->id;
    $vars['view'] = 'category';
    return $vars;
    
}

?>