<?php defined('_JEXEC') or die();
/**
 * @version		1.1.1
 * @package		Read More
 * @subpackage	Plugin
 * @copyright	2009 Rockford Solutions, Inc. All rights reserved.
 * @license		GNU/GPL
 */

jimport('joomla.plugin.plugin');

/**
 * Read More Plugin
 *
 * @package		Read More
 * @subpackage	Plugin
 */
class plgContentReadmore extends JPlugin {
	/**
	 * Javascript code
	 * 
	 * @access	protected
	 * @var		string
	 */
	protected $_javascript = null;
	
	/**
	 * Stylesheet code
	 * 
	 * @access	protected
	 * @var		string
	 */
	protected $_stylesheet = null;
	
	/**
	 * Whether or not to include javascript and stylesheet
	 * 
	 * @access	protected
	 * @var		bool
	 */
	protected $_doIncludes = true;

	/**
	 * Constructor
	 * 
	 * @param	object	Plugin observer
	 * @param	array	Plugin parameters
	 */
	public function __construct(&$subject, $params) {
		parent::__construct($subject, $params);
		
		$com_path = JPATH_ROOT . DS . 'components' . DS . 'com_readmore';
		
		$js_file  = 'js' . DS . 'readmore.js';
		$css_file = 'css' . DS . 'styles.css';
		
		$js_open_tag  = '<script type="text/javascript">';
		$js_close_tag = '</script>';
		
		$css_open_tag  = '<style type="text/css">';
		$css_close_tag = '</style>';
		
		$this->_javascript = $js_open_tag  . file_get_contents($com_path . DS . $js_file)  . $js_close_tag;
		$this->_stylesheet = $css_open_tag . file_get_contents($com_path . DS . $css_file) . $css_close_tag;
	}
	
	/**
	 * Filters content for unauthenticated users
	 * 
	 * @param	object	Article object
	 * @param	array	Article parameters array
	 * @param	int		Pagination offset
	 */
	public function onPrepareContent(&$article, &$params, $limitstart) {
		global $mainframe;
		
		// Load plugin parameters
		$component  = JComponentHelper::getComponent('com_readmore');
		$com_params = new JParameter($component->params);
		
		$scope  = $com_params->get('contentscope');
		$idlist = $com_params->get('contentidlist');
		
		$idlist = explode(',', $idlist);		
		for ($i = 0; $i < count($idlist); $i++) {
			$idlist[$i] = (int) trim($idlist[$i]);
		}
		
		// Determine whether or not to apply filter
		switch ($scope) {
			case 'section':
				$apply = in_array($article->sectionid, $idlist);
			break;
			case 'category':
				$apply = in_array($article->catid, $idlist);
			break;
			default:
				$apply = true;
			break;
		}
		
		// Filter content
		if ($apply) {
			$com_params->set('show_readmore', 0);
			
			$text = '<div id="introtext_' . $article->id . '" class="introtext">' . $article->introtext . '</div>'
				  . '<a id="linktext_' . $article->id . '" class="linktext readon" href="#" onclick="doReadmore(' . $article->id . ');">Read more ...</a>'
				  . '<div id="fulltext_' . $article->id . '" class="fulltext">Loading ...</div>';
			
			$article->text = $text;
			
			// Include javascript and stylesheet
			if ($this->_doIncludes) {				
				$article->text = $this->_javascript . $this->_stylesheet . $article->text;
				
				$this->_doIncludes = false;
			}
		}
	}
}
