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

/**
 * Replace sign to insert chart in article by chart html code.
 * 
 * @param JTableContent  $row
 * @param JParameter     $params
 * @param int            $page
 */

class plgContentARTIOFusionCharts extends JPlugin
{

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

    function onPrepareContent(&$row, &$params, $page = 0)
    {
        $regex = '#{fusionchart id="([^"]*)"([^}]*)}#iU';
        $matches = array();
        if (preg_match_all($regex, $row->text, $matches, PREG_SET_ORDER)) {
            $root = JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_artiofusioncharts' . DS;
            $config = $root . 'config.php';
            $helper = $root . 'helpers' . DS . 'helper.php';
            if (file_exists($config) && file_exists($helper)) {
                require_once ($config);
                require_once ($helper);
                $encoding = 'UTF-8';
                JHTML::_('behavior.caption');
                ARTIOFusionChartsHelper::importFusionJS();
                $count = count($matches);
                for ($i = 0; $i < $count; $i ++) {
                    $match = $matches[$i][0];
                    $id = (int) $matches[$i][1];
                    $chart = ARTIOFusionChartsHelper::getChart($id);
                    $html = ARTIOFusionChartsHelper::displayChart($chart, 'content');
                    $position = mb_strpos($row->text, $match, 0, $encoding);
                    $length = mb_strlen($match, $encoding);
                    $textLength = mb_strlen($row->text, $encoding);
                    $row->text = mb_substr($row->text, 0, $position, $encoding) . $html . mb_substr($row->text, $position + $length, $textLength - $position - $length, $encoding);
                }
            }
        }
        return true;
    }
}
?>