<%
  api = params[:api].present?

  data = @easy_button.execute(@entity)
  data[request_forgery_protection_token] = form_authenticity_token
  data['_method'] = 'patch'

  if @easy_button.silent_mode
    url = @entity.easy_button_update_path
  else
    url = @entity.easy_button_edit_path
  end

  if api
    url.merge!(format: 'json')
  end

  url = url_for(url)
%>

$.extend({
  form: function(url, data, method) {
    if (method == null) method = 'POST';
    if (data == null) data = {};

    var form = $('<form>').attr({
      method: method,
      action: url
    }).css({
      display: 'none'
    });

    var addData = function(name, data) {
      if ($.isArray(data)) {
        for (var i = 0; i < data.length; i++) {
          var value = data[i];
          addData(name + '[]', value);
        }
      } else if (typeof data === 'object') {
        for (var key in data) {
          if (data.hasOwnProperty(key)) {
            addData(name + '[' + key + ']', data[key]);
          }
        }
      } else if (data != null) {
        form.append($('<input>').attr({
          type: 'hidden',
          name: String(name),
          value: String(data)
        }));
      }
    };

    for (var key in data) {
      if (data.hasOwnProperty(key)) {
        addData(key, data[key]);
      }
    }

    return form.appendTo('body');
  }
});

var data = <%= raw data.to_json %>;
var url = "<%= url %>";

<% if api %>
  $.ajax({
    method: 'POST',
    url: '<%= url %>',
    data: data
  });
<% else %>
  $.form(url, data).submit();
<% end %>
