<?php
/**@license setplus: a lightweight HTML editor
 * @author  Levente Hunyadi
 * @version 0.2.0
 * @remarks Copyright (C) 2010-2011 Levente Hunyadi
 * @remarks Licensed under GNU/GPLv3, see http://www.gnu.org/licenses/gpl-3.0.html
 * @see     http://hunyadi.info.hu/projects/setplus
 **/

/*
* setplus: a lightweight HTML editor
* Copyright 2010-2011 Levente Hunyadi
*
* setplus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* setplus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with setplus.  If not, see <http://www.gnu.org/licenses/>.
*/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.plugin.plugin');
jimport('joomla.html.html.behavior');

/**
 * setplus Simple Text Editor plug-in.
 */
class plgEditorSetPlus extends JPlugin {
	/**
	 * Base path for editor files.
	 */
	protected $_basePath = 'media/editors/setplus';

	/**
	 * Constructor.
	 *
	 * @access protected
	 * @param object $subject The object to observe.
	 * @param array $config An array that holds the plug-in configuration.
	 */
	public function __construct(&$subject, $config) {
		parent::__construct($subject, $config);
		$this->loadLanguage();
	}

	/**
	 * Initializes the editor.
	 *
	 * @return string JavaScript initialization string.
	 */
	public function onInit() {
		JHTML::_('behavior.framework', true);  // include MooTools Core and MooTools More
		$basepath = JPATH_ROOT.DS.str_replace('/', DS, $this->_basePath);

		// configure language
		$language = JFactory::getLanguage();
		$languagetag = $language->getTag();
		$languagepath = $basepath.DS.'js'.DS.'language';
		if (file_exists($languagepath.DS.$languagetag.'.js')) {
			$languagescripttag = $languagetag;
		} else {
			list($languagecode, $country) = explode('-', $languagetag);
			if (file_exists($languagepath.DS.$languagecode.'.js')) {
				$languagescripttag = $languagecode;
			} else {
				$languagescripttag = 'en';
			}
		}

		// configure toolbar
		switch ($this->params->get('toolbar', 'advanced')) {
			case 'custom':
				$toolbarbuttons = $this->params->get('toolbar_buttons'); break;
			case 'simple':
				$toolbarbuttons = array('undo','redo','pasteplain','bold','italic','removeformat','symbol','link','unlink','orderedlist','unorderedlist','zoomin','zoomout','fullscreen'); break;
		}

		// use minified sources if enabled and available
		$minify = $this->params->get('minify', true) && file_exists($basepath.DS.'css'.DS.'setplus.min.css');
		$min = $minify ? '.min' : '';

		if ($this->params->get('compress', false)) {  // use compression
			$scripts =
				'<script type="text/javascript" src="'.JURI::root(true).'/'.$this->_basePath.'/js/setplus.php?'.($minify ? '' : 'min=0&amp;').'lang='.$languagescripttag.'"></script>';
		} else {  // do not use compression
			$scripts =
				'<script type="text/javascript" src="'.JURI::root(true).'/'.$this->_basePath.'/js/setplus'.$min.'.js"></script>'.
				'<script type="text/javascript" src="'.JURI::root(true).'/'.$this->_basePath.'/js/language/'.$languagescripttag.$min.'.js"></script>';
		}

		return
			'<link type="text/css" rel="stylesheet" href="'.JURI::root(true).'/'.$this->_basePath.'/css/setplus'.$min.'.css" />'.
			$scripts.
			(isset($toolbarbuttons) ? '<script type="text/javascript">setplus.Options.toolbar = ["'.implode('","', $toolbarbuttons).'"];</script>' : '');
	}

	/**
	* Fetches the editor content.
	*
	* @param string $editor The name of the editor.
	* @return JavaScript code used to retrieve the contents of the editor as HTML text.
	*/
	public function onGetContent($editor) {
		return '$("'.$editor.'").retrieve("setplus-editor").getHTML();';
	}

	/**
	* Set the editor content.
	*
	* @param string $editor The name of the editor.
	* @return JavaScript statement used to set the contents of the editor given editable text as HTML.
	*/
	public function onSetContent($editor, $html) {
		return '$("'.$editor.'").retrieve("setplus-editor").setHTML('.$html.');';
	}

	/**
	* Copy editor content to a form field.
	*
	* @param string $editor The name of the editor.
	* @return JavaScript statement called prior to submitting the HTML form the editor is part of.
	*/
	public function onSave($editor) {
		return '$("'.$editor.'").retrieve("setplus-editor").synchronize();';
	}

	/**
	* Returns javascript code used to inject custom HTML code into the edited text.
	* Editor extender buttons call the javascript method jInsertEditorText, which is defined in this method.
	* @see plugins/editors/tinymce/tinymce.php
	*/
	public function onGetInsertMethod($name) {
		$doc = JFactory::getDocument();
		$js = 'function jInsertEditorText(text, editor) { $(editor).retrieve("setplus-editor").pasteHTML(text); }';
		$doc->addScriptDeclaration($js);

		return true;
	}

	/**
	* Display the editor area.
	* Injects the gallery HTML code into the page HTML source.
	*
	* @param string $name The name of the editor area.
	* @param string $content The content of the field.
	* @param string $width The width of the editor area.
	* @param string $height The height of the editor area.
	* @param int $col The number of columns for the editor area.
	* @param int $row The number of rows for the editor area.
	* @param boolean $buttons True and the editor buttons will be displayed.
	* @param string $id An optional ID for the textarea (note: since 1.6). If not supplied the name is used.
	*/
	public function onDisplay($name, $content, $width, $height, $col, $row, $buttons = true, $id = null, $asset = null, $author = null) {
		if (empty($id)) {
			$id = $name;
		}

		// only add "px" to width and height if they are not given as a percentage
		if (is_numeric($width)) {
			$width .= 'px';
		}

		if (is_numeric($height)) {
			$height .= 'px';
		}

		return
			'<textarea name="'.$name.'" id="'.$id.'" cols="'.$col.'" rows="'.$row.'" style="width:'.$width.'; height:'.$height.';" class="setplus">'.$content.'</textarea>'.
			$this->getButtons($id, $buttons, $asset, $author);
	}

	/**
	* Display Joomla custom editor buttons below editor area.
	* @see plugins/editors/tinymce/tinymce.php
	*/
	private function getButtons($name, $buttons, $asset, $author) {
		// load modal popup behavior
		JHTML::_('behavior.modal', 'a.modal-button');

		$args['name'] = $name;
		$args['event'] = 'onGetInsertMethod';

		$return = '';
		$results[] = $this->update($args);

		foreach ($results as $result) {
			if (is_string($result) && trim($result)) {
				$return .= $result;
			}
		}

		if (is_array($buttons) || (is_bool($buttons) && $buttons)) {
			$results = $this->_subject->getButtons($name, $buttons, $asset, $author);

			// this will allow plugins to attach buttons or change the behavior on the fly using AJAX
			$return .= "\n".'<div id="editor-xtd-buttons">'."\n";

			foreach ($results as $button) {
				// results should be an object
				if ( $button->get('name') ) {
					$modal		= ($button->get('modal')) ? 'class="modal-button"' : null;
					$href		= ($button->get('link')) ? 'href="'.JURI::base().$button->get('link').'"' : null;
					$onclick	= ($button->get('onclick')) ? 'onclick="'.$button->get('onclick').'"' : null;
					$title      = ($button->get('title')) ? $button->get('title') : $button->get('text');
					$return .= '<div class="button2-left"><div class="'.$button->get('name').'"><a '.$modal.' title="'.$title.'" '.$href.' '.$onclick.' rel="'.$button->get('options').'">'.$button->get('text').'</a></div></div>'."\n";
				}
			}

			$return .= '</div>'."\n";
		}

		return $return;
	}
}