/**
 * Shows a detailed summary of the user's quiz or survey answers.
 */
function WPCW_showPage_UserProgess_quizAnswers_load()
{
    global $wpcwdb, $wpdb;
    $wpdb->show_errors();
    $page = new PageBuilder(false);
    $page->showPageHeader(__('Detailed User Quiz/Survey Results', 'wp_courseware'), '75%', WPCW_icon_getPageIconURL());
    $userID = WPCW_arrays_getValue($_GET, 'user_id') + 0;
    $unitID = WPCW_arrays_getValue($_GET, 'unit_id') + 0;
    $quizID = WPCW_arrays_getValue($_GET, 'quiz_id') + 0;
    // Create a link back to the detailed user progress, and back to all users.
    printf('<div class="wpcw_button_group">');
    // Link back to all user summary
    printf('<a href="%s" class="button-secondary">%s</a>&nbsp;&nbsp;', admin_url('users.php'), __('&laquo; Return to User Summary', 'wp_courseware'));
    if ($userDetails = get_userdata($userID)) {
        // Link back to user's personal summary
        printf('<a href="%s&user_id=%d" class="button-secondary">%s</a>&nbsp;&nbsp;', admin_url('users.php?page=WPCW_showPage_UserProgess'), $userDetails->ID, sprintf(__('&laquo; Return to <b>%s\'s</b> Progress Report', 'wp_courseware'), $userDetails->display_name));
    }
    // Try to get the full detailed results.
    $results = WPCW_quizzes_getUserResultsForQuiz($userID, $unitID, $quizID);
    // No results, so abort.
    if (!$results) {
        // Close the button wrapper for above early
        printf('</div>');
        // .wpcw_button_group
        $page->showMessage(__('Sorry, but no results could be found.', 'wp_courseware'), true);
        $page->showPageFooter();
        return;
    }
    // Could potentially have an issue where the quiz has been deleted
    // but the data exists.. small chance though.
    $quizDetails = WPCW_quizzes_getQuizDetails($quizID, true, true, $userID);
    // Extra button - return to gradebook
    printf('<a href="%s&course_id=%d" class="button-secondary">%s</a>&nbsp;&nbsp;', admin_url('admin.php?page=WPCW_showPage_GradeBook'), $quizDetails->parent_course_id, __("&laquo; Return to Gradebook", 'wp_courseware'));
    printf('</div>');
    // .wpcw_button_group
    // #### 1 - Handle grades being updated
    $results = WPCW_showPage_UserProgess_quizAnswers_handingGrading($quizDetails, $results, $page, $userID, $unitID);
    // #### 2A - Check if next action for user has been triggered by the admin.
    $results = WPCW_showPage_UserProgess_quizAnswers_whatsNext_savePreferences($quizDetails, $results, $page, $userID, $unitID);
    // #### 2B - Handle telling admin what's next
    WPCW_showPage_UserProgess_quizAnswers_whatsNext($quizDetails, $results, $page, $userID, $unitID);
    //Ê#### 3 - Handle sending emails if something has changed.
    if (isset($results->sendOutEmails) && $results->sendOutEmails) {
        $extraDetail = isset($results->extraEmailDetail) ? $results->extraEmailDetail : '';
        // Only called if the quiz was graded.
        if (isset($results->quiz_has_just_been_graded) && $results->quiz_has_just_been_graded) {
            // Need to call the action anyway, but any functions hanging off this
            // should check if the admin wants users to have notifications or not.
            do_action('wpcw_quiz_graded', $userID, $quizDetails, number_format($results->quiz_grade, 1), $extraDetail);
        }
        $courseDetails = WPCW_courses_getCourseDetails($quizDetails->parent_course_id);
        if ($courseDetails->email_quiz_grade_option == 'send_email') {
            // Message is only if quiz has been graded.
            if (isset($results->quiz_has_just_been_graded) && $results->quiz_has_just_been_graded) {
                $page->showMessage(__('The user has been sent an email with their grade for this course.', 'wp_courseware'));
            }
        }
    }
    // #### - Table 1 - Overview
    printf('<h3>%s</h3>', __('Quiz/Survey Overview', 'wp_courseware'));
    $tbl = new TableBuilder();
    $tbl->attributes = array('id' => 'wpcw_tbl_progress_quiz_info', 'class' => 'widefat wpcw_tbl');
    $tblCol = new TableColumn(false, 'quiz_label');
    $tblCol->cellClass = 'wpcw_tbl_label';
    $tbl->addColumn($tblCol);
    $tblCol = new TableColumn(false, 'quiz_detail');
    $tbl->addColumn($tblCol);
    // These are the base details for the quiz to show.
    $summaryData = array(__('Quiz Title', 'wp_courseware') => $quizDetails->quiz_title, __('Quiz Description', 'wp_courseware') => $quizDetails->quiz_desc, __('Quiz Type', 'wp_courseware') => WPCW_quizzes_getQuizTypeName($quizDetails->quiz_type), __('No. of Questions', 'wp_courseware') => $results->quiz_question_total, __('Completed Date', 'wp_courseware') => __('About', 'wp_courseware') . ' ' . human_time_diff($results->quiz_completed_date_ts) . ' ' . __('ago', 'wp_courseware') . '<br/><small>(' . date('D jS M Y \\a\\t H:i:s', $results->quiz_completed_date_ts) . ')</small>', __('Number of Quiz Attempts', 'wp_courseware') => $results->attempt_count, __('Permitted Quiz Attempts', 'wp_courseware') => -1 == $quizDetails->quiz_attempts_allowed ? __('Unlimited', 'wp_courseware') : $quizDetails->quiz_attempts_allowed);
    // Quiz details relating to score, etc.
    if ('survey' != $quizDetails->quiz_type) {
        $summaryData[__('Pass Mark', 'wp_courseware')] = $quizDetails->quiz_pass_mark . '%';
        // Still got items to grade
        if ($results->quiz_needs_marking > 0) {
            $summaryData[__('No. of Questions to Grade', 'wp_courseware')] = '<span class="wpcw_status_info wpcw_icon_pending">' . $results->quiz_needs_marking . '</span>';
            $summaryData[__('Overall Grade', 'wp_courseware')] = '<span class="wpcw_status_info wpcw_icon_pending">' . __('Awaiting Final Grading', 'wp_courseware') . '</span>';
        } else {
            $summaryData[__('No. of Question to Grade', 'wp_courseware')] = '-';
            // Show if PASSED or FAILED with the overall grade.
            $gradeData = false;
            if ($results->quiz_grade >= $quizDetails->quiz_pass_mark) {
                $gradeData = sprintf('<span class="wpcw_tbl_progress_quiz_overall wpcw_question_yesno_status wpcw_question_yes">%s%% %s</span>', number_format($results->quiz_grade, 1), __('Passed', 'wp_courseware'));
            } else {
                $gradeData = sprintf('<span class="wpcw_tbl_progress_quiz_overall wpcw_question_yesno_status wpcw_question_no">%s%% %s</span>', number_format($results->quiz_grade, 1), __('Failed', 'wp_courseware'));
            }
            $summaryData[__('Overall Grade', 'wp_courseware')] = $gradeData;
        }
    }
    foreach ($summaryData as $label => $data) {
        $tbl->addRow(array('quiz_label' => $label . ':', 'quiz_detail' => $data));
    }
    echo $tbl->toString();
    // ### 4 - Form Code - to allow instructor to send data back to
    printf('<form method="POST" id="wpcw_tbl_progress_quiz_grading_form">');
    printf('<input type="hidden" name="grade_answers_submitted" value="true">');
    // ### 5 - Table 2 - Each Specific Quiz
    $questionNumber = 0;
    if ($results->quiz_data && count($results->quiz_data) > 0) {
        foreach ($results->quiz_data as $questionID => $answer) {
            $data = $answer;
            // Get the question type
            if (isset($quizDetails->questions[$questionID])) {
                // Store as object for easy reference.
                $quObj = $quizDetails->questions[$questionID];
                // Render the question as a table.
                printf('<h3>%s #%d - %s</h3>', __('Question', 'wp_courseware'), ++$questionNumber, $quObj->question_question);
                $tbl = new TableBuilder();
                $tbl->attributes = array('id' => 'wpcw_tbl_progress_quiz_info', 'class' => 'widefat wpcw_tbl wpcw_tbl_progress_quiz_answers_' . $quObj->question_type);
                $tblCol = new TableColumn(false, 'quiz_label');
                $tblCol->cellClass = 'wpcw_tbl_label';
                $tbl->addColumn($tblCol);
                $tblCol = new TableColumn(false, 'quiz_detail');
                $tbl->addColumn($tblCol);
                $theirAnswer = false;
                switch ($quObj->question_type) {
                    case 'truefalse':
                    case 'multi':
                        $theirAnswer = $answer['their_answer'];
                        break;
                        // File Upload - create a download link
                    // File Upload - create a download link
                    case 'upload':
                        $theirAnswer = sprintf('<a href="%s%s" target="_blank" class="button-primary">%s .%s %s (%s)</a>', WP_CONTENT_URL, $answer['their_answer'], __('Open', 'wp_courseware'), pathinfo($answer['their_answer'], PATHINFO_EXTENSION), __('File', 'wp_courseware'), WPCW_files_getFileSize_human($answer['their_answer']));
                        break;
                        // Open Ended - Wrap in span tags, to cap the size of the field, and format new lines.
                    // Open Ended - Wrap in span tags, to cap the size of the field, and format new lines.
                    case 'open':
                        $theirAnswer = '<span class="wpcw_q_answer_open_wrap"><textarea readonly>' . $data['their_answer'] . '</textarea></span>';
                        break;
                }
                // end of $theirAnswer check
                $summaryData = array(__('Type', 'wp_courseware') => array('data' => WPCW_quizzes_getQuestionTypeName($quObj->question_type), 'cssclass' => ''), __('Their Answer', 'wp_courseware') => array('data' => $theirAnswer, 'cssclass' => ''));
                // Just for quizzes - show answers/grade
                if ('survey' != $quizDetails->quiz_type) {
                    switch ($quObj->question_type) {
                        case 'truefalse':
                        case 'multi':
                            // The right answer...
                            $summaryData[__('Correct Answer', 'wp_courseware')] = array('data' => $answer['correct'], 'cssclass' => '');
                            // Did they get it right?
                            $getItRight = sprintf('<span class="wpcw_question_yesno_status wpcw_question_%s">%s</span>', $answer['got_right'], 'yes' == $answer['got_right'] ? __('Yes', 'wp_courseware') : __('No', 'wp_courseware'));
                            $summaryData[__('Did they get it right?', 'wp_courseware')] = array('data' => $getItRight, 'cssclass' => '');
                            break;
                        case 'upload':
                        case 'open':
                            $gradeHTML = false;
                            $theirGrade = WPCW_arrays_getValue($answer, 'their_grade');
                            // Not graded - show select box.
                            if ($theirGrade == 0) {
                                $cssClass = 'wpcw_grade_needs_grading';
                            } else {
                                $cssClass = 'wpcw_grade_already_graded';
                                $gradeHTML = sprintf('<span class="wpcw_grade_view">%d%% <a href="#">(%s)</a></span>', $theirGrade, __('Click to edit', 'wp_courseware'));
                            }
                            // Not graded yet, allow admin to grade the quiz, or change
                            // the grading later if they want to.
                            $gradeHTML .= WPCW_forms_createDropdown('grade_quiz_' . $quObj->question_id, WPCW_quizzes_getPercentageList(__('-- Select a grade --', 'wp_courseware')), $theirGrade, false, 'wpcw_tbl_progress_quiz_answers_grade');
                            $summaryData[__('Their Grade', 'wp_courseware')] = array('data' => $gradeHTML, 'cssclass' => $cssClass);
                            break;
                    }
                }
                // Check of showing the right answer.
                foreach ($summaryData as $label => $data) {
                    $tbl->addRow(array('quiz_label' => $label . ':', 'quiz_detail' => $data['data']), $data['cssclass']);
                }
                echo $tbl->toString();
            }
            // end if (isset($quizDetails->questions[$questionID]))
        }
        // foreach ($results->quiz_data as $questionID => $answer)
    }
    printf('</form>');
    // Shows a bar that pops up, allowing the user to easily save all grades that have changed.
    ?>
	<div id="wpcw_sticky_bar" style="display: none">
		<div id="wpcw_sticky_bar_inner">
			<a href="#" id="wpcw_tbl_progress_quiz_grading_updated" class="button-primary"><?php 
    _e('Save Changes to Grades', 'wp_courseware');
    ?>
</a>
			<span id="wpcw_sticky_bar_status" title="<?php 
    _e('Grades have been changed. Ready to save changes?', 'wp_courseware');
    ?>
"></span>
		</div>
	</div>
	<br/><br/><br/><br/>
	<?php 
    $page->showPageFooter();
}
/**
 * Function that allows a quiz to be created or edited.
 */
function WPCW_showPage_ModifyQuiz_load()
{
    // Thickbox needed for random and quiz windows.
    add_thickbox();
    $page = new PageBuilder(true);
    $quizDetails = false;
    $adding = false;
    $quizID = false;
    // Check POST and GET
    if (isset($_GET['quiz_id'])) {
        $quizID = $_GET['quiz_id'] + 0;
    } else {
        if (isset($_POST['quiz_id'])) {
            $quizID = $_POST['quiz_id'] + 0;
        }
    }
    // Trying to edit a quiz
    if ($quizDetails = WPCW_quizzes_getQuizDetails($quizID, false, false, false)) {
        // Abort if quiz not found.
        if (!$quizDetails) {
            $page->showPageHeader(__('Edit Quiz/Survey', 'wp_courseware'), '70%', WPCW_icon_getPageIconURL());
            $page->showMessage(__('Sorry, but that quiz/survey could not be found.', 'wp_courseware'), true);
            $page->showPageFooter();
            return;
        } else {
            // Start form prolog - with quiz ID
            printf('<form method="POST" action="%s&quiz_id=%d" name="wpcw_quiz_details_modify" id="wpcw_quiz_details_modify">', admin_url('admin.php?page=WPCW_showPage_ModifyQuiz'), $quizDetails->quiz_id);
            $page->showPageHeader(__('Edit Quiz/Survey', 'wp_courseware'), '70%', WPCW_icon_getPageIconURL());
        }
    } else {
        // Start form prolog - no quiz ID
        printf('<form method="POST" action="%s" name="wpcw_quiz_details_modify" id="wpcw_quiz_details_modify">', admin_url('admin.php?page=WPCW_showPage_ModifyQuiz'));
        $page->showPageHeader(__('Add Quiz/Survey', 'wp_courseware'), '70%', WPCW_icon_getPageIconURL());
        $adding = true;
    }
    // Generate the tabs.
    $tabList = array('wpcw_section_break_quiz_general' => array('label' => __('General Settings', 'wp_courseware')), 'wpcw_section_break_quiz_logic' => array('label' => __('Quiz Behaviour Settings', 'wp_courseware')), 'wpcw_section_break_quiz_results' => array('label' => __('Result Settings', 'wp_courseware')), 'wpcw_section_break_quiz_custom_feedback' => array('label' => __('Custom Feedback', 'wp_courseware'), 'cssclass' => 'wpcw_quiz_only_tab'), 'wpcw_section_break_quiz_questions' => array('label' => __('Manage Questions', 'wp_courseware')));
    global $wpcwdb;
    $formDetails = array('wpcw_section_break_quiz_general' => array('type' => 'break', 'html' => WPCW_forms_createBreakHTML_tab(false)), 'quiz_title' => array('label' => __('Quiz Title', 'wp_courseware'), 'type' => 'text', 'required' => true, 'cssclass' => 'wpcw_quiz_title', 'desc' => __('The title of your quiz or survey. Your trainees will be able to see this quiz title.', 'wp_courseware'), 'validate' => array('type' => 'string', 'maxlen' => 150, 'minlen' => 1, 'regexp' => '/^[^<>]+$/', 'error' => __('Please specify a name for your quiz or survey, up to a maximum of 150 characters, just no angled brackets (&lt; or &gt;).', 'wp_courseware'))), 'quiz_desc' => array('label' => __('Quiz/Survey Description', 'wp_courseware'), 'type' => 'textarea', 'required' => false, 'cssclass' => 'wpcw_quiz_desc', 'rows' => 2, 'desc' => __('(Optional) The description of this quiz. Your trainees won\'t see this description. It\'s just for your reference.', 'wp_courseware'), 'validate' => array('type' => 'string', 'maxlen' => 5000, 'minlen' => 1, 'error' => __('Please limit the description of your quiz to 5000 characters.', 'wp_courseware'))), 'quiz_type' => array('label' => __('Quiz Type', 'wp_courseware'), 'type' => 'radio', 'required' => true, 'cssclass' => 'wpcw_quiz_type wpcw_quiz_type_hide_pass', 'data' => array('survey' => __('<b>Survey Mode</b> - No correct answers, just collect information.', 'wp_courseware'), 'quiz_block' => __('<b>Quiz Mode - Blocking</b> - require trainee to correctly answer questions before proceeding. Trainee must achieve <b>minimum pass mark</b> to progress to the next unit.', 'wp_courseware'), 'quiz_noblock' => __('<b>Quiz Mode - Non-blocking</b> - require trainee to answer a number of questions before proceeding, but allow them to progress to the next unit <b>regardless of their pass mark</b>.', 'wp_courseware'))), 'wpcw_section_break_quiz_logic' => array('type' => 'break', 'html' => WPCW_forms_createBreakHTML_tab(false)), 'quiz_pass_mark' => array('label' => __('Pass Mark', 'wp_courseware'), 'type' => 'select', 'required' => true, 'cssclass' => 'wpcw_quiz_block_only wpcw_quiz_only', 'data' => WPCW_quizzes_getPercentageList(__('-- Select a pass mark --', 'wp_courseware')), 'desc' => __('The minimum pass mark that your trainees need to achieve to progress on to the next unit.', 'wp_courseware')), 'quiz_attempts_allowed' => array('label' => __('Number of Attempts Allowed?', 'wp_courseware'), 'type' => 'select', 'required' => true, 'cssclass' => 'wpcw_quiz_block_only wpcw_quiz_only', 'data' => WPCW_quizzes_getAttemptList(), 'desc' => __('The maximum number of attempts that a trainee is given to complete a quiz for blocking quizzes.', 'wp_courseware')), 'quiz_show_survey_responses' => array('label' => __('Show Survey Responses?', 'wp_courseware'), 'type' => 'radio', 'required' => true, 'cssclass' => 'wpcw_survey_only', 'data' => array('show_responses' => __('<b>Show Responses</b> - Show the trainee their survey responses.', 'wp_courseware'), 'no_responses' => __('<b>No Responses</b> - Don\'t show the trainee their survey responses.', 'wp_courseware')), 'desc' => __('This setting allows you to choose whether or not you want students to be able to review their past survey responses when they return to units.', 'wp_courseware')), 'quiz_paginate_questions' => array('label' => __('Paginate Questions?', 'wp_courseware'), 'type' => 'radio', 'required' => true, 'cssclass' => 'wpcw_quiz_paginate_questions', 'data' => array('use_paging' => __('<b>Use Paging</b> - This setting will display quiz questions one at a time allowing students to progress through questions individually within a frame in your unit page.', 'wp_courseware'), 'no_paging' => __('<b>No Paging</b> - Don\'t use any paging. Show all quiz questions at once on the unit page.', 'wp_courseware')), 'suffix_subitems' => array('use_paging' => array('quiz_paginate_questions_settings' => array('type' => 'checkboxlist', 'required' => false, 'cssclass' => 'wpcw_quiz_paginate_questions_group', 'data' => array('allow_review_before_submission' => '<b>' . __('Allow Review Before Final Submission', 'wp_courseware') . '</b> - ' . __('If selected, students will be presented with an opportunity to review an editable list of all answers before final submission.', 'wp_courseware'), 'allow_students_to_answer_later' => '<b>' . __('Allow Students to Answer Later', 'wp_courseware') . '</b> - ' . __('If selected, the student will be able to click the "Answer Later" button and progress to the next question without answering. The question will be presented again at the end of the quiz.', 'wp_courseware'), 'allow_nav_previous_questions' => '<b>' . __('Allow Navigation to Previous Questions', 'wp_courseware') . '</b> - ' . __('If selected, a "Previous Question" button will be displayed, allowing students to freely navigate backwards and forwards through questions.', 'wp_courseware')))))), 'quiz_timer_mode' => array('label' => __('Set Time Limit for Quiz?', 'wp_courseware'), 'type' => 'radio', 'required' => true, 'cssclass' => 'wpcw_quiz_timer_mode wpcw_quiz_block_only', 'data' => array('use_timer' => __('<b>Specify a Quiz Time Limit</b> - Give the trainee a fixed amount of time to complete the quiz.', 'wp_courseware'), 'no_timer' => __('<b>No Time Limit</b> - the trainee can take as long as they wish to complete the quiz.', 'wp_courseware'))), 'quiz_timer_mode_limit' => array('label' => __('Time Limit (in minutes)', 'wp_courseware'), 'type' => 'text', 'required' => false, 'cssclass' => 'wpcw_quiz_timer_mode_limit wpcw_quiz_timer_mode_active_only wpcw_quiz_block_only', 'extrahtml' => __('Minutes', 'wp_courseware'), 'validate' => array('type' => 'number', 'max' => 1000, 'min' => 1, 'error' => 'Please choose time limit between 1 and 1000 minutes.')), 'wpcw_section_break_quiz_results' => array('type' => 'break', 'html' => WPCW_forms_createBreakHTML_tab(false)), 'quiz_show_answers' => array('label' => __('Show Answers?', 'wp_courseware'), 'type' => 'radio', 'required' => true, 'cssclass' => 'wpcw_quiz_show_answers wpcw_quiz_only', 'data' => array('show_answers' => __('<b>Show Answers</b> - Show the trainee the correct answers before they progress.', 'wp_courseware'), 'no_answers' => __('<b>No Answers</b> - Don\'t show the trainee any answers before they progress.', 'wp_courseware')), 'extrahtml' => '<div class="wpcw_msg_info wpcw_msg wpcw_msg_in_form wpcw_msg_error_no_answers_selected" style="display: none">' . __('If this option is selected, students will not be able to view correct or incorrect answers.', 'wp_courseware') . '</div>', 'suffix_subitems' => array('show_answers' => array('show_answers_settings' => array('type' => 'checkboxlist', 'required' => false, 'cssclass' => '', 'errormsg' => __('Please choose at least one option when showing correct answers.', 'wp_courseware'), 'data' => array('show_correct_answer' => '<b>' . __('Show correct answer', 'wp_courseware') . '</b> - ' . __('Show the trainee the correct answers before they progress.', 'wp_courseware'), 'show_user_answer' => '<b>' . __('Show user\'s answer', 'wp_courseware') . '</b> - ' . __('Show the trainee the answer they submitted before they progress.', 'wp_courseware'), 'show_explanation' => '<b>' . __('Show explanation', 'wp_courseware') . '</b> - ' . __('Show the trainee an explanation for the correct answer (if there is one).', 'wp_courseware'), 'mark_answers' => '<b>' . __('Mark Answers', 'wp_courseware') . '</b> - ' . __('This option will show correct answers with a green check mark, and incorrect answers with a red "X".', 'wp_courseware'), 'show_results_later' => '<b>' . __('Leave quiz results available for later viewing?', 'wp_courseware') . '</b> - ' . __('This setting allows you to choose whether or not you want students to be able to review their past quiz answers when they return to units.', 'wp_courseware')), 'extrahtml' => '<div class="wpcw_msg_error wpcw_msg wpcw_msg_in_form wpcw_msg_error_show_answers_none_selected" style="display: none">' . __('To make use of this showing answers setting, at least one of the above settings should be ticked. Otherwise, no answers are actually shown.', 'wp_courseware') . '</div>')))), 'quiz_results_by_tag' => array('label' => __('Show Results by Tag?', 'wp_courseware'), 'type' => 'checkbox', 'required' => false, 'extralabel' => __('<b>Display results by question tag</b> - In addition to the overall score, indicate a breakdown of the results for each question tag.', 'wp_courseware')), 'quiz_results_by_timer' => array('label' => __('Show Completion Time?', 'wp_courseware'), 'type' => 'checkbox', 'required' => false, 'cssclass' => 'wpcw_quiz_timer_mode_active_only wpcw_quiz_block_only', 'extralabel' => __('<b>Display completion time for timed quiz</b> - If the quiz has been timed, this option will display the student\'s total time used for completing the quiz.', 'wp_courseware')));
    $form = new RecordsForm($formDetails, $wpcwdb->quiz, 'quiz_id', false, 'wpcw_quiz_details_modify');
    $form->customFormErrorMsg = __('Sorry, but unfortunately there were some errors saving the quiz details. Please fix the errors and try again.', 'wp_courseware');
    $form->setAllTranslationStrings(WPCW_forms_getTranslationStrings());
    // Got to summary of quizzes
    $directionMsg = '<br/></br>' . sprintf(__('Do you want to return to the <a href="%s">quiz summary page</a>?', 'wp_courseware'), admin_url('admin.php?page=WPCW_showPage_QuizSummary'));
    // Override success messages
    $form->msg_record_created = __('Quiz details successfully created.', 'wp_courseware') . $directionMsg;
    $form->msg_record_updated = __('Quiz details successfully updated.', 'wp_courseware') . $directionMsg;
    $form->setPrimaryKeyValue($quizID);
    $form->setSaveButtonLabel(__('Save All Quiz Settings &amp; Questions', 'wp_courseware'));
    // Do default checking based on quiz type.
    $form->filterBeforeSaveFunction = 'WPCW_actions_quizzes_beforeQuizSaved';
    $form->afterSaveFunction = 'WPCW_actions_quizzes_afterQuizSaved';
    // Set defaults when creating a new one
    if ($adding) {
        $form->loadDefaults(array('quiz_pass_mark' => 50, 'quiz_type' => 'quiz_noblock', 'quiz_show_survey_responses' => 'no_responses', 'quiz_show_answers' => 'show_answers', 'show_answers_settings' => array('show_correct_answer' => 'on', 'show_user_answer' => 'on', 'show_explanation' => 'on', 'mark_answers' => 'on', 'show_results_later' => 'on'), 'quiz_paginate_questions' => 'no_paging', 'quiz_paginate_questions_settings' => array('allow_review_before_submission' => 'on', 'allow_students_to_answer_later' => 'on', 'allow_nav_previous_questions' => 'on'), 'quiz_timer_mode' => 'no_timer', 'quiz_timer_mode_limit' => '15', 'quiz_results_by_tag' => 'on', 'quiz_results_by_timer' => 'on'));
    }
    // Get the rendered form, extract the start and finish form tags so that
    // we can use the form across multiple panes, and submit other data such
    // as questions along with the quiz itself. We're doing this because the RecordsForm
    // object actually does a really good job, so we don't want to refactor to remove it.
    $formHTML = $form->getHTML();
    $formHTML = preg_replace('/^(\\s*?)(<form(.*?>))/', '', $formHTML);
    $formHTML = preg_replace('/<\\/form>(\\s*?)$/', '', $formHTML);
    // Need to move the submit button to before the closing form tag to allow it
    // to render on the page as expected after the questions drag-n-drop section.
    // Don't bother if we're not showing any questions yet though.
    $buttonHTML = false;
    if ($form->primaryKeyValue > 0) {
        $pattern = '/<p class="submit">(\\C*?)<\\/p>/';
        if (preg_match($pattern, $formHTML, $matches)) {
            // Found it, so add to variable to show later, and strip
            // it from the HTML so far.
            $buttonHTML = $matches[0];
            $formHTML = str_replace($buttonHTML, false, $formHTML);
        }
    }
    // Not got any questions to show yet, so hide questions tab.
    if ($form->primaryKeyValue <= 0) {
        unset($tabList['wpcw_section_break_quiz_questions']);
        unset($tabList['wpcw_section_break_quiz_custom_feedback']);
    }
    // Show a placeholder for an error message that may occur within tabs.
    printf('<div class="wpcw_msg wpcw_msg_error wpcw_section_error_within_tabs">%s</div>', __('Unfortunately, there are a few missing details that need to be added before this quiz can be saved. Please resolve them and try again.', 'wp_courseware'));
    // Render the tabs
    echo WPCW_tabs_generateTabHeader($tabList, 'wpcw_quizzes_tabs');
    // The main quiz settings
    echo $formHTML;
    // Try to see if we've got an ID having saved the form from a first add
    // or we're editing the form
    if ($form->primaryKeyValue > 0) {
        $quizID = $form->primaryKeyValue;
        // Top for jumps.
        printf('<a name="top"></a>');
        // ### 1) Custom Feedback Messages
        printf('<div class="wpcw_form_break_tab"></div>');
        printf('<div class="form-table" id="wpcw_section_break_quiz_custom_feedback">');
        WPCW_showPage_customFeedback_showEditForms($quizID, $page);
        printf('</div>');
        // ### 2) Question Settings
        printf('<div class="wpcw_form_break_tab"></div>');
        printf('<div class="form-table" id="wpcw_section_break_quiz_questions">');
        WPCW_showPage_ModifyQuiz_showQuestionEntryForms($quizID, $page);
        printf('</div>');
    }
    // Reshow the button here
    echo $buttonHTML;
    // The closing form tag
    echo '</form>';
    // .wpcw_tab_wrapper
    echo '</div>';
    // The thickboxes for the page
    WPCW_showPage_thickbox_questionPool();
    WPCW_showPage_thickbox_randomQuestion();
    $page->showPageFooter();
}
    /**
     * Generates the form where the trainer can edit the details of the custom message.
     */
    function generate_editForm()
    {
        $html = false;
        // Build the root of each field name, then append a suffix for each field.
        $fieldSuffix = '_' . $this->feedbackMsgDetails->qfeedback_id;
        $fieldPrefix = 'wpcw_qcfm_sgl_';
        $html .= sprintf('<div id="%swrapper%s"><table class="wpcw_quiz_custom_feedback_wrap_single" cellspacing="0"><tbody>', $fieldPrefix, $fieldSuffix);
        // ### 1) - Show the feedback message - summary field.
        $html .= sprintf('<tr class="wpcw_quiz_custom_feedback_hdr">');
        // Label
        $html .= sprintf('<th>%s:<span class="wpcw_inner_hint">%s</span></th>', __('Message Description', 'wp_courseware'), __('(Required) A quick summary for this message. This will not be displayed to students.'));
        $html .= '<td>';
        // Entry field for message summary name
        $html .= sprintf('<input name="%s" type="text" value="%s" class="wpcw_qcfm_sgl_summary" placeholder="%s">', $fieldPrefix . 'summary' . $fieldSuffix, $this->feedbackMsgDetails->qfeedback_summary, __('e.g. Low score on MyTag section', 'wp_courseware'));
        // Error message if incomplete
        $html .= sprintf('<span class="wpcw_quiz_custom_feedback_error">%s</span>', __('Please specify a quick summary for this message.', 'wp_courseware'));
        $html .= '</td>';
        // Toggle field
        //$html .= sprintf('<td class="wpcw_quiz_custom_feedback_toggle">[+]</td>');
        $html .= '</tr>';
        // ### 2) - Show tag selection field
        $html .= sprintf('<tr>');
        // Label
        $html .= sprintf('<th>%s:<span class="wpcw_inner_hint">%s</span></th>', __('Select Question Tag', 'wp_courseware'), __('(Required) Select the tag for which you want to provide feedback.'));
        // Tag selection
        $html .= '<td>';
        // Dropdown for the tags
        $html .= WPCW_questions_tags_getTagDropdown(__('-- Please choose a tag ---', 'wp_courseware'), $fieldPrefix . 'tag' . $fieldSuffix, $this->feedbackMsgDetails->qfeedback_tag_id, 'wpcw_qcfm_sgl_tag', false, false);
        // Error message if incomplete
        $html .= sprintf('<span class="wpcw_quiz_custom_feedback_error">%s</span>', __('Please select a tag for this message.', 'wp_courseware'));
        // Shows the count of how many tags are available for this tag
        // This has not been continued for now, as it's an extremely expensive operation due to the random questions.
        /*
        					if ($this->feedbackMsgDetails->qfeedback_tag_id > 0)
        					{
        						$questionCount = 3;//WPCW_quizzes_getQuestionCountForTag($this->quizID, $this->feedbackMsgDetails->qfeedback_tag_id);
        						
        						// Show count based on how many questions found for this tag.
        						$html .= sprintf('<span class="wpcw_quiz_custom_feedback_question_count"><b>%d %s</b> %s</span>', 
        							$questionCount,
        							_n('question', 'questions', $questionCount, 'wp_courseware'),
        							__('found for this tag in this quiz.', 'wp_courseware')
        						);
        					}
        					
        					// No selected tag, so just hide this.
        					else {
        						$html .= '<span class="wpcw_quiz_custom_feedback_question_count" style="display: none;"></span>';
        					}*/
        $html .= '</td>';
        // Empty toggle field.
        //$html .= sprintf('<td></td>');
        $html .= '</tr>';
        // ### 3) - Show the score level selection
        $html .= sprintf('<tr class="alternate">');
        // Label
        $html .= sprintf('<th>%s:<span class="wpcw_inner_hint">%s</span></th>', __('Select Question Tag', 'wp_courseware'), __('(Required) Select the tag for which you want to provide feedback.'));
        $html .= '<td class="wpcw_quiz_custom_feedback_score">';
        $html .= sprintf('<span class="wpcw_quiz_custom_feedback_score_label_first">%s</span>', __('Display this message to students who score:', 'wp_courseware'));
        // Score condition check
        $html .= '<span class="wpcw_quiz_custom_feedback_score_radio_wrap">';
        $html .= sprintf('<label><input type="radio" name="%s" value="above" %s /> %s</label>', $fieldPrefix . 'score_type' . $fieldSuffix, $this->feedbackMsgDetails->qfeedback_score_type == 'above' ? 'checked="checked"' : false, __('above', 'wp_courseware'));
        $html .= sprintf('<label><input type="radio" name="%s" value="below" %s /> %s</label>', $fieldPrefix . 'score_type' . $fieldSuffix, $this->feedbackMsgDetails->qfeedback_score_type == 'below' ? 'checked="checked"' : false, __('at or below', 'wp_courseware'));
        $html .= '</span>';
        // Score selection
        $html .= WPCW_forms_createDropdown($fieldPrefix . 'score_grade' . $fieldSuffix, WPCW_quizzes_getPercentageList(false), $this->feedbackMsgDetails->qfeedback_score_grade);
        $html .= sprintf('<span class="wpcw_quiz_custom_feedback_score_label_second">%s</span>', __('across all questions for the tag selected above', 'wp_courseware'));
        // Error message if incomplete
        $html .= sprintf('<span class="wpcw_quiz_custom_feedback_error">%s</span>', __('Please select a trigger score for this message.', 'wp_courseware'));
        $html .= '</td>';
        $html .= '</tr>';
        // ### 4) - Show the message form
        $html .= sprintf('<tr>');
        // Label
        $html .= sprintf('<th>%s:<span class="wpcw_inner_hint">%s</span></th>', __('Custom Feedback Message', 'wp_courseware'), __('(Required) Enter the message to display to students when conditions above are met.'), 'test');
        $html .= '<td>';
        // Text area for message
        $html .= sprintf('<textarea name="%s" rows="7" class="wpcw_qcfm_sgl_message">%s</textarea>', $fieldPrefix . 'message' . $fieldSuffix, $this->feedbackMsgDetails->qfeedback_message);
        // Error message if incomplete
        $html .= sprintf('<span class="wpcw_quiz_custom_feedback_error">%s</span>', __('Please enter a helpful feedback message for the trainee.', 'wp_courseware'));
        $html .= '</td>';
        $html .= '</tr>';
        // ### 5) Show the footer with the delete icon
        $html .= sprintf('<tr class="wpcw_quiz_row_footer">
				<td colspan="3" class="wpcw_question_actions">
					<a href="#" class="wpcw_delete_icon" rel="%s">Delete</a>
				</td>
			</tr>', __('Are you sure you wish to delete this custom feedback message?', 'wp_courseware'));
        $html .= '</tbody></table></div>';
        return $html;
    }