<?php
/**
* @package css2switch
* @author Dominik Gorczyca - mediahof
* 
* --------------------------------------------------------------------------------
* All rights reserved.  css2switch Plugin for Joomla! 1.5
*
**/
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.event.plugin');

class plgSystemCss2switch extends JPlugin
{
	var $cssItems	= false;
	var $altcss		= false;
	var $cssreal	= false;
	var $stdTmpl	= false;

	function OnAfterRender()
	{
		if (strpos($_SERVER['REQUEST_URI'], '/administrator/index') === true) {
			return false;
		}
		global $mainframe;
		$Itemid = JRequest::getInt( 'Itemid' );
		$classFile = JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_css2switch'.DS.'css2switch.class.php';
		if (file_exists($classFile))
		{
			require_once($classFile);
		}
		else
		{
			return false;
		}
		
		$c2s =& new css2switch;
		
		if (!empty($Itemid))
		{
			$this->cssItems = $c2s->tabelleAuslesen('css2switch_items', 'items = '.$Itemid);
			if (is_object($this->cssItems))
			{
				$this->altcss = $this->cssItems->css_datei;
				if ( $this->cssItems->parentid == 'x' || $this->cssItems->parentid == '0' )
				{
					$this->cssreal = $this->altcss;
				}
				else
				{
					$this->cssItems = $c2s->tabelleAuslesen('css2switch_items', 'items = '.$this->cssItems->parentid);
					if ( $this->cssItems->parentid == '0' && $this->altcss == '')
					{
						$this->cssreal = $this->cssItems->css_datei;
					}
					else if ( $this->cssItems->parentid == 'x' || $this->altcss != '')
					{
						$this->cssreal = $this->altcss;
					}
				}
				if (empty($this->cssreal))
				{
					$stdTmpls = $c2s->tabelleAuslesen('css2switch_menutype');
					$menus = $c2s->tabelleAuslesen('menu', 'id='.$Itemid);
					for ($tmpl = 0; $tmpl < count($stdTmpls); $tmpl++)
					{
						if ($stdTmpls[$tmpl]->menutype == $menus->menutype)
						{
							$this->stdTmpl = $stdTmpls[$tmpl]->default_templ;
						}
					}
				}
				$c2s_css		= $this->cssreal;
				$c2s_stdcss		= $this->stdTmpl;
				$c2s_templ		= $mainframe->getTemplate();
				$c2s_website	= JURI::base(true);
			}
			$c2s = null;
			$puffer = JResponse::getBody();
			
			$css_datei = '<!-- Style inserted by css2switch - mediahof -->'."\n"
						.'<link rel="stylesheet" href="'.$c2s_website.'/templates/'.$c2s_templ.'/css/'.$c2s_css.'" '
						.'type="text/css" media="screen" />'."\n";

			$generator = '<meta name="generator" content="';
			$komponente = 'css2switch by Dominik Piotr Gorczyca - www.mediahof.de';
			$puffer = preg_replace('/'.$generator.'(.*?)"(.*?)>/is', $generator.'$1, '.$komponente.'"$2>', $puffer,1);
			if (empty($c2s_css) && strpos($puffer, $c2s_stdcss) === false)
			{
				$css_datei = str_replace('/css/', '/css/'.$c2s_stdcss, $css_datei);
				$c2s_css = 1;
			}
			if(!empty($c2s_css))
			{
				$puffer = preg_replace('/<head(| .*?)>(.*?)<\/head>/is', '<head$1>$2'.$css_datei.'</head>', $puffer,1);
			}
			
			JResponse::setBody(str_replace("\t", ' ', $puffer));
		}
	}
}

?>