var htmlData2;
var formulario2;
var valueOriginal2 = 'Subir';
var nameFile2 = '';

const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result.split(',')[1]);
    reader.onerror = error => reject(error);
});

function creaBase64(e) {
   const file = document.querySelector('#imgSubir').files[0];
   toBase64(file).then((data) => {
        enviarFileBien(data, e)
   })
}


$('.contenedor-final2 .input').blur(function(e){
    if($(this).hasClass('error')){
        $(this).removeClass('error')
        $(this).find('span').empty()
    }
});
$('.contenedor-final2 .input').click(function(e){
    if($(this).hasClass('error')){
        $(this).removeClass('error')
        $(this).find('span').empty()
    }
});

const enviarFileBien = (file, e) => {
    enviando2('Subiendo...', '#btn-main-subir-foto');
    var form = new FormData();
    form.append("action", "actionCorreoTodosDibujamos");
    form.append("file", file);
    form.append("name", nameFile2);
    form.append("html", htmlData2);
    $.ajax({
        url: aj_ajax.ajaxurl,
        type: 'post',
        cache : false,
        processData: false,
        contentType: false,
        data: form,
        success: function (resp) {
            try{
                resp = JSON.parse(resp);
                // console.log(resp);
                if(resp.code == 'failure'){
                    printErrorsAjax2('Algo salio mal! no pudimos subir tu imagen.', '#btn-main-subir-foto')
                    setTimeout(() => {
                        $('#' + formulario2)[0].reset();
                        resetForm2(valueOriginal2, '#btn-main-subir-foto')
                    }, 3000);
                }else{
                    if(resp.code == 'success'){
                        enviado2('Imagen subida!', '#btn-main-subir-foto');
                        $('#' + formulario2)[0].reset();
                        setTimeout(() => {
                            resetForm2(valueOriginal2, '#btn-main-subir-foto')
                        }, 3000);
                    }else{
                        printErrorsAjax2('Algo salio mal! no pudimos subir tu imagen.', '#btn-main-subir-foto')
                        setTimeout(() => {
                            $('#' + formulario2)[0].reset();
                            resetForm2(valueOriginal2, '#btn-main-subir-foto')
                        }, 3000);
                    }
                    
                }
                    
            }catch(e){
                // console.log(e);
                printErrorsAjax2('Algo salio mal! no pudimos subir tu imagen.', '#btn-main-subir-foto')
                setTimeout(() => {
                    $('#' + formulario2)[0].reset();
                    resetForm2(valueOriginal2, '#btn-main-subir-foto')
                }, 3000);
            }
    
        },
        error: function (jqXHR, estado, error) {
            
        },
        complete: function (jqXHR, estado) {

        }
    });
}

const enviarFile = (file, e) => {
    formulario2 = 'form-todos-dibujan';
        
    if(validateRequired2('#' + formulario2)){
      creaBase64(e)
    }
}

$(document).ready(function () {
    
    $('[data-correo-todosDibujan]').on('click', function(e){
        e.preventDefault();
        enviarFile()
    });
});



function validateRequired2(f) {
    var error = false;
    var mesaje = new Array();
    var msj = ''; 
    var name;
    var texto;
    var id;
    htmlData2 = '';
    $(f).find('input').each(function () {
        name = $(this)[0].name;
        type = $(this)[0].type;
        texto = $(this)[0].getAttribute('data-texto');
        id = '#' + name;
        switch(type) {
            case 'text':
                msj = validaVacio2(id, texto);
                if(msj != ''){
                    mesaje.push(msj);  
                    htmlData2 = ''                  
                    error = true;
                    msj = '';
                }else{
                    htmlData2 += '<b>' + texto + '</b>: ' + $(id).val() + '<br>';
                }
                
              break;
            case 'email':
                msj = validaVacio2(id, texto);
                if(msj != ''){
                    mesaje.push(msj);
                    error = true;
                    msj = '';
                }else{
                    msj = validarEmail2($(id).val(), id);
                    if(msj != ''){
                        mesaje.push(msj);
                        error = true;
                        msj = '';
                    }else{
                        htmlData2 += '<b>' + texto + '</b>: ' + $(id).val() + '<br>';
                    }
                }
                
                break;
            case 'file':
                nameFile2 = 'imagen.' + $(this).val().split('.')[($(this).val().split('.').length - 1)]

                msj = validaVacio2(id, texto);
                if(msj != ''){
                    mesaje.push(msj);  
                    // htmlData2 = ''                  
                    error = true;
                    msj = '';
                }else{
                    // htmlData2 += '<b>' + texto + '</b>: ' + $(id).val() + '<br>';
                    file = this
                }
                
              break;
        }

    });


    return !error;
}


function printErrorsAjax2(mensaje, btn){
    try{
        $(btn).removeClass('exito');
        $(btn).removeClass('enviando');
        $(btn).addClass('error');
        $($(btn)[0].children[1]).empty();
        $($(btn)[0].children[1]).append(mensaje);
    }catch(e){
       
    }

}
function resetForm2(mensaje, btn){
    try{
        $(btn).removeClass('error');
        $(btn).removeClass('exito');
        $(btn).removeClass('enviando');
        $($(btn)[0].children[1]).empty();
        $($(btn)[0].children[1]).append(mensaje);
    }catch(e){
       
    }

}
function enviando2(mensaje, btn){
    try{
        $(btn).removeClass('error');
        $(btn).removeClass('exito');
        $(btn).addClass('enviando');
        $($(btn)[0].children[1]).empty();
        $($(btn)[0].children[1]).append(mensaje);
    }catch(e){
       
    }

}
function enviado2(mensaje, btn){
    try{
        $(btn).removeClass('error');
        $(btn).removeClass('enviando');
        $(btn).addClass('exito');
        $($(btn)[0].children[1]).empty();
        $($(btn)[0].children[1]).append(mensaje);
    }catch(e){
       
    }

}

function validaVacio2(id, name){
    if($(id).val() != ''){
        return '';
    }else{
        $(id).parent().addClass('error');
        if($(id).attr("type") == 'file'){
            $($(id).parent()[0].children[1].children[0]).empty()
            $(id).parent()[0].children[1].children[0].append($(id).attr('data-texto') + ' requerido *')
        }else{
            $($(id).parent()[0].children[1]).empty()
            $(id).parent()[0].children[1].append($(id).attr('data-texto') + ' requerido *')
        }
        // $(id).attr('placeholder', 'Empty field !');
        return 'error';
       
    }

}

function validarEmail2(valor, name) {
    if (/^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i.test(valor)) {
        message2 = '';
        return '';
    } else {
        // console.log(name)
        $(name).parent().addClass('error');
        $($(name).parent()[0].children[1]).empty()
        $(name).parent()[0].children[1].append($(name).attr('data-texto') + ' invalido!')
        message2 = 'The email used is not valid';
        return 'The email used is not valid';
    }
}









'use strict';

;( function ( document, window, index )
{
	var inputs = document.querySelectorAll( '.inputfile' );
	Array.prototype.forEach.call( inputs, function( input )
	{
		var label	 = input.nextElementSibling,
			labelVal = label.innerHTML;

		input.addEventListener( 'change', function( e )
		{
            cambiaText(e, label, labelVal)
		});

		// Firefox bug fix
		input.addEventListener( 'focus', function(){ input.classList.add( 'has-focus' ); });
		input.addEventListener( 'blur', function(){ input.classList.remove( 'has-focus' ); });
	});
}( document, window, 0 ));

function cambiaText(e, label, labelVal) {
    var fileName = '';
    if( this.files && this.files.length > 1 )
        fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
    else
        fileName = e.target.value.split( '\\' ).pop();

    if( fileName )
        label.querySelector( 'span' ).innerHTML = fileName;
    else
        label.innerHTML = labelVal;
}
function cambiaText2(e, label, labelVal) {
    var fileName = '';
    if( this.files && this.files.length > 1 )
        fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
    else
        fileName = e.value.split( '\\' ).pop();

    if( fileName )
        label.querySelector( 'span' ).innerHTML = fileName;
    else
        label.innerHTML = labelVal;
}

var dropzone = $('#dropzone')


dropzone.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {
    e.preventDefault();
    e.stopPropagation();
  })

dropzone.on('dragover dragenter', function() {
    $(this).addClass('is-dragover');
  })
dropzone.on('dragleave dragend drop', function() {
    $(this).removeClass('is-dragover');
  })  
  
dropzone.on('drop',function(e) {
	var files = e.originalEvent.dataTransfer.files;
	// Now select your file upload field 
	$('#imgSubir').prop('files',files)

    let input = document.getElementById('imgSubir');
    var label = input.nextElementSibling,
    labelVal = label.innerHTML;
    cambiaText2($(input)[0], label, labelVal);
});