public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

    String currentuserid = externalLogic.getCurrentUserId();

    PollViewParameters ecvp = (PollViewParameters) viewparams;
    Poll poll = null;
    boolean isNew = true;

    UIForm newPoll = UIForm.make(tofill, "add-poll-form");
    LOG.debug("Poll of id: " + ecvp.id);
    if (ecvp.id == null || "New 0".equals(ecvp.id)) {
      UIMessage.make(tofill, "new_poll_title", "new_poll_title");
      // build an empty poll
      LOG.debug("this is a new poll");
      poll = new Poll();
    } else {
      UIMessage.make(tofill, "new_poll_title", "new_poll_title_edit");

      String strId = ecvp.id;
      LOG.debug("got id of " + strId);
      poll = pollListManager.getPollById(Long.valueOf(strId));
      voteBean.setPoll(poll);
      newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId()));

      isNew = false;
    }

    if (!externalLogic.isUserAdmin()
        && !externalLogic.isAllowedInLocation(
            PollListManager.PERMISSION_ADD,
            externalLogic.getCurrentLocationReference(),
            externalLogic.getCurrentuserReference())) {
      tml.addMessage(new TargettedMessage("new_poll_noperms"));
      return;
    }

    // only display for exisiting polls
    if (!isNew) {
      // fill the options list
      UIBranchContainer actionBlock = UIBranchContainer.make(newPoll, "option-headers:");
      UIMessage.make(actionBlock, "options-title", "new_poll_option_title");
      UIInternalLink.make(
          actionBlock,
          "option-add",
          UIMessage.make("new_poll_option_add"),
          new OptionViewParameters(PollOptionProducer.VIEW_ID, null, poll.getPollId().toString()));

      List<Vote> votes = pollVoteManager.getAllVotesForPoll(poll);
      if (votes != null && votes.size() > 0) {
        LOG.debug("Poll has " + votes.size() + " votes");
        UIBranchContainer errorRow = UIBranchContainer.make(tofill, "error-row:", "0");
        UIMessage.make(errorRow, "error", "warn_poll_has_votes");
      }

      List<Option> options = pollListManager.getVisibleOptionsForPoll(poll.getPollId());
      for (int i = 0; i < options.size(); i++) {
        Option o = (Option) options.get(i);
        UIBranchContainer oRow =
            UIBranchContainer.make(actionBlock, "options-row:", o.getOptionId().toString());
        UIVerbatim.make(oRow, "options-name", o.getOptionText());

        UIInternalLink editOption =
            UIInternalLink.make(
                oRow,
                "option-edit",
                UIMessage.make("new_poll_option_edit"),
                new OptionViewParameters(PollOptionProducer.VIEW_ID, o.getOptionId().toString()));

        editOption.decorators =
            new DecoratorList(
                new UITooltipDecorator(
                    messageLocator.getMessage("new_poll_option_edit")
                        + ":"
                        + FormattedText.convertFormattedTextToPlaintext(o.getOptionText())));

        UIInternalLink deleteOption =
            UIInternalLink.make(
                oRow,
                "option-delete",
                UIMessage.make("new_poll_option_delete"),
                new OptionViewParameters(
                    PollOptionDeleteProducer.VIEW_ID, o.getOptionId().toString()));

        deleteOption.decorators =
            new DecoratorList(
                new UITooltipDecorator(
                    messageLocator.getMessage("new_poll_option_delete")
                        + ":"
                        + FormattedText.convertFormattedTextToPlaintext(o.getOptionText())));
      }
    }

    UIMessage.make(tofill, "new-poll-descr", "new_poll_title");
    UIMessage.make(tofill, "new-poll-question-label", "new_poll_question_label");
    UIMessage pollDescr = UIMessage.make(tofill, "new-poll-descr-label", "new_poll_descr_label");
    UIMessage.make(tofill, "new-poll-descr-label2", "new_poll_descr_label2");

    // UIMessage.make(tofill, "new-poll-open-label", "new_poll_open_label");
    // UIMessage.make(tofill, "new-poll-close-label", "new_poll_close_label");

    UIMessage.make(tofill, "new-poll-limits", "new_poll_limits");
    // UIMessage pollMin = UIMessage.make(tofill, "new-poll-min-limits", "new_poll_min_limits");
    // UIMessage pollMax =  UIMessage.make(tofill, "new-poll-max-limits", "new_poll_max_limits");

    // the form fields
    UIInput.make(newPoll, "new-poll-text", "#{poll.text}", poll.getText());

    if (!externalLogic.isMobileBrowser()) {
      // show WYSIWYG editor
      UIInput itemDescr =
          UIInput.make(
              newPoll,
              "newpolldescr:",
              "#{poll.details}",
              poll.getDetails()); // $NON-NLS-1$ //$NON-NLS-2$
      richTextEvolver.evolveTextInput(itemDescr);
      UILabelTargetDecorator.targetLabel(pollDescr, itemDescr);
    } else {
      // do not show WYSIWYG editor in the mobile view
      UIInput itemDescr =
          UIInput.make(
              newPoll,
              "newpolldescr_mobile",
              "#{poll.details}",
              poll.getDetails()); // $NON-NLS-1$ //$NON-NLS-2$
      UILabelTargetDecorator.targetLabel(pollDescr, itemDescr);
    }

    UIInput voteOpen =
        UIInput.make(newPoll, "openDate-iso8601", "poll.voteOpenStr", poll.getVoteOpenStr());
    UIInput voteClose =
        UIInput.make(newPoll, "closeDate-iso8601", "poll.voteCloseStr", poll.getVoteCloseStr());
    // UILabelTargetDecorator.targetLabel(pollOpen, voteOpen);
    // UILabelTargetDecorator.targetLabel(pollClose, voteClose);

    /*
     * access options
     */
    UIMessage pollAccessLabel =
        UIMessage.make(newPoll, "poll_access_label", "new_poll_access_label");
    UIBoundBoolean accessPublic =
        UIBoundBoolean.make(newPoll, "access-public", "poll.isPublic", poll.getIsPublic());
    UIMessage newPollAccessPublicLabel =
        UIMessage.make(newPoll, "new_poll_access_public_label", "new_poll_access_public");

    // SAK-25399: Do not display the public access by default
    if (!externalLogic.isShowPublicAccess()) {
      newPoll.remove(pollAccessLabel);
      newPoll.remove(accessPublic);
      newPoll.remove(newPollAccessPublicLabel);
    }

    String[] minVotes =
        new String[] {
          "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
        };
    String[] maxVotes =
        new String[] {
          "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
        };
    UISelect min =
        UISelect.make(
            newPoll,
            "min-votes",
            minVotes,
            "#{poll.minOptions}",
            Integer.toString(poll.getMinOptions()));
    UISelect max =
        UISelect.make(
            newPoll,
            "max-votes",
            maxVotes,
            "#{poll.maxOptions}",
            Integer.toString(poll.getMaxOptions()));

    /*
     * 	open - can be viewd at any time
     * 	never - not diplayed
     * 	afterVoting - after user has voted
     * 	afterClosing
     *
     */

    String[] values = new String[] {"open", "afterVoting", "afterClosing", "never"};
    String[] labels =
        new String[] {
          messageLocator.getMessage("new_poll_open"),
          messageLocator.getMessage("new_poll_aftervoting"),
          messageLocator.getMessage("new_poll_afterClosing"),
          messageLocator.getMessage("new_poll_never")
        };

    UISelect radioselect =
        UISelect.make(
            newPoll, "release-select", values, "#{poll.displayResult}", poll.getDisplayResult());

    radioselect.optionnames = UIOutputMany.make(labels);

    String selectID = radioselect.getFullID();
    // StringList optList = new StringList();
    UIMessage.make(newPoll, "add_results_label", "new_poll_results_label");
    for (int i = 0; i < values.length; ++i) {

      UIBranchContainer radiobranch =
          UIBranchContainer.make(newPoll, "releaserow:", Integer.toString(i));
      UISelectChoice choice = UISelectChoice.make(radiobranch, "release", selectID, i);
      UISelectLabel lb = UISelectLabel.make(radiobranch, "releaseLabel", selectID, i);
      UILabelTargetDecorator.targetLabel(lb, choice);
    }

    LOG.debug("About to close the form");
    newPoll.parameters.add(new UIELBinding("#{poll.owner}", currentuserid));
    String siteId = externalLogic.getCurrentLocationId();
    newPoll.parameters.add(new UIELBinding("#{poll.siteId}", siteId));

    if (isNew || poll.getPollOptions() == null || poll.getPollOptions().size() == 0) {
      UICommand.make(
          newPoll,
          "submit-new-poll",
          UIMessage.make("new_poll_saveoption"),
          "#{pollToolBean.processActionAdd}");
    } else {
      UICommand.make(
          newPoll,
          "submit-new-poll",
          UIMessage.make("new_poll_submit"),
          "#{pollToolBean.processActionAdd}");
    }

    UICommand cancel =
        UICommand.make(
            newPoll, "cancel", UIMessage.make("new_poll_cancel"), "#{pollToolBean.cancel}");
    cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel"));
    LOG.debug("Finished generating view");
  }
  /* (non-Javadoc)
   * @see uk.org.ponder.rsf.view.ComponentProducer#fillComponents(uk.org.ponder.rsf.components.UIContainer, uk.org.ponder.rsf.viewstate.ViewParameters, uk.org.ponder.rsf.view.ComponentChecker)
   */
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

    EvalViewParameters evalViewParams = (EvalViewParameters) viewparams;
    if (evalViewParams.evaluationId == null) {
      throw new IllegalArgumentException("Cannot access this view unless the evaluationId is set");
    }

    String actionBean = "setupEvalBean.";
    String evaluationOTP = "evaluationBeanLocator." + evalViewParams.evaluationId + ".";
    /**
     * This is the evaluation we are working with on this page, this should ONLY be read from, do
     * not change any of these fields
     */
    EvalEvaluation evaluation = evaluationService.getEvaluationById(evalViewParams.evaluationId);
    String currentEvalState = evaluationService.returnAndFixEvalState(evaluation, true);

    // local variables used in the render logic
    String currentUserId = commonLogic.getCurrentUserId();
    boolean userAdmin = commonLogic.isUserAdmin(currentUserId);
    boolean createTemplate = authoringService.canCreateTemplate(currentUserId);
    boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId);

    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG, locale);
    DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, locale);

    /*
     * top links here
     */
    UIInternalLink.make(
        tofill,
        "summary-link",
        UIMessage.make("summary.page.title"),
        new SimpleViewParameters(SummaryProducer.VIEW_ID));

    if (userAdmin) {
      UIInternalLink.make(
          tofill,
          "administrate-link",
          UIMessage.make("administrate.page.title"),
          new SimpleViewParameters(AdministrateProducer.VIEW_ID));
      UIInternalLink.make(
          tofill,
          "control-scales-link",
          UIMessage.make("controlscales.page.title"),
          new SimpleViewParameters(ControlScalesProducer.VIEW_ID));
    }

    if (createTemplate) {
      UIInternalLink.make(
          tofill,
          "control-templates-link",
          UIMessage.make("controltemplates.page.title"),
          new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID));
      UIInternalLink.make(
          tofill,
          "control-items-link",
          UIMessage.make("controlitems.page.title"),
          new SimpleViewParameters(ControlItemsProducer.VIEW_ID));
    }

    if (beginEvaluation) {
      UIInternalLink.make(
          tofill,
          "control-evaluations-link",
          UIMessage.make("controlevaluations.page.title"),
          new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID));
    } else {
      throw new SecurityException(
          "User attempted to access " + VIEW_ID + " when they are not allowed");
    }

    UIInternalLink.make(
        tofill,
        "eval-settings-link",
        UIMessage.make("evalsettings.page.title"),
        new EvalViewParameters(EvaluationSettingsProducer.VIEW_ID, evalViewParams.evaluationId));
    if (EvalConstants.EVALUATION_STATE_PARTIAL.equals(evaluation.getState())) {
      // creating a new eval
      UIMessage.make(tofill, "eval-start-text", "starteval.page.title");
    }

    UIForm form = UIForm.make(tofill, "evalSettingsForm");

    // REOPENING eval (SPECIAL CASE)
    Date reOpenDueDate = null;
    Date reOpenStopDate = null;
    boolean reOpening = false;
    if (evalViewParams.reOpening) {
      Boolean enableReOpen = (Boolean) settings.get(EvalSettings.ENABLE_EVAL_REOPEN);
      if (enableReOpen) {
        // check if already active, do nothing if not closed
        if (EvalUtils.checkStateAfter(
            currentEvalState, EvalConstants.EVALUATION_STATE_CLOSED, false)) {
          // force the due and stop dates to something reasonable
          Calendar calendar = new GregorianCalendar();
          calendar.setTime(new Date());
          calendar.add(Calendar.DATE, 1);
          reOpenDueDate = calendar.getTime();

          Boolean useStopDate = (Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE);
          if (useStopDate) {
            // assign stop date to equal due date for now
            reOpenStopDate = calendar.getTime();
          }

          // finally force the state to appear active
          currentEvalState = EvalConstants.EVALUATION_STATE_ACTIVE;
          form.parameters.add(
              new UIELBinding(actionBean + "reOpening", true)); // so we know we are reopening
          reOpening = true;
        }
      }
    }

    // EVALUATION TITLE/INSTRUCTIONS

    if (EvalUtils.checkStateBefore(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true)) {
      UIInput.make(form, "title", evaluationOTP + "title");
    } else {
      UIOutput.make(tofill, "title_disabled", evaluation.getTitle());
    }

    if (EvalUtils.checkStateBefore(currentEvalState, EvalConstants.EVALUATION_STATE_CLOSED, true)) {
      UIInput instructionsInput =
          UIInput.make(form, "instructions:", evaluationOTP + "instructions");
      instructionsInput.decorators = new DecoratorList(new UITextDimensionsDecorator(60, 4));
      richTextEvolver.evolveTextInput(instructionsInput);
    } else {
      UIVerbatim.make(tofill, "instructions_disabled", evaluation.getInstructions());
    }

    // only put up the controls/auto binding if this is not already set
    if (evaluation.getTemplate() == null) {
      // Make bottom table containing the list of templates if no template set
      if (evalViewParams.templateId == null) {
        // get the templates usable by this user
        List<EvalTemplate> templateList =
            authoringService.getTemplatesForUser(currentUserId, null, false);
        if (templateList.size() > 0) {
          UIBranchContainer chooseTemplate = UIBranchContainer.make(form, "chooseTemplate:");

          String[] values = new String[templateList.size()];
          String[] labels = new String[templateList.size()];

          // TODO - this is not a good way to do this
          UISelect radios =
              UISelect.make(
                  chooseTemplate, "templateRadio", null, null, actionBean + "templateId", null);
          String selectID = radios.getFullID();
          for (int i = 0; i < templateList.size(); i++) {
            EvalTemplate template = templateList.get(i);
            values[i] = template.getId().toString();
            labels[i] = template.getTitle();
            UIBranchContainer radiobranch =
                UIBranchContainer.make(chooseTemplate, "templateOptions:", i + "");
            UISelectChoice.make(radiobranch, "radioValue", selectID, i);
            UISelectLabel.make(radiobranch, "radioLabel", selectID, i);
            EvalUser owner = commonLogic.getEvalUserById(template.getOwner());
            UIOutput.make(radiobranch, "radioOwner", owner.displayName);
            UIInternalLink.make(
                radiobranch,
                "viewPreview_link",
                UIMessage.make("starteval.view.preview.link"),
                new EvalViewParameters(PreviewEvalProducer.VIEW_ID, null, template.getId()));
          }
          // need to assign the choices and labels at the end here since we used nulls at the
          // beginning
          radios.optionlist = UIOutputMany.make(values);
          radios.optionnames = UIOutputMany.make(labels);
        } else {
          throw new IllegalStateException(
              "User got to evaluation settings when they have no access to any templates... "
                  + "producer suicide was the only way out");
        }
      } else {
        // just bind in the template explicitly to the evaluation
        form.parameters.add(
            new UIELBinding(
                evaluationOTP + "template",
                new ELReference("templateBeanLocator." + evalViewParams.templateId)));
      }
    } else {
      EvalTemplate template = authoringService.getTemplateById(evaluation.getTemplate().getId());
      UIBranchContainer showTemplateBranch = UIBranchContainer.make(tofill, "showTemplate:");
      UIMessage.make(
          showTemplateBranch,
          "eval_template_title",
          "evalsettings.template.title.display",
          new Object[] {template.getTitle()});
      UIInternalLink.make(
          showTemplateBranch,
          "eval_template_preview_link",
          UIMessage.make("evalsettings.template.preview.link"),
          new EvalViewParameters(PreviewEvalProducer.VIEW_ID, null, template.getId()));
      if (!template.getLocked().booleanValue()
          && authoringService.canModifyTemplate(currentUserId, template.getId())) {
        UIInternalLink.make(
            showTemplateBranch,
            "eval_template_modify_link",
            UIMessage.make("general.command.edit"),
            new TemplateViewParameters(ModifyTemplateItemsProducer.VIEW_ID, template.getId()));
      }
    }

    // EVALUATION DATES

    Date today = new Date();
    UIMessage.make(
        tofill,
        "current_date",
        "evalsettings.dates.current",
        new Object[] {dateFormat.format(today), timeFormat.format(today)});

    // retrieve the global setting for use of date only or date and time picker
    Boolean useDateTime = (Boolean) settings.get(EvalSettings.EVAL_USE_DATE_TIME);

    // Start Date
    UIBranchContainer showStartDate = UIBranchContainer.make(form, "showStartDate:");
    generateDateSelector(
        showStartDate,
        "startDate",
        evaluationOTP + "startDate",
        null,
        currentEvalState,
        EvalConstants.EVALUATION_STATE_ACTIVE,
        useDateTime);

    // Due Date
    UIBranchContainer showDueDate = UIBranchContainer.make(form, "showDueDate:");
    generateDateSelector(
        showDueDate,
        "dueDate",
        evaluationOTP + "dueDate",
        reOpenDueDate,
        currentEvalState,
        EvalConstants.EVALUATION_STATE_GRACEPERIOD,
        useDateTime);

    // Stop Date - Show the "Stop date" text box only if allowed in the System settings
    Boolean useStopDate = (Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE);
    if (useStopDate) {
      UIBranchContainer showStopDate = UIBranchContainer.make(form, "showStopDate:");
      generateDateSelector(
          showStopDate,
          "stopDate",
          evaluationOTP + "stopDate",
          reOpenStopDate,
          currentEvalState,
          EvalConstants.EVALUATION_STATE_CLOSED,
          useDateTime);
    }

    // EVALUATION RESULTS VIEWING/SHARING

    // radio buttons for the results sharing options
    UISelect resultsSharingRadios =
        UISelect.make(
                form,
                "dummyRadioSharing",
                EvalToolConstants.EVAL_RESULTS_SHARING_VALUES,
                EvalToolConstants.EVAL_RESULTS_SHARING_LABELS_PROPS,
                evaluationOTP + "resultsSharing",
                null)
            .setMessageKeys();
    String resultsSharingId = resultsSharingRadios.getFullID();
    for (int i = 0; i < EvalToolConstants.EVAL_RESULTS_SHARING_VALUES.length; ++i) {
      UIBranchContainer radiobranch = UIBranchContainer.make(form, "resultsSharingChoice:", i + "");
      UISelectChoice choice = UISelectChoice.make(radiobranch, "radioValue", resultsSharingId, i);
      UISelectLabel.make(radiobranch, "radioLabel", resultsSharingId, i)
          .decorate(new UILabelTargetDecorator(choice));
    }

    // show the view date only if allowed by system settings
    if (((Boolean) settings.get(EvalSettings.EVAL_USE_VIEW_DATE)).booleanValue()) {
      UIBranchContainer showViewDate = UIBranchContainer.make(form, "showViewDate:");
      generateDateSelector(
          showViewDate,
          "viewDate",
          evaluationOTP + "viewDate",
          null,
          currentEvalState,
          EvalConstants.EVALUATION_STATE_VIEWABLE,
          useDateTime);
    }

    // all types of users view results on the same date or we can configure the results viewing
    // separately
    boolean sameViewDateForAll = (Boolean) settings.get(EvalSettings.EVAL_USE_SAME_VIEW_DATES);

    // Student view date
    Boolean studentViewResults = (Boolean) settings.get(EvalSettings.STUDENT_ALLOWED_VIEW_RESULTS);
    UIBranchContainer showResultsToStudents =
        UIBranchContainer.make(form, "showResultsToStudents:");
    generateSettingsControlledCheckbox(
        showResultsToStudents,
        "studentViewResults",
        evaluationOTP + "studentViewResults",
        studentViewResults,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_VIEWABLE, true));
    generateViewDateControl(
        showResultsToStudents,
        "studentsViewDate",
        evaluationOTP + "studentsDate",
        studentViewResults,
        useDateTime,
        sameViewDateForAll);

    // Instructor view date
    Boolean instructorViewResults =
        (Boolean) settings.get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS);
    UIBranchContainer showResultsToInst = UIBranchContainer.make(form, "showResultsToInst:");
    generateSettingsControlledCheckbox(
        showResultsToInst,
        "instructorViewResults",
        evaluationOTP + "instructorViewResults",
        instructorViewResults,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_VIEWABLE, true));
    generateViewDateControl(
        showResultsToInst,
        "instructorsViewDate",
        evaluationOTP + "instructorsDate",
        instructorViewResults,
        useDateTime,
        sameViewDateForAll);

    // RESPONDENT SETTINGS

    // Student Allowed Leave Unanswered
    Boolean studentUnanswersAllowed =
        (Boolean) settings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
    UIBranchContainer showBlankQuestionAllowedToStut =
        UIBranchContainer.make(form, "showBlankQuestionAllowedToStut:");
    generateSettingsControlledCheckbox(
        showBlankQuestionAllowedToStut,
        "blankResponsesAllowed",
        evaluationOTP + "blankResponsesAllowed",
        studentUnanswersAllowed,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true));

    // Student Modify Responses
    Boolean studentModifyReponses = (Boolean) settings.get(EvalSettings.STUDENT_MODIFY_RESPONSES);
    UIBranchContainer showModifyResponsesAllowedToStu =
        UIBranchContainer.make(form, "showModifyResponsesAllowedToStu:");
    generateSettingsControlledCheckbox(
        showModifyResponsesAllowedToStu,
        "modifyResponsesAllowed",
        evaluationOTP + "modifyResponsesAllowed",
        studentModifyReponses,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true));

    // ADMIN SETTINGS SECTION

    UISelect authControlSelect =
        UISelect.make(
                form,
                "auth-control-choose",
                EvalToolConstants.AUTHCONTROL_VALUES,
                EvalToolConstants.AUTHCONTROL_LABELS,
                evaluationOTP + "authControl")
            .setMessageKeys();
    if (EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true)) {
      RSFUtils.disableComponent(authControlSelect);
    }

    if (userAdmin) {
      // If the person is an admin (any kind), then we need to show these instructor opt in/out
      // settings

      UIMessage.make(
          form, "instructor-opt-instructions", "evalsettings.admin.settings.instructions");
      UIMessage.make(form, "instructor-opt-header", "evalsettings.instructor.opt.desc");

      // If "EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE" is set as configurable
      // i.e. NULL in the database then show the instructor opt select box. Else just show the value
      // as label
      String instUseFromAboveValue =
          (String) settings.get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE);
      if (instUseFromAboveValue == null
          || EvalToolConstants.ADMIN_BOOLEAN_CONFIGURABLE.equals(instUseFromAboveValue)) {
        UISelect instOpt =
            UISelect.make(
                    form,
                    "instructorOpt",
                    EvalToolConstants.INSTRUCTOR_OPT_VALUES,
                    EvalToolConstants.INSTRUCTOR_OPT_LABELS,
                    evaluationOTP + "instructorOpt")
                .setMessageKeys();
        if (EvalUtils.checkStateAfter(
            currentEvalState, EvalConstants.EVALUATION_STATE_INQUEUE, true)) {
          RSFUtils.disableComponent(instOpt);
        }
      } else {
        int index =
            ArrayUtil.indexOf(EvalToolConstants.INSTRUCTOR_OPT_VALUES, instUseFromAboveValue);
        String instUseFromAboveLabel = EvalToolConstants.INSTRUCTOR_OPT_LABELS[index];
        // Displaying the label corresponding to INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value set as
        // system property
        UIMessage.make(form, "instructorOptLabel", instUseFromAboveLabel);
        // Doing the binding of this INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value so that it can be
        // saved in the database
        form.parameters.add(
            new UIELBinding(evaluationOTP + "instructorOpt", instUseFromAboveValue));
      }
    }

    // EVALUATION REMINDERS SECTION

    // email available template link
    UIInternalLink.make(
        form,
        "emailAvailable_link",
        UIMessage.make("evalsettings.available.mail.link"),
        new EmailViewParameters(
            PreviewEmailProducer.VIEW_ID,
            null,
            EvalConstants.EMAIL_TEMPLATE_AVAILABLE,
            evaluation.getId()));

    // email reminder control
    UISelect reminderDaysSelect =
        UISelect.make(
                form,
                "reminderDays",
                EvalToolConstants.REMINDER_EMAIL_DAYS_VALUES,
                EvalToolConstants.REMINDER_EMAIL_DAYS_LABELS,
                evaluationOTP + "reminderDays")
            .setMessageKeys();
    if (EvalUtils.checkStateAfter(
        currentEvalState, EvalConstants.EVALUATION_STATE_GRACEPERIOD, true)) {
      RSFUtils.disableComponent(reminderDaysSelect);
    }

    // email reminder template link
    UIInternalLink.make(
        form,
        "emailReminder_link",
        UIMessage.make("evalsettings.reminder.mail.link"),
        new EmailViewParameters(
            PreviewEmailProducer.VIEW_ID,
            null,
            EvalConstants.EMAIL_TEMPLATE_REMINDER,
            evaluation.getId()));

    // email from address control
    String defaultEmail = (String) settings.get(EvalSettings.FROM_EMAIL_ADDRESS);
    UIMessage.make(
        form, "eval-from-email-note", "evalsettings.email.sent.from", new String[] {defaultEmail});
    UIInput.make(form, "reminderFromEmail", evaluationOTP + "reminderFromEmail");

    // EVALUATION EXTRAS SECTION
    Boolean categoriesEnabled = (Boolean) settings.get(EvalSettings.ENABLE_EVAL_CATEGORIES);
    if (categoriesEnabled) {
      UIBranchContainer extrasBranch = UIBranchContainer.make(form, "showEvalExtras:");

      // eval category
      if (categoriesEnabled) {
        UIBranchContainer categoryBranch = UIBranchContainer.make(extrasBranch, "showCategory:");
        UIInput.make(categoryBranch, "eval-category", evaluationOTP + "evalCategory");
        if (evaluation.getEvalCategory() != null) {
          UILink.make(
                  categoryBranch,
                  "eval-category-direct-link",
                  UIMessage.make("general.direct.link"),
                  commonLogic.getEntityURL(
                      EvalCategoryEntityProvider.ENTITY_PREFIX, evaluation.getEvalCategory()))
              .decorate(new UITooltipDecorator(UIMessage.make("general.direct.link.title")));
        }
      }
    }

    // EVAL SETTINGS SAVING CONTROLS
    // if this evaluation is already saved, show "Save Settings" button else this is the "Continue
    // to Assign to Courses" button
    String messageKey = "evalsettings.save.settings.link";
    if (EvalConstants.EVALUATION_STATE_PARTIAL.equals(evaluation.getState())) {
      messageKey = "evalsettings.continue.assigning.link";
    }
    if (reOpening) {
      messageKey = "evalsettings.reopening.eval.link";
    }
    UICommand.make(
        form,
        "continueAssigning",
        UIMessage.make(messageKey),
        actionBean + "completeSettingsAction");
    UIMessage.make(tofill, "cancel-button", "general.cancel.button");

    // this fills in the javascript call (areaId, selectId, selectValue, reminderId)
    // NOTE: RSF bug causes us to have to generate the ids manually
    // (http://www.caret.cam.ac.uk/jira/browse/RSF-65)
    UIInitBlock.make(
        tofill,
        "initJavascript",
        "EvalSystem.initEvalSettings",
        new Object[] {
          "evaluation_reminder_area",
          authControlSelect.getFullID() + "-selection",
          EvalConstants.EVALUATION_AUTHCONTROL_NONE,
          reminderDaysSelect.getFullID() + "-selection"
        });
  }
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
    if (((GeneralViewParameters) viewparams).getSendingPage() != -1) {
      // will fail if page not in this site
      // security then depends upon making sure that we only deal with this page
      try {
        simplePageBean.updatePageObject(((GeneralViewParameters) viewparams).getSendingPage());
      } catch (Exception e) {
        System.out.println("PagePicker permission exception " + e);
        return;
      }
    }

    UIOutput.make(tofill, "html")
        .decorate(new UIFreeAttributeDecorator("lang", localeGetter.get().getLanguage()))
        .decorate(new UIFreeAttributeDecorator("xml:lang", localeGetter.get().getLanguage()));

    boolean canEditPage = (simplePageBean.getEditPrivs() == 0);

    String source = ((GeneralViewParameters) viewparams).getSource();
    // summaryPage is the "index of pages". It has status icons and links, but isn't a chooser
    // otherwise we have the chooser page for the "add subpage" command
    boolean summaryPage = "summary".equals(source);

    if (summaryPage) {
      GeneralViewParameters view = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
      // path defaults to null, which is next
      UIOutput.make(tofill, "return-div");
      UIInternalLink.make(tofill, "return", messageLocator.getMessage("simplepage.return"), view);
      UIOutput.make(tofill, "title", messageLocator.getMessage("simplepage.page.index"));
    } else {
      UIOutput.make(tofill, "title", messageLocator.getMessage("simplepage.page.chooser"));
    }

    // Explain which pages may be deleted
    if (summaryPage && canEditPage) {
      UIOutput.make(tofill, "deleteAlert");
    }

    // this looks at pages in the site, which should be safe
    // but need to make sure the item we update is legal

    Long itemId = ((GeneralViewParameters) viewparams).getItemId();

    simplePageBean.setItemId(itemId);

    SimplePage page = simplePageBean.getCurrentPage();
    currentPageId = page.getPageId();

    if (itemId != null && itemId != -1) {
      SimplePageItem currentItem = simplePageToolDao.findItem(itemId);
      if (currentItem == null) return;
      // trying to hack on item not on this page
      if (currentItem.getPageId() != page.getPageId()) return;
    }

    // list we're going to display
    List<PageEntry> entries = new ArrayList<PageEntry>();

    // build map of all pages, so we can see if any are left over
    Map<Long, SimplePage> pageMap = new HashMap<Long, SimplePage>();

    Set<Long> sharedPages = new HashSet<Long>();

    // all pages
    List<SimplePage> pages = simplePageToolDao.getSitePages(simplePageBean.getCurrentSiteId());
    for (SimplePage p : pages) pageMap.put(p.getPageId(), p);

    // set of all top level pages, actually the items pointing to them
    List<SimplePageItem> sitePages =
        simplePageToolDao.findItemsInSite(toolManager.getCurrentPlacement().getContext());
    Set<Long> topLevelPages = new HashSet<Long>();
    for (SimplePageItem i : sitePages) topLevelPages.add(Long.valueOf(i.getSakaiId()));

    // this adds everything you can find from top level pages to entries. But make sure user can see
    // the tool
    for (SimplePageItem sitePageItem : sitePages) {
      // System.out.println("findallpages " + sitePageItem.getName() + " " + true);
      findAllPages(
          sitePageItem, entries, pageMap, topLevelPages, sharedPages, 0, true, canEditPage);
    }

    // warn students if we aren't showing all the pages
    if (!canEditPage && somePagesHavePrerequisites) UIOutput.make(tofill, "onlyseen");

    // now add everything we didn't find that way
    if (canEditPage && pageMap.size() > 0) {
      // marker
      PageEntry marker = new PageEntry();
      marker.level = -1;
      entries.add(marker);
      for (SimplePage p : pageMap.values()) {
        if (p.getOwner() == null) {
          PageEntry entry = new PageEntry();
          entry.pageId = p.getPageId();
          entry.itemId = null;
          entry.title = p.getTitle();
          entry.level = 0;

          // TopLevel determines if we can select the page.
          // Since this means that the page is detached, it isn't
          // a conflict to be able to select it.
          entry.toplevel = false;

          entries.add(entry);
        }
      }
    }

    if (canEditPage && sharedPages.size() > 0) UIOutput.make(tofill, "sharedpageexplanation");

    UIForm form = UIForm.make(tofill, "page-picker");
    Object sessionToken = SessionManager.getCurrentSession().getAttribute("sakai.csrf.token");
    if (sessionToken != null)
      UIInput.make(form, "csrf", "simplePageBean.csrfToken", sessionToken.toString());

    ArrayList<String> values = new ArrayList<String>();
    ArrayList<String> initValues = new ArrayList<String>();
    for (PageEntry entry : entries) {
      if (entry.level >= 0) {
        values.add(entry.pageId.toString());
        initValues.add("");
      }
    }

    UISelect select = null;
    if (summaryPage)
      select =
          UISelect.makeMultiple(
              form,
              "page-span",
              values.toArray(new String[1]),
              "#{simplePageBean.selectedEntities}",
              initValues.toArray(new String[1]));
    else
      select =
          UISelect.make(
              form,
              "page-span",
              values.toArray(new String[1]),
              "#{simplePageBean.selectedEntity}",
              null);

    int index = 0;
    boolean showDeleteButton = false;

    for (PageEntry entry : entries) {

      UIBranchContainer row = UIBranchContainer.make(form, "page:");
      if (entry.toplevel)
        row.decorate(
            new UIFreeAttributeDecorator("style", "list-style-type:none; margin-top:0.5em"));

      if (entry.level < 0) {
        UIOutput.make(row, "heading", messageLocator.getMessage("simplepage.chooser.unused"));
        if (summaryPage) UIOutput.make(row, "chooseall");
      }
      // if no itemid, it's unused. Only canedit people will see it
      else if (summaryPage && entry.itemId != null) {
        int level = entry.level;
        if (level > 5) level = 5;
        String imagePath = "/lessonbuilder-tool/images/";
        SimplePageItem item = simplePageBean.findItem(entry.itemId);
        SimplePageLogEntry logEntry = simplePageBean.getLogEntry(entry.itemId);
        String note = null;
        if (logEntry != null && logEntry.isComplete()) {
          imagePath += "checkmark.png";
          note = messageLocator.getMessage("simplepage.status.completed");
        } else if (logEntry != null && !logEntry.getDummy()) {
          imagePath += "hourglass.png";
          note = messageLocator.getMessage("simplepage.status.inprogress");
        } else if (!canEditPage && somePagesHavePrerequisites) {
          // it's too complex to compute prerequisites for all pages, and
          // I'm concerned that faculty may not be careful in setting them
          // for pages that would normally not be accessible. So if there are
          // any prerequisites in the site, only show pages that are
          // in progress or done.
          continue;
        } else {
          imagePath += "not-required.png";
        }
        UIOutput.make(row, "status-image").decorate(new UIFreeAttributeDecorator("src", imagePath));
        GeneralViewParameters p = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
        p.setSendingPage(entry.pageId);
        p.setItemId(entry.itemId);
        // reset the path to the saved one
        p.setPath("log");
        UIInternalLink.make(row, "link", p)
            .decorate(new UIFreeAttributeDecorator("style", "padding-left: " + (2 * level) + "em"));
        String levelstr = null;
        if (level > 0)
          levelstr =
              messageLocator
                  .getMessage("simplepage.status.level")
                  .replace("{}", Integer.toString(level));
        if (levelstr != null) {
          if (note != null) note = levelstr + " " + note;
          else note = levelstr;
        }
        if (note != null) UIOutput.make(row, "link-note", note + " ");
        UIOutput.make(row, "link-text", entry.title);

        if (enableShowItems) {
          UIOutput.make(row, "item-list-toggle");
          UIOutput.make(row, "itemListContainer")
              .decorate(
                  new UIFreeAttributeDecorator("style", "margin-left: " + (3 * level) + "em"));
          UIOutput.make(row, "itemList");

          Set<String> myGroups = simplePageBean.getMyGroups();

          for (SimplePageItem pageItem : simplePageToolDao.findItemsOnPage(entry.pageId)) {

            // if item is group controlled, skip if user isn't in one of the groups
            Collection<String> itemGroups = null;
            try {
              itemGroups = simplePageBean.getItemGroups(pageItem, null, false);
            } catch (IdUnusedException e) {
              // underlying assignment, etc, doesn't exist. skip the item
              continue;
            }
            if (itemGroups != null) {
              boolean groupsOk = false;
              for (String group : itemGroups) {
                if (myGroups.contains(group)) {
                  groupsOk = true;
                  break;
                }
              }
              if (!groupsOk) continue;
            }

            UIBranchContainer itemListItem = UIBranchContainer.make(row, "item:");

            if (pageItem.isRequired()) {
              UIOutput.make(itemListItem, "required-image");
            } else {
              UIOutput.make(itemListItem, "not-required-image");
            }

            UIOutput.make(itemListItem, "item-icon").decorate(getImageSourceDecorator(pageItem));

            if (pageItem.isPrerequisite()) {
              itemListItem.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
            }

            if (SimplePageItem.TEXT == pageItem.getType()) {
              UIOutput.make(
                      itemListItem,
                      "name",
                      messageLocator.getMessage("simplepage.chooser.textitemplaceholder"))
                  .decorate(new UIFreeAttributeDecorator("class", "text-item-placeholder"));
            } else if (SimplePageItem.BREAK == pageItem.getType()) {
              String text = null;
              if ("section".equals(pageItem.getFormat()))
                text = messageLocator.getMessage("simplepage.break-here");
              else text = messageLocator.getMessage("simplepage.break-column-here");
              UIOutput.make(itemListItem, "name", text)
                  .decorate(new UIFreeAttributeDecorator("class", "text-item-placeholder"));

            } else {
              UIOutput.make(itemListItem, "name", pageItem.getName());
            }
            // UIOutput.make(itemListItem, "page1",
            // Boolean.toString(lessonsAccess.isItemAccessible(pageItem.getId(),simplePageBean.getCurrentSiteId(),"c08d3ac9-c717-472a-ad91-7ce0b434f42f", simplePageBean)));
          }
        }
        index++;

        // for pagepicker or summary if canEdit and page doesn't have an item
      } else {
        int level = entry.level;
        if (level > 5) level = 5;
        if (!summaryPage /*&& !entry.toplevel*/) { // i.e. pagepicker; for the moment to edit
                                                   // something you need to attach it to something
          UISelectChoice.make(row, "select", select.getFullID(), index)
              .decorate(
                  new UIFreeAttributeDecorator(
                      "title", entry.title + " " + messageLocator.getMessage("simplepage.select")));
        } else if (summaryPage) { // i.e. summary if canEdit and page doesn't have an item
          UISelectChoice.make(row, "select-for-deletion", select.getFullID(), index)
              .decorate(
                  new UIFreeAttributeDecorator(
                      "title",
                      entry.title
                          + " "
                          + messageLocator.getMessage("simplepage.select-for-deletion")));
          showDeleteButton = true; // at least one item to delete
        }

        GeneralViewParameters params = new GeneralViewParameters();
        params.viewID = PreviewProducer.VIEW_ID;
        params.setSendingPage(entry.pageId);

        UIInternalLink.make(row, "link", params)
            .decorate(new UIFreeAttributeDecorator("style", "padding-left: " + (2 * level) + "em"))
            .decorate(new UIFreeAttributeDecorator("target", "_blank"));
        String levelstr =
            messageLocator
                    .getMessage("simplepage.status.level")
                    .replace("{}", Integer.toString(level))
                + " ";
        if (level > 0) UIOutput.make(row, "link-note", levelstr);
        UIOutput.make(row, "link-text", entry.title);

        index++;
      }

      if (canEditPage
          && entry != null
          && entry.pageId != null
          && sharedPages.contains(entry.pageId)) {
        UIOutput.make(row, "shared");
      }

      // debug code for development. this will be removed at some point
      // UIOutput.make(row, "page2",
      // lessonsAccess.printPath(lessonsAccess.getPagePaths(entry.pageId)));
      // UIOutput.make(row, "page1", Boolean.toString(lessonsAccess.isPageAccessible(entry.pageId,
      // simplePageBean.getCurrentSiteId(), "c08d3ac9-c717-472a-ad91-7ce0b434f42f",
      // simplePageBean)));

      if (ServerConfigurationService.getBoolean("lessonbuilder.accessibilitydebug", false)) {
        if (entry != null
            && entry.pageId != null
            && lessonsAccess.isPageAccessible(
                entry.pageId,
                simplePageBean.getCurrentSiteId(),
                "c08d3ac9-c717-472a-ad91-7ce0b434f42f",
                null)) {
          UIOutput.make(row, "page1");
        }
        if (entry != null
            && entry.pageId != null
            && lessonsAccess.isPageAccessible(
                entry.pageId,
                simplePageBean.getCurrentSiteId(),
                "c08d3ac9-c717-472a-ad91-7ce0b434f42f",
                simplePageBean)) {
          UIOutput.make(row, "page2");
        }
        if (entry != null
            && entry.pageId != null
            && lessonsAccess.isItemAccessible(
                entry.itemId,
                simplePageBean.getCurrentSiteId(),
                "c08d3ac9-c717-472a-ad91-7ce0b434f42f",
                null)) {
          UIOutput.make(row, "item1");
        }
        if (entry != null
            && entry.pageId != null
            && lessonsAccess.isItemAccessible(
                entry.itemId,
                simplePageBean.getCurrentSiteId(),
                "c08d3ac9-c717-472a-ad91-7ce0b434f42f",
                simplePageBean)) {
          UIOutput.make(row, "item2");
        }
      }
    }

    if (!summaryPage) {

      UIInput.make(form, "item-id", "#{simplePageBean.itemId}");

      if (itemId == -1 && !((GeneralViewParameters) viewparams).newTopLevel) {
        UIOutput.make(form, "hr");
        UIOutput.make(form, "options");
        UIBoundBoolean.make(form, "subpage-next", "#{simplePageBean.subpageNext}", false);
        UIBoundBoolean.make(form, "subpage-button", "#{simplePageBean.subpageButton}", false);
      }

      String returnView = ((GeneralViewParameters) viewparams).getReturnView();
      if (returnView != null && returnView.equals("reorder")) {
        // return to Reorder, to add items from this page
        UICommand.make(
            form,
            "submit",
            messageLocator.getMessage("simplepage.chooser.select"),
            "#{simplePageBean.selectPage}");
      } else if (((GeneralViewParameters) viewparams).newTopLevel) {
        UIInput.make(
            form,
            "addBefore",
            "#{simplePageBean.addBefore}",
            ((GeneralViewParameters) viewparams).getAddBefore());
        UICommand.make(
            form,
            "submit",
            messageLocator.getMessage("simplepage.chooser.select"),
            "#{simplePageBean.addOldPage}");
      } else {
        UIInput.make(
            form,
            "addBefore",
            "#{simplePageBean.addBefore}",
            ((GeneralViewParameters) viewparams).getAddBefore());
        UICommand.make(
            form,
            "submit",
            messageLocator.getMessage("simplepage.chooser.select"),
            "#{simplePageBean.createSubpage}");
      }
      UICommand.make(
          form,
          "cancel",
          messageLocator.getMessage("simplepage.cancel"),
          "#{simplePageBean.cancel}");
    } else if (showDeleteButton) {
      UICommand.make(
          form,
          "submit",
          messageLocator.getMessage("simplepage.delete-selected"),
          "#{simplePageBean.deletePages}");
    }
  }