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

jimport( 'joomla.plugin.plugin' );
jimport( 'joomla.filesystem.file');
jimport( 'joomla.utilities.string');
jimport( 'joomla.language.helper');
jimport( 'joomla.environment.browser');

/**
 * AccordionFAQ Content Plugin
 *
 */
class plgContentAccordionfaq extends JPlugin
{

	/**
	 * Constructor
	 *
	 * For php4 compatability we must not use the __constructor as a constructor for plugins
	 * because func_get_args ( void ) returns a copy of all passed arguments NOT references.
	 * This causes problems with cross-referencing necessary for the observer design pattern.
	 *
	 * @param object $subject The object to observe
	 * @param object $params  The object that holds the plugin parameters
	 * @since 1.5
	 */
	function plgContentAccordionfaq( &$subject, $params )
	{
		parent::__construct( $subject, $params );
	}

	/**
	 * onPrepareContent
	 *
	 * Method is called by the view
	 *
	 * @param 	object		The article object.  Note $article->text is also available
	 * @param 	object		The article params
	 * @param 	int			The 'page' number (defaults to 0)
	 */
	function onPrepareContent( &$article, &$params, $limitstart=0 )
	{

		if (! preg_match_all( "/{\s*accordionfaq\s*.*?}/is", $article->text, $matches ))
		{
			return;
		}
		$count = count($matches[0]);

		if ($count)
		{

			$plugin			= JPluginHelper::getPlugin('content', 'accordionfaq');
			$pluginParams	= new JParameter( $plugin->params );

			for ($i = 0; $i < $count; $i++)
			{
				$matchline = str_replace( "&nbsp;", ' ', $matches[0][$i]);
				$matchline = html_entity_decode( $matchline, ENT_QUOTES, 'UTF-8' );
				$match = preg_replace( '/{\s*accordionfaq\s*/i', '', $matchline );
				$match = str_replace( '}', '', $match );
				$match = preg_replace( "/\s/s", " ", $match );
				$match = trim( $match );
				$parray = array();
				while (preg_match( "/([ ])*([A-Za-z0-9]*)([ ])*=([ ])*\"([^\"]+)\"/i", $match, $p ) > 0
					||preg_match( "/([ ])*([A-Za-z0-9]*)([ ])*=([ ])*'([^']+)'/i", $match, $p ) > 0
					||preg_match( "/([ ])*([A-Za-z0-9]*)([ ])*=([ ])*([^ ,]+)([ ,]*)/i", $match, $p ) > 0
					)
				{
					$parray[JString::strtolower($p[2])] = $p[5];
					$match = str_replace( $p[0], '', $match);
				}
				if (!isset($parray['echo']))
				{
					$paramArray = $pluginParams->toArray();
					$plgparams = new plgAccordionfaqParams();
					$plgparams->init( $paramArray, $parray );
					$output = $this->doOutput( $article, $plgparams, $matchline );
					$article->text = str_replace( $matches[0][$i], $output, $article->text );
					continue;
				}
				if (preg_match( "/([ ])*(echo)([ ])*=([ ])*([^ ,}]+)([ ,]*)/i", $matchline, $p ) > 0)
				{
					$match = str_replace( $p[0], '', $matchline);
					$article->text = str_replace( $matches[0][$i], $match, $article->text );
				}
			}
		}
	}

	function doOutput( &$article, &$params, &$faqline )
	{
		$html = "";
		$document = &JFactory::getDocument();

		if (! $this->editParamNames( $params, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		$cssfile = $params->get("cssfile","plugins/content/accordionfaq/css/accordionfaq.css");
		$faqid = $params->get("faqid","accordion1");
		$faqclass = $params->get("faqclass","");
		$header = $params->get("header",'h3');
		if (! $this->editTrueFalse( "autoheight", $params, "1", $autoheight, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		if (! $this->editTrueFalse( "autonumber", $params, "0", $autonumber, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		if (! $this->editTrueFalse( "alwaysopen", $params, "1", $alwaysopen, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		if (! $this->editTrueFalse( "warnings", $params, "1", $warnings, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		if (! $this->editTrueFalse( "usedynamiccssload", $params, "1", $usedynamiccssload, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		if (! $this->editEvent( "event", $params, "click", $event, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		if (! $this->editAnimation( "animation", $params, "none", $animation, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		$active = $params->get("active","");
		if (! $this->editNumeric( "scrolltime", $params, 1000, $scrolltime, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		$scrolltime = max( $scrolltime, 1);
		if (! $this->editNumeric( "scrolloffset", $params, 0, $scrolloffset, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		if (! $this->editJqueryInclude( "includejquery", $params, "2", $includejquery, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		if (! $this->editJqueryNoConflict( "jquerynoconflict", $params, "1", $noconflict, $html))
		{
			return $this->formattedError( $html, $faqline );
		}
		if ($active == "")
		{
			$active = "false";
		}
		else
		{
			if (! is_numeric($active))
			{
				$active = "'#".$active."'";
			}
		}
		$faqitem = JRequest::getString( 'faqitem', '' );
		if ($faqitem != "")
		{
			if (JString::strpos( $faqitem, $faqid ) === 0)
			{
				$faqitemparts = JString::str_split( $faqitem, JString::strlen( $faqid) );
				if (isset( $faqitemparts[1]))
				{
					if (is_numeric($faqitemparts[1]))
					{
						$faqitemid = (int)$faqitemparts[1];
						$active = $faqitemid;
						$jumpto = $faqitem;
					}
					else
					{
						$active = "'#".$faqitemparts[1]."'";
						$jumpto = $faqitemparts[1];
					}
				}
				else
				{
					$jumpto = $faqitem;
				}
			}
		}
		$printfaq = JRequest::getString( "print", 'false');
		if ($printfaq == "1")
		{
			if (isset( $jumpto ))
			{
				unset( $jumpto );
			}
			$animation = 'false';
			$printfaq = 'true';
		}
		else
		{
			$printfaq = 'false';
		}
		$browser	= &JBrowser::getInstance();
		$isIE6		= false;

		if ($browser->getBrowser() == "msie" && $browser->getMajor() <= 6)
		{
			$isIE6 = true;
			$ie6css = JPATH_BASE . DS . $cssfile;
			$ie6css = JPath::clean( $ie6css, DS );
			if (JString::substr($ie6css, JString::strlen( $ie6css ) - 4, 4) == '.css')
			{
				$ie6css = JString::substr_replace($ie6css, '-ie6.css', JString::strlen( $ie6css ) - 4, 4 );
			}
			if (JFile::exists($ie6css))
			{
				$styledata = JFile::read($ie6css);
				$newtext = preg_replace( "/src=( )*'( )*([^' ]+)'/i", "src='" . JURI::root(true) . "\\3" . "'", $styledata );
				$newtext = preg_replace( "/url\(( )*'( )*([^' ]+)'/i", "url('" . JURI::root(true) . "\\3" . "'", $newtext );
				$document->addStyleDeclaration($newtext);
			}
		}
		$document->addStyleSheet( JURI::root(true)."/".$cssfile );

		$cssbase = JPATH_BASE . DS . $cssfile;
		$cssbase = JPath::clean( $cssbase, DS );
		$cssfilename = JFile::getName( $cssbase );
		$cssbase = str_replace( $cssfilename, '', $cssbase );
		$faqbase = str_replace( $cssfilename, '', $cssfile );
		$faqclassarray = preg_split( "/[\s]+/", $faqclass );
		for($i = 0; $i < count($faqclassarray); $i++)
		{
			if (preg_match("/(.*)faq$/i", $faqclassarray[$i], $match ))
			{
				$faqfile = $cssbase.$faqclassarray[$i].".css";
				if (JFile::exists($faqfile))
				{
					if ($usedynamiccssload == 'tru')
					{
						$document->addStyleSheet( JURI::root(true)."/".$faqbase."css.php?id=".$faqid."&amp;faq=".$faqclassarray[$i] );
					}
					else
					{
						$document->addStyleSheet( JURI::root(true)."/".$faqbase.$faqclassarray[$i].".css" );
					}
					if ($isIE6)
					{
						$ie6css = $cssbase.$faqclassarray[$i]."-ie6.css";
						if (JFile::exists($ie6css))
						{
							$styledata = JFile::read($ie6css);
							$newtext = preg_replace( "/src=( )*'( )*([^' ]+)'/i", "src='" . JURI::root(true) . "\\3" . "'", $styledata );
							$newtext = preg_replace( "/url\(( )*'( )*([^' ]+)'/i", "url('" . JURI::root(true) . "\\3" . "'", $newtext );
							$newtext = preg_replace( "/\.".$faqclassarray[$i]."/", "#".$faqid.".".$faqclassarray[$i], $newtext );
							$document->addStyleDeclaration($newtext);
						}
					}
				}
				else
				{
					if ($warnings == 'tru')
					{
						$warntext = "WARNING: CSS file for faqclass ".$faqclassarray[$i]." does not exist (".$faqfile.").";
						$html .= $this->formattedError( $warntext, $faqline );
					}
				}
			}
			else
			{
				if ($warnings == 'tru')
				{
					if (! $this->editFaqClass( $faqclassarray[$i], $warntext))
					{
						$html .= $this->formattedError( $warntext, $faqline );
					}
				}
			}
		}

		if ($includejquery != 0)
		{
			if ($includejquery == 1)
			{
				JHTML::_('script', 'jquery-1.6.1.js', 'plugins/content/accordionfaq/js/' );
			}
			else
			{
				JHTML::_('script', 'jquery-1.6.1.min.js', 'plugins/content/accordionfaq/js/' );
			}
		}
		JHTML::_('script', 'preparefaq.js', 'plugins/content/accordionfaq/js/' );

		$script  = "// <!--\n";
		$script .= "if (typeof (preparefaq) === 'undefined') var preparefaq = new prepareFaq();\n";
		$script .= "preparefaq.onFunctionAvailable( 'jQuery', 300, function() {\n";
		$script .= "	preparefaq.setjQuery();\n";
		if ($printfaq == 'false')
		{
			$script .= "	preparefaq.loadScript( '". JURI::root(true) . "/plugins/content/accordionfaq/js/jquery.accordion.js' );\n";
		}
		if ($animation != "false")
		{
			$script .= "	preparefaq.loadScript( '". JURI::root(true) . "/plugins/content/accordionfaq/js/jquery.easing.js' );\n";
		}
		$script .= "	preparefaq.loadScript( '". JURI::root(true) . "/plugins/content/accordionfaq/js/jquery.dimensions.js' );\n";
		if (isset($jumpto))
		{
			$script .= "	preparefaq.loadScript( '". JURI::root(true) . "/plugins/content/accordionfaq/js/bookmarkscroll.js' );\n";
		}
		if ($noconflict)
		{
			$script	.= "	jQuery.noConflict();\n";
		}
		$script .= "	jQuery(document).ready(function(){ \n";
		$script .= "		preparefaq.exec( { id: '".$faqid."', header: '".$header."', autonumber: ".$autonumber."e, print: ".$printfaq." } );\n";
		$script .= "		preparefaq.onFunctionAvailable( 'preparefaq.getjQuery().fn.accordion', 300, function() {\n";
		$script .= "			preparefaq.getjQuery()('#".$faqid."').accordion( { \n";
		$script .= "				  header: '".$header."'\n";
		$script .= "				, autoheight: ".$autoheight."e\n";
		$script .= "				, alwaysOpen: ".$alwaysopen."e\n";
		$script .= "				, active: ".$active."\n";
		$script .= "			 	, animated: ".$animation."\n";
		$script .= "			 	, event: '".$event."'\n";
		$script .= "			});\n";
		$script .= "		});\n";
		if (isset($jumpto))
		{
			$script .= "/***********************************************\n";
			$script .= "* Scrolling HTML bookmarks- © Dynamic Drive DHTML code library (www.dynamicdrive.com)\n";
			$script .= "* This notice MUST stay intact for legal use\n";
			$script .= "* Visit Project Page at http://www.dynamicdrive.com for full source code\n";
			$script .= "***********************************************/\n";
			$script .= "		preparefaq.onObjectAvailable( 'bookmarkscroll', 300, function() {\n";
			$script .= "			bookmarkscroll.init();\n";
			$script .= "			bookmarkscroll.scrollTo( '".$jumpto."', {duration: ".$scrolltime.", yoffset: ".$scrolloffset." } );\n";
			$script .= "			});\n";
		}
		$script .= "	});\n";
		$script .= "});\n";
		$script .= "// -->\n";
		$document->addScriptDeclaration( $script );

		$html 	.= "<div id=\"".$faqid."\" class=\"accordionfaq ".$faqclass."\">";
		$html 	.= "<p></p>";
		$html 	.= "</div>";
		return $html;
	}

	function editNumeric( $paramname, &$params, $default, &$value, &$errortext )
	{
		$paramvalue = $params->get( $paramname, $default );
		if (is_numeric($paramvalue))
		{
			$value = (int)$paramvalue;
			return true;
		}
		$errortext = "ERROR: Parameter ".$paramname."='".$paramvalue."' is invalid. ";
		$errortext .= "'".$paramvalue."' must be a number.";
		return false;
	}

	function editJqueryInclude( $paramname, &$params, $default, &$value, &$errortext )
	{
		$valid['0'] = "0";
		$valid['1'] = "1";
		$valid['2'] = "2";
		$valid['no'] = "0";
		$valid['yes'] = "1";
		$valid['n'] = "0";
		$valid['y'] = "1";
		$valid['comp'] = "2";
		return $this->editParam( $paramname, $params, $default, $valid, $value, $errortext );
	}

	function editJqueryNoConflict( $paramname, &$params, $default, &$value, &$errortext )
	{
		$valid['0'] = "0";
		$valid['1'] = "1";
		$valid['no'] = "0";
		$valid['yes'] = "1";
		$valid['n'] = "0";
		$valid['y'] = "1";
		$valid['enable'] = "1";
		$valid['disable'] = "0";
		return $this->editParam( $paramname, $params, $default, $valid, $value, $errortext );
	}

	function editTrueFalse( $paramname, &$params, $default, &$value, &$errortext )
	{
		$valid['true'] = "tru";
		$valid['false'] = "fals";
		$valid['yes'] = "tru";
		$valid['no'] = "fals";
		$valid['on'] = "tru";
		$valid['off'] = "fals";
		$valid['t'] = "tru";
		$valid['f'] = "fals";
		$valid['y'] = "tru";
		$valid['n'] = "fals";
		$valid['1'] = "tru";
		$valid['0'] = "fals";
		return $this->editParam( $paramname, $params, $default, $valid, $value, $errortext );
	}

	function editEvent( $paramname, &$params, $default, &$value, &$errortext )
	{
		$valid['click'] = "click";
		$valid['dblclick'] = "dblclick";
		$valid['mouseover'] = "mouseover";
		return $this->editParam( $paramname, $params, $default, $valid, $value, $errortext );
	}

	function editParamNames( &$params, &$errortext )
	{
		$valid['faqid'] = "1";
		$valid['cssfile'] = "1";
		$valid['includejquery'] = "1";
		$valid['jquerynoconflict'] = "1";
		$valid['faqclass'] = "1";
		$valid['header'] = "1";
		$valid['autonumber'] = "1";
		$valid['autoheight'] = "1";
		$valid['alwaysopen'] = "1";
		$valid['active'] = "1";
		$valid['animation'] = "1";
		$valid['event'] = "1";
		$valid['scrolltime'] = "1";
		$valid['scrolloffset'] = "1";
		$valid['warnings'] = "1";
		$valid['usedynamiccssload'] = "1";
		$paramnamesarray = $params->getArray();
		$paramnames = array_keys( $paramnamesarray );
		foreach( $paramnames as $paramname)
		{
			if (! isset( $valid[strtolower($paramname)]))
			{
				$validvalues = array_keys( $valid );
				$validlist = implode( $validvalues, ", ");
				$errortext = "ERROR: Parameter '".$paramname."' is invalid. ";
				$errortext .= "Acceptable values for '".$paramname."' are ".$validlist.".";
				return false;
			}
		}
		return true;
	}

	function editFaqClass( $classname, &$errortext )
	{
		$valid['round3'] = "1";
		$valid['round5'] = "1";
		$valid['round7'] = "1";
		$valid['round9'] = "1";
		$valid['headerbackground'] = "1";
		$valid['headerborder'] = "1";
		$valid['contentbackground'] = "1";
		$valid['contentborder'] = "1";
		$valid['border'] = "1";
		$valid['bcolor'] = "1";
		$valid['defaulticon'] = "1";
		$valid['onoff'] = "1";
		$valid['plus'] = "1";
		$valid['plus2'] = "1";
		$valid['plus3'] = "1";
		$valid['arrow'] = "1";
		$valid['greenarrow'] = "1";
		$valid['orangearrow'] = "1";
		$valid['orangearrow2'] = "1";
		$valid['help'] = "1";
		$valid['help2'] = "1";
		$valid['power'] = "1";
		$valid['check'] = "1";
		$valid['rtl'] = "1";
		$valid['alignright'] = "1";
		$valid['alignleft'] = "1";
		$valid['aligncenter'] = "1";
		if (! isset( $valid[strtolower($classname)]))
		{
			$validvalues = array_keys( $valid );
			$validlist = implode( $validvalues, ", ");
			$errortext = "WARNING: faqclass '".$classname."' is invalid. ";
			$errortext .= "Acceptable values for '".$classname."' are ".$validlist.".";
			return false;
		}
		return true;
	}

	function editAnimation( $paramname, &$params, $default, &$value, &$errortext )
	{
		$valid['none'] = "false";
		$valid['slide'] = "'slide'";
		$valid['easeslide'] = "'easeslide'";
		$valid['bounceslide'] = "'bounceslide'";
		return $this->editParam( $paramname, $params, $default, $valid, $value, $errortext );
	}

	function editParam( $paramname, &$params, $default, &$valid, &$value, &$errortext )
	{
		$paramvalue = $params->get( $paramname, $default );
		if (isset($valid[strtolower($paramvalue)]))
		{
			$value = $valid[strtolower($paramvalue)];
			return true;
		}
		$validvalues = array_keys( $valid );
		$validlist = implode( $validvalues, ", ");
		$errortext = "ERROR: Parameter ".$paramname."='".$paramvalue."' is invalid. ";
		$errortext .= "Acceptable values for '".$paramvalue."' are ".$validlist.".";
		return false;
	}

	function formattedError( $errortext, $faqline )
	{
		$text = "<p style=\"color: red;background-color: yellow;\">\n";
		$text .= "<b>".htmlspecialchars($faqline)."<br/>";
		$text .= "Accordionfaq plugin,  ".$errortext."</b>";
		$text .= "</p>\n";
		return $text;
	}
}

class plgAccordionfaqParams
{
	var $_params = array();

	function init( &$params1, &$params2 )
	{
		$this->_params = array_merge( $params1, $params2 );
	}

	function get( $name, $default = '' )
	{
		if (isset($this->_params[$name]) && $this->_params[$name] != "")
		{
			return $this->_params[$name];
		}
		return $default;
	}
	function getArray()
	{
		return $this->_params;
	}
}
?>