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

@ICheckMixin = {

  iCheckIgnore: false
  checkboxes: []

  iCheckify: () ->
    @setCheckboxState()
    @enableICheck()

  setSingleCheckbox: (checkbox) ->
    selector = checkbox.selector

    if checkbox.stateKey?
      choice = @state[checkbox.stateKey]
    else
      choice = @props[checkbox.propsKey]

    $candidate = @root.find(selector)


    @iCheckIgnore = true

    if $candidate.attr('type') == 'radio'
      if choice?
        $found = @root.find(selector + '[value="' + choice + '"]')
        $found.iCheck('check').attr('checked', true)
      else
        $candidate.iCheck('uncheck').attr('checked', false)
    else
      if choice
        $candidate.iCheck('check').attr('checked', true);
      else
        $candidate.iCheck('uncheck').attr('checked', false);
    @iCheckIgnore = false

  setCheckboxState: () ->
    for checkbox in this.checkboxes
      @setSingleCheckbox(checkbox)
    return
  enableSingle: (checkbox) ->
    selector = checkbox.selector

    checkBoxes = @root.find(selector + '[type="checkbox"]')
    if checkBoxes.length > 0
      context.JK.checkbox(checkBoxes)
      checkBoxes.on('ifChanged', (e) => @checkIfCanFire(e))
    radioBoxes = @root.find(selector + '[type="radio"]')
    if radioBoxes.length > 0
      context.JK.checkbox(radioBoxes)
      radioBoxes.on('ifChanged', (e) => @checkIfCanFire(e))


  enableICheck: (e) ->
    if !@root?
      return

    for checkbox in this.checkboxes
      @enableSingle(checkbox)

    true

  checkIfCanFire: (e) ->
    if @iCheckIgnore
      return

    if @checkboxChanged?
      @checkboxChanged(e)
    else
      logger.error("no checkbox changed defined")
}