<?php
/*
 *
 * @package		ARI Smart Content
 * @author		ARI Soft
 * @copyright	Copyright (c) 2011 www.ari-soft.com. All rights reserved
 * @license		GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
 * 
 */

defined('_JEXEC') or die('Restricted access');

jimport('joomla.plugin.plugin');

class plgSystemAriSmartContent extends JPlugin
{
	var $_loaded = false;
	var $_isComponentInstalled = null;

	function __construct(&$subject, $config)
	{
		parent::__construct($subject, $config); 
	}

	function onAfterRender()
	{
		$option = JRequest::getString('option');

		$document = JFactory::getDocument();
		if ($document->getType() == 'pdf')
			return ;

		$mainframe = JFactory::getApplication();
		if ($mainframe->isAdmin() || !$this->_isAriSmartContentInstalled()) 
			return ;

		if ($option == 'com_content' && JRequest::getString('view') == 'form' && JRequest::getString('layout') == 'edit')
			return ;		

		$this->_load();

		$smartContentHelper = AriSmartContentApplicationHelper::getInstance();
		if (!$smartContentHelper->needExecutePlugins($option))
			return ;

		AriKernel::import('Document.DocumentIncludesManager');
	
		$includesManager = new AriDocumentIncludesManager();

		$content = JResponse::getBody();

		JResponse::setBody(
			$smartContentHelper->executePlugins(
				$content
			)
		);

		$includes = $includesManager->getDifferences();
		AriDocumentHelper::addCustomTagsToDocument($includes);
	}

	function _load()
	{
		if ($this->_loaded) 
			return ;

		$componentPath = JPATH_SITE . '/administrator/components/com_arismartcontent/';
			
		require_once $componentPath . 'kernel/class.AriKernel.php';
		
		require_once $componentPath . 'defines.php';

		AriKernel::import('Application.ARISmartContent.Utils.Helper');
		AriKernel::import('Application.ARISmartContent.Utils.ApplicationHelper');
		
		$this->_loaded = true;
	}

	function _isAriSmartContentInstalled()
	{
		if (is_null($this->_isComponentInstalled))
		{
			$path = JPATH_ROOT;
			$adminBasePath = $path . '/administrator/components/com_arismartcontent';
			
			$this->_isComponentInstalled = @file_exists($adminBasePath); 
		}

		return $this->_isComponentInstalled; 
	}
}