<?php

// -----------------------------------------------------------------------
// This file is part of AROUNDMe
//
// Copyright (C) 2003 - 2006 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.org
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option) any
// later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------

include "inc/header.inc.php";


//ACS check
if (!empty($_REQUEST['group_id'])) {
	$group_id = $_REQUEST['group_id'];
	include_once ('inc/header_group.inc.php');
	
	if (!$group_acs->checkPermission($c_acs['arr_acs']['resource']['group']['quiz'], $c_acs['arr_acs']['privilege']['allow_access'])) { //resourece_id, Priv_id
		header("Location: grp_view.php?group_id=" . $_REQUEST['group_id'] . "&" . strip_tags(SID));
		exit;
	}
	
	require_once($languagePath . 'grp_common.lang.php');
}
elseif (!isset($rss_access_granted) && (!$user_acs->checkPermission($c_acs['arr_acs']['resource']['node']['quiz'], $c_acs['arr_acs']['privilege']['allow_access']))) { //resourece_id, Priv_id
	header("Location: " . $_SESSION['user_homepage'] . "?" . strip_tags(SID));
	exit;
}


// SETUP QUIZ ------------------------------------------------------------
require_once('class/Quiz.class.php');
$quiz = new Quiz($db, null);
$quiz->rsp_level_id = $rsp_level_id;

if (isset($_REQUEST['quiz_id'])) {
	$quiz->quiz_id = $_REQUEST['quiz_id'];
}


// SETUP LANGUAGE --------------------------------------------------------
require_once($languagePath . 'common.lang.php');
require_once($languageArrayPath . 'arr_user.lang.php');


//SETUP WIKI -------------------------------------------------------------
require_once('class/Wiki/Wiki.php');
$wiki = new Text_Wiki();


// SETUP COMMENTS --------------------------------------------------------
require_once('class/Comment.class.php');
$comment = new Comment($db, $c_node['rsp']['item_type']['quiz']);

if (isset($me['user_id'])) {
	$comment->user_id = $me['user_id'];
}

$comment->wiki = $wiki;


// SETUP TAGS ------------------------------------------------------------
require_once('class/Tag.class.php');
$tag = new Tag($db, $c_node['rsp']['item_type']['quiz']);

if (isset($me['user_id'])) {
	$tag->user_id = $me['user_id'];
}


// SETUP BOOKMARKS -------------------------------------------------------
if (isset($me['user_id'])) {
	require_once('class/Bookmark.class.php');
	$bookmark = new Bookmark($db, $c_node['rsp']['item_type']['quiz'], $me['user_id']);
}


// PROCESS FORM ----------------------------------------------------------
if (isset($_REQUEST['view']) && $_REQUEST['view'] == "node") {
	unset($_REQUEST['view']);
}


if (!empty($frmdata['take_quiz'])) {
	unset($quiz->rsp_level_id);
	$quiz->quiz_id = $frmdata['quiz_id'];
	
	$output_quiz = $quiz->selQuiz(1, null);
	
	$display ="quiz";
}
elseif (!empty($frmdata['submit_quiz'])) {
	// check that each question has an answer
	unset($quiz->rsp_level_id);
	$quiz->quiz_id = $frmdata['quiz_id'];
	
	$questions = $quiz->selQuestions();
	
	if (isset($questions)) {
		foreach ($questions as $key => $q):
			// did we get an answer
			if (!isset($frmdata['answers'][$q['question_id']])) {
				$GLOBALS['am_error_log'][] = array(52, 1, $q['question_id']);
			}
		endforeach;
	}
	
	if (empty($GLOBALS['am_error_log'])) {
		// calculate, insert and display results.
		$output_quiz = $quiz->selQuiz(1);
		
		// was each answer correct?
		if (isset($output_quiz['questions'])) {
			$question_total = 0;
			$question_correct = 0;
			$question_incorrect = 0;
			
			foreach ($output_quiz['questions'] as $key => $q):
				$question_total++;
				
				if ($q['question_correct_option_id'] == $frmdata['answers'][$q['question_id']]) {
					$question_correct++;
				}
				else {
					$question_incorrect++;
				}
			endforeach;
			
			// work work this out as a percentage
			echo $question_correct;
			
			$percentage_correct = round((100 / $question_total) * $question_correct);
			// pass or fail
			if ($percentage_correct >= $output_quiz['quiz_pass_rate']) {
				$output_quiz['passed'] = true;
				$lang['txt_result_text'] = $lang['txt_quiz_pass'];
			}
			else {
				$lang['txt_result_text'] = $lang['txt_quiz_fail'];
			}
			
			// apply scored to lang text
			$lang['txt_result_text'] = str_replace('SYS_QUIZ_SCORE', $question_correct, $lang['txt_result_text']);
			$lang['txt_result_text'] = str_replace('SYS_QUIZ_TOTAL', $question_total, $lang['txt_result_text']);
			$lang['txt_result_text'] = str_replace('SYS_QUIZ_PERCENT', $percentage_correct, $lang['txt_result_text']);
			$lang['txt_result_text'] = str_replace('SYS_PASS_RATE', $output_quiz['quiz_pass_rate'], $lang['txt_result_text']);
			
			if (empty($output_quiz['quiz_retake_daycount'])) {
				$lang['txt_retake'] = "";
			}
			else {
				$lang['txt_retake'] = str_replace('SYS_RETAKE', $output_quiz['quiz_retake_daycount'], $lang['txt_retake']);
			}
			
			// insert result
			$quiz->quiz_id = $output_quiz['quiz_id'];
			$quiz->user_id = $me['user_id'];
			$data['result_mark'] = $percentage_correct;
			
			$quiz->insertResult($data);
			
			$output_quiz['answers'] = $frmdata['answers'];
			$output_quiz['percentage_correct'] = $percentage_correct;
			
		}
		
		$display = "result";
	}
	else {
		$output_quiz = $quiz->selQuiz(1);
		
		$output_quiz['answers'] = $frmdata['answers'];
		
		$display ="quiz";
	}
}
elseif (isset($_POST['update_tag'])) {
	$frmdata['item_id'] = $frmdata['quiz_id'];
	$tag->deleteItemTags($frmdata);
	$tag->insertTags($frmdata);
	
	return header("Location: pol_view.php?quiz_id=". $frmdata['quiz_id'] . "&" . strip_tags(SID));
	exit;
}
elseif (isset($_POST['preview'])) {
	unset($quiz->rsp_level_id);
	$output_comment = $frmdata;
	$output_comment['comment_body'] = stripslashes($output_comment['comment_body']);
	$output_comment['comment_body'] = str_replace("\"", "'", $output_comment['comment_body']);
	$output_comment['display_comment_body'] = $wiki->transform($output_comment['comment_body'], 'Xhtml');
	
	$quiz->quiz_id = $_REQUEST['quiz_id'];
	
	$output_quiz = $quiz->selPoll();
	
	$display = "preview_comment";
}
elseif (isset($_POST['insert'])) { // comment
	$comment->item_id = $frmdata['quiz_id'];
	$comment->item_user_id = $frmdata['item_user_id'];
	$comment->insertComment($frmdata);
	
	if (empty($GLOBALS['am_error_log'])) {
		//setup statistics
		require_once('class/Statistic.class.php');
		$statistic = new Statistic($db);
		
		if (isset($frmdata['group_id'])) {
			$comment->group_id = $frmdata['group_id'];
		}
		
		//update user stats
		$statistic->statistic_type_id = $c_node['statistic']['user']['total_comments'];
		$comment->user_id = $me['user_id'];
		$statistic->user_id = $me['user_id'];
		$statistic->setStatistic($comment->getCommentCount());
		
		if (isset($frmdata['group_id'])) {
			$statistic->group_id = $frmdata['group_id'];
			
			//update group stats
			unset($comment->user_id, $statistic->user_id, $comment->rsp_item_type_id, $comment->item_id, $comment->item_user_id);
			$statistic->statistic_type_id = $c_node['statistic']['group']['total_comments'];
			$statistic->setStatistic($comment->getCommentCount());
			
			//group member comments
			$statistic->statistic_type_id = $c_node['statistic']['group_member']['total_comments'];
			$statistic->user_id = $me['user_id'];
			$comment->user_id = $me['user_id'];
			$statistic->setStatistic($comment->getCommentCount());
		}
		
		// update bookmarks to trigger notification
		if (isset($me['user_id'])) {
			$bookmark->bookmark_type = $c_node['bookmark']['type']['watch'];
			$bookmark->updateBookmarkNotification($frmdata['quiz_id'], 1);
		}
		
		return header("Location: pol_view.php?quiz_id=". $frmdata['quiz_id'] . "&" . strip_tags(SID));
		exit;
	}
}
elseif (isset($_POST['edit_again'])) {
	$output_comment = $frmdata;
	$output_comment['comment_body'] = stripslashes($output_comment['comment_body']);
	
	$quiz->quiz_id = $_REQUEST['quiz_id'];
	
	$output_quiz = $quiz->selPoll();
}
elseif (isset($_REQUEST['bookmark']) && isset($me['user_id'])) { // bookmark options for this item
	$bookmark->item_id = $_REQUEST['quiz_id'];
	
	if ($_REQUEST['bookmark'] == "ins_mark") {
		$bookmark->bookmark_type = $c_node['bookmark']['type']['watch'];
		
		if (!empty($_REQUEST['notify'])) {
			$bookmark->insertBookmark(1);
		}
		else {
			$bookmark->insertBookmark();
		}
	}
	elseif ($_REQUEST['bookmark'] == "del_mark") {
		$bookmark->bookmark_type = $c_node['bookmark']['type']['watch'];
		$bookmark->deleteBookmark();
	}
	elseif ($_REQUEST['bookmark'] == "ins_tip") {
		$bookmark->bookmark_type = $c_node['bookmark']['type']['recommend'];
		$bookmark->insertBookmark();
	}
	elseif ($_REQUEST['bookmark'] == "del_tip") {
		$bookmark->bookmark_type = $c_node['bookmark']['type']['recommend'];
		$bookmark->deleteBookmark();
	}
	
	header("Location: pol_view.php?quiz_id=". $_REQUEST['quiz_id'] . "&" . strip_tags(SID));
	exit;
}
elseif (isset($_REQUEST['view'])) {
	if ($_REQUEST['view'] == "my_groups" && isset($me['user_id'])) {
		$file->noimage = $c_node['file']['image']['thumb'][3]['noimage'];
		$file->thumb = $c_node['file']['image']['thumb'][3]['name'];
		$quiz->file = $file;
		
		require_once('class/Group.class.php');
		$group = new Group($db, $file);
		$group->registration_types = $c_node['group']['registration_type'];
		$group->user_id = $me['user_id'];
		
		$mygroups = $group->getMyGroups();
		
		if (!empty($mygroups)) {
			foreach ($mygroups as $key => $i):
				$quiz->group_ids[] = $i['group_id'];
			endforeach;
		}
		else {
			$quiz->group_ids[] = 0;
		}
		
		$quiz->limit = $c_node['display']['max_list_rows'];
		$group_quizzes = $quiz->selQuizzes();
		
		//sort quizzes into groups
		if (!empty($mygroups)) {
			foreach ($mygroups as $item_key => $i):
				foreach($group_quizzes as $content_key => $c):
					if ($i['group_id'] == $c['group_id']) {
						$mygroups[$item_key]['quizzes'][] = $c;
						unset ($group_quizzes[$content_key]);
					}
				endforeach;
			endforeach;
		}
		
		$lang['txt_intro_group'] = str_replace('SYS_KEYWORD_NUMBER', $c_node['display']['max_list_rows'], $lang['txt_intro_group']);
		$lang['txt_outro_group'] = str_replace('SYS_KEYWORD_NUMBER', $c_node['display']['max_list_rows'], $lang['txt_outro_group']);
		
		$output_my_group_quizzes = $mygroups;
		
	}
	elseif ($_REQUEST['view'] == "my_network" && isset($me['user_id'])) {
		//get the latest relations quizzes
		unset($quiz->rsp_level_id);
		$file->noimage = $c_node['file']['image']['thumb'][3]['noimage'];
		$file->thumb = $c_node['file']['image']['thumb'][3]['name'];
		$quiz->file = $file;
		$my_network = $_SESSION['relations'];
		
		if (!empty($my_network)) {
			foreach($my_network as $key => $i):
				$quiz->user_ids[] = $i['user_id_relation'];
				$user->user_ids[] = $i['user_id_relation'];
			endforeach;
		}
		else {
			$quiz->user_ids[] = 0;
			$user->user_ids[] = 0;
		}
		
		$user->file = $file;
		$output_users = $user->selUsers();
		
		$quiz->limit = $c_node['display']['max_list_rows'];
		$network_quizzes = $quiz->selQuizzes();
		
		//sort quizzes under people
		if (!empty($output_users)) {
			foreach ($output_users as $item_key => $i):
				foreach($network_quizzes as $content_key => $c):
					if ($i['user_id'] == $c['user_id']) {
						$output_users[$item_key]['quizzes'][] = $c;
						unset ($network_quizzes[$content_key]);
					}
				endforeach;
			endforeach;
		}
		
		$output_my_network_quizzes = $output_users;
		
		$lang['txt_intro_network'] = str_replace('SYS_KEYWORD_NUMBER', $c_node['display']['max_list_rows'], $lang['txt_intro_network']);
		$lang['txt_outro_network'] = str_replace('SYS_KEYWORD_NUMBER', $c_node['display']['max_list_rows'], $lang['txt_outro_network']);
		
		$menu_section = "network";
	}
	elseif ($_REQUEST['view'] == "my_quizzes" && isset($me['user_id'])) {
		//get my quizzes
		unset($quiz->rsp_level_id);
		$file->noimage = $c_node['file']['image']['thumb'][3]['noimage'];
		$file->thumb = $c_node['file']['image']['thumb'][3]['name'];
		$quiz->file = $file;
	
		$quiz->user_id = $me['user_id'];
		
		$output_quizzes = $quiz->selQuizzes();
		
		$menu_section = "my";
	}
	elseif ($_REQUEST['view'] == "marked_quizzes" && isset($me['user_id'])) {
		//get my marked quizzes
		unset($quiz->rsp_level_id);
		$file->noimage = $c_node['file']['image']['thumb'][3]['noimage'];
		$file->thumb = $c_node['file']['image']['thumb'][3]['name'];
		$quiz->file = $file;
		
		$bookmark->bookmark_type = $c_node['bookmark']['type']['watch'];
		$bookmark->rsp_item_type_id = $c_node['rsp']['item_type']['quiz'];
		$watched_quiz_ids = $bookmark->getBookmarks();
		
		if (!empty($watched_quiz_ids)) {
			$quiz->quiz_ids = $watched_quiz_ids;
			$output_quizzes = $quiz->selQuizzes();
		}
		
		// remove quizzes published by me
		if (!empty($output_quizzes)) {
			foreach($output_quizzes as $key => $i):
				if ($me['user_id'] == $i['user_id']) {
					unset ($output_quizzes[$key]);
				}
			endforeach;
		}
		
		$lang['txt_intro'] = $lang['txt_intro_marked'];
	}
	elseif ($_REQUEST['view'] == "tipped_quizzes" && isset($me['user_id'])) {
		//get my relations tipped quizzes
		unset($quiz->rsp_level_id);
		$file->noimage = $c_node['file']['image']['thumb'][3]['noimage'];
		$file->thumb = $c_node['file']['image']['thumb'][3]['name'];
		$quiz->file = $file;
		
		unset($bookmark->user_id);
		
		$my_network = $_SESSION['relations'];
		
		if (!empty($my_network)) {
			foreach($my_network as $key => $i):
				$bookmark->user_ids[] = $i['user_id_relation'];
				$user->user_ids[] = $i['user_id_relation'];
			endforeach;
		}
		else {
			$bookmark->user_ids[] = 0;
			$user->user_ids[] = 0;
		}
		
		$user->file = $file;
		$output_users = $user->selUsers();
		
		$bookmark->bookmark_type = $c_node['bookmark']['type']['recommend'];
		$bookmark->rsp_item_type_id = $c_node['rsp']['item_type']['quiz'];
		$recommended_quiz_ids = $bookmark->getBookmarks(1);
		
		if (!empty($recommended_quiz_ids)) {
			foreach($recommended_quiz_ids as $key => $i):
				$quiz->quiz_ids[] = $i['item_id'];
			endforeach;
			
			$recommended_quizzes = $quiz->selQuizItems();
			
			//sort quizzes under people
			if (!empty($output_users) && !empty($recommended_quizzes)) {
				foreach ($output_users as $item_key => $i): // for each user we get their tipped items
					foreach($recommended_quiz_ids as $bookmark_key => $b):
						if ($i['user_id'] == $b['user_id']) {
							// we get the quiz
							foreach($recommended_quizzes as $content_key => $c):
								if ($c['quiz_id'] == $b['item_id']) {
									$output_users[$item_key]['quizzes'][] = $c;
									unset ($recommended_quizzes[$content_key]);
								}
							endforeach;
						}
					endforeach;
				endforeach;
			}
			
		}
		$output_recommended_quizzes = $output_users;
		$lang['txt_intro'] = $lang['txt_intro_tipped'];
	}
	elseif ($_REQUEST['view'] == "results" && isset($me['user_id'])) {
		//get the quizzes that I have completed
		$quiz->user_id = $me['user_id'];
		$quiz_participation = $quiz->selResults();
		
		
		$file->noimage = $c_node['file']['image']['thumb'][3]['noimage'];
		$file->thumb = $c_node['file']['image']['thumb'][3]['name'];
		$quiz->file = $file;
		
		//get my quizzes
		unset($quiz->rsp_level_id);
		
		if (!empty($quiz_participation)) {
			foreach($quiz_participation as $key => $i):
				$quiz->quiz_ids[] = $i['quiz_id'];
			endforeach;
		}
		else {
			$quiz->quiz_ids[] = 0;
		}
		
		
		$output_quizzes = $quiz->selQuizzes();
		
		//get the last result for each quiz
		if (isset($output_quizzes)) {
			foreach ($output_quizzes as $key => $i):
				$output_quizzes[$key]['result'] = $quiz->selResult($i['quiz_id']);
			endforeach;
		}
		
		$menu_section = "my";
	
	}
}
elseif (isset($_REQUEST['user_id'])) {
	//get quizzes for this user (if relation)
	unset($quiz->rsp_level_id);
	$quiz->user_id = $_REQUEST['user_id'];
	
	$output_quizzes = $quiz->selPolls();
	
	// get the user
	$output_profile = $user->selProfile(null, $_REQUEST['user_id']);
	
	
	$file->noimage = $c_node['file']['image']['thumb'][1]['noimage'];
	$file->thumb = $c_node['file']['image']['thumb'][1]['name'];
	//setup file
	if (isset($output_profile['file_id'])) {
		$file->file_id = $output_profile['file_id'];
		$output_profile['image'] = $file->getFileRecord();
	}
	if (isset($output_profile) && empty($output_profile['image'])) {
		$output_profile['image']['file_title'] = "";
		$output_profile['image']['file'] = $file->noimage;
	}
}
elseif (isset($_REQUEST['quiz_id'])) {
	$quiz->user_id = $me['user_id'];
	unset($quiz->rsp_level_id);
	$quiz->quiz_id = $_REQUEST['quiz_id'];
	
	$output_quiz = $quiz->selQuiz();
}
elseif (isset($_REQUEST['group_id'])) {
	$quiz->group_id = $_REQUEST['group_id'];
	
	$file->noimage = $c_node['file']['image']['thumb'][3]['noimage'];
	$file->thumb = $c_node['file']['image']['thumb'][3]['name'];
	$quiz->file = $file;
	
	unset($menu_section);
	
	$output_quizzes = $quiz->selQuizzes();
	
}
else { // get the latest item published to node
	$file->noimage = $c_node['file']['image']['thumb'][3]['noimage'];
	$file->thumb = $c_node['file']['image']['thumb'][3]['name'];
	$quiz->file = $file;
	
	$quiz->rsp_item_type_id = $c_node['rsp']['item_type']['quiz'];
	$quiz->rsp_status_id = $c_node['rsp']['status']['live'];
	
	$output_quizzes = $quiz->selQuizzes();
	
	$menu_section = "magazine";
	
	$_REQUEST['view'] = "node";
}


// CHECK PERMISSION TO VIEW QUIZ ------------------------------------------
if (!empty($output_quiz)) {
	// Are we allowed to see this quiz?
	require_once($languageArrayPath . 'arr_rsp.lang.php');
	
	require_once('class/Rsp.class.php');
	$rsp = new Rsp($db, $c_node['rsp']['item_type']['quiz']);
	$output_quiz['rsp'] = $rsp->selRspItem($output_quiz['quiz_id']);
	
	
	if (isset($me['user_id']) && $me['user_id'] == $output_quiz['user_id']) {
		// is the author me?
		$allow_view = 1;
	}
	elseif (isset($rss_access_granted)) { // RSS Feed link
		$allow_view = 1;
	}
	elseif (!empty($output_quiz['rsp'])) { // is the item set to public?
		foreach ($output_quiz['rsp'] as $key => $i):
			if ($i['level_id'] == $c_node['rsp']['rsp_level']['public']) {
				$allow_view = 1;
				break;
			}
			elseif (!empty($_SESSION['s_md5']) && empty($i['degree_id']) && $i['level_id'] == $c_node['rsp']['rsp_level']['node']) { // is the item set to node and the user logged in?
				$allow_view = 1;
				break;
			}
			elseif (!empty($i['degree_id'])) { // is it set to network and are they in my network?
				foreach($_SESSION['relations'] as $key => $r):
					if ($output_quiz['user_id'] == $r['user_id_relation']) {
						$allow_view = 1;
						break;
					}
					
					if (isset($allow_view)) {
						break;
					}
				endforeach;
			}
		endforeach;
	}
	
	if (!empty($output_quiz['group_id'])) {
		require_once('class/Group.class.php');
		require_once($languagePath . 'grp_common.lang.php');
		require_once($languageArrayPath . 'arr_group.lang.php');
		$group = new Group($db, null);
		$group->registration_types = $c_node['group']['registration_type'];
		$group->group_id = $output_quiz['group_id'];
		$output_group = $group->getGroup();
		
		//setup acs
		$group_acs = new Acs(null, $db, $c_node['arr_acs']['role_type']['group']);
		$group_acs->group_id = $output_quiz['group_id'];
		
		// if access not allowed so far, check that I have view permissions within group
		if (isset($me['user_id'])) {
			$group->user_id = $me['user_id'];
			$output_group['member'] = $group->getGroupMembership();
		}
		
		if (empty($output_group['member']['role_id'])) {
			// treat as a visitor to the group
			$output_group['member'] = $group_acs->getGroupRole(null, 1);
		}
		
		$group_acs->role_id = $output_group['member']['role_id'];
		
		
		if (!isset($allow_view) && $group_acs->checkPermission($c_acs['arr_acs']['resource']['group']['quiz'], $c_acs['arr_acs']['privilege']['allow_access'])) { //resourece_id, Priv_id
			$allow_view = 1;
		}
		
		$quiz->group_id = $output_quiz['group_id'];
		
		unset($menu_section);
		
	}
	
	
	if (!isset($allow_view)) {
		unset($output_quiz);
	}
}


// FORMAT POLL -------------------------------------------------------
if (!empty($output_quiz)) {
	// check the start date
	
	// check the end date
	
	//wikify body
	$wiki_path = "lib_view.php?page=";
	$wiki_image_base = "get_file.php?file=";
	
	if (!empty($output_quiz['group_id'])) {
		$wiki_new_path = "lib_edit.php?group_id=" . $output_quiz['group_id'] . "&page=";
	}
	else {
		$wiki_new_path = "lib_edit.php?page=";
	}
	
	$wiki->setRenderConf('xhtml', 'wikilink', 'view_url', $wiki_path);
	$wiki->setRenderConf('xhtml', 'wikilink', 'new_url', $wiki_new_path);
	$wiki->setRenderConf('xhtml', 'image', 'base', $wiki_image_base);
	$output_quiz['quiz_body_intro_display'] = $wiki->transform($output_quiz['quiz_body_intro'], 'Xhtml');
	$output_quiz['quiz_body_exit_pass_display'] = $wiki->transform($output_quiz['quiz_body_exit_pass'], 'Xhtml');
	$output_quiz['quiz_body_exit_fail_display'] = $wiki->transform($output_quiz['quiz_body_exit_fail'], 'Xhtml');
	
}


if (!empty($output_quiz) && !empty($frmdata['result'])) { // display results
	//get comments
	if (isset($_SESSION['user_preferences']['comment_mode']) && $_SESSION['user_preferences']['comment_mode'] == "normal_mode") {
		$comment->no_comment_parent_id = 1;
	}
	
	unset($comment->user_id);
	if (!empty($output_quiz['group_id'])) {
		$comment->group_id = $output_quiz['group_id'];
	}
	
	$output_comments = $comment->selComments($quiz->quiz_id);
	
	$datetime = date("Y-m-d H:i:s");
	
	// if the quiz is live or ended we do not allow editing
	if ($output_quiz['quiz_start_datetime'] <= $datetime) {
	    $output_quiz['quiz_allow_edit'] = 1;
	}
	
	// if the quiz is live allow comments to be added.
	if (($output_quiz['quiz_start_datetime'] <= $datetime) && ($datetime <= $output_quiz['quiz_end_datetime'])) {
	    $output_quiz['quiz_allow_comments'] = 1;
	}
}
elseif (!empty($output_quiz) && !empty($frmdata['take_quiz'])) { // display quiz

}
elseif (!empty($output_quiz)) {
	// are we allowed to edit this quiz?
	$output_quiz['quiz_allow_edit'] = 1;
	
	
	// get all my results for this quiz
	if (empty($frmdata)) {
		$output_quiz['results']= $quiz->selResult($output_quiz['quiz_id'], 1);
	}
	
	// GET AUTHOR
	if (!empty($output_quiz['group_id'])) {
		$output_group['author'] = $group->getGroupMembership($output_quiz['user_id']);
		
		if (!empty($output_group['author']['profile_id'])) {
			$output_author = $user->selProfile($output_group['author']['profile_id'], null);
		}
	}
	else {
		$output_author = $user->selProfile(null, $output_quiz['user_id']);
	}
	
	// GET BOOKMARK --------------------------------------------------
	if (isset($bookmark)) {
		$bookmark->item_id = $quiz->quiz_id;
		$bookmark->bookmark_type = $c_node['bookmark']['type']['watch'];
		if ($bookmark->getBookmark()) {
			$bookmark->updateBookmark();
			$output_quiz['bookmark']['watch'] = 1;
		}
		
		$bookmark->bookmark_type = $c_node['bookmark']['type']['recommend'];
		if ($bookmark->getBookmark()) {
			$bookmark->updateBookmark();
			$output_quiz['bookmark']['recommend'] = 1;
		}
	}
	
	
	//get quiz image
	if (isset($output_quiz['file_id'])) {
		$file->thumb = $c_node['file']['image']['thumb'][1]['name'];
		$file->file_id = $output_quiz['file_id'];
		$output_quiz['image'] = $file->getFileRecord();
	}
	
	//get tags
	$tag->item_id = $output_quiz['quiz_id'];
	$output_my_tags = $tag->selTags();
	unset($tag->user_id);
	$output_item_tags = $tag->selTags(1);
	
	if (isset($_REQUEST['stats'])) {
		// how many people have taken the quiz X times?
		$query = "
			SELECT count(quiz_id) as total 
			FROM " . $db->prefix . "_quiz_result 
			WHERE 
			quiz_id=" . $output_quiz['quiz_id'] . " 
			group by user_id"
		;
		
		$result = $db->Execute($query);
		
		$total1 = "0";
		$total2 = "0";
		$total3 = "0";
		$total_over3 = "0";
		
		if (isset($result->fields)) {
			while (!$result->EOF) {
				if ($result->fields['total'] == 1) {
					$total1++;
				}
				elseif ($result->fields['total'] == 2) {
					$total2++;
				}
				elseif ($result->fields['total'] == 3) {
					$total3++;
				}
				elseif ($result->fields['total'] > 3) {
					$total_over3++;
				}
				
				$result->MoveNext();
			}
		}
		
		$output_stats['chart_times_taken']['data'] = $total1 . "," . $total2 . "," . $total3 . "," . $total_over3;
		
		// what is the summary of scores
		$query = "
			SELECT count(quiz_id) as total, result_mark 
			FROM " . $db->prefix . "_quiz_result 
			WHERE 
			quiz_id=" . $output_quiz['quiz_id'] . " 
			group by result_mark 
			order by total"
		;
		
		$data = array();
		$y_axiz = array();
		
		if (isset($result->fields)) {
			while (!$result->EOF) {
				array_push($data, $result->fields['total']);
				array_push($y_axiz, $result->fields['result_mark']);
				
				$result->MoveNext();
			}
			
			$output_stats['chart_score']['data'] = implode(",", $data);
			$output_stats['chart_score']['y_axiz'] = implode(",", $y_axiz);
		}
	}
}




if (!empty($output_quizzes)) {
	unset($comment->user_id, $comment->section_item_id, $comment->rsp_item_type_id);
	$comment->rsp_item_type_id = $c_node['rsp']['item_type']['quiz'];
	
	foreach($output_quizzes as $key => $i):
		if (!empty($i['quiz_allow_comments'])) {
			$output_quizzes[$key]['comment_total'] = $comment->getCommentCount($i['quiz_id']);
		}
	endforeach;
	
	$tag->rsp_item_type_id = $c_node['rsp']['item_type']['quiz'];
	foreach ($output_quizzes as $key => $i):
		$tag->item_id = $i['quiz_id'];
		$output_quizzes[$key]['tags'] = $tag->selTags();
	endforeach;
	
	//get the last result for each quiz
	$quiz->user_id = $me['user_id'];
	if (isset($output_quizzes)) {
		foreach ($output_quizzes as $key => $i):
			$output_quizzes[$key]['result'] = $quiz->selResult($i['quiz_id']);
		endforeach;
	}
}


// SETUP TEMPLATE ---------------------------------------------------------
if (!empty($_REQUEST['tag'])) {
	$body->set('tag', $_REQUEST['tag']);
}

if (!empty($display)) {
	$body->set('display', $display);
}

if (!empty($_REQUEST['view'])) {
	$body->set('view', $_REQUEST['view']);
}

if (!empty($output_quiz)) {
	$body->set('quiz', $output_quiz);
	$body->set('rsp_config', $c_node['rsp']);
	$lang['nav_breadcrumb_note'] = $output_quiz['quiz_title'];
}

if (!empty($output_quiz_history)) {
	$body->set('quiz_history', $output_quiz_history);
}

if (!empty($output_quiz_usage)) {
   $body->set('quiz_usage', $output_quiz_usage);
}

if (!empty($output_quizzes)) {
   $body->set('quizzes', $output_quizzes);
   unset($lang['nav_breadcrumb']);
}

if (!empty($output_comments)) {
	$body->set('comments', $output_comments);
}

if (!empty($output_comment)) {
	$body->set('comment', $output_comment);
}

if (!empty($output_author)) {
	$body->set('author', $output_author);
}

if (!empty($output_my_tags)) {
	$body->set('my_tags', $output_my_tags);
}

if (!empty($output_item_tags)) {
	$body->set('item_tags', $output_item_tags);
}

if (!empty($output_group)) {
	$body->set('group', $output_group);
	$tpl->set('group', $output_group);
}

if (!empty($output_my_group_quizzes)) {
	$body->set('my_group_quizzes', $output_my_group_quizzes);
}

if (!empty($output_my_network_quizzes)) {
	$body->set('my_network_quizzes', $output_my_network_quizzes);
}

if (!empty($output_recommended_quizzes)) {
	$body->set('recommended_quizzes', $output_recommended_quizzes);
}

if (!empty($output_profile)) {
	$body->set('profile', $output_profile);
}

$body->set('batch_enabled', $c_node['batch']['enabled']);
$body->set('rspconfig', $c_node['rsp']);

include "inc/footer.inc.php";

?>
