<commit_before>require [
  'jquery'
  'underscore'
  'Backbone'
  'react',
  'react-dom'
  'sfu_course_form/compiled/models/User'
  'sfu_course_form/compiled/models/Term'
  'sfu_course_form/compiled/models/Course'
  'sfu_course_form/compiled/collections/AmaintTermList'
  'sfu_course_form/compiled/collections/TermList'
  'sfu_course_form/compiled/views/terms/TermListView'
  'sfu_course_form/compiled/collections/CourseList'
  'sfu_course_form/compiled/views/courses/CourseListView'
  'sfu_course_form/compiled/views/courses/SelectableCourseListView'
  'sfu_course_form/compiled/collections/SandboxList'
  'sfu_course_form/compiled/views/sandboxes/SandboxListView',
  'jsx/sfu_copyright_compliance_notice/SFUCopyrightComplianceNotice',
  'jqueryui/autocomplete'
], ($, _, Backbone, React, ReactDOM, User, Term, Course, AmaintTermList, TermList, TermListView, CourseList, CourseListView, SelectableCourseListView, SandboxList, SandboxListView, SFUCopyrightComplianceNotice) ->

  user = {}
  currentUser = {}
  terms = new TermList
  suggestedTerms = new TermList
  amaintTerms = {}
  searchedCourseList = new CourseList()
  searchedCourseListView = {}
  selectedCourseList = new CourseList()
  selectedCourseListView = {}
  searchTermSelect = {}

  userIdTextbox = {}
  enrollMeCheckbox = {}
  enrollMeAsSelect = {}
  crosslistCheckbox = {}
  crosslistTitle = {}

  nonCalendarCourseTextbox = {}
  nonCalendarTermSelect = {}

  sandboxList = {}
  sandboxListView = {}

  adhocTextbox = {}

  timeId = do ->
    now = new Date()
    [now.getMonth() + 1, now.getDate(), now.getYear() - 100, now.getTime().toString().substr(10)].join('')

  getUsernameToDisplay = ->
    if user == currentUser then 'yourself' else user.get('sfu_id')

  getCourses = ->
    # first, fetch terms in which the user teaches
    amaintTerms = new AmaintTermList(user.get('sfu_id'))
    amaintTerms.fetch
      success: (incomingTerms) ->
        # then, add ones that matches our master "terms" list to a list of suggested terms
        incomingTerms.each (incomingTerm) ->
          matchedTerm = terms.find((term) -> incomingTerm.get('peopleSoftCode') == term.get('sis_source_id'))
          suggestedTerms.add matchedTerm if matchedTerm
        # finally, fetch and display all courses from these suggested terms
        termListView = new TermListView({collection: suggestedTerms})
        $('#courses-suggested').html termListView.render().el
        suggestedTerms.fetchAllCourses(user.get('sfu_id'))
      error: ->
        $('#courses-suggested').html '<p>No suggested courses found</p>'
    suggestedTerms

  getSandboxes = ->
    sandboxList = new SandboxList(user.get('sfu_id'))
    sandboxListView = new SandboxListView
      collection: sandboxList
      el: $('#sandboxes')
    sandboxListView.username = getUsernameToDisplay()
    sandboxList.fetch
      error: ->
        sandboxListView.renderEmpty()

  initPayload = ->
    payload = username: user.get('sfu_id')
    if enrollMeCheckbox.prop 'checked'
      payload['enroll_me'] = currentUser.get('sfu_id')
      payload['enroll_me_as'] = enrollMeAsSelect.val()
    payload

  processSubmitCalendar = ->
    if selectedCourseList.length == 0
      alert 'You must select at least one course to continue.'
      return

    showStep '4'

    payload = initPayload()
    payload['cross_list'] = true if crosslistCheckbox.prop 'checked'

    selectedCourseList.each (course) ->
      payload["selected_course_#{course.cid}_#{course.get('peopleSoftCode')}"] = course.get('key')

    submitRequest payload, '3-calendar'

  processSubmitNonCalendar = ->
    if $.trim(nonCalendarCourseTextbox.val()) == ''
      alert 'The Course Name must not be empty'
      return

    showStep '4'
    payload = initPayload()

    termCode = nonCalendarTermSelect.val()

    payload["selected_course_#{timeId}_#{nonCalendarTermSelect.val()}"] = "ncc-#{payload.username}-#{timeId}-#{termCode}-#{nonCalendarCourseTextbox.val()}"

    submitRequest payload, '3-non_calendar'

  processSubmitSandbox = ->
    showStep '4'
    payload = initPayload()

    payload["selected_course_sandbox_#{timeId}"] = "sandbox-#{payload.username}-#{timeId}"

    submitRequest payload, '3-sandbox'

  processSubmitAdhoc = ->
    # With ad hoc spaces, the user is always create the space for him/herself
    user = currentUser

    if $.trim(adhocTextbox.val()) == ''
      alert 'The Name of Space must not be empty'
      return

    showStep '4'
    payload = initPayload()

    payload["selected_course_adhoc_#{timeId}"] = "adhoc-#{payload.username}-#{timeId}-#{adhocTextbox.val()}"

    # NOTE: The adhoc form fields are in step 1
    submitRequest payload, '1'

  submitRequest = (payload, destinationOnFailure) ->
    request = $.post '/sfu/course/create', payload
    request.done (data) ->
      if data.success
        showStep '5'
      else
        $.flashError "Course request failed: #{data.message} Please try again."
        showStep destinationOnFailure
    request.fail ->
      console.log request
      $.flashError 'The course request cannot be processed at this time. Please try again.'
      showStep destinationOnFailure

  processFaculty = (action) ->
    userId = userIdTextbox.val()
    validUserId = /^[a-z_0-9]+$/

    if action == 'action-identify-faculty-delegate'
      unless validUserId.test(userId)
        alert 'Instructor Computer ID contains invalid characters. Please correct it before continuing.'
        return
      user = new User(userId)
      user.fetch()
    else
      user = currentUser

    if user.hasLoaded
      showFacultyStep()
    else
      showStep '2-loading'

    $(document).one 'userloaded', -> showFacultyStep()

    $(document).one 'userloaderror', ->
      # deregister the successful event listener to avoid duplicates later
      $(document).off 'userloaded'
      # bring user to a previous step to allow for correction
      if action == 'action-identify-faculty-delegate'
        # user was creating for someone else
        alert 'Instructor Computing ID is invalid. Please double check before continuing.'
        showDelegateStep()
      else
        # user was creating for him/herself; this error is unlikely, but we handle it anyway
        alert 'Your Computing ID is invalid. Please contact Canvas help.'
        showStep '1'

  showFacultyStep = ->
    $('.username-display').text(getUsernameToDisplay())
    $('#sandbox-name-display').text("Sandbox - #{user.get('sfu_id')} - #{timeId}")
    getCourses()
    getSandboxes()
    showStep '2-faculty'

  showDelegateStep = ->
    showStep '1-delegate'
    userIdTextbox.focus()

  showNonCalendarStep = ->
    showStep '3-non_calendar'
    nonCalendarCourseTextbox.focus()

  showStep = (name) ->
    # hide all steps, then only show the specified one
    $('section.step').hide()
    $("#step-#{name}").show()

  handleActionClick = (event) ->
    event.preventDefault()
    action = $(this).attr('id')
    switch action
      when 'action-identify-student' then showStep '2-student'
      when 'action-identify-faculty-delegate-pending' then showDelegateStep()
      when 'action-identify-faculty-delegate', 'action-identify-faculty' then processFaculty action
      when 'action-course-calendar' then showStep '3-calendar'
      when 'action-course-non_calendar' then showNonCalendarStep()
      when 'action-course-sandbox' then showStep '3-sandbox'
    # submit actions
      when 'action-submit-calendar' then processSubmitCalendar()
      when 'action-submit-non_calendar' then processSubmitNonCalendar()
      when 'action-submit-sandbox' then processSubmitSandbox()
      when 'action-submit-adhoc' then processSubmitAdhoc()
    # back actions
      when 'action-back-faculty-delegate' then showStep '1'
      when 'action-back-calendar', 'action-back-non_calendar', 'action-back-sandbox' then showStep '2-faculty'
    # redirect actions
      when 'action-go-dashboard' then window.location = '/'
      when 'action-go-course_list' then window.location = '/courses'
      when 'action-go-start_over', 'action-go-start_over-sidebar' then window.location.reload()
      when 'action-open-help' then window.open 'http://www.sfu.ca/tlc/technology.html', '_blank'

  # create relevant labels for the calendar course submit button
  updateCalendarSubmitButton = ->
    button = $('#action-submit-calendar')
    if crosslistCheckbox.prop 'checked'
      button.text('Create Single Cross-listed Course')
    else
      button.text(if selectedCourseList.length <= 1 then 'Create Course' else 'Create Courses')

  handleSelectedCourseListChange = ->
    # update the course list
    selectedCourseListView.render()
    updateCalendarSubmitButton()
    canCrosslist = yes
    # one can only cross-list more than one course
    canCrosslist &= selectedCourseList.length > 1
    # one can only cross-list courses from the same term
    canCrosslist &= selectedCourseList.terms().length == 1
    if canCrosslist
      # only enable cross-list checkbox if cross-listing is possible/logical
      crosslistCheckbox.removeAttr('disabled')
      # when cross-listing, show concatenated course name
      names = selectedCourseList.map (course) ->
        "#{course.get 'name'}#{course.get 'number'} - #{course.get 'section'}"
      crosslistTitle.text "The new course will be called: #{names.join ' / '}"
    else
      crosslistCheckbox.attr('disabled', 'disabled').prop('checked', false).triggerHandler('change')
      crosslistTitle.text 'No cross-list'

  $(document).ready ->


    ReactDOM.render(
      React.createElement(
        SFUCopyrightComplianceNotice,
        { className: 'sfu-ic-wizard-box__message-text__copyright_compliance' }
      ),
      document.getElementsByClassName('copyright')[0]
    )

    # attach behavior to action links
    $('button.action').bind 'click', handleActionClick

    # extract master "terms" list from the HTML drop-down menu
    searchTermSelect = $('#sel-search-term')
    searchTermSelect.children('option').each ->
      terms.add new Term
        sis_source_id: $(this).attr('value')
        name: $(this).text()

    # pre-fetch the current user
    userIdTextbox = $('#txt-user_id')
    userIdTextbox.bind 'keydown', (event) -><commit_msg>Fix rendering of SFUCopyrightComplianceNotice in new course form<commit_after>require [
  'jquery'
  'underscore'
  'Backbone'
  'react',
  'react-dom'
  'sfu_course_form/compiled/models/User'
  'sfu_course_form/compiled/models/Term'
  'sfu_course_form/compiled/models/Course'
  'sfu_course_form/compiled/collections/AmaintTermList'
  'sfu_course_form/compiled/collections/TermList'
  'sfu_course_form/compiled/views/terms/TermListView'
  'sfu_course_form/compiled/collections/CourseList'
  'sfu_course_form/compiled/views/courses/CourseListView'
  'sfu_course_form/compiled/views/courses/SelectableCourseListView'
  'sfu_course_form/compiled/collections/SandboxList'
  'sfu_course_form/compiled/views/sandboxes/SandboxListView',
  'jsx/sfu_copyright_compliance_notice/SFUCopyrightComplianceNotice',
  'jqueryui/autocomplete'
], ($, _, Backbone, React, ReactDOM, User, Term, Course, AmaintTermList, TermList, TermListView, CourseList, CourseListView, SelectableCourseListView, SandboxList, SandboxListView, SFUCopyrightComplianceNotice) ->

  user = {}
  currentUser = {}
  terms = new TermList
  suggestedTerms = new TermList
  amaintTerms = {}
  searchedCourseList = new CourseList()
  searchedCourseListView = {}
  selectedCourseList = new CourseList()
  selectedCourseListView = {}
  searchTermSelect = {}

  userIdTextbox = {}
  enrollMeCheckbox = {}
  enrollMeAsSelect = {}
  crosslistCheckbox = {}
  crosslistTitle = {}

  nonCalendarCourseTextbox = {}
  nonCalendarTermSelect = {}

  sandboxList = {}
  sandboxListView = {}

  adhocTextbox = {}

  timeId = do ->
    now = new Date()
    [now.getMonth() + 1, now.getDate(), now.getYear() - 100, now.getTime().toString().substr(10)].join('')

  getUsernameToDisplay = ->
    if user == currentUser then 'yourself' else user.get('sfu_id')

  getCourses = ->
    # first, fetch terms in which the user teaches
    amaintTerms = new AmaintTermList(user.get('sfu_id'))
    amaintTerms.fetch
      success: (incomingTerms) ->
        # then, add ones that matches our master "terms" list to a list of suggested terms
        incomingTerms.each (incomingTerm) ->
          matchedTerm = terms.find((term) -> incomingTerm.get('peopleSoftCode') == term.get('sis_source_id'))
          suggestedTerms.add matchedTerm if matchedTerm
        # finally, fetch and display all courses from these suggested terms
        termListView = new TermListView({collection: suggestedTerms})
        $('#courses-suggested').html termListView.render().el
        suggestedTerms.fetchAllCourses(user.get('sfu_id'))
      error: ->
        $('#courses-suggested').html '<p>No suggested courses found</p>'
    suggestedTerms

  getSandboxes = ->
    sandboxList = new SandboxList(user.get('sfu_id'))
    sandboxListView = new SandboxListView
      collection: sandboxList
      el: $('#sandboxes')
    sandboxListView.username = getUsernameToDisplay()
    sandboxList.fetch
      error: ->
        sandboxListView.renderEmpty()

  initPayload = ->
    payload = username: user.get('sfu_id')
    if enrollMeCheckbox.prop 'checked'
      payload['enroll_me'] = currentUser.get('sfu_id')
      payload['enroll_me_as'] = enrollMeAsSelect.val()
    payload

  processSubmitCalendar = ->
    if selectedCourseList.length == 0
      alert 'You must select at least one course to continue.'
      return

    showStep '4'

    payload = initPayload()
    payload['cross_list'] = true if crosslistCheckbox.prop 'checked'

    selectedCourseList.each (course) ->
      payload["selected_course_#{course.cid}_#{course.get('peopleSoftCode')}"] = course.get('key')

    submitRequest payload, '3-calendar'

  processSubmitNonCalendar = ->
    if $.trim(nonCalendarCourseTextbox.val()) == ''
      alert 'The Course Name must not be empty'
      return

    showStep '4'
    payload = initPayload()

    termCode = nonCalendarTermSelect.val()

    payload["selected_course_#{timeId}_#{nonCalendarTermSelect.val()}"] = "ncc-#{payload.username}-#{timeId}-#{termCode}-#{nonCalendarCourseTextbox.val()}"

    submitRequest payload, '3-non_calendar'

  processSubmitSandbox = ->
    showStep '4'
    payload = initPayload()

    payload["selected_course_sandbox_#{timeId}"] = "sandbox-#{payload.username}-#{timeId}"

    submitRequest payload, '3-sandbox'

  processSubmitAdhoc = ->
    # With ad hoc spaces, the user is always create the space for him/herself
    user = currentUser

    if $.trim(adhocTextbox.val()) == ''
      alert 'The Name of Space must not be empty'
      return

    showStep '4'
    payload = initPayload()

    payload["selected_course_adhoc_#{timeId}"] = "adhoc-#{payload.username}-#{timeId}-#{adhocTextbox.val()}"

    # NOTE: The adhoc form fields are in step 1
    submitRequest payload, '1'

  submitRequest = (payload, destinationOnFailure) ->
    request = $.post '/sfu/course/create', payload
    request.done (data) ->
      if data.success
        showStep '5'
      else
        $.flashError "Course request failed: #{data.message} Please try again."
        showStep destinationOnFailure
    request.fail ->
      console.log request
      $.flashError 'The course request cannot be processed at this time. Please try again.'
      showStep destinationOnFailure

  processFaculty = (action) ->
    userId = userIdTextbox.val()
    validUserId = /^[a-z_0-9]+$/

    if action == 'action-identify-faculty-delegate'
      unless validUserId.test(userId)
        alert 'Instructor Computer ID contains invalid characters. Please correct it before continuing.'
        return
      user = new User(userId)
      user.fetch()
    else
      user = currentUser

    if user.hasLoaded
      showFacultyStep()
    else
      showStep '2-loading'

    $(document).one 'userloaded', -> showFacultyStep()

    $(document).one 'userloaderror', ->
      # deregister the successful event listener to avoid duplicates later
      $(document).off 'userloaded'
      # bring user to a previous step to allow for correction
      if action == 'action-identify-faculty-delegate'
        # user was creating for someone else
        alert 'Instructor Computing ID is invalid. Please double check before continuing.'
        showDelegateStep()
      else
        # user was creating for him/herself; this error is unlikely, but we handle it anyway
        alert 'Your Computing ID is invalid. Please contact Canvas help.'
        showStep '1'

  showFacultyStep = ->
    $('.username-display').text(getUsernameToDisplay())
    $('#sandbox-name-display').text("Sandbox - #{user.get('sfu_id')} - #{timeId}")
    getCourses()
    getSandboxes()
    showStep '2-faculty'

  showDelegateStep = ->
    showStep '1-delegate'
    userIdTextbox.focus()

  showNonCalendarStep = ->
    showStep '3-non_calendar'
    nonCalendarCourseTextbox.focus()

  showStep = (name) ->
    # hide all steps, then only show the specified one
    $('section.step').hide()
    $("#step-#{name}").show()

  handleActionClick = (event) ->
    event.preventDefault()
    action = $(this).attr('id')
    switch action
      when 'action-identify-student' then showStep '2-student'
      when 'action-identify-faculty-delegate-pending' then showDelegateStep()
      when 'action-identify-faculty-delegate', 'action-identify-faculty' then processFaculty action
      when 'action-course-calendar' then showStep '3-calendar'
      when 'action-course-non_calendar' then showNonCalendarStep()
      when 'action-course-sandbox' then showStep '3-sandbox'
    # submit actions
      when 'action-submit-calendar' then processSubmitCalendar()
      when 'action-submit-non_calendar' then processSubmitNonCalendar()
      when 'action-submit-sandbox' then processSubmitSandbox()
      when 'action-submit-adhoc' then processSubmitAdhoc()
    # back actions
      when 'action-back-faculty-delegate' then showStep '1'
      when 'action-back-calendar', 'action-back-non_calendar', 'action-back-sandbox' then showStep '2-faculty'
    # redirect actions
      when 'action-go-dashboard' then window.location = '/'
      when 'action-go-course_list' then window.location = '/courses'
      when 'action-go-start_over', 'action-go-start_over-sidebar' then window.location.reload()
      when 'action-open-help' then window.open 'http://www.sfu.ca/tlc/technology.html', '_blank'

  # create relevant labels for the calendar course submit button
  updateCalendarSubmitButton = ->
    button = $('#action-submit-calendar')
    if crosslistCheckbox.prop 'checked'
      button.text('Create Single Cross-listed Course')
    else
      button.text(if selectedCourseList.length <= 1 then 'Create Course' else 'Create Courses')

  handleSelectedCourseListChange = ->
    # update the course list
    selectedCourseListView.render()
    updateCalendarSubmitButton()
    canCrosslist = yes
    # one can only cross-list more than one course
    canCrosslist &= selectedCourseList.length > 1
    # one can only cross-list courses from the same term
    canCrosslist &= selectedCourseList.terms().length == 1
    if canCrosslist
      # only enable cross-list checkbox if cross-listing is possible/logical
      crosslistCheckbox.removeAttr('disabled')
      # when cross-listing, show concatenated course name
      names = selectedCourseList.map (course) ->
        "#{course.get 'name'}#{course.get 'number'} - #{course.get 'section'}"
      crosslistTitle.text "The new course will be called: #{names.join ' / '}"
    else
      crosslistCheckbox.attr('disabled', 'disabled').prop('checked', false).triggerHandler('change')
      crosslistTitle.text 'No cross-list'

  $(document).ready ->


    ReactDOM.render(
      React.createElement(
        SFUCopyrightComplianceNotice.default,
        { className: 'sfu-ic-wizard-box__message-text__copyright_compliance' }
      ),
      document.getElementsByClassName('copyright')[0]
    )

    # attach behavior to action links
    $('button.action').bind 'click', handleActionClick

    # extract master "terms" list from the HTML drop-down menu
    searchTermSelect = $('#sel-search-term')
    searchTermSelect.children('option').each ->
      terms.add new Term
        sis_source_id: $(this).attr('value')
        name: $(this).text()

    # pre-fetch the current user
    userIdTextbox = $('#txt-user_id')
    userIdTextbox.bind 'keydown', (event) ->
{'fraction_non_alphanumeric': 0.11712766476413483, 'fraction_numerical': 0.0032196692521586417, 'mean_word_length': 3.4985736229975863, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 75, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5328861', 'n_tokens_mistral': 6217, 'n_tokens_neox': 5944, 'n_words': 1409}