{% load i18n %}
<div class="row">
  <div class="col-2">
    <form role="form" method="post" action="{{request.prefix}}/execute/launch/exporttofolder/">{% csrf_token %}
      <button type="submit" class="btn btn-primary" id="exporttofolder" value="{% trans "export"|capfirst %}">{% trans "export"|capfirst %}</button>
    </form>
  </div>
  <div class="col-10">
    <p>{% trans "Exports the plan (purchase orders, distribution orders and manufacturing orders) as a set of CSV files." %}</p>
  </div>
</div>
<div class="row mb-2">
  <div class="col flex-grow-1 offset-2"><strong>{% trans 'file name'|capfirst %}</strong></div>
  <div class="col-1 text-center"><strong>{% trans 'size'|capfirst %}</strong></div>
  <div class="col-2 text-center"><strong>{% trans 'changed'|capfirst %}</strong></div>
  <div class="col-auto text-center">
    <div class="btn btn-sm btn-primary" data-bs-toggle="tooltip" data-bs-placement="top"
      data-bs-title="{% trans 'Download all files' %}" onClick="downloadExportFile(1)">
      <span class="fa fa-arrow-down"></span>
    </div>
    <div class="btn btn-sm btn-danger deletefile" data-bs-toggle="tooltip" data-bs-placement="top"
      data-bs-title="{% trans 'Delete all files' %}" onClick="deleteExportFile(1)">
      <span class="fa fa-close"></span>
    </div>
    <div class="btn btn-sm invisible btn-primary">
      <span class="fa fa-edit"></span>
    </div>
  </div>
</div>
{% for j in data_exports %}
<div class="row mb-2" data-file="{{j.name}}">
  <div class="col flex-grow-1 offset-2">{{j.name}}</div>
  <div class="col-auto text-nowrap text-center">{{j.size}}</div>
  <div class="col-auto text-nowrap text-center">{{j.timestamp}}</div>
  <div class="col-auto text-center">
    <button class="btn btn-sm btn-primary downloadfile" data-bs-toggle="tooltip"{% if not j.timestamp %} disabled{% endif %}
      data-bs-placement="top" data-bs-title="Download file" onClick="downloadExportFile(1, '{{j.name}}')">
      <span class="fa fa-arrow-down"></span>
    </button>
    <button class="btn btn-sm btn-danger deletefile" data-bs-toggle="tooltip"{% if not j.timestamp %} disabled{% endif %}
      data-bs-placement="top" data-bs-title="{% trans "Delete file" %}" onClick="deleteExportFile(1, '{{j.name}}')">
      <span class="fa fa-close"></span>
    </button>
    <div class="btn btn-sm btn-primary" onclick="toggleAddExport(true, this)"
      data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Edit" %}">
      <span class="fa fa-edit" ></span>
    </div>
  </div>
</div>
<div class="row mb-3 d-none" data-file="{{j.name}}"
  style="border-style:solid; border-radius:10px; border-width:1px; margin:10px 0 10px 0">
    <div class="col-auto">
      <button class="btn btn-primary w-100 text-capitalize" onclick="saveExport(this)" style="margin-top: 15px">
        {% trans "Save" %}
      </button>
      <button class="btn btn-primary w-100 text-capitalize" onclick="deleteExport(this)" style="margin-top: 15px">
        {% trans "delete" %}
      </button>
    </div>
    <div class="col">
        <div class="row mb-3 mt-3">
          <div class="col-3">{% trans "name"|capfirst %}
          </div>
          <div class="col-9">
            <div class="input-group">
                <input type="text" class="form-control add-export-name" data-field="name" value="{{j.basename}}" placeholder="Unique name">
                <button class="btn btn-outline-primary dropdown-toggle add-export-extension" type="button" data-bs-toggle="dropdown" aria-expanded="false">{{j.extension}}</button>
                <ul class="dropdown-menu dropdown-menu-end">
                  <li><a class="dropdown-item" onclick="setExportExtension(event.target, '.csv')">.csv</a></li>
                  <li><a class="dropdown-item" onclick="setExportExtension(event.target, '.csv.gz')">.csv.gz</a></li>
                  <li><a class="dropdown-item" onclick="setExportExtension(event.target, '.xlsx')">.xlsx</a></li>
                  <li><a class="dropdown-item" onclick="setExportExtension(event.target, '.json')">.json</a></li>
                  <li><a class="dropdown-item" onclick="setExportExtension(event.target, '.json.gz')">.json.gz</a></li>
                </ul>
            </div>
          </div>
        </div>
        <div class="row mb-3">
          <div class="col-3">{% trans "type"|capfirst %}</div>
          <div class="col-9">
             <div class="dropdown">
               <button class="btn btn-outline-secondary btn-text-outline dropdown-toggle w-100 text-start add-export-type" type="button" data-bs-toggle="dropdown" data-value="{% firstof j.exporttype '' %}">
                 {% if j.exporttype == "sql" %}SQL query{% elif j.exporttype == "report" %}Report{% elif j.exporttype == "customreport" %}Custom report{% else %}{% trans "Select export type" %}{% endif %}
               </button>
               <ul class="dropdown-menu w-100">
                 <li><a class="dropdown-item" href="#" data-value="sql" onclick="setExportType(this, event)">SQL query</a></li>
                 <li><a class="dropdown-item" href="#" data-value="report" onclick="setExportType(this, event)">Report</a></li>
                 <li><a class="dropdown-item" href="#" data-value="customreport" onclick="setExportType(this, event)">Custom report</a></li>
               </ul>
             </div>
          </div>
        </div>
        <div class="{% if j.exporttype != "sql" %}d-none {% endif %}row mb-3 optional" data-type="sql">
          <div class="col">
             <div class="form-floating">
               <textarea class="form-control add-export-sql">{{j.sql | default:''}}</textarea>
               <label>SQL query</label>
             </div>
          </div>
        </div>
        <div class="{% if j.exporttype != "customreport" %}d-none {% endif %}row mb-3 optional" data-type="customreport">
          <div class="col-3 text-nowrap">{% trans "custom report"|capfirst%}</div>
          <div class="col-9">
             <div class="dropdown">
               <button class="btn btn-outline-secondary btn-text-outline dropdown-toggle w-100 text-start add-export-customreport" type="button" data-bs-toggle="dropdown" data-value="{% firstof j.reportid '' %}">
                 {% if j.reportid %}{% for r in customreports %}{% if j.reportid == r.1 %}{{r.0}}{% endif %}{% endfor %}{% else %}{% trans "Select report" %}{% endif %}
               </button>
               <ul class="dropdown-menu w-100">
                 {% for r in customreports %}<li><a class="dropdown-item" href="#" data-value="{{r.1}}" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">{{r.0}}</a></li>{% endfor %}
               </ul>
             </div>
          </div>
        </div>
        <div class="{% if j.exporttype != "report" %}d-none {% endif %}row mb-3 optional" data-type="report">
          <div class="col-3">{% trans "report"|capfirst %}</div>
          <div class="col-9">
             <div class="dropdown">
               <button class="btn btn-outline-secondary btn-text-outline dropdown-toggle w-100 text-start add-export-report" type="button" data-bs-toggle="dropdown" data-value="{% firstof j.report '' %}">
                 {% if j.report %}{% for r in reports %}{% if j.report == r.1 %}{{r.0}}{% endif %}{% endfor %}{% else %}{% trans "Select report" %}{% endif %}
               </button>
               <ul class="dropdown-menu w-100">
                 {% for r in reports %}<li><a class="dropdown-item" href="#" data-value="{{r.1}}" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">{{r.0}}</a></li>{% endfor %}
               </ul>
             </div>
          </div>
        </div>
        <div class="{% if j.exporttype != "report" %}d-none {% endif %}row mb-3 optional" data-type="report">
          <div class="col-3">{% trans "bucket size"|capfirst %}</div>
          <div class="col-9">
             <div class="dropdown d-inline-block">
               <button class="btn btn-outline-secondary btn-text-outline dropdown-toggle w-auto add-export-bucket" type="button" data-bs-toggle="dropdown" data-value="{% firstof j.arguments.buckets 'week' %}">
                 {% firstof j.arguments.buckets 'week' %}
               </button>
               <ul class="dropdown-menu">
                 <li><a class="dropdown-item" href="#" data-value="day" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">day</a></li>
                 <li><a class="dropdown-item" href="#" data-value="week" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">week</a></li>
                 <li><a class="dropdown-item" href="#" data-value="month" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">month</a></li>
                 <li><a class="dropdown-item" href="#" data-value="quarter" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">quarter</a></li>
                 <li><a class="dropdown-item" href="#" data-value="year" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">year</a></li>
               </ul>
             </div>
          </div>
        </div>
        <div class="{% if j.exporttype != "report" %}d-none {% endif %}row mb-3 optional" data-type="report">
          <div class="col-3">{% trans "horizon"|capfirst %}</div>
          <div class="col-9">
             <input style="width:4.5em" type="number" class="form-control d-inline arrows add-export-horizon" min="0" max="99" value="{{j.arguments.horizonlength}}">
             <div class="dropdown d-inline-block">
               <button class="btn btn-outline-secondary btn-text-outline dropdown-toggle w-auto add-export-horizonbucket" type="button" data-bs-toggle="dropdown" data-value="{% firstof j.arguments.horizonunit 'week' %}">
                 {% firstof j.arguments.horizonunit 'week' %}
               </button>
               <ul class="dropdown-menu">
                 <li><a class="dropdown-item" href="#" data-value="day" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">day</a></li>
                 <li><a class="dropdown-item" href="#" data-value="week" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">week</a></li>
                 <li><a class="dropdown-item" href="#" data-value="month" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">month</a></li>
                 <li><a class="dropdown-item" href="#" data-value="quarter" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">quarter</a></li>
                 <li><a class="dropdown-item" href="#" data-value="year" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">year</a></li>
               </ul>
             </div>
          </div>
        </div>
  </div>
  <div class="col-auto mt-3 mb-3">
    <button type="button" class="btn-close float-end" onclick="toggleAddExport(false, this)"></button>
  </div>
</div>
{% endfor %}

<!-- row for the plus icon to add an export -->
<div class="row" data-file="adding-a-new-export">
  <div class="col-auto text-center ms-auto">
      <div class="btn btn-sm btn-primary" id="export_add" onclick="toggleAddExport(true, this)" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Add" %}">
      <span class="fa fa-plus"></span>
      </div>
  </div>
</div>

<!-- Add an export -->
<div class="row d-none" data-file="adding-a-new-export"
  style="border-style:solid; border-radius:10px; border-width:1px; margin:10px 0 10px 0">
    <div class="col-auto">
      <button class="btn btn-primary w-100" onclick="saveExport(this)" style="margin-top: 15px">
        {% trans "Save" %}
      </button>
    </div>
    <div class="col">
        <div class="row mb-3 mt-3">
          <div class="col-3">{% trans "name"|capfirst %}
          </div>
          <div class="col-9">
            <div class="input-group">
                <input type="text" class="form-control add-export-name" data-field="name" value="" placeholder="Unique name">
                <button class="btn btn-outline-primary dropdown-toggle add-export-extension" type="button" data-bs-toggle="dropdown" aria-expanded="false">.csv</button>
                <ul class="dropdown-menu dropdown-menu-end">
                  <li><a class="dropdown-item" onclick="setExportExtension(event.target, '.csv')">.csv</a></li>
                  <li><a class="dropdown-item" onclick="setExportExtension(event.target, '.csv.gz')">.csv.gz</a></li>
                  <li><a class="dropdown-item" onclick="setExportExtension(event.target, '.xlsx')">.xlsx</a></li>
                  <li><a class="dropdown-item" onclick="setExportExtension(event.target, '.json')">.json</a></li>
                  <li><a class="dropdown-item" onclick="setExportExtension(event.target, '.json.gz')">.json.gz</a></li>
                </ul>
            </div>
          </div>
        </div>
        <div class="row mb-3">
          <div class="col-3">{% trans "type"|capfirst %}</div>
          <div class="col-9">
             <div class="dropdown">
               <button class="btn btn-outline-secondary btn-text-outline dropdown-toggle w-100 text-start add-export-type" type="button" data-bs-toggle="dropdown" data-value="">
                 {% trans "Select export type" %}
               </button>
               <ul class="dropdown-menu w-100">
                 <li><a class="dropdown-item" href="#" data-value="sql" onclick="setExportType(this, event)">SQL query</a></li>
                 <li><a class="dropdown-item" href="#" data-value="report" onclick="setExportType(this, event)">Report</a></li>
                 <li><a class="dropdown-item" href="#" data-value="customreport" onclick="setExportType(this, event)">Custom report</a></li>
               </ul>
             </div>
          </div>
        </div>
        <div class="row mb-3 d-none optional" data-type="sql">
          <div class="col">
             <div class="form-floating">
               <textarea class="form-control add-export-sql"></textarea>
               <label>SQL query</label>
             </div>
          </div>
        </div>
        <div class="row mb-3 d-none optional" data-type="customreport">
          <div class="col-3 text-nowrap">{% trans "custom report"|capfirst%}</div>
          <div class="col-9">
             <div class="dropdown">
               <button class="btn btn-outline-secondary btn-text-outline dropdown-toggle w-100 text-start add-export-customreport" type="button" data-bs-toggle="dropdown" data-value="">
                 {% trans "Select report" %}
               </button>
               <ul class="dropdown-menu w-100">
                 {% for r in customreports %}<li><a class="dropdown-item" href="#" data-value="{{r.1}}" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">{{r.0}}</a></li>{% endfor %}
               </ul>
             </div>
          </div>
        </div>
        <div class="row mb-3 d-none optional" data-type="report">
          <div class="col-3">{% trans "report"|capfirst %}</div>
          <div class="col-9">
             <div class="dropdown">
               <button class="btn btn-outline-secondary btn-text-outline dropdown-toggle w-100 text-start add-export-report" type="button" data-bs-toggle="dropdown" data-value="">
                 {% trans "Select report" %}
               </button>
               <ul class="dropdown-menu w-100">
                 {% for r in reports %}<li><a class="dropdown-item" href="#" data-value="{{r.1}}" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">{{r.0}}</a></li>{% endfor %}
               </ul>
             </div>
          </div>
        </div>
        <div class="row mb-3 d-none optional" data-type="report">
          <div class="col-3">{% trans "bucket size"|capfirst %}</div>
          <div class="col-9">
             <div class="dropdown d-inline-block">
               <button class="btn btn-outline-secondary btn-text-outline dropdown-toggle w-auto add-export-bucket" type="button" data-bs-toggle="dropdown" data-value="week">
                 week
               </button>
               <ul class="dropdown-menu">
                 <li><a class="dropdown-item" href="#" data-value="day" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">day</a></li>
                 <li><a class="dropdown-item" href="#" data-value="week" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">week</a></li>
                 <li><a class="dropdown-item" href="#" data-value="month" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">month</a></li>
                 <li><a class="dropdown-item" href="#" data-value="quarter" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">quarter</a></li>
                 <li><a class="dropdown-item" href="#" data-value="year" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">year</a></li>
               </ul>
             </div>
          </div>
        </div>
        <div class="row mb-3 d-none optional" data-type="report">
          <div class="col-3">{% trans "horizon"|capfirst %}</div>
          <div class="col-9">
             <input style="width:4.5em" type="number" class="form-control d-inline arrows add-export-horizon" min="0" max="99" value="12">
             <div class="dropdown d-inline-block">
               <button class="btn btn-outline-secondary btn-text-outline dropdown-toggle w-auto add-export-horizonbucket" type="button" data-bs-toggle="dropdown" data-value="week">
                 week
               </button>
               <ul class="dropdown-menu">
                 <li><a class="dropdown-item" href="#" data-value="day" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">day</a></li>
                 <li><a class="dropdown-item" href="#" data-value="week" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">week</a></li>
                 <li><a class="dropdown-item" href="#" data-value="month" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">month</a></li>
                 <li><a class="dropdown-item" href="#" data-value="quarter" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">quarter</a></li>
                 <li><a class="dropdown-item" href="#" data-value="year" onclick="var btn=$(this).closest('.dropdown').find('.dropdown-toggle');btn.text($(this).text()).attr('data-value',$(this).attr('data-value'));event.preventDefault();">year</a></li>
               </ul>
             </div>
          </div>
        </div>
  </div>
  <div class="col-auto mt-3 mb-3">
    <button type="button" class="btn-close float-end" onclick="toggleAddExport(false, this)"></button>
  </div>
</div>

<script>
function deleteExportFile(folder, filename) {
  $.jgrid.hideModal("#searchmodfbox_grid");
  var dialogcontent;
  if (typeof filename === 'undefined') {
    dialogcontent = "{% trans 'You are about to delete all files' %}";
    filename = 'AllFiles';
  } else {
    dialogcontent = interpolate(gettext("You are about to delete file %s"), [filename]);
  }

  $("#popup").html('<div class="modal-dialog">'+
    '<div class="modal-content">'+
      '<div class="modal-header">'+
        '<h5 class="modal-title">{% trans 'Delete file' %}</h5>'+
        '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans 'Close' %}"></button>' +
      '</div>'+
      '<div class="modal-body"><p>'+
      dialogcontent +
      '</p></div>'+
      '<div class="modal-footer justify-content-between">'+
        '<input type="submit" id="cancelbutton" role="button" class="btn btn-primary pull-left" data-bs-dismiss="modal" value="{% trans 'Cancel' %}">'+
        '<input type="submit" id="confirmbutton" role="button" class="btn btn-danger float-end" value="{% trans 'Confirm' %}">'+
      '</div>'+
    '</div>'+
  '</div>' );
  showModal('popup');

  $('#confirmbutton').on('click', function() {
    $.ajax({
      url: "{{request.prefix}}/execute/deletefromfolder/" + folder + "/" + filename + "/",
      type: ("delete").toUpperCase(),
      success: function () {
        if (filename === 'AllFiles') {
          $("#popup .modal-body>p").text("{% trans 'All data files were deleted' %}");
        } else {
          $("#popup .modal-body>p").text(interpolate(gettext("File %s was deleted"), [filename]));
        }
        $('#confirmbutton').hide();
        $('#cancelbutton').attr('value', "{% trans 'Close' %}");
        $('#cancelbutton').one('click', function() {location.reload();});
      },
      error: function (result, stat, errorThrown) {
        if (result.status == 401) {
          location.reload();
          return;
        }
        var filelist = result.responseText.split(' / ');
        var elem = $("#popup .modal-body>p");
        if (filelist.length === 1) {
          elem.text(interpolate(gettext("File %s was not deleted"), [filename]));
        } else {
          for (var i = 1; i < filelist.length; i++) {
            if (i === 1) {
              elem.text(interpolate(gettext("File %s was not deleted"), [filelist[i]]));
            } else {
              elem.parent().append('<p>'+interpolate(gettext("File %s was not deleted"), [filelist[i]])+'</p>');
            }
          }
        }
        $("#popup .modal-body>p").addClass('alert alert-danger');
        $('#confirmbutton').hide();
        $('#cancelbutton').attr('value', "{% trans 'Close' %}");
        $('#cancelbutton').one('click', function() {$("#popup").hide();});
        }
    })
  })
}

function downloadExportFile(folder, filename) {
  $.jgrid.hideModal("#searchmodfbox_grid");
  if (typeof filename === 'undefined')
    window.open("{{request.prefix}}/execute/downloadfromfolder/" + folder + "/", '_blank');
  else
  	window.open("{{request.prefix}}/execute/downloadfromfolder/" + folder + "/" + filename + '/', '_blank');
}

function toggleAddExport(show, el) {
  var name = $(el).closest(".row").attr("data-file");
  var root = $(el).closest(".card-body");
  root.find("[data-file='" + name + "']").toggleClass("d-none");
}

function updateExportTypeOptions(myform) {
  var extension = myform.find(".add-export-extension").first().text().trim();
  var typeBtn = myform.find(".add-export-type").first();
  var hideReport = extension === ".json" || extension === ".json.gz";
  var reportItem = typeBtn.next(".dropdown-menu").find("[data-value='report']").parent();

  reportItem.toggleClass("d-none", hideReport);
  if (hideReport && typeBtn.attr("data-value") === "report") {
    typeBtn.text("SQL query").attr("data-value", "sql");
    changeExportType(typeBtn.get(0));
  }
}

function setExportType(el, event) {
  var btn = $(el).closest('.dropdown').find('.dropdown-toggle');
  btn.text($(el).text()).attr('data-value', $(el).attr('data-value'));
  changeExportType(btn.get(0));
  event.preventDefault();
}

function setExportExtension(el, extension) {
  var myform = $(el).closest(".col");
  myform.find(".add-export-extension").first().text(extension);
  updateExportTypeOptions(myform);
}

function saveExport(el) {
  var myform = $(el).closest(".row");
  var getBtnVal = function(cls) {
    var btn = myform.find(cls).first();
    return btn.length ? btn.attr("data-value") : null;
  };
  var data = {
      "name": myform.find(".add-export-name").first().val()
         + myform.find(".add-export-extension").first().html(),
      "type": getBtnVal(".add-export-type")
      };
  if (myform.attr("data-file") != "adding-a-new-export") {
    data["currentname"] = myform.attr("data-file");
  }
  if (data["type"]  == "sql") {
    data["sql"] = myform.find(".add-export-sql").first().val();
  } else if (data["type"]  == "report") {
    data["report"] = getBtnVal(".add-export-report");
    data["bucket"] = getBtnVal(".add-export-bucket");
    data["horizon"] = myform.find(".add-export-horizon").first().val();
    data["horizonbucket"] = getBtnVal(".add-export-horizonbucket");
  } else if (data["type"] == "customreport") {
    data["report"] = getBtnVal(".add-export-customreport");
  }
  $.ajax({
    url: "{{request.prefix}}/execute/exports/",
    data: JSON.stringify(data),
    type: "POST",
    contentType: "application/json",
    success: function () {
      location.reload();
    },
    error: function (jqXHR, stat, errorThrown) {
      $('#popup').html('<div class="modal-dialog">'+
          '<div class="modal-content">'+
            '<div class="modal-header bg-danger">'+
              '<h5 class="modal-title">'+ gettext("Error")+'</h5>'+
              '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans 'Close' %}"></button>' +              '</div>'+
            '<div class="modal-body"><p>'+
              jqXHR.responseText+
            '</p></div>'+
          '</div>'+
      '</div>' );
      showModal('popup');
    }
  });
  event.preventDefault();
}

function deleteExport(el) {
  var name = $(el).closest(".row").attr("data-file");
  $.ajax({
      url: "{{request.prefix}}/execute/exports/",
      data: JSON.stringify({"delete": name}),
      type: "POST",
      contentType: "application/json",
      success: function () {
        location.reload();
      },
      error: function (jqXHR, stat, errorThrown) {
        $('#popup').html('<div class="modal-dialog">'+
            '<div class="modal-content">'+
              '<div class="modal-header bg-danger">'+
                '<h5 class="modal-title">'+ gettext("Error")+'</h5>'+
                '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans 'Close' %}"></button>' +              '</div>'+
              '<div class="modal-body"><p>'+
                jqXHR.responseText+
              '</p></div>'+
            '</div>'+
        '</div>' );
        showModal('popup');
      }
  });
}

function changeExportType(el) {
  var t = $(el).attr("data-value");
  var myform = $(el).closest(".col");
  myform.find(".optional[data-type!=" + t + "]").addClass("d-none");
  myform.find(".optional[data-type=" + t + "]").removeClass("d-none");
}

$(function() {
  $(".add-export-extension").each(function() {
    updateExportTypeOptions($(this).closest(".col"));
  });
});

</script>
