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

/**
 * Contains page rendering helpers.
 */
class DesignerPage
{

    public $page;
    public $positions = array();
    public $prevModuleScript = '';

    public static $inlineScripts = array();

    private $_componentProxy = null;
    private $_counter = 0;


    public function __construct($page)
    {
        $this->page = $page;
        $this->processJoomlaOwnScripts();
        $this->combineVMScripts($this->page->_scripts);
    }

    /*
     * Process Joomla! head scripts
     */
    public function processJoomlaOwnScripts()
    {
        //process inline script
        if (count($this->page->_script) > 0) {
            DesignerPage::$inlineScripts[] = '<script type="text/javascript">' . $this->page->_script['text/javascript'] . '</script>';
            unset($this->page->_script['text/javascript']);
        }
    }

    public function combineVMScripts(& $scripts, $append = false)
    {
        // process virtuemart source scripts
        $app = JFactory::getApplication('site');
        $themeName = $app->getTemplate();
        $themeDir = JPATH_SITE . '/templates/' . $themeName;
        $virtueMartJs = $themeDir . (true === $GLOBALS['designer_settings']['is_preview'] ? '/editor' : '') . '/virtuemart.js';
        $contentJs = '';
        if ($append)
            $contentJs = file_get_contents($virtueMartJs);
        foreach ($scripts as $script => $attrs) {
            if (preg_match('/com_virtuemart\/assets\/js\/(.*)/', $script, $matches)) {
                $lower = strtolower($matches[1]);
                if ('jquery.min.js' !== $lower && 'jquery.noconflict.js' !== $lower) {
                    $root = JURI::root(true);
                    $path = str_replace($root, '', $script);
                    $filePath = JPATH_BASE . '/' . $path;
                    // remove facebox.js - this script already included to virtuemart.ex.js
                   if (file_exists($filePath) && 'facebox.js' !== $lower)
                        $contentJs .= "\r\n/* Script: $script */\r\n" . file_get_contents($filePath);
                    unset($scripts[$script]);
                }
            }
        }
        file_put_contents($virtueMartJs, $contentJs);
    }

    public function combineVMInlineScript(& $script) {
        if (isset($script['text/javascript']) && $this->prevModuleScript !== $script['text/javascript']) {
            $app = JFactory::getApplication('site');
            $themeName = $app->getTemplate();
            $themeDir = JPATH_SITE . '/templates/' . $themeName;
            $virtueMartJs = $themeDir . (true === $GLOBALS['designer_settings']['is_preview'] ? '/editor' : '') . '/virtuemart.js';
            $contentJs = file_get_contents($virtueMartJs);
            $new = str_replace($this->prevModuleScript, '', $script['text/javascript']);
            $script['text/javascript'] = $this->prevModuleScript;
            file_put_contents($virtueMartJs, $contentJs . $new);
        }
    }

    /**
     * Include  Joomla! head and VirtueMart component scripts after theme scripts
     */
    public function includeScripts()
    {
        foreach(DesignerPage::$inlineScripts as $script)
            echo $script;
    }

    /*
     * Checks whether Joomla! has system messages to display and renders theirs.
     */
    public function renderSystemMessages()
    {
        $app = JFactory::getApplication();
        $messages = $app->getMessageQueue();
        ob_start();
        if (is_array($messages) && count($messages))
            foreach ($messages as $msg) {
                if (isset($msg['type']) && isset($msg['message'])) {
                    switch ($msg['type']) {
                        case "info":
                            echo renderTemplateFromIncludes('funcInfoMessage', array($msg['message']), 'prototypes');
                            break;
                        case "error":
                            echo renderTemplateFromIncludes('funcErrorMessage', array($msg['message']), 'prototypes');
                            break;
                        case "warning":
                            echo renderTemplateFromIncludes('funcWarningMessage', array($msg['message']), 'prototypes');
                            break;
                        case "notice":
                            echo renderTemplateFromIncludes('funcSuccessMessage', array($msg['message']), 'prototypes');
                            break;
                        default:
                            echo $msg['message'];
                    }
                }
            }
        return ob_get_clean();
    }

    /**
     * Returns true when any of the positions contains at least one module.
     * Example:
     *  if ($obj->containsModules('top1', 'top2', 'top3')) {
     *   // the following code will be executed when one of the positions contains modules:
     *   ...
     *  }
     */
    public function containsModules()
    {
        foreach (func_get_args() as $position)
            if (0 != $this->page->countModules($position))
                return true;
        return false;
    }

    public function renderTemplate($startPath)
    {
        $document = JFactory::getDocument();
        $templates = dirname($startPath) . '/templates/';
        $template = $templates . $GLOBALS['designer_settings']['currentTemplate'];

        ob_start();
        include_once $template;
        $template = ob_get_contents();
        ob_end_clean();

        foreach($this->positions as $position) {
            preg_match_all('/<jdoc:include\ type="([^"]+)" id="([^"]*)" name="' . $position . '" (.*)\/>/iU', $template, $matches);
            $this->_counter = count($matches[0]);
            $template = preg_replace_callback('#<jdoc:include\ type="([^"]+)" id="([^"]*)" name="(' . $position . ')" (.*)\/>#iU', array( &$this, '_positionDuplicator'), $template);
        }

        return $template;
    }

    private function _positionDuplicator($matches)
    {
       if ($this->_counter != 1){
            $content =  str_replace($matches[3], $matches[2], $matches[0]);
       } else
            $content =  $matches[0];
       $this->_counter--;
       return $content;
    }

    public function position($position, $style = null, $id = '')
    {
        array_push($this->positions, $position);

        $g = array_count_values($this->positions);
        $count = $g[$position];
        if ($count > 1 && !empty($id)) {
            $key = array_search($position, $this->positions);
            unset($this->positions[$key]);
        }
        return '<jdoc:include type="modules" id="' . $id . '" name="' . $position . '" style="drstyle"' . ' drstyle="' . (null != $style ?  $style : '') . '" />';
    }

    public function buildDataPositionAttr($name)
    {
        return $GLOBALS['designer_settings']['is_preview'] ? 'data-position=' . $name : '';
    }

    private function parseInlineScripts($matches) {
        DesignerPage::$inlineScripts[] = $matches[0];
        return "";
    }

    /**
     * Process and including needed template
     */
    public function componentWrapper()
    {
        if ($this->page->getType() != 'html')
            return;
        $option = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');
        $layout = JRequest::getCmd('layout');
        $content = $this->page->getBuffer('component');

        // Processing of all links
        $content = funcContentRoutesCorrector($content);
        $themeDir = dirname(dirname(dirname(__FILE__)));
        $templatesDir = $themeDir . '/templates/';

        // Workarounds for Joomla bugs and inconsistencies:
        switch ($option) {
            case "com_content":
                switch ($view) {
                    case "form":
                        if ("edit" == $layout)
                            $content = str_replace('<button type="button" onclick="', '<button type="button" class="button" onclick="', $content);
                        break;
                    case "article":
                        $tmpl = 'page' === $GLOBALS['designer_settings']['currentTemplate'] ?
                            'pageTemplate.php' : 'singlePostTemplate.php';
                        if (file_exists($templatesDir . $tmpl)) {
                            $GLOBALS['designer_settings']['currentTemplate'] = $tmpl;
                        }
                        break;
                    case "category":
                    case "featured":
                    case "archive":
                        if (file_exists($templatesDir . 'blogTemplate.php')) {
                            $GLOBALS['designer_settings']['currentTemplate'] = 'blogTemplate.php';
                        }
                        break;
                    case "archive":
                        $content = preg_replace_callback('/<script[^>]*>([\s\S]+?)<\/script>/', array( &$this, 'parseInlineScripts'), $content);
                        break;
                }
                break;
            case "com_virtuemart":
                switch ($view) {
                    case "category":
                        if (file_exists($templatesDir . 'products.php')){
                            $GLOBALS['designer_settings']['currentTemplate'] = 'products.php';
                        }
                        break;
                    case "productdetails":
                        if (file_exists($templatesDir . 'productOverview.php')){
                            $GLOBALS['designer_settings']['currentTemplate'] = 'productOverview.php';
                        }
                        break;
                     case "cart":
                        if (file_exists($templatesDir . 'shoppingCartTemplate.php')){
                            $GLOBALS['designer_settings']['currentTemplate'] = 'shoppingCartTemplate.php';
                        }
                }
                break;
            case "com_users":
                switch ($view) {
                    case "remind":
                        if ("" == $layout) {
                            $content = str_replace('<button type="submit">', '<button type="submit" class="button">', $content);
                            $content = str_replace('<button type="submit" class="validate">', '<button type="submit" class="button">', $content);
                        }
                        break;
                    case "reset":
                        if ("" == $layout) {
                            $content = str_replace('<button type="submit">', '<button type="submit" class="button">', $content);
                            $content = str_replace('<button type="submit" class="validate">', '<button type="submit" class="button">', $content);
                        }
                        break;
                    case "registration":
                        if ("" == $layout)
                            $content = str_replace('<button type="submit" class="validate">', '<button type="submit" class="button validate">', $content);
                        break;
                }
                break;
            default:
                break;
        }
        $app = JFactory::getApplication();
        $menu = $app->getMenu();
        $lang = JFactory::getLanguage();
        if ('default.php' == $GLOBALS['designer_settings']['currentTemplate'] && $menu->getActive() == $menu->getDefault($lang->getTag())) {
            if (file_exists($templatesDir . 'home.php')){
                $GLOBALS['designer_settings']['currentTemplate'] = 'home.php';
            }
        }
        // Code injections:
        switch ($option) {
            case "com_content":
                switch ($view) {
                    case "form":
                        if ("edit" == $layout)
                            $this->page->addScriptDeclaration($this->getWysiwygBackgroundImprovement());
                        break;
                }
                break;
        }

        $this->page->setBuffer($content, 'component');

    }

    public function getComponentProxy()
    {
        return $this->_componentProxy;
    }

    public function getWysiwygBackgroundImprovement()
    {
        ob_start();
?>
window.addEvent('domready', function() {
    var waitFor = function (interval, criteria, callback) {
        var interval = setInterval(function () {
            if (!criteria())
                return;
            clearInterval(interval);
            callback();
        }, interval);
    };
    var editor = ('undefined' != typeof tinyMCE)
        ? tinyMCE
        : (('undefined' != typeof JContentEditor)
            ? JContentEditor : null);
    if (null != editor) {
        // fix for TinyMCE editor
        waitFor(75,
            function () {
                if (editor.editors)
                    for (var key in editor.editors)
                        if (editor.editors.hasOwnProperty(key))
                            return editor.editors[key].initialized;
                return false;
            },
            function () {
                var ifr = jQuery('#jform_articletext_ifr');
                var ifrdoc = ifr[0] && ifr[0].contentDocument;
                ifrdoc && jQuery('link[href*="/css/editor.css"]', ifrdoc).ready(function () {
                    jQuery('link[href$="content.css"]', ifrdoc).remove();
                    ifr.css('background', 'transparent').attr('allowtransparency', 'true');
                    var ifrBodyNode = jQuery('body', ifrdoc);
                    var layout = jQuery('table.mceLayout');
                    var toolbar = layout.find('.mceToolbar');
                    var toolbarBg = toolbar.css('background-color');
                    var statusbar = layout.find('.mceStatusbar');
                    var statusbarBg = statusbar.css('background-color');
                    layout.css('background', 'transparent');
                    toolbar.css('background', toolbarBg);
                    toolbar.css('direction', '');
                    statusbar.css('background', statusbarBg);
                    ifrBodyNode.css('background', 'transparent');
                    ifrBodyNode.attr('dir', 'ltr');
                });
            });
    } else if ('undefined' != typeof CKEDITOR) {
        CKEDITOR.on('instanceReady', function (evt) {
            var includesTemplateStyle = 0 != jQuery('link[href*="/css/template.css"]', evt.editor.document.$).length;
            var includesEditorStyle = 0 != jQuery('link[href*="/css/editor.css"]', evt.editor.document.$).length;
            if (includesTemplateStyle || includesEditorStyle) {
                jQuery('#cke_ui_color').remove();
                var ifr = jQuery('#cke_contents_text>iframe');
                ifr.parent().css('background', 'transparent')
                    .parent().parent().parent().parent()
                    .css('background', 'transparent');
                console.log(jQuery('.cke_wrapper'));
                ifr.attr('allowtransparency', 'true');
                ifr.css('background', 'transparent');
                var ifrdoc = ifr.attr('contentDocument');
                jQuery('body', ifrdoc).css('background', 'transparent');
                /*if (includesTemplateStyle)
                    jQuery('body', ifrdoc).attr('id', 'bd-main').addClass('bd-postcontent');*/
            }
        });
    }
});
<?php
        return ob_get_clean();
    }
}
