//tira os files do input e joga num temporário
var tmp_files = new Array();

//document.getElementById("result").innerHTML = ""


//arrastar e sontar na div
var obj = $("#result");
obj.on('dragenter', function (e) 
{
    e.stopPropagation();
    e.preventDefault();
    $(this).css('border', '2px solid #0B85A1');
});
obj.on('dragover', function (e) 
{
     e.stopPropagation();
     e.preventDefault();
});
obj.on('drop', function (e) 
{
 
     $(this).css('border', '2px dotted #0B85A1');
     e.preventDefault();
     var files = e.originalEvent.dataTransfer.files;
 
     //We need to send dropped files to Server
     handleFileUpload(files,obj);
});

function handleFileUpload(files,obj)
{
	adicionaFilesUploads(files);
}
///


 $(document).ready(function(){
    $('.add_more').click(function(e){
        e.preventDefault();
        $(".upload_file").before("<input type='file' name='file[]'  multiple/><br>");
    });
});


$("#imp_arquivo").on("change",'#selecao-arquivo', function(){
	//alert($('#selecao-arquivo').length)
    files = this.files;
	multiplos = true;
	remover = true;
	if ($('.label_img').length > 0) {
		if($(".label_img").attr("multiplos")) {
			if($(".label_img").attr("multiplos") == "false")
			{
				multiplos = false;
			}
		 }
		if($(".label_img").attr("remover")) {
			if($(".label_img").attr("remover") == "false")
			{
				remover = false;
			}
		 }
	}	 
     adicionaFilesUploads(files, multiplos, remover);
	 //$( "#selecao-arquivo" ).remove();
	 $("#selecao-arquivo").val(null);
	 //$("#imp_arquivo").html('<input type="file" name="file[]" style=" display: none" id="selecao-arquivo" multiple />');	
	
});
cont = 0;
function adicionaFilesUploads(files, multiplos, remover)
{
	var names = "";
	//alert(files.length)
	if(! multiplos)
	{
		tmp_files = new Array();
		$("#item0").remove();
		$("#itemBd0").remove();
		$("#result").html();
		cont = 0;
	}
	   for (var i = 0; i < files.length; i++) 
	   {
			file = files[i];
			tmp_files.push([file,cont,false])
			names += file.name + "<br/>";
			//alert(file.name+" ")
			extensao = (file.name.substring(file.name.lastIndexOf("."))).toLowerCase(); 
			nome = (file.name.substring(0,file.name.lastIndexOf("."))).toLowerCase();
			if (validaExtensao( extensao))
			{	  
					strRemover = "";
					if(remover)
					{
						strRemover = "<a href='javascript:void(0);' onclick=\"removerFilesUploads('"+cont+"')\">Remover</a>";
					}
				   $("#result").append("<div id='item"+cont+"' style='float: left; height: 100px;  text-align: center; color: #999999; margin: 10px; overflow:hidden '><img id='preview"+nome+"' style='height: 80px'/>"+strRemover+"<br><div style='max-width: 150px;'>"+file.name+"</div></div>");
					document.getElementById('preview'+nome).src = URL.createObjectURL(file)//e.target.result;
				  
			}
			else
			{
				strRemover = "";
				if(remover)
				{
					strRemover = "<a href='javascript:void(0);' onclick=\"removerFilesUploads('"+cont+"')\">Remover</a>";
				}
				$("#result").append("<div id='item"+cont+"' style='float: left; height: 100px; text-align: center; color: #999999; margin: 10px; overflow:hidden '><i style='font-size: 80px; color: #999999;' class='"+extensoes_icon(extensao)+"'></i>"+strRemover+"<br><div style='max-width: 150px;'>"+file.name+"</div></div>")
			}
			$("#remover").css('display', 'none');
		    cont += 1;   
	 
	   }
}
function removerFilesUploads(id)
{
	//alert(fileName)
	$.each(tmp_files, function(i, file)
	{
		//alert(file.name)
		//var file = fileSelect.files[0]
		//formData.append("file[]", file , file.name);//name file tye
		if(file[1] == id)
		{
			$("#item"+id).remove();
			tmp_files.splice(i, 1); 
			return true;
		}
	});
	return false;
}	
  
 function doSubmit(fechar_modal = "", form_filtro ="", resultado_filtro ="")
 {
    // Form Data
    var formData = new FormData();

	$.each(tmp_files, function(i, file)
	{
		//alert(file.name)
		//var file = fileSelect.files[0]
		formData.append("file[]", file[0] , file[0].name);//name file tye
	});
	$(".file_padrao_html").each(function(){
		//alert(this.name)
		if(this.files.length > 0)
		{	
			formData.append(this.name, this.files[0], this.files[0].name);//name file tye
		}	
	});
	$(".upload_file *").each(function(){
		if($(this).attr("name")) {
			formData.append($(this).attr("name"),$(this).val())
		}	
		if($(this).attr("editor")) {
			//alert($(this).html())
			formData.append($(this).attr("editor"),CKEDITOR.instances.editor.getData())
		}
	});
    //var input1 = document.getElementById("body");
    // formData.append("body", input1.value)
    // Http Request  
    var request = new XMLHttpRequest();
	
	//retorno
	$(".modal").css("z-index:","0");
	$( "body" ).append( "<div id='bloquear_pagina' style='position: fixed; width: 100%; height: 100%;  z-index:99999; top:0; left: 0;'></div>" );
	statusInicioRequisicao();
	request.onreadystatechange = function() {
	if (request.readyState === 4) {
		 objRet = JSON.parse(request.response);
		 $( "#bloquear_pagina" ).remove();
		 
		 $(".modal").css("z-index:","99999");
		 statusFimRequisicao();
		 alert(objRet.mensagem)
		 if(objRet.mensagem.toLowerCase().includes("sucesso") || objRet.mensagem.toLowerCase().includes("successfully"))
		 {
				//fechar modal
				if(fechar_modal != "")
				{
					$(fechar_modal).css("display","none");
				}
				//atualizar lista
				if(form_filtro != "")
				{	
					filtraDados(form_filtro, resultado_filtro);
				}	
		 }
		}
	  }
  
    request.open('POST', $(".upload_file").attr("controller"));
    request.send(formData);
  }

  
/*
$(".upload_file").submit(function(e){
	
	
    // prevent the form from submitting
    e.preventDefault();
    $.ajax({
        url: 'upload.php',
        type: 'POST',
        contentType:false,
        processData: false,
        // pass the form in the FormData constructor to send all the data inside the form
        data: new FormData(this),
        success: function(result) {
            alert(result);
        },
        error: function(xhr, result, errorThrown){
            alert('Request failed.');
        }
    });
    //$('#picture').val('');
    //$('#body').val('');
});
*/


function validaExtensao(extensao)
{
	extensoes_imagem = new Array(".gif", ".jpg", ".png", ".jpeg"); 
	permitida = false; 
    for (var i = 0; i < extensoes_imagem.length; i++) { 
       if (extensoes_imagem[i].toLowerCase() == extensao.toLowerCase()) { 
		return true;
       } 
    } 
	return false;
}
function extensoes_icon(extensao)
{
	extensoes = new Array(
	['.pdf','fa fa-file-pdf-o'],
	['.docx','fa fa-file-text-o'],
	['.txt','fa fa-file-text-o'],
	['.doc','fa fa-file-text-o'],
	['.mp4','fa fa-file-video-o'],
	['.avi','fa fa-file-video-o'])
	for (var i = 0; i < extensoes.length; i++) { 
		if(extensoes[i][0].toLowerCase() == extensao.toLowerCase())
		{
			return extensoes[i][1];
		}
	}
	return "far fa-file";
}

function removerFilesUploadsBd(seletor, dir)
{
	if(confirm('Deseja realmente apagar do servidor?'))
	{	
		aLik = $(".upload_file").attr("controller").split("?");
		$.post(aLik[0]+"?mod=excluir_file",{file: dir});
		$("#itemBd"+seletor).remove();
	}	
}