<?php
    /**
    * @package tcshortcodes plugin
    * @author themescreative http://www.themescreative.com
    * @copyright Copyright (c) 2010 - 2013 themescreative
    * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or Later
    */	

    //no direct accees
    defined ('_JEXEC') or die ('resticted aceess');

    jimport( 'joomla.event.plugin' );
    $jversion = new JVersion;
	$document = JFactory::getDocument();
	if (version_compare($jversion->getShortVersion(), '3.0.0', '<')){
	$document->addScript('https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js');
	}
    class  plgSystemtcshortcodes extends JPlugin
    {
        function onAfterInitialise()
        {
            $tcshortcodes_path = JPATH_PLUGINS.'/system/tcshortcodes/core/tcshortcodes.php';
            if (file_exists($tcshortcodes_path)) {
                require_once($tcshortcodes_path);
                tcshortcodes::getInstance();

            } else {
                echo JText::_('tcshortcodes not found.');
                jexit();
            }
        }


        function onAfterRender()
        {
            if(  !JFactory::getApplication()->isAdmin() ){

                $document = JFactory::getDocument();
                $type = $document->getType();

                if($type=='html') {

                    $oldhead = $document->getHeadData();  // old head

                    $data =  JResponse::getBody();
                    tcshortcodes::getInstance()->importShortCodeFiles();

                    $data = shtcode_unautop($data);
                    $data = do_shtcode($data); 
                    $newhead = $document->getHeadData();  // new head
                    $scripts =  (array)  array_diff_key($newhead['scripts'], $oldhead['scripts']);
                    $styles  =  (array) array_diff_key($newhead['styleSheets'], $oldhead['styleSheets']);

                    $new_head_data = '';

                    foreach ($scripts as $key => $type)
                        $new_head_data .= '<script src="' . $key . '"></script>';

                    foreach ($styles as $key => $type)
                        $new_head_data .=  '<link rel="stylesheet" href="' . $key . '" />';

                    $data = str_replace('</head>', $new_head_data . "\n</head>", $data);

                    JResponse::setBody($data);
                }
            }
        }

}