<commit_before>window.FormAjaxSubmit = ($form) ->
	@_$form = $form
	@_validationObject = null
	@_sending = false

(->

  #@trigger ['ajax-before-submit', 'ajax-submit-done', 'ajax-submit-fail', 'ajax-submit-always']

  FormAjaxSubmit::init = ->

    validation_data = @__getValidationData()
    @__loadValidationRules validation_data
    @_validationObject = @_$form.validate(validation_data)

  FormAjaxSubmit::displayFieldErrors = (errors) ->
    messages = {}

    $.each errors, (field, message) =>
      messages['data[' + field + ']'] = message

    unless $.isEmptyObject(messages)
      try
        @_validationObject.showErrors messages
      catch e
        @displayGlobalErrors messages
      return true
    false

  FormAjaxSubmit::displayGlobalErrors = (errors) ->
    $.each errors, (i, error) ->
      #todo show global errors


  FormAjaxSubmit::.__loadValidationRules = (validation_data) ->
    #TODO load custom validation


  FormAjaxSubmit::__getValidationData = ->
    _self = this

    highlight: (element) ->
      $(element).parent().removeClass('success').addClass 'error'

    unhighlight: (element) ->
      $(element).parent().removeClass('error').addClass 'success'

    submitHandler: ->
      return if _self._sending
      lazySubmitHandler = -> _self._submitHandler()
      if _self.handlerExist('ajax-before-submit')
        _self.trigger('ajax-before-submit', [ lazySubmitHandler ])
      else
        lazySubmitHandler.call()
      return false


  FormAjaxSubmit::__processFormError = (data) ->
    showFieldErrors = @displayFieldErrors(data.errors)
    console.log showFieldErrors unless showFieldErrors

  FormAjaxSubmit::__removeFormErrors = ->
    @_$form.find('.error-message').remove()

  FormAjaxSubmit::_submitHandler = ->
    for instance of CKEDITOR.instances
      CKEDITOR.instances[instance].updateElement()

    @_sending = true
    _self = this
    items = @_$form.serializeObject()

    # Workaround for select2 values serialization
    # It finds all 'array' members of data hash,
    # and splits their values by ',', cleaning all
    # non-space characters.
    for memb of items.data
      array = items.data[memb]
      if $.isArray(array)
        newArray = []

        for val in array
          cleanVal = val.replace(/\s+/g,'')
          if cleanVal.length > 0
            newArray = $.merge(newArray, cleanVal.split(','))

        items.data[memb] = if newArray.length is 0 then [''] else newArray

    $.ajax(
      url: @_$form.attr('action')
      type: @_$form.attr('method')
      data: items
      dataType: 'json'
    ).done((data) ->
      _self.trigger('ajax-submit-done', [data])
      $(document).trigger('ajax-submit-done', [data]) #rm_todo remove global events
      _self.__removeFormErrors()
    ).fail((response) ->
      try
        data = JSON.parse( response.responseText )
        _self.trigger('ajax-submit-fail', [data])
        _self.__processFormError( data )
      #rm_todo error catching.
      #rm_todo extract fail process method
    ).always((response) ->
      data = if (response.responseJSON) then response.responseJSON else response
      window.notifier.notify(message: data.message) if data.message
      _self.trigger('ajax-submit-always', [data])
      _self._sending = false
    )

  FormAjaxSubmit::trigger = ->
    @_$form.triggerHandler.apply(@_$form, arguments)

  FormAjaxSubmit::handlerExist = (name)->
    jQuery._data( @_$form[0] ).events[ name ]

  @
)()

formatingErrors = ->
  $.validator.setDefaults showErrors: (errorMap, errorList) ->

    $.each errorList, (index, error) ->

      $(error.element).parent().children('.error-message').remove()

      if $.isArray(error.message)
        message = error.message.join('<br>')
      else
        message = error.message

      notify = $([
        '<span class="error-message">'
          message
          '<i class="ico error-buble"></i>'
        '</span>'
      ].join(''))

      $(error.element).after notify
      return

  return

setupFormSubmit = -> 
  
  formatingErrors.call()

  $('form').each (i, form) ->
    (new FormAjaxSubmit($(form))).init()

$ ->
  $(document).on 'ready page:load', setupFormSubmit<commit_msg>Few fixes for form serializer<commit_after>window.FormAjaxSubmit = ($form) ->
	@_$form = $form
	@_validationObject = null
	@_sending = false

(->

  #@trigger ['ajax-before-submit', 'ajax-submit-done', 'ajax-submit-fail', 'ajax-submit-always']

  FormAjaxSubmit::init = ->

    validation_data = @__getValidationData()
    @__loadValidationRules validation_data
    @_validationObject = @_$form.validate(validation_data)

  FormAjaxSubmit::displayFieldErrors = (errors) ->
    messages = {}

    $.each errors, (field, message) =>
      messages['data[' + field + ']'] = message

    unless $.isEmptyObject(messages)
      try
        @_validationObject.showErrors messages
      catch e
        @displayGlobalErrors messages
      return true
    false

  FormAjaxSubmit::displayGlobalErrors = (errors) ->
    $.each errors, (i, error) ->
      #todo show global errors


  FormAjaxSubmit::.__loadValidationRules = (validation_data) ->
    #TODO load custom validation


  FormAjaxSubmit::__getValidationData = ->
    _self = this

    highlight: (element) ->
      $(element).parent().removeClass('success').addClass 'error'

    unhighlight: (element) ->
      $(element).parent().removeClass('error').addClass 'success'

    submitHandler: ->
      return if _self._sending
      lazySubmitHandler = -> _self._submitHandler()
      if _self.handlerExist('ajax-before-submit')
        _self.trigger('ajax-before-submit', [ lazySubmitHandler ])
      else
        lazySubmitHandler.call()
      return false


  FormAjaxSubmit::__processFormError = (data) ->
    showFieldErrors = @displayFieldErrors(data.errors)
    console.log showFieldErrors unless showFieldErrors

  FormAjaxSubmit::__removeFormErrors = ->
    @_$form.find('.error-message').remove()

  FormAjaxSubmit::_submitHandler = ->
    for instance of CKEDITOR.instances
      CKEDITOR.instances[instance].updateElement()

    @_sending = true
    _self = this
    items = @_$form.serializeObject()

    # Workaround for select2 values serialization
    # It finds all 'array' members of data hash,
    # and splits their values by ',', cleaning all
    # non-space characters.
    #todo extract. All class need super refactoring. Sergey, you can do it :)
    for memb of items.data
      array = items.data[memb]
      if $.isArray(array)
        newArray = []

        for val in array
          cleanVal = val.replace(/\s+/g,'')
          if cleanVal.length > 0
            newArray = $.merge(newArray, cleanVal.split(','))

        items.data[memb] = if newArray.length is 0 then [''] else newArray

    input_method = @_$form.find('input[name="_method"]')
    items['_method'] = input_method.val() if input_method instanceof jQuery

    $.ajax(
      url: @_$form.attr('action')
      type: @_$form.attr('method')
      data: items
      dataType: 'json'
    ).done((data) ->
      _self.trigger('ajax-submit-done', [data])
      $(document).trigger('ajax-submit-done', [data]) #rm_todo remove global events
      _self.__removeFormErrors()
    ).fail((response) ->
      try
        data = JSON.parse( response.responseText )
        _self.trigger('ajax-submit-fail', [data])
        _self.__processFormError( data )
      #rm_todo error catching.
      #rm_todo extract fail process method
    ).always((response) ->
      data = if (response.responseJSON) then response.responseJSON else response
      window.notifier.notify(message: data.message) if data.message
      _self.trigger('ajax-submit-always', [data])
      _self._sending = false
    )

  FormAjaxSubmit::trigger = ->
    @_$form.triggerHandler.apply(@_$form, arguments)

  FormAjaxSubmit::handlerExist = (name)->
    jQuery._data( @_$form[0] ).events[ name ]

  @
)()

formatingErrors = ->
  $.validator.setDefaults showErrors: (errorMap, errorList) ->

    $.each errorList, (index, error) ->

      $(error.element).parent().children('.error-message').remove()

      if $.isArray(error.message)
        message = error.message.join('<br>')
      else
        message = error.message

      notify = $([
        '<span class="error-message">'
          message
          '<i class="ico error-buble"></i>'
        '</span>'
      ].join(''))

      $(error.element).after notify
      return

  return

setupFormSubmit = -> 
  
  formatingErrors.call()

  $('form').each (i, form) ->
    (new FormAjaxSubmit($(form))).init()

$ ->
  $(document).on 'ready page:load', setupFormSubmit
{'fraction_non_alphanumeric': 0.1398885535175296, 'fraction_numerical': 0.0009287206872533086, 'mean_word_length': 2.924829157175399, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 69, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '6743740', 'n_tokens_mistral': 2616, 'n_tokens_neox': 2544, 'n_words': 539}