main.js 22.7 KB
Newer Older
1 2 3
var cont_experiencia = 0;
let cont_estudios = 0;
let cont_tecnologia = 0;
4

willgonzz committed
5
let cont_cargo = 0;
6 7 8
const experiencias = [];
const estudios = [];
const tecnologias = [];
9
let noValidateFlag = false;
10

willgonzz committed
11
const postulaciones = [];
12

13
var cont_referencias=0 ;
14 15
const referencias= [];

16 17 18 19 20 21 22 23 24 25
form = document.querySelector("form");
const depSelect = document.querySelector("#departamentos");

console.log("saddsa", bootstrap)
const modalCargo = bootstrap.Modal.getOrCreateInstance(document.getElementById('cargoForm'))
const modalExperiencia = bootstrap.Modal.getOrCreateInstance(document.getElementById('experienciaForm'))
const modalTecnologia = bootstrap.Modal.getOrCreateInstance(document.getElementById('tecnologiaForm'))
const modalEstudio = bootstrap.Modal.getOrCreateInstance(document.getElementById('estudioForm'))
const modalReferencia = bootstrap.Modal.getOrCreateInstance(document.getElementById('referenciaForm'))
//variable ciudades esta declarada en el jsp
26

27
/*-----------------Definicion de funciones de poblacion de elementos y validaciones----------------------------------------*/
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
const formValidator = function () {
    'use strict'

    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.querySelectorAll('.needs-validation')
    var expForm = document.querySelector('#agregar-exp')


    // Loop over them and prevent submission
    Array.prototype.slice.call(forms)
        .forEach(function (form) {
            form.addEventListener('submit', function (event) {
                if (!form.checkValidity()) {
                    event.preventDefault()
                    event.stopPropagation()
44
                    noValidateFlag = true;
45 46 47 48 49 50
                }

                form.classList.add('was-validated')
            }, false)
        })
}
51 52 53 54 55 56 57 58
function fechasMaxMin(){
    var today = new Date();
    var dd = today.getDate()-1;
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();

    if (dd < 10) {
        dd = '0' + dd;
59
    }
60

61 62 63
    if (mm < 10) {
        mm = '0' + mm;
    }
64

65
    today = yyyy + '-' + mm + '-' + dd;
66

67

68 69 70 71 72 73 74
    let fechaDesdeEstudio = document.querySelector("#fechaDesdeEstudio");
    let fechaDesdeExperiencia = document.querySelector("#fechaDesdeExperiencia");
    let fechaHastaEstudio = document.querySelector("#fechaHastaEstudio");
    let fechaHastaExperiencia = document.querySelector("#fechaHastaExperiencia");
    let fechaNacimiento = document.querySelector("#fechaNacimiento");
    let fechas = [fechaDesdeEstudio,fechaDesdeExperiencia,fechaHastaEstudio,fechaHastaExperiencia,fechaNacimiento]
    fechas.forEach(fch => fch.addEventListener('keydown',()=>false))//no dejar cargar manualmente fechas
75

76 77 78
    fechaDesdeEstudio.setAttribute("max", today);
    fechaDesdeExperiencia.setAttribute("max", today);
    fechaNacimiento.setAttribute("max", today);
79

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    fechaDesdeExperiencia.addEventListener("change", ()=>{
        fechaHastaExperiencia.setAttribute("min", fechaDesdeExperiencia.value)
    })
    fechaDesdeEstudio.addEventListener("change", ()=>{
        fechaHastaEstudio.setAttribute("min", fechaDesdeEstudio.value)
    })
}

 function listarCiudades(depId){
    const ciuAmostrar = ciudades.filter(c=>c.departamentoId==depId);
    const ciudad = document.querySelector("select[name=ciudadId]");
    const frag = document.createDocumentFragment();
    for (const ciu of ciuAmostrar) {
        const opt = document.createElement("option");    
        opt.value = ciu.id;
        opt.innerHTML = ciu.nombre;
        opt.setAttribute("data-departamentoId",ciu.departamentoId);
        frag.appendChild(opt)
98
    }
99 100
    ciudad.replaceChildren(frag);
    
101
    
102
}
103

104 105 106 107 108 109
function validarfecha(fechaDesde, fechaHasta){
    let fechadehoy= new Date().toISOString().slice(0,10);

    if(fechaDesde>fechadehoy ){
       return "la fecha desde no puede ser mayor a la fecha actual" ;   
    }
110
    
111 112 113 114 115 116 117
    if(fechaHasta =! null && fechaDesde>fechaHasta){
        return "la fecha desde no puede ser mayor a la fecha hasta";
    
    }
        return false
  
}
118
/*-----------------Tecnologia----------------------------------------*/
willgonzz committed
119 120 121 122 123
function agregarFieldTecnologia(){
    //recoger del form
    const pairs = {};
    const formtecn = document.querySelector("[name=tecnologia-form]");
    const formData = new FormData(formtecn);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

    //Validacion
    let returnFlag = false;

    let requiredValues = ["nombre", "nivel"]

    formData.forEach((value, key)=>{
        if(requiredValues.includes(key)
            && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });

    if(returnFlag===true){
        let message = "Rellene "
        for(let i=0;i<requiredValues.length;i++){
            message+=", "+requiredValues[i];
        }
        message += " como minimo."
        alert(message);
        return;
    }

willgonzz committed
148 149 150 151
    for (const [name, value] of formData){
        pairs[name] = value
    }
    tecnologias[cont_tecnologia]={}
152
    tecnologias[cont_tecnologia]["tecnologia"]=pairs["tecnologia-id"]=="-1"?{nombre: pairs["tecnologia-nombre"]}:{id: pairs["tecnologia-id"],nombre:document.querySelector('[name=tecnologia-id] > option[value="'+pairs["tecnologia-id"]+'"]').innerHTML}
willgonzz committed
153 154 155
    tecnologias[cont_tecnologia]["nivel"]=pairs.nivel
    //tecnologias[cont_tecnologia] = pairs;
    formtecn.reset();
156
    document.querySelector("#tecnologia-nombre").classList.add('d-none')
willgonzz committed
157 158 159 160
    //imprimir lista actualizada
    const div = document.querySelector("#tecnologias")
    const div1 = document.createElement('div');
    console.log(tecnologias[0])
161

162
    let content1=''
willgonzz committed
163 164 165 166
    for (let index = 0; index < tecnologias.length; index++) {
        const tecn = tecnologias[index];
        if(tecn==null) continue;
        content1 += `
167 168 169 170 171
        <div class="col-auto" id="tecn-${index}">
        ${tecn.tecnologia.nombre} ( ${tecn.nivel} <i class="bi bi-star-fill"></i> ) &nbsp; <i class="bi bi-trash-fill" onclick="eliminarTecnologia(event)"></i>       
            
            
            
172
        </div>
willgonzz committed
173 174 175
        
        `
    }
176 177 178 179
    //content1 += "</ul>" 
    div.innerHTML = content1
    //div.innerHTML = '';
    //div.appendChild(div1);
willgonzz committed
180
    cont_tecnologia++;
181
    document.querySelector("#no-valid-tecno").style.display = "none";
182
    modalTecnologia.hide()
183
}
willgonzz committed
184 185 186 187 188 189
function eliminarTecnologia(event) {
    //eliminar del array
    tecnologias[event.target.parentElement.id.split("-")[1]]=null
    //eliminar en html
    event.target.parentElement.remove()
}
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
/*----------------Experiencia-----------------------------------------*/
function agregarFieldExpierncia(event){
    //recoger del form
    const pairs = {};
    const formexp = document.querySelector("[name=experiencia-form]");
    formexp.classList.add('was-validated')
    const formData = new FormData(formexp);
    let error=validarfecha(formData.get("fechaDesde"), formData.get("fechaHasta"))
    let appendTo = "Hasta";
    if (error) {

            if(error.includes("desde")) appendTo = "Desde";
            
            
            formexp['fecha'+appendTo].setCustomValidity(error)
            formexp.querySelector(".errorFecha"+appendTo).innerHTML = error;
            console.log(error);
            
209 210
    }
    else{
211 212
        formexp.fechaDesde.setCustomValidity('')
        formexp.fechaHasta.setCustomValidity('')
213
    }
214 215 216 217
    
    const reconocimientos = [{},{},{}];
    let pos_rec;
    let returnFlag = false;
218

219
    let requiredValues = ["institucion", "cargo", "fechaDesde"]
220

221 222 223 224 225 226 227
    formData.forEach((value, key)=>{
        if(requiredValues.includes(key)
        && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });
228

229 230 231 232 233 234 235
    if(returnFlag===true){
        let message = "Rellene "
        for(let i=0;i<requiredValues.length;i++){
            message+=", "+requiredValues[i];
        }
        message += " como minimo."
        //alert(message);
236 237
        return;
    }
238

239 240 241 242 243 244 245 246
    for (const [name, value] of formData){
        pos_rec = name.split("-");//rec-nombre-index
        if (pos_rec.length > 1) {
            reconocimientos[pos_rec[2]][pos_rec[1]] = value
        }
        else{
            pairs[name] = value
        }
247

248
    }
249 250 251 252 253 254 255 256 257 258 259 260 261 262
    pairs["reconocimientos"] = reconocimientos.filter(rec => rec.nombre);
    experiencias[cont_experiencia] = pairs;
    formexp.reset();
    formexp.classList.remove('was-validated')
    //imprimir lista actualizada
    const div = document.querySelector("#experiencias")
    const div1 = document.createElement('div');
    
    let content='';
    for (let index = 0; index < experiencias.length; index++) {
        const exp = experiencias[index];
        if(exp==null) continue;
        content += `
        <div class="col border border-3" id="exp-${index}">
263
                    <center><h4>Experiencia <i class="bi bi-trash-fill" onclick="eliminarExperiencia(${index})"></i></h4></center>
264 265 266 267 268 269 270
                    <label><b>Institucion:</b>&nbsp  ${exp.institucion}</label><br>  
                    <label><b>Fecha Inicio: </b>&nbsp ${exp.fechaDesde}</label><br>
                    <label><b>Fecha Fin: </b>&nbsp ${exp.fechaHasta}</label><br>
                    <label><b>Referencia: </b>&nbsp ${exp.nombreReferencia}</label><br>
                    <label><b>Telefono de la referencia: </b>&nbsp ${exp.telefonoReferencia}</label><br>
                    <label><b>Cargo: </b>&nbsp ${exp.cargo}</label><br>
                    <label><b>Motivo de salida: </b>&nbsp ${exp.motivoSalida}</label><br>
271
                    
272 273 274 275
            
        </div>
        
        `
276
    }
277 278 279 280 281 282
    //content += "</ul>" 
    div.innerHTML = content
    //div.innerHTML = '';
    //div.appendChild(div1);
    cont_experiencia++;
    modalExperiencia.hide()
283
}
284
function eliminarExperiencia(index) {
285
    //eliminar del array
286
    experiencias[index]=null
287
    //eliminar en html
288 289
    document.getElementById("exp-"+index).remove()
    //event.target.parentElement.remove()
290
}
291
/*---------------Estudios---------------------------*/
292 293 294

function agregarFieldEstudio(){
    //recoger del form
295 296
    let pairs = {};
    const formest = document.querySelector("[name=estudio-form]");
297
    const formData = new FormData(formest);
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    formest.classList.add('was-validated')
    let error=validarfecha(formData.get("fechaDesde"), formData.get("fechaHasta"))
    let appendTo = "Hasta";
    if (error) {

            if(error.includes("desde")) appendTo = "Desde";
            
            formest['fecha'+appendTo].setCustomValidity(error)
            formest.querySelector(".errorFecha"+appendTo).innerHTML = error;
            console.log(error);
            
    }
    else{
        formest.fechaDesde.setCustomValidity('')
        formest.fechaHasta.setCustomValidity('')
    }
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

    //Validacion
    let returnFlag = false;

    let requiredValues = ["tipoDeEstudio", "institucion", "estado", "fechaDesde", "temaDeEstudio"]

    formData.forEach((value, key)=>{
        if(requiredValues.includes(key)
            && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });

    if(returnFlag===true){
        let message = "Rellene "
        for(let i=0;i<requiredValues.length;i++){
            message+=", "+requiredValues[i];
        }
        message += " como minimo."
334
        //alert(message);
335 336 337 338
        return;
    }


339 340
    const estudioReconocimiento = [{},{},{}];
    let pos_rec;
341
    for (const [name, value] of formData){
342 343 344 345 346 347 348 349
        pos_rec = name.split("-");//rec-nombre-index
        if (pos_rec.length > 1) {
            estudioReconocimiento[pos_rec[2]][pos_rec[1]] = value
        }
        else{
            pairs[name] = value
        }
        
350
    }
351 352 353 354 355 356
    let nombre = pairs["institucion"]
    delete pairs["institucion"]
    console.log(pairs)
    pairs["institucion"] = {  }
    pairs["institucion"].nombre = nombre
    pairs["institucion"].subNombre = ""
357
    pairs["estudioReconocimiento"] = estudioReconocimiento.filter(rec => rec.nombre);
358 359 360 361 362
    estudios[cont_estudios] = pairs;
    formest.reset();
    //imprimir lista actualizada
    const div = document.querySelector("#estudios")
    const div1 = document.createElement('div');
363
    let content='';
364 365 366 367 368
    
    for (let index = 0; index < estudios.length; index++) {
        const est = estudios[index];
        if(est==null) continue;
        content += `
369
        <div class="col border border-3" id="est-${index}">
370
        <center><h4>Estudio <i class="bi bi-trash-fill" onclick="eliminarEstudio(${index})"></i></h4></center>
371 372 373 374 375 376
            <label><b>Institucion: </b>&nbsp ${est.institucion.nombre}</label><br>
            <label><b>Tipo de estudio: </b>&nbsp ${est.tipoDeEstudio}</label><br>  
            <label><b>Carrera: </b>&nbsp ${est.temaDeEstudio}</label><br>     
            <label><b>Fecha Inicio: </b>&nbsp ${est.fechaDesde}</label><br>
            <label><b>Fecha Fin: </b>&nbsp ${est.fechaHasta}</label><br>
            <label><b>Estado: </b>&nbsp ${est.estado}</label><br>
377
            
378
        </div>
379 380 381
        
        `
    }
382 383 384 385
 
    div.innerHTML = content
    //div.innerHTML = '';
    //div.appendChild(div1);
386
    cont_estudios++;
387 388
    formest.classList.remove('was-validated')
    modalEstudio.hide()
389 390
}

391
function eliminarEstudio(index) {
392
    //eliminar del array
393
    estudios[index]=null
394
    //eliminar en html
395
    document.getElementById("est-"+index).remove()
396
}
397
/*------------Cargos----------------------------------------*/
willgonzz committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
function agregarFieldCargo(){
    //recoger del form
    const pairs = {};
    const formcar = document.querySelector("[name=cargo-form]");
    const formData = new FormData(formcar);

    //Validacion
    let returnFlag = false;

    let requiredValues = ["nombre"]

    formData.forEach((value, key)=>{
        if(requiredValues.includes(key)
            && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });

    if(returnFlag===true){
        let message = "Rellene "
        for(let i=0;i<requiredValues.length;i++){
            message+=", "+requiredValues[i];
        }
        message += " como minimo."
        alert(message);
        return;
    }
426

willgonzz committed
427 428 429 430
    for (const [name, value] of formData){
        pairs[name] = value
    }
    console.log(pairs)
431 432 433 434
    for(let i=0;i<cont_cargo;i++){
        if(postulaciones[i]!==null){
            if(postulaciones[i]["id"]===pairs["cargo-id"]){
                alert("Ya has agregado ese cargo!")
435
                //cont_cargo--;
436 437 438 439
                return;
            }
        }
    }
willgonzz committed
440 441 442 443 444 445 446 447 448
    postulaciones[cont_cargo]={}
    postulaciones[cont_cargo]["id"]=pairs["cargo-id"]
    //postulaciones[cont_cargo]["cargo"]=pairs["cargo-id"]=="-1"?{nombre: pairs["cargo-nombre"]}:{id: pairs["cargo-id"],nombre:document.querySelector('[name=cargo-id] > option[value="'+pairs["cargo-id"]+'"]').innerHTML}
    console.log(postulaciones)
    formcar.reset();
    //imprimir lista actualizada
    const div = document.querySelector("#cargos")
    const div1 = document.createElement('div');

449
    let content1=''
willgonzz committed
450 451 452 453
    for (let index = 0; index < postulaciones.length; index++) {
        const car = postulaciones[index];
        if(car==null) continue;
        content1 += `
454
        <div class="col-auto" id="car-${index}" style="text-transform: uppercase;">
455
            ${document.querySelector('[name=cargo-id] >  option[value="'+car.id+'"]').innerHTML} &nbsp;<i class="bi bi-trash-fill" onclick="eliminarCargoPostulante(event)"></i>     
456
            
457 458
        </div>

willgonzz committed
459 460
        `
    }
461 462 463 464
    //content1 += "</ul>" 
    div.innerHTML = content1
    //div.innerHTML = '';
    //div.appendChild(div1);
willgonzz committed
465
    cont_cargo++;
466
    document.querySelector("#no-valid-cargo").style.display = "none";
467
    modalCargo.hide()
willgonzz committed
468 469 470 471 472 473 474
}
function eliminarCargoPostulante(event) {
    //eliminar del array
    postulaciones[event.target.parentElement.id.split("-")[1]]=null
    //eliminar en html
    event.target.parentElement.remove()
}
475

476
/*--------------Referencias----------------------------- */
477 478 479 480
function agregarFieldReferencia(event){
    //recoger del form
    const pairs = {};
    const formexp = document.querySelector("[name=referencia-form]");
481
    formexp.classList.add('was-validated')
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    const formData = new FormData(formexp);
    const referenciaPersonal = [{},{},{}];
    let pos_rec;
    let returnFlag = false;

    let requiredValues = ["nombre", "relacion", "telefono"]

    formData.forEach((value, key)=>{
        if(requiredValues.includes(key)
        && value==="" && returnFlag == false){
            console.log(key, value)
            returnFlag = true;
        }
    });

    if(returnFlag===true){
        let message = "Rellene "
        for(let i=0;i<requiredValues.length;i++){
            message+=", "+requiredValues[i];
        }
        message += " como minimo."
503
        //alert(message);
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
        return;
    }

    for (const [name, value] of formData){
        pos_rec = name.split("-");//rec-nombre-index
        if (pos_rec.length > 1) {
            referenciaPersonal[pos_rec[2]][pos_rec[1]] = value
        }
        else{
            pairs[name] = value
        }

    }
    pairs["referenciaPersonal"] = referenciaPersonal.filter(rec => rec.nombre);
    referencias[cont_referencias] = pairs;
    formexp.reset();
    //imprimir lista actualizada
    const div = document.querySelector("#referencia")
    const div1 = document.createElement('div');
523
    let content=''
524 525 526 527
    for (let index = 0; index < referencias.length; index++) {
        const exp = referencias[index];
        if(exp==null) continue;
        content += `
528 529 530
        <div class="col border border-3" id="ref-${index}">
        <center><h4>Referencia Personal <i class="bi bi-trash-fill" onclick="eliminarReferencia(${index})"></i></h4></center> 
            
531 532 533
            <label><b>Nombre: </b>&nbsp ${exp.nombre}</label><br>
            <label><b>Telefono: </b>&nbsp ${exp.telefono}</label><br>
            <label><b>Relacion: </b>&nbsp ${exp.relacion}</label><br>
534
            
535
        </div>
536 537 538
        
        `
    }
539 540 541 542
    //content += "</ul>" 
    div.innerHTML = content
    //div.innerHTML = '';
    //div.appendChild(div1);
543
    cont_referencias++;
544
    formexp.classList.remove('was-validated')
545
    modalReferencia.hide()
546
}
547
function eliminarReferencia(index) {
548
    //eliminar del array
549
    referencias[index]=null
550
    //eliminar en html
551
    document.getElementById("ref-"+index).remove()
552
}
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
/*--------------Form submit----------------------------- */
function serializeJSON (form) {
    // Create a new FormData object
    const formData = new FormData(form);

    if(formData.get('fechaNacimiento')>=new Date().toISOString().slice(0,10)){
        form['fechaNacimiento'].setCustomValidity('Fecha de nacimiento debe ser menor que actual')
        noValidateFlag = true;
        return;
    }
    else{
        form['fechaNacimiento'].setCustomValidity('')   
    }


    // Create an object to hold the name/value pairs
    const pairs = {};

    // Add each name/value pair to the object
    for (const [name, value] of formData) {
        pairs[name] = value
    }
    pairs["experiencias"] = experiencias.filter(exp => exp)//eliminacion de nulos
    pairs["estudios"] = estudios.filter(est => est)//eliminacion de nulos
    pairs["tecnologias"] = tecnologias.filter(tec => tec)//eliminacion de nulos
    pairs["postulaciones"] = postulaciones.filter(car => car)//eliminacion de nulos
    pairs["referencias"] = referencias.filter(tec => tec)
    if(pairs["postulaciones"].length<1){
        document.querySelector("#no-valid-cargo").style.display = "block";
        noValidateFlag = true;
    }else{
        document.querySelector("#no-valid-cargo").style.display = "none";
    }
    console.log(pairs["tecnologias"])
    if(pairs["tecnologias"].length<1){
        document.querySelector("#no-valid-tecno").style.display = "block";
        noValidateFlag = true;
    }else{
        document.querySelector("#no-valid-tecno").style.display = "none";
    }
    if(noValidateFlag){
        return;
    }
    noValidateFlag = false
    
    // Return the JSON string
    return JSON.stringify(pairs, null, 2);
}

function obtenerCV(){
    let input = document.querySelector('#cvFile')
    return input.files[0];
  
}

async function postData(url = '', data = {}) {
    var token = document.querySelector("meta[name='_csrf']").content;
    var headerxs = document.querySelector("meta[name='_csrf_header']").content;
    // Default options are marked with *
    let senddata = {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
            //'Content-Type': undefined//'application/json',
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: data // body data type must match "Content-Type" header
    }
    senddata["headers"][headerxs] = token;
    let response = null
    if(!noValidateFlag){
        response = await fetch(url, senddata);
    }
    return response; // parses JSON response into native JavaScript objects
}

function formatearJsonWithFile(json, file){
    formData = new FormData();

    formData.append("file", file);
    formData.append('postulante', new Blob([json], {
                type: "application/json"
            }));
    return formData
}

/*--------------Llamar funciones y agregar listeners----------------------------- */
formValidator();
fechasMaxMin();
listarCiudades(depSelect.value);

form.addEventListener("submit",(evt)=>{
    // if (!form.checkValidity()) {
    //     evt.preventDefault()
    //     evt.stopPropagation()
    // }
    // form.classList.add('was-validated')
    evt.preventDefault();
    let formSerialized = serializeJSON(form);
    let fileCV = obtenerCV();
    if(!noValidateFlag){
        postData('work-with-us', formatearJsonWithFile(formSerialized,fileCV))
            .then(response => {
                if(response.status==200 || response.status==302){
                    location.replace(response.url);
                }else{
                    
                    errorDispatcher(response.text().then(value => console.log(value)));
                    
                }
            },(reason)=>{
                errorDispatcher(reason);
            });
        }
    noValidateFlag = false
} );

function errorDispatcher(reason){
    const errorSection = document.querySelector("#errorSection")
    errorSection.innerHTML = `
    <div  class="alert alert-warning alert-dismissible fade show " role="alert">
        <strong>Ha ocurrido un error</strong>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>`;
    console.log(reason)
    errorSection.focus()
}

//evento para cambio de ciudad segun departamento
depSelect.addEventListener("change",evt => listarCiudades(evt.target.value))