@*--
<?php

class Config
{
    public static $base;
    public static $themeId;
    public static $themeName;
    public static $startFiles = array();
    public static $projectData;
    public static $revision;
    public static $cache;
    public static $hashes;
    public static $appIndex;
    public static $infoData = array();

    private static $homeLink = '';

    protected static $_instance;

    private function __construct(){}

    private function __clone(){}

    public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public static function injectionDesigner($config) {

        $showDesigner = JRequest::getVar('editor', '');

        self::initialize($config['themeObject']);

        $document = JFactory::getDocument();

        // restore preview theme from backup
        if ('1' === $showDesigner) {

            $document->_scripts     = array();
            $document->_script      = array();
            $document->_styleSheets = array();
            $document->_style       = array();

            $originalDir = JPATH_SITE . '/templates/' . self::$themeName;
            $editorDir = $originalDir . '/editor';
            $tmpDir = $originalDir . '/tmp';
            
            // remove old preview theme
            if (file_exists($editorDir))
                Helper::removeDir($editorDir, false);
            else
                Helper::createDir($editorDir);
                
            // remove temporary files
            if (file_exists($tmpDir))
                Helper::removeDir($tmpDir);

            $preview = new Preview(self::$themeName);

            $files = Helper::enumerateRecursive($originalDir);
            foreach($files as $path => $content) {
                if (preg_match('/functions\.php$/', $path))
                    $content = str_replace('\'is_preview\' => false', '\'is_preview\' => true', $content);
                if (preg_match('/script\.js$/', $path))
                    $content = str_replace('var PREVIEW = false', 'var PREVIEW = true', $content);
                if (preg_match('/^app|editor/', $path))
                    continue;
                $pos_last_slash = strrpos($path, "/");
                $fullpath = $editorDir . '/' . $path;
                if (false !== $pos_last_slash) {
                    $currentDir = $editorDir . '/' . substr($path, 0, $pos_last_slash + 1);
                    Helper::createDir($currentDir);
                }
                $content = $preview->restoreDataId($path, $content);
                file_put_contents($fullpath, $content);
            }
            // change doctype declaration to html5
            $app =  JFactory::getApplication('administrator');
            $indx = JPATH_ADMINISTRATOR . '/templates/' . $app->getTemplate() . '/index.php';
            if (file_exists($indx) && is_writable($indx)) {
                $content = file_get_contents($indx);
                $content = preg_replace('/<!DOCTYPE[^>]*>/', '<!DOCTYPE html>', $content);
                $ieCompatible = '<meta http-equiv="X-UA-Compatible" content="IE=edge" />';
                if (false === strpos($content, $ieCompatible))
                    $content = preg_replace("/(<head[^>]*>)/", "$1\r\n  " .  $ieCompatible, $content);
                file_put_contents($indx, $content);
            }
        }

        $jQuery =  JURI::root(true) . '/templates/' . $config['themeObject']->template . '/jquery.js';
        $document->addScript($jQuery);
        $core =  JURI::root(true) . '/media/system/js/core.js';
        $document->addScript($core);

        ob_start()
    ?>
    <script>
    var showDesigner = '<?php echo $showDesigner; ?>',
        config = {
            index           : '<?php echo self::$appIndex; ?>',
            templateId      : '<?php echo self::$themeId; ?>',
            revision        : '<?php echo self::$revision; ?>',
            projectData     : <?php  echo self::$projectData; ?>,
            cssJsSources    : <?php  echo self::$cache; ?>,
            md5Hashes       : <?php  echo self::$hashes; ?>,
            infoData        : <?php  echo self::$infoData; ?>
        };

    jQuery(function ($) {
        $('#<?php echo $config['parameterObject']->id; ?>').click(function (e) {
            e.preventDefault();
            if (!showDesigner) {
                var params = {};
                params.siteTitle = $('#jform_params_siteTitle').val();
                params.siteSlogan = $('#jform_params_siteSlogan').val();
                params.logoFile = $('#jform_params_logoFile').val();
                $.ajax({
                    type: "post",
                    url: config.index,
                    dataType: "json",
                    data: {
                        action: 'setParameters',
                        templateId  : config.templateId,
                        params      : params
                    },
                    success: function () {},
                    error: function () {}
                });
                $('#edit').click();
            } else {

                $('head, body').html('');

                head = document.getElementsByTagName('head')[0];
                provider = document.createElement('script');

                provider.type= 'text/javascript';
                provider.src= '<?php echo self::$startFiles['dataProvider']; ?>';
                head.appendChild(provider);
                provider.onload = function() {
                    var start = document.createElement('script');
                    start.type = 'text/javascript';
                    start.src = '<?php echo self::$startFiles['start']; ?>';
                    head.appendChild(start);
                };
            }
        });

        $('#edit').click(function () {
            document.location.href = $(this).attr('href');
        });

        if (showDesigner) {
            $('#<?php echo $config['parameterObject']->id; ?>').click();
        }
    });

</script>
    <button name="<?php echo $config['parameterObject']->name; ?>" id="<?php echo $config['parameterObject']->id; ?>">Edit Template</button>
    <a id="edit" href="<?php echo $_SERVER['REQUEST_URI'].'&editor=1'; ?>" style="display:none"></a>
    <?php
      return ob_get_clean();
    }

    private static function initialize($themeObject)
    {
        self::$base             = '' !== JURI::root(true) ? JURI::root(true) : '../../..';
        self::$themeId          = $themeObject->id;
        self::$themeName        = $themeObject->template;

        $infoData['isThemeActive'] = 1 == $themeObject->home ? true : false;
        $infoData['themeName'] = $themeObject->template;

        $themePath = JPATH_SITE . '/templates/' . self::$themeName;
        include_once $themePath . '/app/' . 'Helper.php';
        include_once $themePath . '/app/' . 'Project.php';
        include_once $themePath . '/app/' . 'Storage.php';
        include_once $themePath . '/app/' . 'Preview.php';

        Project::$projectFile = JPATH_SITE . '/templates/' . self::$themeName . '/app/project.json';

        $domain = Project::getProperty('domain');

        self::$projectData = json_encode(Project::getProperty('projectdata'));
        self::$revision = Project::getProperty('revision');

        $ver = md5(round(microtime(true)));
        self::$startFiles['dataProvider'] =  JURI::root(true) . '/templates/' . self::$themeName . '/app/DataProvider.js?version=' . $ver;
        self::$startFiles['start'] = $domain . '/loader/start.js?version=' . $ver;

        $infoData['templates'] = self::getThemeTemplates(); // here initialized homeLink
        $infoData['cmsVersion'] = self::getVersions();

        $infoData['startPage'] = self::$base . '/' . (self::$homeLink ? self::$homeLink . '&' : '?') . 'template=' . self::$themeName . '&is_preview=on';
        $infoData['adminPage'] = self::$base . '/' . 'administrator';

        self::$appIndex = self::$base  . '/templates/' . self::$themeName . '/app/' . 'index.php';

        $cacheFile = $themePath . '/app/cache.json';
        $cache = new Cache($cacheFile);
        self::$cache = $cache->get()->toJson();

        $hashesFile = $themePath . '/app/hashes.json';
        $hashes = new Hash($hashesFile);
        self::$hashes = $hashes->get()->toJson();

        self::$infoData = json_encode($infoData);
    }

    private static function getVersions()
    {
        $versions = array('joomla' => JVERSION);
        if (!class_exists('VmConfig')) {
            $configFile = dirname(JPATH_COMPONENT_ADMINISTRATOR) . '/com_virtuemart/' . 'helpers/' . 'config.php';
            if (file_exists($configFile)) {
                require($configFile);
                $versions['virtuemart'] = VmConfig::getInstalledVersion();
            }
        } else {
            $versions['virtuemart'] = VmConfig::getInstalledVersion();
        }
        return $versions;
    }

    private static function isPageCheckItem($item)
    {
        $params = $item->params;
        if ('0' !== $params->get('show_category'))
            return false;
        if ('0' !== $params->get('show_create_date'))
            return false;
        if ('0' !== $params->get('show_modify_date'))
            return false;
        if ('0' !== $params->get('show_publish_date'))
            return false;
        if ('0' !== $params->get('show_author'))
            return false;
        if ('0' !== $params->get('show_print_icon'))
            return false;
        if ('0' !== $params->get('show_email_icon'))
            return false;
        return true;
    }

    private static function getThemeTemplates()
    {
        $resultTemplatesList = array();
        $client = JApplicationHelper::getClientInfo(0);
        $pathToManifest = JPath::clean($client->path.'/templates/' . self::$themeName . '/templateDetails.xml');
        if (file_exists($pathToManifest) && JRequest::getVar('editor')) {

            // instantiate the frontend application.
            JFactory::$application = JApplication::getInstance('site');

            // create templates list
            $site   = JFactory::getApplication('site');
            $menu   = $site->getMenu('site');
            if (0 == JRequest::setVar('Itemid'))
                JRequest::setVar('Itemid', $menu->getDefault()->id);
            $menuModules = array();
            $xml = simplexml_load_file($pathToManifest);
            if (isset($xml->positions[0])) {
                foreach ($xml->positions[0] as $position) {
                    $modules = JModuleHelper::getModules($position);
                    foreach ($modules as $mod) {
                        if('mod_menu' == $mod->module) {
                            $menuModules[] = $mod;
                        }
                    }
                }
            }
            $possibleTemplatesList = array();
            foreach ($menuModules as $menu) {
                $params = new JRegistry;
                $params->loadString($menu->params);
                require_once $client->path.'/modules/mod_menu/helper.php';
                $list = modMenuHelper::getList($params);
                foreach($list as $item) {
                    if (isset($item->query['option'])) {
                        $value = $item->query['option'];
                        $view = $item->query['view'];
                        $link = $item->link . (isset($item->id) ? '&Itemid=' . $item->id : '');
                        if (isset($item->query['view'])) {
                            $value .= '@' . $item->query['view'];
                            if ('article' === $view)
                                $value .= self::isPageCheckItem($item) ? '@is_page' : '';
                        }

                        if (!in_array($value, $possibleTemplatesList))
                            $possibleTemplatesList[$link] = $value;

                        if ($item->home && '*' === $item->language) {
                            self::$homeLink = $link;
                            $possibleTemplatesList[$link] = '#';
                            /*$index = array_search($value, $possibleTemplatesList);
                            if (false !== $index)
                                unset($possibleTemplatesList[$index]);
                            $possibleTemplatesList[$link] = $value;*/
                        }
                    }
                }
            }
            $existsTemplatesList = array('shoppingCartTemplate' => 'com_virtuemart@cart', 'products' => 'com_virtuemart@category',
                'productOverview' => 'com_virtuemart@productdetails', 'singlePostTemplate' => 'com_content@article',
                'blogTemplate' => 'com_content@category', 'pageTemplate' => 'com_content@article@is_page', 'home' => '#');

            $previewGets = '&template=' . self::$themeName . '&is_preview=on';
            foreach($existsTemplatesList as $name => $etl) {
                foreach($possibleTemplatesList as $url => $ptl) {
                    if ($etl === $ptl) {
                       $resultTemplatesList[$name] = self::$base . '/' . $url . $previewGets;
                       unset($possibleTemplatesList[$url]);
                       break;
                    }
                }
            }
            //add default template
            if (count($possibleTemplatesList) > 0) {
                $flippedArray = array_flip($possibleTemplatesList);
                $defaultLink = self::$base . '/' . array_shift($flippedArray) . $previewGets;
            } else {
                $defaultLink = '';
            }
            $resultTemplatesList['default'] = $defaultLink;
            //add 404 template
            $resultTemplatesList['template404'] = self::$base . '/index.php?option=com_error' . $previewGets;
            // instantiate the backend application.
            JFactory::$application = JApplication::getInstance('administrator');
        }
        return $resultTemplatesList;
    }
}--*@