$(document).ready(function(){

  var tableAt;
  var tableIn;
  initPage();
  initTable(tableAt, tableIn);

});

function initPage() {
  $(":input").inputmask();
  $('#loadPublicacao').hide();
  $('#btmCancelar').click(function(){
    resetForm('formCadastrar');
  }); 
}//initPage

function resetForm(form) {
  $('#'+form).each(function(){
    this.reset(); 
  });
}//ResetForm

function initTable(tableAt, tableIn) {
  tableAt = 
  $('#datatable-user-active').DataTable( {
    //serverSide: false,
    processing: true,
    responsive: true,
    ajax: {
        url: 'manter.php',
        type: "POST",
        data : {
            acao : "manterUsuario",
            tipoAcao: "listarAll",
            nivel: "1",
            status: true
        },
        dataSrc: ''
    },
    columns: [
            { data: "user_nome" },
            { data: "user_email" },
            { data: "user_cpf" },
            { data: "data_formatada" },
            { 
              //data: "id_admin", 
              defaultContent: "<button type='button' class='btn btn-success' id='atualizar' title='Atualizar'><span class='fa fa-pencil'></button>&nbsp;"+
                              "<button type='button' class='btn btn-danger' id='desativar' title='Desativar'><span class='fa fa-ban'></button>"
            }
        ],
    fixedHeader: true,
    "language": {
      "lengthMenu": "Exibir _MENU_ por página",
      "zeroRecords": "Nada encontrado, desculpe.",
      "processing": "Processando...",
      "info": "Exibindo página _PAGE_ de _PAGES_",
      "infoEmpty": "Nenhum registro disponível",
      "infoFiltered": "(Filtrado de _MAX_ registros totais)",
      "search": "Buscar: ",
      "paginate": {
        "first":      "Primeiro",
        "last":       "Último",
        "next":       "Prox",
        "previous":   "Anterior"
      }
    }
  });//DataTable-active

  tableIn =
  $('#datatable-user-inactive').DataTable( {
    //serverSide: false,
    processing: true,
    responsive: true,
    ajax: {
        url: 'manter.php',
        type: "POST",
        data : {
            acao : "manterUsuario",
            tipoAcao: "listarAll",
            nivel: "0",
            status: false
        },
        dataSrc: ''
    },
    columns: [
            { data: "user_nome" },
            { data: "user_email" },
            { data: "user_cpf" },
            { data: "data_formatada" },
            { 
              //data: "id_admin", 
              defaultContent: "<button type='button' class='btn btn-success' id='atualizar' title='Atualizar'><span class='fa fa-pencil'></button>&nbsp;"+
                              "<button type='button' class='btn btn-warning' id='ativar' title='Ativar'><span class='fa fa-check'></button>"
            }
        ],
    fixedHeader: true,
    "language": {
      "lengthMenu": "Exibir _MENU_ por página",
      "zeroRecords": "Nada encontrado, desculpe.",
      "processing": "Processando...",
      "info": "Exibindo página _PAGE_ de _PAGES_",
      "infoEmpty": "Nenhum registro disponível",
      "infoFiltered": "(Filtrado de _MAX_ registros totais)",
      "search": "Buscar: ",
      "paginate": {
        "first":      "Primeiro",
        "last":       "Último",
        "next":       "Prox",
        "previous":   "Anterior"
      }
    }
  });//DataTable-active

  $('#datatable-user-active tbody').on( 'click', 'button', function () {
    var data = tableAt.row( $(this).parents('tr') ).data();
    var idClick = $(this).attr('id');
    switch(idClick) {
      case 'atualizar':
          updateObj(data);
          break;
      case 'desativar':
          enabDisabled(data.user_id, tableAt, tableIn, 'I');
          break;
      default:
          $('#alertaErro').show();
            setTimeout(function() {
            $('#alertaErro').hide();
          }, 1000);  
    }
    //console.log(data);
    //alert(data.id_admin);
    //table.fnClearTable();//table.clear().draw();
  });//onClick

  $('#datatable-user-inactive tbody').on( 'click', 'button', function () {
    var data = tableIn.row( $(this).parents('tr') ).data();
    var idClick = $(this).attr('id');
    switch(idClick) {
      case 'atualizar':
          updateObj(data);
          break;
      case 'ativar':
          enabDisabled(data.user_id, tableAt, tableIn, 'A');
          break;
      default:
          $('#alertaErro').show();
            setTimeout(function() {
            $('#alertaErro').hide();
          }, 1000);  
    }
    //console.log(data);
    //alert(data.id_admin);
    //table.fnClearTable();//table.clear().draw();
  });//onClick

  $('#formCadastrar').submit(function(){  
    var json = jQuery(this).serialize();
    cadastrar(json, tableAt);
    return false;
  });//CreateForm

  $('#formAtualizar').submit(function(){
    var json = jQuery(this).serialize();
    var status = $("#statusAt").val();
    if (status == '1') {
      submitUp(json, tableAt);
    }if (status == '0') {
      submitUp(json, tableIn);
    }
    return false;
  });//Update Form

  $("button.close").click(function(){
    //$('#datatable-cond-active').DataTable().ajax.reload();
    var status = $("#statusAt").val();
    var reload = $("#reloadAt").val();

    if (status == '1' && reload == 1) {
      tableAt.ajax.reload();
    }if (status == '0' && reload == 1) {
      tableIn.ajax.reload();
    }
  });
}//initTable

function cadastrar(json, table) {
  $('#loadPublicacao').show();
  var acao = 'manterUsuario';
  var tipoAcao = 'adicionar';             
  $.ajax({
    url:"manter.php",                    
    type:"post",                            
    data: json+"&acao="+acao+"&tipoAcao="+tipoAcao,
    success: function (result){             
      if(result==1){                      
        $('#loadPublicacao').hide();
        table.ajax.reload();
        resetForm('formCadastrar');
        
        $("#msg-success").html("<strong id='msg-success'>Usuário Cadastrado</strong>");
        $('#alertaSucesso').show();

        setTimeout(function() {
          $('#alertaSucesso').hide();
        }, 2000);
      
      }if(result != 1){
        $('#loadPublicacao').hide();
        $('#alertaErro').show();
        setTimeout(function() {
          $('#alertaErro').hide();
        }, 2000);                 
      }  
    }//success
  });//ajax
}//cadastrar

function updateObj(obj) {
  $("#reloadAt").val('0');
  $("#idAt").val(obj.user_id);
  $("#statusAt").val(obj.user_status);
  $("#nomeAt").val(obj.user_nome);
  $("#emailAt").val(obj.user_email);
  $("#cpfAt").val(obj.user_cpf);
  $("#dataAt").val(obj.user_date_nasc);

  $("button#btnAtualizar").prop('disabled', false);
  $("#myModalAtualizar").modal({backdrop: false});
  $('#submitGif').hide();
  $('#retornoAt').hide();
}//updateObj

function submitUp(json) {
  $('#submitGif').show();
  $('#retornoAt').hide();
  var acao = 'manterUsuario';
  var tipoAcao = 'editar';
  $.ajax({
    type: "POST",
    url: "manter.php",
    data: json+"&acao="+acao+"&tipoAcao="+tipoAcao,
    success: function(result)
    {
      if(result==1){
        $('#submitGif').hide();
        $('#retornoAt').show();
        $("#reloadAt").val('1');
        $('#retornoAt').addClass('animated shake');                     
        $("#retornoAt").html("<p class='text-center'>Informações atualizadas!</p>");
        
      }if (result !=1){
        $('#submitGif').hide();
        $('#retornoAt').show();
        $('#retornoAt').addClass('animated shake');                     
        $("#retornoAt").html("<p class='text-center'>"+ result+ "</p>");
      }
    }
  })
}//submitUp

function enabDisabled(idDelete, tableAt, tableIn, status) {
  if (status == 'A') {
    stName = "ativar";
  }if (status == 'I') {
    stName = "inativar";
  }
  bootbox.confirm({
    message: "<h3 class='text-center'>Deseja "+stName+" este Usuário?</h3>",
    buttons: {
      confirm: {
        label: 'Sim!',
        className: 'btn-success'
      },
      cancel: {
        label: 'Cancelar!',
        className: 'btn-danger'
      }
    },
    callback: function (confirma) {
      if (confirma == true) {
        $('#loadPublicacao').show();
        var acao = 'manterUsuario';
        var tipoAcao = 'enabDisabled'; 
        $.ajax({
          url:"manter.php",                    
          type:"post",                            
          data: "Id_Del="+idDelete+"&acao="+acao+"&tipoAcao="+tipoAcao+"&status="+status,
          success: function (result){ 
            if (result == 1) {
              $('#loadPublicacao').hide();
              $("#msg-info").html("<strong id='msg-info'>Status atualizado!</strong>");
              $('#alertaInfo').show();
              tableAt.ajax.reload();
              tableIn.ajax.reload();
              setTimeout(function() {
                $('#alertaInfo').hide();
              }, 3000);   
            }if (result !=1){
              $('#loadPublicacao').hide();
              $('#alertaErro').show();
              $("#msg-erro").html("<strong id='msg-erro'>Ocorreu um erro!</strong>");
              setTimeout(function() {
                $('#alertaErro').hide();
              }, 2000);                   
            }
          }
        });
      }else{

      }
    }//callback
  });//bootbox
}//delUser
