
<form
  id="form_field_new"
  name="form_field_new"
  action=""
  method="post"
  data-parsley-validate="true"
>
  {{#if id}}<input type="hidden" id="field_id" name="id" value="{{ id }}" />{{/if}}
  <p>
    <label for="field_type"><%= __('Select a field type:') %></label>
    <select
      id="field_type"
      name="type"
      data-parsley-required="true"
      data-parsley-required-message="<%= __('Please specify a type.') %>"
    >
      <option value="">--</option>
      <option
        {{#ifCond type '==' 'text'}}selected="selected"{{/ifCond}}
        value="text"><%= __('Text Input') %>
      </option>
      <option
        {{#ifCond type '==' 'textarea'}}selected="selected"{{/ifCond}}
        value="textarea"><%= __('Text Area') %>
      </option>
      <option
        {{#ifCond type '==' 'radio'}}selected="selected"{{/ifCond}}
        value="radio"><%= __('Radio buttons') %>
      </option>
      <option
        {{#ifCond type '==' 'checkbox'}}selected="selected"{{/ifCond}}
        value="checkbox"><%= __('Checkbox') %>
      </option>
      <option
        {{#ifCond type '==' 'select'}}selected="selected"{{/ifCond}}
        value="select"><%= _x('Select', 'Form input type') %>
      </option>
      <option
        {{#ifCond type '==' 'date'}}selected="selected"{{/ifCond}}
        value="date"><%= __('Date') %>
      </option>
    </select>
  </p>
  <p>
    <label for="field_name"><%= __("Field name:") %></label>
    <input
      id="field_name"
      type="text"
      name="name"
      value="{{ name }}"
      data-parsley-required="true"
      data-parsley-required-message="<%= __('Please specify a name.') %>"
    />
  </p>
  <hr />

  <div class="field_type_form"></div>

  <p class="mailpoet_align_right">
    <input type="submit" value="<%= __('Done') %>" class="button-primary" />
  </p>
</form>

<script type="text/javascript">
  jQuery(function($) {

    $(function() {
      loadFieldForm();

      $('#form_field_new').parsley().on('form:submit', function(parsley) {
        // get data
        var data = $(this.$element).mailpoetSerializeObject();

        // save custom field
        MailPoet.Ajax.post({
          api_version: window.mailpoet_api_version,
          endpoint: 'customFields',
          action: 'save',
          data: data
        }).done(function(response) {
          // close popup
          MailPoet.Modal.close();

          MailPoet.trackEvent('Forms > Add new custom field', {
            'Field type': data.type,
            'MailPoet Free version': window.mailpoet_version
          });

          if(WysijaForm.updateBlock(response.data) === true) {
            // trigger save, if a block has been updated
            mailpoet_form_save(false);
          }

          mailpoet_form_fields();

          if(data.id) {
            MailPoet.Notice.success(
              "<%= __('Updated custom field %$1s') | escape('js') %>".replace('%$1s', '"' + encodeHtmlValue(data.name) + '"')
            );
          } else {
            MailPoet.Notice.success(
              "<%= __('Added custom field %$1s') | escape('js') %>".replace('%$1s', '"' + encodeHtmlValue(data.name) + '"')
            );
          }
        }).fail(function(response) {
          if(response.errors.length > 0) {
            MailPoet.Notice.error(
              response.errors.map(function(error) { return error.message; }),
              { positionAfter: '#field_name' }
            );
          }
        });
        return false;
      });
    });

    $('#form_field_new #field_type').on('change', function() {
      loadFieldForm($(this).val());
    });

    function loadFieldForm(type) {
      type = (type === undefined) ? $('#form_field_new #field_type').val() : type;
      if(type !== '') {
        var template = Handlebars.compile($('#form_template_field_'+type).html()),
            data = {type: type},
            field_id = $('#form_field_new #field_id').val();

        if(field_id !== undefined && field_id.length > 0) {
          var params = $('.mailpoet_form_field[wysija_id="'+field_id+'"]').attr('wysija_params');
          if(params !== undefined) {
            data.params = JSON.parse(params);
          }
        }
        // render field template
        $('#form_field_new .field_type_form').html(template(data));
      } else {
        $('#form_field_new .field_type_form').html('');
      }
    }
  });
</script>
