{% extends 'base.html' %}
{% load static %}

{% block body %}
    <link href="{% static 'css/grabacion.css' %}" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://stephino.github.io/dist/recorder.js"></script>


    <script src="//cdn.jsdelivr.net/jquery/2.1.4/jquery.js"></script>
    <script src="//wzrd.in/standalone/blob-util@latest"></script>

    <h2 class="card-title text-dark row justify-content-center font-weight-bold mb-5">Editar {{ formulario.titulo }}</h2>

    <h4 class="card-title text-dark row justify-content-center font-weight-bold"><i class="fa fa-file-text-o mr-4" aria-hidden="true"></i>Página Principal</h4>
    <div id="titulo-secction" class="row justify-content-center">
        <div class="col align-self-center ">
            <div class="card">
                <div class="card-body">
                    <span class="bmd-help error"></span>
                    <fieldset class="form-group">
                        <label class="bmd-label-floating" for="tituloPagina">Titulo</label>
                        <input class="form-control mt-2" type="text" name="titulo" id="tituloPagina" autofocus value="{{ pagina.titulo }}">
                    </fieldset>
                    <fieldset class="form-group">
                        <label class="bmd-label-floating" for="subtitulo">Subtitulo</label>
                        <textarea class="form-control mt-2" type="text" name="subtitulo" id="subtitulo" rows="3" autofocus >{{ pagina.subtitulo }}</textarea>
                    </fieldset>
                    <fieldset class="form-group">
                        <label class="bmd-label-floating" for="cuerpo">Cuerpo</label>
                        <textarea class="form-control mt-2" type="text" name="cuerpo" id="cuerpo" rows="3" autofocus >{{ pagina.cuerpo }}</textarea>
                    </fieldset>
                </div>
            </div>
        </div>
    </div>

    <h4 class="card-title text-dark row mt-5 justify-content-center font-weight-bold"><i class="fa fa-user mr-4" aria-hidden="true"></i>Datos personales</h4>
    <div id="datosPersonales" class="row justify-content-center">
        <div class="col align-self-center" id="datoscontainer">
            {% for info in informaciones %}
                <div class="card mt-4" id="carddato{{ forloop.counter0 }}">
                    <div class="card-body">
                        <span class="bmd-help error"></span>
                        <fieldset class="form-group">
                            <label class="bmd-label-floating" for="dato{{ forloop.counter0 }}">Dato</label>
                            <input class="form-control mt-1" type="text" name="{{ info.id }}" id="dato{{ forloop.counter0 }}" value="{{ info.pregunta }}" autofocus>
                        </fieldset>
                        <fieldset class="form-group">
                            <label class="bmd-label-floating" for="datotipo{{ forloop.counter0 }}">Tipo de dato</label>
                            <select class="form-control" type="text" id="datotipo{{ forloop.counter0 }}" autofocus>
                                {% if info.tipo == 'texto' %}
                                    <option value="texto" selected>Texto</option>
                                    <option value="fecha">Fecha</option>
                                    <option value="sino">Respuesta Si/No</option>
                                {% elif info.tipo == 'fecha'%}
                                    <option value="texto">Texto</option>
                                    <option value="fecha" selected>Fecha</option>
                                    <option value="sino">Respuesta Si/No</option>
                                {% else %}
                                    <option value="texto">Texto</option>
                                    <option value="fecha">Fecha</option>
                                    <option value="sino" selected>Respuesta Si/No</option>
                                {% endif %}
                            </select>
                        </fieldset>
                    </div>
                </div>
            {% endfor %}

        </div>
    </div>
    <div class="row justify-content-center mt-3">
        <a href="javascript:void(0);" onclick="nuevo_dato(this)" style="text-decoration: none;">
            <div class="row justify-content-center" style="margin-top: 32px">
                <button  type="button" class="btn btn-secondary bmd-btn-fab">
                    <i class="fa fa-plus" aria-hidden="true" style="color: black!important;"></i>
                </button>
            </div>
        </a>

        <a class="ml-5" href="javascript:void(0);" onclick="delete_dato(this)" style="text-decoration: none;">
            <div class="row justify-content-center" style="margin-top: 32px">
                <button  type="button" class="btn btn-secondary bmd-btn-fab">
                    <i class="fa fa-minus" aria-hidden="true" style="color: black!important;"></i>
                </button>
            </div>
        </a>
    </div>


    <h3 class="card-title text-dark mt-5 row justify-content-center font-weight-bold"><i class="fa fa-microphone mr-4" aria-hidden="true"></i>Formulario</h3>
    <!-- Formulario titulo -->
    <div id="titulo-secction" class="row justify-content-center">
        <div class="col align-self-center ">
            <div class="card">
                <div class="card-body">
                    <span class="bmd-help error"></span>
                    <fieldset class="form-group">
                        <label class="bmd-label-floating" for="inputTitulo">Titulo</label>
                        <input class="form-control" type="text" name="titulo" id="inputTitulo" value="{{ formulario.titulo }}" autofocus>
                    </fieldset>
                </div>
            </div>
        </div>
    </div>

    <div class="row justify-content-center">
        <div class="col align-self-center" id="secciones-holder" data-prototype="">
            <div id="sections">
                {% for seccion in secciones %}
                    <div class="card mt-5" id="{{ forloop.counter0 }}">
                        <div class="card-body">
                            <span class="bmd-help error"></span>
                            <fieldset class="form-group">
                                <label class="bmd-label-floating inline-group" for="inputType{{ forloop.counter0 }}">Tipo de contexto</label>
                                <select class="form-control" type="text" name="tipocontexto{{ forloop.counter0 }}" id="inputType{{ forloop.counter0 }}" autofocus onchange="view_options('inputType0')">
                                    {% if seccion.tipoContexto == 'texto' %}
                                        <option value="texto" selected>Texto</option>
                                        <option value="audio">Audio</option>
                                        <option value="imagen">Imagen</option>
                                    {% elif seccion.tipoContexto == 'audio' %}
                                        <option value="texto">Texto</option>
                                        <option value="audio" selected>Audio</option>
                                        <option value="imagen">Imagen</option>
                                    {% else %}
                                        <option value="texto">Texto</option>
                                        <option value="audio">Audio</option>
                                        <option value="imagen" selected>Imagen</option>
                                    {% endif %}
                                </select>

                                <label class="bmd-label-floating inline-group mt-3" for="inputContext{{ forloop.counter0 }}" id="labelContext{{ forloop.counter0 }}">Contexto</label>
                                <textarea class="form-control" name="{{ seccion.id }}" id="inputContext{{ forloop.counter0 }}" rows="3">{{ seccion.texto }}</textarea>


                                {% if seccion.imagen %}
                                    <br>
                                    <img class="mb-5" src="{% static seccion.imagen %}" style="max-height:400px">
                                {% endif %}
                            </fieldset>

                            <div class="row" style="display: none" id="inputImage0">
                                <label class="bmd-label-floating inline-group ml-3" for="inputImagen" id="labelImagen">Contexto</label>
                                <div class="col-lg-6 mx-auto">
                                    <!-- Upload image input-->
                                    <div class="input-group mb-3 px-2 py-2 rounded-pill bg-white shadow-sm">
                                        <input id="upload" type="file" name="upload0" onchange="readURL(this);" class="form-control border-0">
                                    </div>
                                    <!-- Uploaded image area-->
                                    <div class="image-area mt-4"><img id="imageResult{{ forloop.counter0 }}" src="#" alt="" class="img-fluid rounded shadow-sm mx-auto d-block"></div>
                                </div>
                            </div>

                            <div class="holder" id="holderAudio{{ forloop.counter0 }}">
                                <label class="bmd-label-floating inline-group mt-3" for="inputAudio">Audio de ejemplo</label>
                                <div data-role="controls{{ forloop.counter0 }}" class="controls" id="cont{{ forloop.counter0 }}">
                                    <button type="button" class="btn border rounded" onclick="grabacio({{ forloop.counter0 }})" id="btn{{ forloop.counter0 }}"><i class="fa fa-microphone pr-2" aria-hidden="true"></i>Record audio</button>
                                </div>
                                <div data-role="recordings{{ forloop.counter0 }}" class="recordings" id="rec{{ forloop.counter0 }}">
                                    <div class="row">
                                        {% if seccion.audio %}
                                            <audio controls src="{% static seccion.audio %}"></audio>
                                            <a href="{% static seccion.audio %}" id="a{{ forloop.counter0 }}" name="{{ seccion.audio }}" download="x">▼</a>
                                        {% endif %}
                                    </div>
                                </div>
                                <!--<button id='compararbutton' onclick="createDownloadLink(blob_copy, document.getElementById('0').name)" style="margin-bottom: 20px; margin-left: 150px">Save audio</button>-->
                            </div>
                            <p onclick="eliminarseccion({{ forloop.counter0 }}, {{ seccion.id }})" class="mt-4 font-weight-bold" style="color: red!important;">Eliminar</p>
                        </div>
                    </div>
                {% endfor %}
            </div>
            <div class="row justify-content-center mt-5">
                <a href="javascript:void(0);" onclick="nueva_seccion(this)" style="text-decoration: none;">
                    <div class="row justify-content-center" style="margin-top: 32px">
                        <button  type="button" class="btn btn-secondary bmd-btn-fab">
                            <i class="fa fa-plus" aria-hidden="true" style="color: black!important;"></i>
                        </button>
                    </div>
                </a>

                <a class="ml-5" href="javascript:void(0);" onclick="delete_seccion(this)" style="text-decoration: none;">
                    <div class="row justify-content-center" style="margin-top: 32px">
                        <button  type="button" class="btn btn-secondary bmd-btn-fab">
                            <i class="fa fa-minus" aria-hidden="true" style="color: black!important;"></i>
                        </button>
                    </div>
                </a>
            </div>

        </div>

    </div>

    <div class="row justify-content-center mt-5">
        <a href="javascript:void(0);" onclick="action_submit()">
            <button  type="button" class="btn btn-secondary bmd-btn-fab mb-5">
                <i class="fa fa-floppy-o" aria-hidden="true" style="color: black!important;"></i>
            </button>
        </a>
    </div>


{% endblock %}

{% block footer1 %}
{% endblock %}

{% block action_buttons %}


{% endblock %}

{% block javascripts %}
    <script>
        var cont = 0
        var cont_recorder = 0
        var last_id = null
        var blob_list = new Array(20).fill(null);

        var editedAudios = [];

        var deletedAudios = [];

        var myRecorder = {
            objects: {
                context: null,
                stream: null,
                recorder: null
            },
            init: function () {
                if (null === myRecorder.objects.context) {
                    myRecorder.objects.context = new (
                            window.AudioContext || window.webkitAudioContext
                            );
                }
            },
            start: function () {
                var options = {audio: true, video: false};
                navigator.mediaDevices.getUserMedia(options).then(function (stream) {
                    myRecorder.objects.stream = stream;
                    myRecorder.objects.recorder = new Recorder(
                            myRecorder.objects.context.createMediaStreamSource(stream),
                            {numChannels: 1}
                    );
                    myRecorder.objects.recorder.record();
                }).catch(function (err) {});

            },
            stop: function (listObject, id_num) {

                if (null !== myRecorder.objects.stream) {
                    myRecorder.objects.stream.getAudioTracks()[0].stop();
                }
                if (null !== myRecorder.objects.recorder) {
                    myRecorder.objects.recorder.stop();

                    // Validate object
                    if (null !== listObject
                            && 'object' === typeof listObject
                            && listObject.length > 0) {
                        // Export the WAV file
                        myRecorder.objects.recorder.exportWAV(function (blob) {
                            var today = new Date();
                            var filename = String(String(today.getMinutes()) + String(today.getSeconds() + String(today.getMilliseconds())))
                            console.log(filename)

                            if (filename.length<6){
                                while(filename.length<6){
                                    filename = filename + "0"
                                }
                            }else if(filename.length>6){
                                filename = filename.substring(0,6)
                            }

                            console.log(filename)
                            blob_list[id_num] = blob;
                            //createDownloadLink(blob_copy, filename)

                            var url = (window.URL || window.webkitURL)
                                .createObjectURL(blob);

                            // Prepare the playback
                            var audioObject = $('<audio controls></audio>')
                                .attr('src', url);

                            // Prepare the download link
                            var downloadObject = $('<a>&#9660;</a>')
                                .attr('href', url)
                                .attr('id', 'a'+id_num)
                                .attr('name', filename)
                                .attr('download', new Date().toUTCString() + '.wav');

                            // Wrap everything in a row
                            var holderObject = $('<div class="row"></div>')
                                .append(audioObject)
                                .append(downloadObject);
                            cont++;

                            // Append to the list

                            listObject.append(holderObject);


                        });
                    }
                }


            }
        };
        function grabacio(id_num){
            var $ = jQuery;
            var id = 'btn' + id_num;

            editedAudios.push('inputContext'+id_num);

            // Prepare the recordings list
            var recordings = "recordings" + id_num;
            var controls = "controls" + id_num;
            var data = '[data-role= ' + recordings +']';
            var listObject = $(data);

            var listChild = document.getElementById("rec"+id_num);
            if(listChild.childElementCount > 0){
                listChild.removeChild(listChild.childNodes[0]);
            }

            if(last_id != id_num){
                cont_recorder = 0;
            }
            // Initialize the recorder
            if(cont_recorder==0){
                myRecorder.init();
                last_id = id_num;
            }

            cont_recorder++;

            // Get the button state
            var buttonState = !!$(this).attr('data-recording');

            // Toggle
            if (!buttonState) {
                $(this).attr('data-recording', 'true');
                myRecorder.start();
                var buton = document.getElementById(id);
                buton.innerText="";
                buton.style.backgroundColor = '#ff2038';


                var icon = document.createElement("i");
                icon.className= "fa fa-stop pr-2";
                icon.setAttribute("aria-hidden", true);
                buton.append(icon, "Stop audio");
            } else {
                $(this).attr('data-recording', '');
                myRecorder.stop(listObject, id_num);
                var buton = document.getElementById(id);
                buton.innerText="";
                buton.style.backgroundColor = '#745AAA';


                var icon = document.createElement("i");
                icon.className= "fa fa-microphone pr-2";
                icon.setAttribute("aria-hidden", true);
                buton.append(icon, "Record audio");
            }


        };

        function createDownloadLink(blob_f, filename) {
            var fd = new FormData();
            console.log(typeof blob_f);
            fd.append('audio',blob_f, filename);
            var framerate = myRecorder.objects.recorder.context.sampleRate;
            $.ajax({
                url: "{% url 'grafic' 5678 %}".replace(/5678/, framerate),
                type: "POST",
                data: fd,
                processData: false,
                contentType: 'application/json',
                success : function(json,data) {
                    var filename = document.getElementById('0').name
                    console.log(filename);
                },
                error : function(xhr, errmsg, err) {
                    alert("Drawing could not be saved!");
                }
            });

        }

        function passForm(){
            var titulo = document.getElementById('inputTitulo').value;
            var tituloPagina = document.getElementById('tituloPagina').value;
            var subtitulo = document.getElementById('subtitulo').value;
            var cuerpo = document.getElementById('cuerpo').value;
            var data_dict = {'formulario_id': {{ formulario.id }},
                'numSecciones':num_seccion, 'numSeccionesAnterior': {{ formulario.numSecciones }},
                'titulo': titulo, 'tituloPagina': tituloPagina, 'subtitulo': subtitulo, 'cuerpo': cuerpo}

            var string_deleted = '';
            for(var i = 0; i<deletedAudios.length; i++){
                string_deleted = string_deleted + deletedAudios[i] +',';
            }

            data_dict['deleted_sections'] = string_deleted;
            data_dict['num_deleted_sections'] = deletedAudios.length;

            for(var i = 0; i<num_seccion; i++){
                if(document.getElementById('inputContext'+i)){
                    var id = document.getElementById('inputContext'+i).name;

                    var tipo = document.getElementById('inputType'+i).value;
                    var texto = document.getElementById('inputContext'+i).value;

                    var audio = null;
                    if(document.getElementById('a'+i)){
                        audio = document.getElementById('a'+i).name;
                    }

                    var imagen = null;
                    if(tipo == 'imagen'){
                        imagen = document.getElementById('imageResult'+i).src;
                    }

                    data_dict['seccion'+i] =  {'id': id, 'tipo': tipo, 'texto': texto, 'audio': audio, 'imagen': imagen, 'posicion': i}
                }

            }

            data_dict['numDatos'] = num_dato;
            data_dict['numDatosAnterior'] = {{numDatos}};
            for(var i = 0; i<num_dato; i++){
                var tipo = document.getElementById('datotipo'+i).value;
                var pregunta = document.getElementById('dato'+i).value;
                var id = document.getElementById('dato'+i).name;

                data_dict['informacion'+i] =  {'id': id, 'tipo': tipo, 'pregunta': pregunta, 'posicion':i}
            }

            $.ajax({
                url: "{% url 'formedit' %}",
                type: "POST",
                data: data_dict,
                success : function(json,data) {
                    location.href = "{% url 'adminprofile' user.username %}"
                },
                error : function(xhr, errmsg, err) {
                    alert("Drawing could not be saved!");
                }
            });

        }
    </script>

    <script type="text/javascript">

        function view_options(id){
            var option = document.getElementById(id).value;
            var num_select = id.substr(id.length - 1);

            if(option == 'audio'){
                document.getElementById('inputImage'+num_select).style.display = 'none';

                document.getElementById('holderAudio'+num_select).style.display = 'block';

                document.getElementById('inputContext'+num_select).style.display = 'block';
                document.getElementById('labelContext'+num_select).style.display = 'block';
            }else if(option == 'texto') {
                document.getElementById('inputImage'+num_select).style.display = 'none';

                document.getElementById('holderAudio'+num_select).style.display = 'block';

                document.getElementById('inputContext'+num_select).style.display = 'block';
                document.getElementById('labelContext'+num_select).style.display = 'block';
            }else{
                document.getElementById('inputImage'+num_select).style.display = 'block';

                document.getElementById('holderAudio'+num_select).style.display = 'block';

                document.getElementById('inputContext'+num_select).style.display = 'block';
                document.getElementById('labelContext'+num_select).style.display = 'block';
            }
        };

        var num_seccion = {{formulario.numSecciones}};
        var num_dato = {{numDatos}};

        function action_submit(){
            if(!control_inputs()){
               return false;
            }

            for(var i = 0; i<num_seccion; i++){
                if(editedAudios.includes('inputContext'+i)){
                    createDownloadLink(blob_list[i], document.getElementById('a'+i).name)
                }
            }
            passForm();
        }

        function control_inputs(){
            var titulo = document.getElementById('inputTitulo').value;
            var tituloPagina = document.getElementById('tituloPagina').value;
            var dato = document.getElementById('dato0').value;

            if(!tituloPagina){
                alert("Debes introducir un título en la pagina principal antes de guardar.");
                return false;
            }

            if(!dato){
                alert("Debes introducir un dato personal mínimo.");
                return false;
            }

            if(!titulo){
                alert("Debes introducir un título antes de guardar.");
                return false;
            }

            if(!titulo.match(/^[a-zA-Z\s0-9]*$/)){
                alert("El titulo solo puede contener letras numeros o espacios.");
                return false;
            }
            return true;
        }

        function nueva_seccion(element){
            let container = document.getElementById('sections');
            var card = document.createElement("div");
            card.className = "card mt-4";
            card.id = num_seccion;

            var card_body = document.createElement("div");
            card_body.className = "card-body";

            var card_span = document.createElement("span");
            card_span.className = "bmd-help error";

            var fieldset = document.createElement("fieldset");
            fieldset.className = "form-group";

            var label = document.createElement("label");
            label.className= "bmd-label-floating inline-group";
            label.htmlFor = "inputType"+num_seccion;
            label.innerHTML = "Tipo de contexto";

            var select = document.createElement("select");
            select.className= "form-control";
            select.type = "text";
            select.name= "tipocontexto"+num_seccion;
            select.id = "inputType"+num_seccion;
            select.autofocus = true;
            select.setAttribute('onchange', "view_options('inputType"+num_seccion+"')");

            var optionText = document.createElement("option");
            optionText.value = "texto";
            optionText.innerHTML = "Texto";
            optionText.selected = true;
            var optionAudio = document.createElement("option");
            optionAudio.value = "audio";
            optionAudio.innerHTML = "Audio";
            var optionImagen = document.createElement("option");
            optionImagen.value = "imagen";
            optionImagen.innerHTML = "Imagen";
            select.append(optionText, optionAudio, optionImagen);

            var label_margin = document.createElement("label");
            label_margin.className= "bmd-label-floating inline-group mt-3";
            label_margin.htmlFor = "inputContext"+num_seccion;
            label_margin.id = "labelContext"+num_seccion;
            label_margin.innerHTML = "Contexto";

            var textarea = document.createElement("textarea");
            textarea.className = "form-control";
            textarea.name = "contexto"+num_seccion;
            textarea.id = "inputContext"+num_seccion;
            textarea.rows = 3;

            card_body.append(card_span);
            fieldset.append(label, select, label_margin, textarea);

            var inputImage = document.createElement("div");
            inputImage.className="row";
            inputImage.style.display = 'none';
            inputImage.id = "inputImage"+num_seccion;

            var labelCont = document.createElement("label");
            labelCont.className = "bmd-label-floating inline-group ml-3";
            labelCont.htmlFor = "inputImagen";
            labelCont.id = "labelImagen";
            labelCont.innerHTML = "Contexto";

            var coll = document.createElement("div");
            coll.className = "col-lg-6 mx-auto";

            var inputgroup = document.createElement("div");
            inputgroup.className = "input-group mb-3 px-2 py-2 rounded-pill bg-white shadow-sm";

            var readURL = document.createElement("input");
            readURL.id = "upload";
            readURL.type = "file";
            readURL.setAttribute('onchange', 'readURL(this)');
            readURL.name = "upload" + num_seccion;
            readURL.className = "form-control border-0";
            inputgroup.append(readURL);

            var result = document.createElement("div");
            result.className = "image-area mt-4";

            var finalIm = document.createElement("img");
            finalIm.id = "imageResult"+num_seccion;
            finalIm.src="#";
            finalIm.alt = "";
            finalIm.className = "img-fluid rounded shadow-sm mx-auto d-block";
            result.append(finalIm);

            coll.append(inputgroup, result);
            inputImage.append(labelCont, coll);

            var holder = document.createElement("div");
            holder.className = "holder";
            holder.id = "holderAudio" + num_seccion;

            var label_margin_audio = document.createElement("label");
            label_margin_audio.className= "bmd-label-floating inline-group mt-3";
            label_margin_audio.htmlFor = "inputAudio"+num_seccion;
            label_margin_audio.innerHTML = "Audio de ejemplo";

            var controls = document.createElement("div");
            controls.setAttribute('data-role', 'controls'+num_seccion);
            controls.className = "controls";
            controls.id = 'cont' + num_seccion;

            var btn = document.createElement("button");
            btn.type="button"; btn.className = "btn border rounded";
            btn.setAttribute('onclick', 'grabacio('+num_seccion+')');
            btn.id = "btn"+num_seccion;

            var i = document.createElement("i");
            i.className = "fa fa-microphone pr-2";
            i.setAttribute('aria-hidden', 'true');

            btn.append(i, "Record audio");
            controls.append(btn);

            var recordings = document.createElement("div");
            recordings.setAttribute('data-role', 'recordings'+num_seccion);
            recordings.className = "recordings";
            recordings.id = 'rec'+num_seccion;

            holder.append(label_margin_audio, controls, recordings);

            card_body.append(fieldset, inputImage, holder);
            card.append(card_body);
            container.appendChild(card);
            num_seccion++;
        }

        function delete_seccion(element){
            if(num_seccion > {{formulario.numSecciones}}){
                var card_remove = document.getElementById(num_seccion-1);
                card_remove.remove();
                num_seccion = num_seccion-1;
            }

        }

        function nuevo_dato(element) {
            let container = document.getElementById('datoscontainer');
            var card = document.createElement("div");
            card.className = "card mt-4";
            card.id = "carddato"+num_dato;

            var card_body = document.createElement("div");
            card_body.className = "card-body";

            var card_span = document.createElement("span");
            card_span.className = "bmd-help error";

            var fieldset = document.createElement("fieldset");
            fieldset.className = "form-group";

            var label = document.createElement("label");
            label.className = "bmd-label-floating";
            label.htmlFor = "dato" + num_dato;
            label.innerHTML = "Dato";

            var inputdato = document.createElement("input");
            inputdato.className = "form-control mt-1";
            inputdato.type = "text";
            inputdato.id = "dato" + num_dato;
            inputdato.autofocus = true;

            fieldset.append(label, inputdato)

            var fieldset2 = document.createElement("fieldset");
            fieldset2.className = "form-group";

            var labeltipo = document.createElement("label");
            labeltipo.className = "bmd-label-floating";
            labeltipo.htmlFor = "datotipo" + num_dato;
            labeltipo.innerHTML = "Tipo de dato";

            var select = document.createElement("select");
            select.className= "form-control";
            select.type = "text";
            select.id = "datotipo"+num_dato;
            select.autofocus = true;

            var optionText = document.createElement("option");
            optionText.value = "texto";
            optionText.innerHTML = "Texto";
            optionText.selected = true;

            var optionFecha = document.createElement("option");
            optionFecha.value = "fecha";
            optionFecha.innerHTML = "Fecha";

            var optionSino = document.createElement("option");
            optionSino.value = "sino";
            optionSino.innerHTML = "Respuesta Si/No";

            select.append(optionText, optionFecha, optionSino);
            fieldset2.append(labeltipo, select);

            card_body.append(card_span, fieldset, fieldset2);
            card.append(card_body);
            container.append(card);

            num_dato = num_dato+1;
        }

        function delete_dato(element){
            if(num_dato > {{informaciones|length}}){
                var card_remove = document.getElementById("carddato"+(num_dato-1));
                card_remove.remove();
                num_dato = num_dato-1;
            }

        }

        function eliminarseccion(element, id){
            var card_remove = document.getElementById(element);
            card_remove.remove();

            deletedAudios.push(id);

            return true;
        }
        /*  ==========================================
            SHOW UPLOADED IMAGE
        * ========================================== */
        function readURL(input) {
            var name = input.name.substr(input.name.length - 1);
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                var imageResult = '#imageResult'+ name;
                reader.onload = function (e) {
                    $(imageResult)
                        .attr('src', e.target.result);
                };
                reader.readAsDataURL(input.files[0]);
            }
        }

        $(function () {
            $('#upload').on('change', function () {
                readURL(input);
            });
        });

        /*  ==========================================
            SHOW UPLOADED IMAGE NAME
        * ========================================== */
        var input = document.getElementById( 'upload' );
        var infoArea = document.getElementById( 'upload-label' );

        input.addEventListener( 'change', showFileName );
        function showFileName( event ) {
          var input = event.srcElement;
          var fileName = input.files[0].name;
          infoArea.textContent = 'File name: ' + fileName;
        }
    </script>
{% endblock %}