context = window
teacherActions = window.JK.Actions.Teacher

@TeacherSetupMixin = {
  onAppInit: (app) ->
    @app=app
    screenBindings = {
      'beforeShow': @beforeShow
    }
    @root = jQuery(this.getDOMNode())
    @app.bindScreen("teachers/setup/#{@screenName()}", screenBindings)

  beforeShow: (data) ->
    if data? && data.d?
      @teacherId = data.d
      teacherActions.load.trigger({teacher_id: @teacherId})
    else
      teacherActions.load.trigger({})

    if @myBeforeShow?
      @myBeforeShow()

  handleErrors: (changes) ->
    $(".error-text", @root).remove()
    if changes.errors?
      @addError(k,v) for k,v of changes.errors

    changes.errors?

  addError: (k,v) ->
    teacherField = @root.find(".teacher-field[name='#{k}']")
    teacherField.append("<div class='error-text'>#{v.join()}</div>")
    $("input", teacherField).addClass("input-error")

  getParams:() =>
    params = {}
    q = window.location.href.split("?")[1]
    if q?
      q = q.split('#')[0]
      raw_vars = q.split("&")
      for v in raw_vars
        [key, val] = v.split("=")
        params[key] = decodeURIComponent(val)
    params

  teacherSetupSource:() ->
    if @postmark? then @postmark else "/client#/account"

  teacherSetupDestination:(phase) ->
    pm = if @postmark? then "?p=#{encodeURIComponent(@postmark)}" else ""
    # TODO: encode postmark as part of this URI when available:
    "/client#/teachers/setup/#{phase}"
}