<?php

require_once('Login.class.php');

class Template {
	private $indent = 0;
	private $ret = false;
	private $base = '/';
	private $db = null;

	public function status($status) {
		header($_SERVER["SERVER_PROTOCOL"]." $status"); 
		header("Status: $status");
	}
	
	public function __construct($base_url, $mm=null) {
		$this->base = $base_url;
		if ($mm!==null)
			$this->db = $mm->database();
	}
	
	public function setRet($ret) {
		$this->ret = $ret;
	}
	
	private function tabs() {
		$str = '';
		for ($i=0;$i<$this->indent;$i++) { $str .= "\t"; }
		return $str;
	}

	private function attr($attr='') {
		$tags='';
		if (is_array($attr)) {
			foreach($attr as $key=>$value) {
				$tags .= " $key=\"$value\"";
			}
		}
		return $tags;
	}
	
	public function tag($tag, $attr='', $content=false) {
		$tags = $this->attr($attr);
		$str = $this->tabs()."<$tag$tags";
		if ($content===false) {
			$str.= " />";
		} else {
			$str.= ">$content</$tag>";
		}
		$str.= "\n";
		if ($this->ret) return $str;
		echo $str;
	}
	
	public function openTag($tag, $attr='') {
		$tags = $this->attr($attr);
		$str = $this->tabs()."<$tag$tags>\n";
		$this->indent++;
		if ($this->ret) return $str;
		echo $str;
	}
	
	public function closeTag($tag) {
		$this->indent--;
		$str = $this->tabs()."</$tag>\n";
		if ($this->ret) return $str;
		echo $str;
	}

	public function text($text) {
		$str = $this->tabs().$text."\n";
		if ($this->ret) return $str;
		echo $str;
	}

	public function paragraph($text, $attr='', $return=false) {
		$tabs = $this->tabs();
		$tags = $this->attr($attr);
		$str = $tabs."<p$tags>";
		$str.= wordwrap($text, 78-($this->indent*8), "\n$tabs  ");
		$str.= "</p>\n";
		if ($this->ret||$return) return $str;
		echo $str;
	}

	public function link($target, $text, $return=false) {
		$ret = $this->ret;
		$this->ret |= $return;
		$str = $this->tag('a', array('href'=>$target), $text);
		$this->ret = $ret;
		if ($this->ret||$return) return $str;
		echo $str;		
	}
	public function url($page) {
		return $this->base.$page;
	}

	public function row($cells) {
		$str = $this->openTag('tr');
		foreach ($cells as $cell)
			$str.= $this->tag('td', array(), $cell);
		$str.= $this->closeTag('tr');
		if ($this->ret) return $str;
		echo $str;
	}
	private function css($file, $media) {
		$str.= $this->tag('link', array('rel'=>"stylesheet",
		                                'type'=>"text/css",
		                                'href'=>$this->url($file),
		                                'media'=>$media));
		if ($this->ret) return $str;
		echo $str;
	}
	public function header($title) {
		$db = $this->db;
		if ($db==null) {
			$username = false;
		} else {
			$username = $db->getUsername(Login::isLoggedIn());
		}

		$ret = $this->ret;
		$this->ret = true;
		
		$logged_in = ($username!==false);
		
		$str = '<?xml version="1.0" encoding="utf-8"?>'."\n";
		$str.= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"'."\n";
		$str.= '"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'."\n";
		
		$xmlns = "http://www.w3.org/1999/xhtml";
		$str.= $this->openTag('html', array('xmlns'=>$xmlns,
		                                    'lang'=>"en-us",
		                                    'dir'=>"ltr"));
		$this->indent = 0; // don't indent for the <html> tag
		
		$str.= $this->openTag('head');
		$str.= $this->tag('title', array(), htmlspecialchars($title));
		$str.= $this->css('style.css', 'all');
		$str.= $this->css('screen.css', 'screen');
		$str.= $this->css('logo-style.css', 'screen');
		$str.= $this->closeTag('head');
		
		$body_class = 'logged'.($logged_in?'in':'out');
		$str.= $this->openTag('body', array('class'=>$body_class));

		$str.= $this->openTag('div', array('class'=>'infobar'));
		if ($logged_in) {
			$user = htmlentities($username);
			
			$str.= $this->link($this->url(''), "Home");
			$str.= $this->link($this->url("users/$user"),"@$user");
			$str.= $this->logout_button('Logout');
		} else {
			$url=$_SERVER['REQUEST_URI'];
			$str.= $this->openTag('form',
			                      array('action'=>$this->url('auth'),
			                            'method'=>'post'));
			$str.= $this->tag('input', array('type'=>'hidden',
			                          'name'=>'action',
			                          'value'=>'login'));
			$str.= $this->tag('input', array('type'=>'hidden',
			                          'name'=>'url',
			                          'value'=>$url));
			$str.= $this->tag('label',
			                  array('for'=>'username'),'Username:');
			$str.= $this->tag('input', array('type'=>'text',
			                          'name'=>'username',
			                          'id'=>'username'));
			$str.= $this->tag('label',
			                  array('for'=>'password'),'Password:');
			$str.= $this->tag('input', array('type'=>'password',
			                          'name'=>'password',
			                          'id'=>'password'));
			$str.= $this->tag('input', array('type'=>'submit',
			                          'value'=>'Login'));
			$str.= $this->link($this->url("users/new"),'New Account');
			$str.= $this->closeTag('form');
		}
		$str.= $this->closeTag('div');

		$str.= $this->openTag('div',array('class'=>'main'));
		$str.= $this->openTag('div',array('class'=>'main_sub'));

		$this->ret = $ret;
		if ($this->ret) return $str;
		echo $str;
	}

	public function footer() {
		$str = $this->closeTag('div');
		$str.= $this->closeTag('div');
		$str.= $this->closeTag('body');
		$str.= $this->closeTag('html');
		
		if ($this->ret) return $str;
		echo $str;
	}
	
	public function openFieldset($name, $lock=false) {
		$class = ($lock?' class="readonly"':'');
		$str = $this->text("<fieldset$class><legend>$name</legend><ul>");
		$this->indent++;
		if ($this->ret) return $str;
		echo $str;
	}
	
	public function closeFieldset() {
		$this->indent--;
		$str = $this->text("</ul></fieldset>");
		if ($this->ret) return $str;
		echo $str;
	}
	
	public function input($id, $label, $hint, $html, $tags=null) {
		if ($tags===null) { $tags=array(); }
		$str = $this->openTag('li', $tags);
		$str.= $this->tag('label', array('for'=>$id), $label);
		$str.= $this->text($html);
		if (strlen($hint)>0) {
			$str.=$this->paragraph($hint,
			                       Array('class'=>'form_data'));
		}
		$str.= $this->closeTag('li');
		if ($this->ret) return $str;
		echo $str;
	}
	
	private function inputStr($type, $id, $default, $lock) {
		$value = htmlentities($default);
		$tag = ($lock?"readonly='readonly' ":'');
		return "<input type='$type' name='$id' id='$id' value=\"$value\" $tag/>";
	}
	public function inputTextArea($id, $label, $hint='', $default='', $lock=FALSE) {
		$value = htmlentities($default);
		$tag = ($lock?"readonly='readonly' ":'');
		return $this->input($id, $label, $hint,
		                    "<textarea name='$id' id='$id' $tag>$value</textarea>",
		                    array('class'=>'wide'));
	}
		
	public function inputText($id, $label, $hint='', $default='', $lock=FALSE) {
		return $this->input($id, $label, $hint,
		                    $this->inputStr('text', $id, $default, $lock));
	}
	
	public function inputPassword($id, $label, $hint='', $default='', $lock=FALSE) {
		return $this->input($id, $label, $hint,
		                    $this->inputStr('password', $id, $default, $lock));
	}
	
	public function inputNewPassword($id, $label, $default='', $lock=FALSE) {
		return $this->input($id, $label,
		    "Type the same password twice, to make sure you don't mistype.",
		    $this->inputStr('password', $id, $default, $lock).
		    "\n".$this->tabs()."\t".
		    $this->inputStr('password', $id.'_verify', $default,$lock));
	}
	public function inputBool($id, $label, $hint='', $default=FALSE, $lock=FALSE) {
		$tag = '';
		if ($lock) $tag.= "readonly='readonly' ";
		if ($default) $tag.= "checked='checked' ";
		return $this->input($id, $label, $hint,
		                    "<input type='hidden' name='$id' value='false' />".
		                    "<input type='checkbox' id='$id' name='$id' value='true' $tag>");
		                    
		$attrib =  array('type'=>'checkbox',
		                 'id'=>$id,
		                 'name'=>$name.'[]',
		                 'value'=>$value);
		if ($default) $attrib['checked']='checked';
		if ($lock   ) $attrib['readonly']='readonly';
		
		$str = $this->openTag('li');
		$str.= $this->tag('input', $attrib);
		$str.= $this->tag('label', array('for'=>$id), $label);
		$str.= $this->closeTag('li');
		
		if ($this->ret) return $str;
		echo $str;

	}

	public function inputBoolArray($name, $value, $label, $default=FALSE, $lock=FALSE) {
		$id = $name.'_'.$value;
		$attrib =  array('type'=>'checkbox',
		                 'id'=>$id,
		                 'name'=>$name.'[]',
		                 'value'=>$value);
		if ($default) $attrib['checked']='checked';
		if ($lock   ) $attrib['readonly']='readonly';
		
		$str = $this->openTag('li');
		$str.= $this->tag('input', $attrib);
		$str.= $this->tag('label', array('for'=>$id), $label);
		$str.= $this->closeTag('li');
		
		if ($this->ret) return $str;
		echo $str;

	}
	
	public function inputP($text, $error=false) {
		$str = $this->openTag('li');
		$str.=$this->paragraph($text,
		                       array('class'=>($error?' error':'')));
		$str.= $this->closeTag('li');
		if ($this->ret) return $str;
		echo $str;		
	}
	
	public function logout_button($text) {
		$str = $this->openTag('form',array('action'=>$this->url('auth'),
		                                   'method'=>"post",
		                                   'style'=>'display:inline'));
		$str.= $this->tag('input', array('type'=>'hidden',
		                           'name'=>'action',
		                           'value'=>'logout'));
		$str.= $this->tag('input', array('type'=>'submit',
		                                 'value'=>$text));
		$str.= $this->closeTag('form');
		if ($this->ret) return $str;
		echo $str;		
	}
}