$('.datepicker').datepicker({
	format: 'dd/mm/yyyy',
	endDate: '0d',
	autoclose: true,
	language: 'pt-BR'
});

$('.datepicker').mask('00/00/0000');

$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
$('#tabelaArquivos').html('<table id="tbArquivos" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
$('#tbArquivos').dataTable({
	"data": [],
	"order": [[ 3, 'desc' ]],
	"columns": [{"title": "Nome"}, {"title": "Login"},{"title": "Último Login"}, {"title": "Data de Criação"}, ,{"title": "Opções"}, {"title": "Link do Drive"}],
	"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
	responsive: true,
	"columnDefs": [{"targets": 4, "orderable": false}]
});

function modal_editar(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modal_editar_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modal_editar_2(id);
	}
}

function modal_editar_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_usuario_arquivos",
			data: {'id' : id},
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				$('#modal-sistema-conteudo').html(data);
				$('#modal-sistema').modal();
			},
			beforeSend: function(){
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao abrir modal."); return;
			}
		});
	});
}

function modal_confirmacao(id){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modal_confirmacao_2(id);
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modal_confirmacao_2(id);
	}
}

function modal_confirmacao_2(id){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_usuario_arquivos_deletar",
			data: {'id' : id},
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				$('#modal-confirmacao-conteudo').html(data);
				$('#modal-confirmacao').modal();
			},
			beforeSend: function(){
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao abrir modal."); return;
			}
		});
	});
}

function modalNovoCliente(){
	if($('.dtr-bs-modal').hasClass("in")){
		$('.dtr-bs-modal').one('hidden.bs.modal', function () {
			modalNovoCliente_2();
		});
		$('.dtr-bs-modal').modal('hide');
	}
	else{
		modalNovoCliente_2();
	}
}

function modalNovoCliente_2(){
	$(document).ready(function(){
		jQuery.ajax({
			type: "POST",
			url: "action/abrir_modal_novo_usuario_arquivos",
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				$('#modal-sistema-conteudo').html(data);
				$('#modal-sistema').modal();
			},
			beforeSend: function(){
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao abrir modal."); return;
			}
		});
	});
}

function fechar_modal(){
	$('#modal-sistema').modal('hide');
}

function fechar_modal_confirmacao(){
	$('#modal-confirmacao').modal('hide');
}

function atualizar_linha(json){
	var table = $('#tbArquivos').DataTable();
	var registro = json;
	var tableRow = table.row(".id"+registro.id);
	var rowData = tableRow.data();
	if (rowData == null){
		return;
	}
	rowData[1] = registro.nome;
	rowData[2] = registro.login;
	rowData[6] = "<a href='"+registro.link+"' target='_blank'>" + registro.link + "</a>";
	tableRow.data(rowData);
	tableRow.invalidate();
	table.draw(false);
}

function adicionar_linhas(json){
	var table = $('#tbArquivos').DataTable();
	var newRows = [];
	for (var i=0; i < json.length; i++){
		var date = Date.parse(json[i].data).toString('dd/MM/yyyy HH:mm:ss');
		var date2 = Date.parse(json[i].data2).toString('dd/MM/yyyy HH:mm:ss');
		var editar = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+json[i].id+")' class='btn btn-default text-orange' title='Clique para editar o cliente.'><i class='fa fa-edit'></i></a><a href= 'javascript:void(0);' onclick='modal_confirmacao("+json[i].id+")' class='btn btn-default text-red' title='Clique para deletar o cliente.'><i class='fa fa-trash'></i></a></div>";
		var dados = ["",json[i].nome, json[i].login, date, date2,editar, "<a href='"+json[i].link+"' target='_blank'>" + json[i].link + "</a>", json[i].id];
		newRows[i] = dados;
	}
	table.rows.add(newRows);
	table.draw(false);
}

function remover_cliente(id){
	var table = $('#tbArquivos').DataTable();
	var tableRow = table.row(".id"+id.toString());
	var rowData = tableRow.data();
	if (rowData == null){
		return;
	}
	tableRow.remove();
	table.draw(false);
}

function carregar_dados(){
	$(document).ready(function() {
		var dados = jQuery('#formArquivos').serialize();
		jQuery.ajax({
			type: "POST",
			url: "action/atualizar_arquivos",
			data: dados,
			success: function(data){
				$('.preloader').css({display:"none"});
				if(data == '-1') {window.location.href = "./"; return;}
				if(data.substring(0,2) == "-2") {toastr.clear(); toastr.error(data.substring(2)); return;}
				var json = JSON.parse(data);
				var table_data = [];
				for (var i=0; i < json.length; i++){
					var date = Date.parse(json[i].data).toString('dd/MM/yyyy HH:mm:ss');
					var date2 = Date.parse(json[i].data2).toString('dd/MM/yyyy HH:mm:ss');
					var editar = "<div class='btn-group'><a href= 'javascript:void(0);' onclick='modal_editar("+json[i].id+")' class='btn btn-default text-orange' title='Clique para editar o cliente.'><i class='fa fa-edit'></i></a><a href= 'javascript:void(0);' onclick='modal_confirmacao("+json[i].id+")' class='btn btn-default text-red' title='Clique para deletar o cliente.'><i class='fa fa-trash'></i></a></div>";
					table_data[i] = ["",json[i].nome, json[i].login, date, date2,editar, "<a href='"+json[i].link+"' target='_blank'>" + json[i].link + "</a>", json[i].id];
				}
				$(document).ready(function() {
					$.fn.dataTable.moment( 'DD/MM/YYYY HH:mm:ss');
					$('#tabelaArquivos').html('<table id="tbArquivos" style="width: 100%;" class="table table-striped table-bordered dataTable no-footer cell-border nowrap responsive compact"></table>');
					$('#tbArquivos').dataTable({
						"data": table_data,
						"order": [[ 4, 'desc' ]],
						"columns": [{},{"title": "Nome"}, {"title": "Login"},{"title": "Último Login"}, {"title": "Data de Criação"},{"title": "Opções", "className": "table-buttons"}, {"title": "Link do Drive"}],
						"lengthMenu": [[25, 50, 100, -1], ["25","50","100", "todas"]],
						responsive: {
						    details: {
						    	type: 'column',
						        display: $.fn.dataTable.Responsive.display.modal( {
						            header: function ( row ) {
						                return '<span style="margin-right: 10px"><b>Dados da Ligação</b></span>';
						            }
						        } ),
						        renderer: function ( api, rowIdx, columns ) {
						        	text = "";
						        	text += columns[4].data + "<br>";
						        	for(i = 0;i < columns.length;i++){
						        		column = columns[i];
						        		if(i == 4) { continue; }
						        		if(i > 0) text += "<br>";
						        		text += "<b>" + column.title + ": </b>" + column.data;
						        	}
						        	return text;
						        }
						    }
						},
						"deferRender": true,
						"columnDefs": [{"targets": 5, "orderable": false}, {className: 'control', orderable: false, targets: 0, width: "5%"}],
						"createdRow": function ( row, data, index ) {
							$(row).addClass("id"+data[7]);
						}
					});
				});
			},
			beforeSend: function(){
				$('.preloader').css({display:"block"});
			},
			complete: function(){
				$('.preloader').css({display:"none"});
			},
			error: function(){
				$('.preloader').css({display:"none"});
				toastr.clear(); toastr.error("Houve um erro ao atualizar"); return;
			}
		});
	});
}

function atualizar(){
	var valor = $('#data').val();
	if(valor == "CUSTOM_DATE")
		$('.datadiv').removeClass("hide");
	else{
		$('.datadiv').addClass("hide");
		carregar_dados();
	}
}

$(document).ready(function(){
	carregar_dados();
});

$('#data, #switch').change(function(){ atualizar(); });
$('#datapersonalizada').click(function(){
	carregar_dados();
});