(function(context,$) {

  "use strict"

  context.JK = context.JK || {}
  context.JK.AccountProfileInterests = function(app) {
    var $document = $(document)
    var logger = context.JK.logger
    var EVENTS = context.JK.EVENTS
    var api = context.JK.Rest()
    var ui = new context.JK.UIHelper(JK.app)
    var user = {}
    var profileUtils = context.JK.ProfileUtils
    var masterGenreList = []

    var NONE_SPECIFIED = 'None specified'
    var GENRE_LIST_DELIMITER = ', '

    var $screen = $('#account-profile-interests')

    var SELECT_GENRE_SELECTOR = '.select-genre'
    var GENRE_LIST_SELECTOR = '.genre-list'

    // virtual bands
    var $virtualBandYes = $screen.find('#virtual-band-yes')
    var $virtualBandNo = $screen.find('#virtual-band-no')
    var $virtualBandGenres = $screen.find('#virtual-band-genres')
    var $btnVirtualBandGenreSelect = $virtualBandGenres.find(SELECT_GENRE_SELECTOR)
    var $virtualBandGenreList = $virtualBandGenres.find(GENRE_LIST_SELECTOR)
    var $virtualBandCommitment = $screen.find('#virtual-band-commitment')

    // traditional bands
    var $traditionalBandYes = $screen.find('#traditional-band-yes')
    var $traditionalBandNo = $screen.find('#traditional-band-no')
    var $traditionalBandGenres = $screen.find('#traditional-band-genres')
    var $btnTraditionalBandGenreSelect = $traditionalBandGenres.find(SELECT_GENRE_SELECTOR)
    var $traditionalBandGenreList = $traditionalBandGenres.find(GENRE_LIST_SELECTOR)
    var $traditionalBandCommitment = $screen.find('#traditional-band-commitment')
    var $traditionalTouringOption = $screen.find('#traditional-band-touring')

    // paid sessions
    var $paidSessionsYes = $screen.find('#paid-sessions-yes')
    var $paidSessionsNo = $screen.find('#paid-sessions-no')
    var $paidSessionsGenres = $screen.find('#paid-sessions-genres')
    var $btnPaidSessionsGenreSelect = $paidSessionsGenres.find(SELECT_GENRE_SELECTOR)
    var $paidSessionsGenreList = $paidSessionsGenres.find(GENRE_LIST_SELECTOR)
    var $hourlyRate = $screen.find('#hourly-rate')
    var $dailyRate = $screen.find('#daily-rate')

    // free sessions
    var $freeSessionsYes = $screen.find('#free-sessions-yes')
    var $freeSessionsNo = $screen.find('#free-sessions-no')
    var $freeSessionsGenres = $screen.find('#free-sessions-genres')
    var $btnFreeSessionsGenreSelect = $freeSessionsGenres.find(SELECT_GENRE_SELECTOR)
    var $freeSessionsGenreList = $freeSessionsGenres.find(GENRE_LIST_SELECTOR)

    // cowriting
    var $cowritingYes = $screen.find('#cowriting-yes')
    var $cowritingNo = $screen.find('#cowriting-no')
    var $cowritingGenres = $screen.find('#cowriting-genres')
    var $btnCowritingGenreSelect = $cowritingGenres.find(SELECT_GENRE_SELECTOR)
    var $cowritingGenreList = $cowritingGenres.find(GENRE_LIST_SELECTOR)
    var $cowritingPurpose = $screen.find('#cowriting-purpose')

    var $btnCancel = $screen.find('.account-edit-profile-cancel')
    var $btnBack = $screen.find('.account-edit-profile-back')
    var $btnSubmit = $screen.find('.account-edit-profile-submit')

    function beforeShow(data) {
    }

    function afterShow(data) {
      if (window.ProfileStore.solo) {
        $btnBack.hide()
        $btnSubmit.text('SAVE & RETURN TO PROFILE');
      }
      else {
        $btnBack.show()
        $btnSubmit.text('SAVE & NEXT');
      }

      renderInterests()
    }

    function resetForm() {
      $screen.find('form .error-text').remove()
      $screen.find('form .error').removeClass("error")
    }

    function populateAccountProfile(userDetail) {

      // Column 1 - options
      if (userDetail) {

        if (userDetail.virtual_band) {
          $virtualBandYes.iCheck('check').attr('checked', 'checked')
        }
        else {
          $virtualBandNo.iCheck('check').attr('checked', 'checked')
        }

        if (userDetail.traditional_band) {
          $traditionalBandYes.iCheck('check').attr('checked', 'checked')
        }
        else {
          $traditionalBandNo.iCheck('check').attr('checked', 'checked')
        }

        if (userDetail.paid_sessions) {
          $paidSessionsYes.iCheck('check').attr('checked', 'checked')
        }
        else {
          $paidSessionsNo.iCheck('check').attr('checked', 'checked')
        }

        if (userDetail.free_sessions) {
          $freeSessionsYes.iCheck('check').attr('checked', 'checked')
        }
        else {
          $freeSessionsNo.iCheck('check').attr('checked', 'checked')
        }

        if (userDetail.cowriting) {
          $cowritingYes.iCheck('check').attr('checked', 'checked')
        }
        else {
          $cowritingNo.iCheck('check').attr('checked', 'checked')
        }
      }

      // Column 2 - genres
      var genres = profileUtils.virtualBandGenreList(userDetail.genres)
      var genreIds = profileUtils.getGenreIds(profileUtils.virtualBandGenres(userDetail.genres));
      $virtualBandGenreList.data('genres', genreIds).html(genres && genres.length > 0 ? genres : NONE_SPECIFIED)

      genres = profileUtils.traditionalBandGenreList(userDetail.genres)
      var genreIds = profileUtils.getGenreIds(profileUtils.traditionalBandGenres(userDetail.genres));
      $traditionalBandGenreList.data('genres', genreIds).html(genres && genres.length > 0 ? genres : NONE_SPECIFIED)

      genres = profileUtils.paidSessionGenreList(userDetail.genres)
      var genreIds = profileUtils.getGenreIds(profileUtils.paidSessionGenres(userDetail.genres));
      $paidSessionsGenreList.data('genres', genreIds).html(genres && genres.length > 0 ? genres : NONE_SPECIFIED)

      genres = profileUtils.freeSessionGenreList(userDetail.genres)
      var genreIds = profileUtils.getGenreIds(profileUtils.freeSessionGenres(userDetail.genres));
      $freeSessionsGenreList.data('genres', genreIds).html(genres && genres.length > 0 ? genres : NONE_SPECIFIED)

      genres = profileUtils.cowritingGenreList(userDetail.genres)
      var genreIds = profileUtils.getGenreIds(profileUtils.cowritingGenres(userDetail.genres));
      $cowritingGenreList.data('genres', genreIds).html(genres && genres.length > 0 ? genres : NONE_SPECIFIED)

      // Column 3 - misc (play commitment, rates, cowriting purpose)
      $virtualBandCommitment.val(userDetail.virtual_band_commitment)
      context.JK.dropdown($virtualBandCommitment)

      $traditionalBandCommitment.val(userDetail.traditional_band_commitment)
      context.JK.dropdown($traditionalBandCommitment)

      $traditionalTouringOption.val(userDetail.traditional_band_touring ? '1' : '0')
      context.JK.dropdown($traditionalTouringOption)

      // convert the value to cents
      $hourlyRate.val(profileUtils.normalizeMoneyForDisplay(userDetail.paid_sessions_hourly_rate));
      $dailyRate.val(profileUtils.normalizeMoneyForDisplay(userDetail.paid_sessions_daily_rate));

      $cowritingPurpose.val(userDetail.cowriting_purpose)
      context.JK.dropdown($cowritingPurpose)

      renderOptionalControls()
    }

    function bindGenreSelector(type, $btnSelect, $genreList) {
      $btnSelect.unbind('click').bind('click', function(e) {
        e.preventDefault()
        var genreText = $genreList.html()
        var genres = []
        if (genres !== NONE_SPECIFIED) {
          genres = genreText.split(GENRE_LIST_DELIMITER)
        }

        ui.launchGenreSelectorDialog(type, genres, function(selectedGenres) {
          $genreList.data('genres', selectedGenres).html(selectedGenres && selectedGenres.length > 0 ? selectedGenres.join(GENRE_LIST_DELIMITER) : NONE_SPECIFIED)
        })

        return false
      })
    }

    function events() {

      bindGenreSelector('virtual bands', $btnVirtualBandGenreSelect, $virtualBandGenreList)
      bindGenreSelector('traditional bands', $btnTraditionalBandGenreSelect, $traditionalBandGenreList)
      bindGenreSelector('paid sessions', $btnPaidSessionsGenreSelect, $paidSessionsGenreList)
      bindGenreSelector('free sessions', $btnFreeSessionsGenreSelect, $freeSessionsGenreList)
      bindGenreSelector('co-writing', $btnCowritingGenreSelect, $cowritingGenreList)

      $btnCancel.click(function(e) {
        e.stopPropagation()
        window.ProfileActions.cancelProfileEdit()
        return false
      })

      $btnBack.click(function(e) {
        e.stopPropagation()
        navigateTo('/client#/account/profile/experience')
        return false
      })

      enableSubmits()

      context.JK.dropdown($virtualBandCommitment)
      context.JK.dropdown($traditionalBandCommitment)
      context.JK.dropdown($cowritingPurpose)
      $screen.on('ifToggled', 'input[type="radio"].dependent-master', renderOptionalControls);
    }

    function enableSubmits() {
      $btnSubmit.on("click", function(e) {
        e.stopPropagation()
        handleUpdateProfile()
        return false
      })

      $btnSubmit.removeClass("disabled")
    }

    function disableSubmits() {
      $btnSubmit.addClass("disabled")
      $btnSubmit.off("click")
    }

    function renderInterests() {
      $.when(api.getUserProfile())
        .done(function(userDetail) {
          populateAccountProfile(userDetail)
        })
    }

    function isChecked(val) {
      return (val && val != "false");
    }

    function renderOptionalControls(e) {
      if(e){e.stopPropagation()}


      // Is virtual band selected?
      if (isChecked($screen.find($('input[name="virtual_band"]:checked')).val())) {
        $screen.find($(".virtual-band-dependent")).removeClass("hidden")
      } else {
        $screen.find($(".virtual-band-dependent")).addClass("hidden")
      }

      // Is traditional band selected?
      if (isChecked($screen.find($('input[name="traditional_band"]:checked')).val())) {
        $screen.find($(".traditional-band-dependent")).removeClass("hidden")
      } else {
        $screen.find($(".traditional-band-dependent")).addClass("hidden")
      }

      // Is paid sessions selected?
      if (isChecked($screen.find($('input[name="paid_sessions"]:checked')).val())) {
        $screen.find($(".paid-sessions-dependent")).removeClass("hidden")
      } else {
        $screen.find($(".paid-sessions-dependent")).addClass("hidden")
      }

      // Is free sessions selected?
      if (isChecked($screen.find($('input[name="free_sessions"]:checked')).val())) {
        $screen.find($(".free-sessions-dependent")).removeClass("hidden")
      } else {
        $screen.find($(".free-sessions-dependent")).addClass("hidden")
      }

      // Is cowriting selected?
      if (isChecked($screen.find($('input[name="cowriting"]:checked')).val())) {
        $screen.find($(".cowriting-dependent")).removeClass("hidden")
      } else {
        $screen.find($(".cowriting-dependent")).addClass("hidden")
      }

      return false;
    }

    function navigateTo(targetLocation) {
      context.location = targetLocation
    }

    function handleUpdateProfile() {
      disableSubmits()
      resetForm()

      api.updateUser({
        virtual_band: $screen.find('input[name=virtual_band]:checked').val(),
        virtual_band_genres: $virtualBandGenreList.data('genres'),
        virtual_band_commitment: $virtualBandCommitment.val(),

        traditional_band: $screen.find('input[name=traditional_band]:checked').val(),
        traditional_band_genres: $traditionalBandGenreList.data('genres'),
        traditional_band_commitment: $traditionalBandCommitment.val(),
        traditional_band_touring: $traditionalTouringOption.val(),

        paid_sessions: $screen.find('input[name=paid_sessions]:checked').val(),
        paid_session_genres: $paidSessionsGenreList.data('genres'),
        paid_sessions_hourly_rate: profileUtils.normalizeMoneyForSubmit($hourlyRate.val()),
        paid_sessions_daily_rate: profileUtils.normalizeMoneyForSubmit($dailyRate.val()),

        free_sessions: $screen.find('input[name=free_sessions]:checked').val(),
        free_session_genres: $freeSessionsGenreList.data('genres'),

        cowriting: $screen.find('input[name=cowriting]:checked').val(),
        cowriting_genres: $cowritingGenreList.data('genres'),
        cowriting_purpose: $cowritingPurpose.val()
      })
      .done(postUpdateProfileSuccess)
      .fail(postUpdateProfileFailure)
      .always(enableSubmits)
    }

    function postUpdateProfileSuccess(response) {
      $document.triggerHandler(EVENTS.USER_UPDATED, response)
      ProfileActions.editProfileNext('samples')
    }

    function postUpdateProfileFailure(xhr, textStatus, errorMessage) {

      var errors = JSON.parse(xhr.responseText)

      if(xhr.status == 422) {
        context.JK.append_errors($hourlyRate, 'paid_sessions_hourly_rate', errors)
        context.JK.append_errors($dailyRate, 'paid_sessions_daily_rate', errors)

        if(errors.errors.length > 0) {
          app.notifyServerError(xhr)
        }
      }
      else {
        app.ajaxError(xhr, textStatus, errorMessage)
      }
    }

    function initialize() {
      var screenBindings = {
        'beforeShow': beforeShow,
        'afterShow': afterShow
      }

      app.bindScreen('account/profile/interests', screenBindings)

      events()

      $screen.find('.interest-options').iCheck({
        checkboxClass: 'icheckbox_minimal',
        radioClass: 'iradio_minimal',
        inheritClass: true
      })

      profileUtils.initializeHelpBubbles($screen)
    }

    this.initialize = initialize
    this.beforeShow = beforeShow
    this.afterShow = afterShow
    return this
  }

})(window,jQuery)