<?php

class vB5_Template_Javascript
{

	protected static $instance;
	protected $pending = array();

	public static function instance()
	{
		if (!isset(self::$instance))
		{
			$c = __CLASS__;
			self::$instance = new $c;
		}

		return self::$instance;
	}

	public function register($files)
	{
		foreach ($files as $file)
		{
			if (!in_array($file, $this->pending))
			{
				$this->pending[] = $file;
			}
		}
	}

	public function resetPending()
	{
		$this->existing = array();
		$this->pending = array();
	}

	public function insertJs(&$content)
	{
		$config = vB5_Config::instance();

		$simpleversion = vB5_Template_Options::instance()->get('options.simpleversion');;

		$replace = '';
		foreach($this->pending as $js)
		{
			$replace .= '<script type="text/javascript" src="' . htmlspecialchars("{$config->baseurl}/$js?v=$simpleversion") . "\"></script>\n";
		}

		if (stripos($content, '</body>') !== FALSE)
		{
			$replace .= '</body>';
			$content = str_replace('</body>', $replace, $content);
		}
		else
		{
			$content .= $replace;
		}
	}
}
