<?php
	error_reporting(0);
	
	$conf = array(
		"autoload"		=> true,
		"distinct"		=> true,
		"compress"		=> false,

		"dontminify"	=> array(
			"plugin.bootstrap.datetimepicker.min.js",
		)	
	);


	$files = array(
		"jquery.min.js",
		"bootstrap.min.js",
		"jquery.ui.min.js",
		"jquery.ui.fix.js",
	);

	require_once "../../lib/debug.php";
	require_once "../../lib/include/file.php";
	require_once "../../lib/include/dir.php";

	if ($conf["compress"]) 
		require_once "../../3rdparty/minify/js.php";

	function LoadFiles() {
		global $prio , $conf , $files , $lasttime;

		$_files = CDir::GetFiles("." , "js");
		sort($_files);

		if (is_array($_files)) {

			foreach ($_files as $key => $val) {
				$_files[$key] = str_replace("./" , "" , str_replace(".js" , "" , $val));
			}


			foreach ($_files as $key => $val) {
				if (stristr($val , "plugin.")) {
					$files[] = $val . ".js";
				}				
			}			

			foreach ($_files as $key => $val) {
				if (stristr($val , "custom")) {
					$files[] = $val . ".js";
				}				
			}
		}


		foreach ($files as $key => $val) {
			if (($tmp =filectime($val)) > $lasttime) {
				$lasttime = $tmp;
			}				
		}


		$cache = "../../../upload/_cache/admin-{$lasttime}-" . (int)$conf["distinct"] . "-" . (int)$conf["compress"]. "-" . md5(json_encode($files)) . ".js";

		if (file_exists($cache)) {
			return CFile::Get($cache);
		}

		foreach ($files as $key => $val) {
			if ($conf["distinct"]) {
				$content .= "document.write('<script src=\"assets/js/{$val}\"></script>');";
			} else 	
				$content .=  "\n" . compress(CFile::Get( $val) , "{$val}");
		}

		if ($cache) {
			CFile::Save($cache , $content);
		}

		return $content;

	}

	$content = LoadFiles();


	function compress($buffer , $path ) {
		global $conf;

		if ($conf["compress"] && !in_array($path , $conf["dontminify"]) && !stristr($path, ".min.js")) {
			$buffer = Minifier::minify($buffer, array('flaggedComments' => false));
		}

		return $buffer;
	}
	
//	header('Last-Modified: '.gmdate('D, d M Y H:i:s', $lasttime ).' GMT', true, 304);
	header("ETag: \"{$lasttime}\"");

	header("Content-type: application/x-javascript");
	header("Cache-Control: max-age=2692000, public");

	header("Content-Length: ".strlen($content)); 
	echo $content;
	die();
	

?>