{% extends "base.html" %}
{% load staticfiles %}
{% load i18n %}

{% load bootstrap3 %}
{% load massive_bootstrap_form %}
{% load static %}
{% block title %}Printing interface{% endblock %}

{% block content %}
<form class="form" method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <h3>{% trans "Printing Menu" %}</h3>
  {{ jobform.management_form }}
  {% bootstrap_formset_errors jobform %}
  <div id="form_set" class="form-group">
    {% for job in jobform.forms %}
    <div class='file_to_print form-inline'>
      {% bootstrap_form job label_class='sr-only' %}
      <button class="btn btn-danger btn-sm" id="id_form-0-job-remove" type="button">
        <span class="fa fa-times"></span>
      </button>
    </div>
    {% endfor %}
  </div>
  <input class="btn btn-primary btn-sm" role="button" value="{% trans "Add a file"%}" id="add_one">
  {% bootstrap_button action_name button_type="submit" icon="star" %}
</form>
<script type="text/javascript">

  var template = `{% bootstrap_form jobform.empty_form label_class='sr-only' %}
          <button class="btn btn-danger btn-sm"
            id="id_form-__prefix__-job-remove" type="button">
            <span class="fa fa-times"></span>
        </button>`
  
  function add_job() { 
        var new_index = 
            document.getElementsByClassName('file_to_print').length;
        document.getElementById('id_form-TOTAL_FORMS').value ++;
        var new_job = document.createElement('div');
        new_job.className = 'file_to_print form-inline';
        new_job.innerHTML = template.replace(/__prefix__/g, new_index);
        document.getElementById('form_set').appendChild(new_job);
	add_listener_for_id(new_index);  
  }


	  function del_job(event){
	  var job = event.target.parentNode;
	  job.parentNode.removeChild(job);
	  document.getElementById('id_form-TOTAL_FORMS').value --;
	  }
	  

function add_listener_for_id(i){
	  document.getElementById('id_form-' + i.toString() + '-job-remove')
	  .addEventListener("click", function(event){
                  var job = event.target.parentNode;
	          job.parentNode.removeChild(job);
     	          document.getElementById('id_form-TOTAL_FORMS').value --;
	        }
	      )
	    }
	  
	  
  // Add events manager when DOM is fully loaded
  document.addEventListener(
     "DOMContentLoaded",
     function() {
        document.getElementById("add_one")
          .addEventListener("click", add_job, true);
	document.getElementById('id_form-0-job-remove')
	  .addEventListener("click", function(event){
                  var job = event.target.parentNode;
	          job.parentNode.removeChild(job);
     	          document.getElementById('id_form-TOTAL_FORMS').value --;
	        }
	      )
	  
  }

  );

</script>
{% endblock %}

