<?php

/**
 *
 * @copyright	2010 frasq.org
 * @version		1
 * @link		http://www.frasq.org
 */

require_once 'requesturi.php';

define('VIEWS_DIR', ROOT_DIR . DIRECTORY_SEPARATOR . 'views');

function dispatch($languages) {
	global $base_path;

	$req = $base_path ? substr(request_uri(), strlen($base_path)) : request_uri();

	$url = parse_url($req);
	$path = isset($url['path']) ? trim(urldecode($url['path']), '/') : false;
	$query = isset($url['query']) ? $url['query'] : false;

	if (empty($path)) {
		$path = false;
	}

	/* site language */
	$p = $path ? explode('/', $path) : false;
	$lang = $p ? $p[0] : false;

	if ($lang && in_array($lang, $languages, true)) {
		array_shift($p);
		$path = implode('/', $p);
	}
	else {
		require_once 'locale.php';

		$lang=locale();

		if (!$lang or !in_array($lang, $languages, true)) {
			$lang = $languages[0];
		}
	}
	
	if (!$path)
		$path='home';

	$output=view($path, $lang);
	
	if ($output) {
		echo $output;
	}
}

function view($view, $lang=false) {
	$file = $lang ? VIEWS_DIR.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.$view.'.phtml' : VIEWS_DIR.DIRECTORY_SEPARATOR.$view.'.phtml';
	if (!file_exists($file)) {
		header('HTTP/1.0 404 Not Found');
		exit;
	}
	return render($file);
}

function render($file) {
	global $base_path, $base_url, $base_root;
	ob_start();
	require $file;
	return ob_get_clean();
}

