<?php
/**
* @package plugin Nomad
* @copyright (C) 2010-2011 RicheyWeb - www.richeyweb.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* Nomad Copyright (c) 2011 Michael Richey.
* Nomad is licensed under the http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
*
* Nomad version 1.0 for Joomla 1.6.x devloped by RicheyWeb
*
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

/**
 * AdminExile system plugin
 */
class plgSystemNomad extends JPlugin
{
    function onAfterRoute()
    {
        //only operate for logged in users
        $user = JFactory::getUser();
        if(!$user->id) return;

        //only operate on the site
        $app = JFactory::getApplication();
        if($app->isAdmin()) return;

        //only operate on html pages
        $doc = JFactory::getDocument();       
        if($doc->getType() != 'html') return;

        //only operate if there are rules
        $rules = json_decode(base64_decode($this->params->get('rules')));    
        if(!count($rules)) return;
        
        $matches=array();
        foreach($rules as $key=>$rule) {
            switch($rule->type) {
                case 'global':
                    $matches['global']=$rule->destination;
                    break;
                case 'group':
                    if(in_array($rule->selector,$user->groups)) {
                        $matches['group']=$rule->destination;
                    }
                    break;
                case 'user':
                    if($user->id == $rule->selector) {
                        $matches['user']=$rule->destination;
                    }
                    break;
            }
        }
        if(count($matches)) {
            $menu = $app->getMenu();
            $current = $menu->getActive();
            $home = $menu->getDefault();
            if($current->id != $home->id) return;
            $itemid = false;
            foreach(array('user','group','global') as $key) {
                if(array_key_exists($key,$matches)) {
                    $menuitem = $menu->getItem($matches[$key]);
                    $itemid = $matches[$key];
                    break;
                }
            }
            if($itemid) $app->redirect(JRoute::_($menuitem->link.'&Itemid='.$itemid));
        }
        return;
    }
}
