<?php
/*
 * 				Marcel Boersma
 */


class Template_parser{
	
		var $error = 0;
		var $opmaak;
		var $menu;
		var $files = array();
		var $page;
		var $content;
	
		function _constructor($page){
			
			if(empty($page)){
				$this->page = "home.0";
			}else{
				$this->page = $page;
			}
			
			
			if( ! opendir("tekst/") && !opendir("index/") ){
				$this->error = 1;
				$this->printerror();
			}
			if($this->error == 0){
		        
				$this->_buildmenu();
				$this->_buildcontent();
				
			    $Handler_all= fopen("index/index.html", "r");
                $allread= fread($Handler_all,filesize("index/index.html"));
                $Full_index=$allread;
                
                $this->opmaak .= $this->menu;
                $this->opmaak .= $this->content;
                
                $TEMPLATE=$Full_index;
                $TEMPLATE=str_replace("{INSERT_CONTENT}",$this->opmaak,$TEMPLATE);
				
				
				
				$this->opmaak .= $TEMPLATE;
				
				return $TEMPLATE;			
			
			}
		}
		
		function _buildmenu(){
			$this->menu = "<div id='menu'>\n\t\t<ul>\n";
			
				if($handle = opendir("tekst/")){
					while(false !== ($file = readdir($handle))){
						if($file != ".." && $file != "." && !empty($file) && $file != ".DS_Store"){
							array_push($this->files, $file);
						}
					}
				}
				if(count($this->files) != 0){
					
					$this->resort_array();
					
					for($i = 0; $i< count($this->files); $i++){
						
							$titel = explode(".", $this->files[$i]);
							$this->menu .= "\t\t\t<li><a href = '?page=".$this->files[$i]."'>".$titel[0]."</a></li>\n";
					}
				}else{
						$this->menu .= "\t\t\t<li><a href='?page=home.html'>home</a></li>\n";
				}
				
				$this->menu .= "\t\t</ul>\n\t</div>\n";
		
				
		}
		
		function _buildcontent(){
				$this->content .= "<div id='content'>\n";
			
				if(!in_array($this->page, $this->files)){
					$this->error = 2;
					$this->printerror();
				}else{
				
					$file = "tekst/".$this->page;
					$Handler_all = fopen($file , "r");
          	        $allread = fread($Handler_all,filesize($file));
                    $Full_index = $allread;
                    
					$this->content .= $Full_index;
				}
				
				$this->content .= "\n</div>";
			
		}
		
		function printerror(){
			switch($this->error){
				case '1' : $message = "De map 'tekst' en/of 'index' bestaat niet!";
				break;
				case '2' : $message = "Pagina bestaat niet!";
			}
			echo $message;
			exit();
		}
		
		function resort_array(){
				foreach($this->files AS $key => $value ){
							$array_key = explode(".", $value);
							$this->files[$array_key[1]] = $value;
				}
		}
	
}

$pagetype=htmlspecialchars($_GET['page']);

$object = new Template_parser();
echo $object->_constructor($pagetype);


?>