<?php
//          putenv("ORACLE_HOME=/local/opt/oraclient/product/8.1.7");
//          putenv("ORA_NLS=/local/opt/oraclient/product/8.1.7/ocommon/nls/admin/data");
//          putenv("NLS_LANG=american_america.we8iso8859p1");
	// Start session first since sessions are cookie-based!
	session_start();
		
	// Include project header-file
	// Must be dlo.inc in current directory in order for admin-module to work...
	require("dlo.inc");
	
	$lanCode=filter_input(INPUT_GET, "language", FILTER_SANITIZE_STRING);
	$articleID=filter_input(INPUT_GET, "articleID", FILTER_VALIDATE_INT);
	
	// Set language
	if (isset($lanCode)) {
		setcookie("dloLanguage", $lanCode, time() + 30*24*60*60, "/", false, true);
	} else if (isset($dloLanguage)) {
		$lanCode=$dloLanguage;
	} else {
		$lanCode="NO";
	}	
	
	// Set default article if no article is specified
	if(!isset($articleID)) { $articleID=DEFAULT_ARTICLE; }	
	
	$db = new dbLinks(); // dbLinks extends dbTemplates
	
	$tpl=beginPage(PROJECT_PAGE_NAME);
	$tpl->assign("currentArticleID", $articleID);

	$SQL="SELECT articleID, parentID, category, isIndex, showInIndex, title, ingress, article, ".FLD_ARTICLEDATE.", articleType, image FROM ".TBL_ARTICLES." WHERE articleID=:id";
	$resRow=$db->safeTemplateAssignSQL($SQL, $tpl, 0, 0, [":id" => $articleID]);
	
	// Output some debug-information
	// echo "Debug:<br>";
	// echo "ArticleType: ".$resRow["ARTICLETYPE"]."<br>";
	
	switch ($resRow['ARTICLETYPE']) {
		case '2':
			$quizID=filter_input(INPUT_GET, "quizID", FILTER_VALIDATE_INT);

			if($quizID) {
				// Parse Quiz part.

				$db->tplLinkMenu($tpl, "navigationTree", "navtree", $lanCode, $articleID);
											
				if($_SESSION['dloQuizSequence'][++$_SESSION['dloQuizSequenceIndex']]) {
					
					$tpl->assign(array(
						"childLinks" => "<A HREF='index.php?articleID=".$resRow['ARTICLEID']."&quizID=".$_SESSION['dloQuizSequence'][$_SESSION['dloQuizSequenceIndex']]."'><IMG SRC='".BUTTONLIB."quiz_red.gif' name='button5' onmouseover='img_act(\"button5\")' onmouseout='img_inact(\"button5\")' alt='Neste tilfeldige quiz' width='50' height='35' border='0'></A>",
						"imageNavigation" => ""
					));
				} else {
					$tpl->assign(array(
						"childLinks" => "<IMG SRC='".BUTTONLIB."quiz_gray.gif' alt='Quiz ferdig' width='50' height='35'>",
						"imageNavigation" => "",
						"ARTICLE" => ""
					));
				}

				$SQL_tmp = "SELECT image FROM ".TBL_ARTICLES." WHERE articleid=:id";

				$resRow_tmp = $db->safeTemplateAssignSQL($SQL_tmp, $tpl, 0, 0, [":id" => $quizID]);
				
				$tpl->assign(array(
					"IMAGE" => $resRow_tmp['IMAGE'],
					"Width" => "1100",
					"Height" => "660"
				));					

				$tpl->define(array("ARTICLE" => "flash_image.tpl"));

				$tpl->parse("ARTICLE","ARTICLE");	
			
			} else { // First time visited.
				// Quiz-article
				// Startpage for a RANDOM Sequence of articles
				
				$resArray = array();
				
				// We need the QuizClass...
				require('../Includes/dbQuizSelect.class');
				$qSel = new dbQuizSelect();
				$qSel->getRandomArray($resArray, $resRow, $db);

				if(count($resArray) != 0) {

					$i=0;
					
					$_SESSION['dloQuizSequence']=$resArray;//$sequence;
					$_SESSION['dloQuizSequenceStartID']=$articleID;
					$_SESSION['dloQuizSequenceIndex']=0;
					$_SESSION['dloQuizSequenceCurrentArticle']=$_SESSION['dloQuizSequence'][0];
				
					$db->currentArticle=$articleID;
					$db->tplLinkMenu($tpl, "navigationTree", "navtree", $lanCode, $articleID);
				
					$tpl->assign(array(
						"childLinks" => "<A HREF='index.php?articleID=".$resRow['ARTICLEID']."&quizID=".$_SESSION['dloQuizSequence'][$_SESSION['dloQuizSequenceIndex']]."'><IMG SRC='".BUTTONLIB."quiz_red.gif' name='button5' onmouseover='img_act(\"button5\")' onmouseout='img_inact(\"button5\")' alt='Start quiz' width='50' height='35' border='0'></A>",
						"imageNavigation" => ""
					));
				} else {
					$db->tplLinkMenu($tpl, "navigationTree", "navtree", $lanCode, $articleID);

					$tpl->assign(array(
						"childLinks" => "<H3>Ingen quiz tilgjenglig.</H3>",
						"imageNavigation" => ""
					));
				}
			}
								
			$tpl->parse("mainText", ".article");
			break;
	
		case '4':
			// This is not used at the moment...

			$db->currentArticle=$articleID;
			$db->tplLinkMenu($tpl, "navigationTree", "navtree", $lanCode, $articleID);
			
			$tpl->define(array(
				"imagemap" => "imagemap.tpl"
				));
			
			$SQL="SELECT mapID, image, areas FROM dlo2_imagemaps WHERE articleID=$articleID";
			$imagemapRow = $db->templateAssignSQL($SQL, $tpl);

			$tpl->parse("mainText", "imagemap");
			break;
			
		case '5':
		case '6':
		case '8':
		case '9':
			$db->currentArticle=$articleID;

			// Since the bread crumb trail needs an article that is in index and/or is an index,
			// one has to search for the first article that has these qualities and insert it into
			// the $db->tplLinkMenu(...)

			$resRow_tmp = $resRow;
			/*			
			while($resRow_tmp['SHOWININDEX'] == '0' && $resRow_tmp['ISINDEX'] == '0') {
				$SQL_tmp = "SELECT articleID, parentID, showinindex, isindex FROM ".TBL_ARTICLES." WHERE articleID=".$resRow_tmp['PARENTID'];
				
				$db->Query($SQL_tmp);

				$resRow_tmp = $db->fetch_row("ASSOC");
			}
			*/
			$db->tplLinkMenu($tpl, "navigationTree", "navtree", $lanCode, $resRow_tmp['ARTICLEID']);

			$tpl->define(array(
				"img_article" => "img_article.tpl",
				"image_menu" => "image_menu.tpl",
			));			

			$tpl->assign("ProjectRoot", "$PROJECT_ROOT");

			$nav = new navigationBar();
						
			if($_GET['isImageMap'] == '1') {			
			
				// An image map.

				$nav->createNavBar($tpl, "imageNavigation", "image_menu", $articleID, '1');

				$SQL="SELECT mapID, image, areas FROM ".TBL_IMAGEMAPS." WHERE articleID=$articleID";
				$imagemapRow = $db->templateAssignSQL($SQL, $tpl);
				
			} else if ($resRow['ARTICLETYPE'] == '8') {
				$tpl->assign(array(
					"imageNavigation" => "",
//					"Width" => "100%",
//					"Height" => "100%"
					"Width" => "1100",
					"Height" => "660"
				));

				$tpl->define(array(
					"imageInArticle" => "flash_image.tpl"
				));
			} else if ($resRow['ARTICLETYPE'] == '9') {

				$nav->createNavBar($tpl, "imageNavigation", "image_menu", $articleID);

				$tpl->assign(array(
					"Width" => "1100",
					"Height" => "660"
				));

				$tpl->define(array(
					"img_article" => "flash_article.tpl"
				));
				$tpl->define(array(
					"imageInArticle" => "art_image.tpl"
				));
			} else {
				$nav->createNavBar($tpl, "imageNavigation", "image_menu", $articleID);

				$tpl->define(array(
					"imageInArticle" => "art_image.tpl"
				));
			}
			
			$tpl->parse("imageInArticle","imageInArticle"); 

			$tpl->parse("mainText","img_article");

			break;
			
		case "11": // Decisionpoints
				
				// These articles has lot of special features, and needs to be handled all in a special way
				$tpl->define(array(
					"nextActive" => "decision_next_active.tpl",
					"nextInActive" => "decision_next_inactive.tpl"
					));
				
				// Navigation
					if ($resRow["SHOWININDEX"]) {
						// This is a startpage, and as such should appear in the navigationTree
						$db->tplLinkMenu($tpl, "navigationTree", "navtree", $lanCode, $resRow['ARTICLEID']);
						// And it should also be the owner of all the others in the mix
						$_SESSION["dlodecisionpointOwner"]=$resRow['ARTICLEID'];
					} else {
						// This is not a starpage, so use the owner set before as entry-point for the navigatiob.
						$db->tplLinkMenu($tpl, "navigationTree", "navtree", $lanCode, $_SESSION["dlodecisionpointOwner"]);
					}
				
				// Get the current article's information from the decisions-table
				$SQL_AUX="SELECT * FROM ".TBL_DECISIONS." WHERE articleID=".$articleID;
				$db->Query($SQL_AUX);
				$auxRow=$db->fetch_row('ASSOC');
				
				// Define default template if it's missing
				if (!$auxRow["TEMPLATEID"]) { $auxRow["TEMPLATEID"]=1; }
				
				$tpl->define(array(
					// templateID is numeric from db, define the templateas decision_<templateID>.tpl
					"decisionPoint" => "decision_".$auxRow["TEMPLATEID"].".tpl",
					"decisionAnswer" => "decision_answer.tpl"
					));
				
				// Now, lets find the current article's potensial answers
				$SQL="SELECT articleID AS answerID, title AS answerTitle FROM ".TBL_ARTICLES." WHERE parentID='$articleID' ORDER BY articleOrder";
				$db->templateParseSQL($SQL, $tpl, "answers", "decisionAnswer");

				
				switch ($auxRow["TEMPLATEID"]) {
					case '1': // Article should be shown in it's own page
						if ($auxRow["NEXTARTICLEID"]) {
							if (!$auxRow["REQUIRECORRECT"]) {
								$tpl->assign("NEXTARTICLEID", $auxRow["NEXTARTICLEID"]);
								$tpl->parse("nextButton", "nextActive");
							} else {
								$tpl->parse("nextButton", "nextInActive");
							}
						} else {
							$tpl->assign("nextButton", "");
						}
						break;
						
					case '2':
						
						// Also display parent
						$SQL="SELECT ingress AS parentingress, article as parentarticle, nextarticleid as parentNextArticleID, requireCorrect as PARENTREQUIRECORRECT FROM ".TBL_ARTICLES.", ".TBL_DECISIONS." WHERE ".TBL_ARTICLES.".articleID=".TBL_DECISIONS.".articleID AND ".TBL_ARTICLES.".articleID=".$resRow["PARENTID"];
						$parentRow=$db->templateAssignSQL($SQL, $tpl);
						
						// Now, lets find the parent's answers
						$SQL="SELECT articleID AS answerID, title AS answerTitle FROM ".TBL_ARTICLES." WHERE parentID=".$resRow["PARENTID"]."ORDER BY articleOrder";
						$db->templateParseSQL($SQL, $tpl, "parentAnswers", "decisionAnswer");

						// Next article
						if ($parentRow["PARENTNEXTARTICLEID"]) {
							// Parent has a next-article, show it?
							if (($parentRow["PARENTREQUIRECORRECT"]&&$auxRow["ISCORRECT"]) || !$parentRow["PARENTREQUIRECORRECT"]) {
								$tpl->assign("NEXTARTICLEID", $parentRow["PARENTNEXTARTICLEID"]);
								$tpl->parse("nextButton", "nextActive");
							} else {
								$tpl->parse("nextButton", "nextInActive");
							}
						} else {
							$tpl->assign("nextButton", "");
						}
						break;
				}
				
				$tpl->parse("mainText", "decisionPoint");
			break;
		default:
			// This is the default article-mode (also known as articleType 1)
			// Nav Tree

			$db->currentArticle=$articleID;

			// Since the bread crumb trail needs an article that is in index and/or is an index,
			// one has to search for the first article that has these qualities and insert it into
			// the $db->tplLinkMenu(...)

			$resRow_tmp = $resRow;
			/*			
			while($resRow_tmp['SHOWININDEX'] == '0' && $resRow_tmp['ISINDEX'] == '0') {
				$SQL_tmp = "SELECT articleID, parentID, showinindex, isindex FROM ".TBL_ARTICLES." WHERE articleID=".$resRow_tmp['PARENTID'];
				
				$db->Query($SQL_tmp);

				$resRow_tmp = $db->fetch_row("ASSOC");
			}
			*/
			$db->tplLinkMenu($tpl, "navigationTree", "navtree", $lanCode, $resRow_tmp['ARTICLEID']);

			$tpl->assign("imageNavigation", "");			

			if ($resRow["ISINDEX"]) {
				// Current article is an index, display the children 	
				$db->tplLinkList($tpl, "childLinks", "linkList", $resRow["ARTICLEID"]);
			} 
			
			$tpl->parse("mainText", ".article");
			break;
	}

	// Add admin-console if admin
	if (isset($_SESSION["dloIsAdmin"])) {
		$tpl->define(array(
			"adminAddChild" => "adm_cmdAddChild.tpl",
			"adminAddNext" => "adm_cmdAddNext.tpl"
			));
			
		switch ($resRow["ARTICLETYPE"]) {
			case '11':
					$tpl->parse("adminAddButton", "adminAddNext");
				break;
			default:
					$tpl->parse("adminAddButton", "adminAddChild");
				break;
		} // end switch

		$tpl->parse("adminConsole", "admin");
	};
	
	$tpl->parse("main", "main");
	$tpl->parse("main", "uio_profil");
	$tpl->FastPrint();
?>




