$(document).ready(function(){

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

});

function initPage() {
  $('#loadPublicacao').hide();
  $('#btmCancelar').click(function(){
    resetForm('formCadastrar');
  }); 

}//initPage

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


function initTable(tableAt, tableIn) {
  var teste = "ok";
  tableAt = 
  $('#datatable-galeria-active').DataTable( {
    //serverSide: false,
    processing: true,
    responsive: true,
    ajax: {
        url: 'manter.php',
        type: "POST",
        data : {
            acao : "manterGaleria",
            tipoAcao: "listarAll",
            status: true
        },
        dataSrc: ''
    },
    columns: [
            { data: "gal_nome"  },
            { 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-info' id='acessar' title='Acessar'><span class='fa fa-folder-open-o'></button>&nbsp;"+
                              "<button type='button' class='btn btn-warning' id='desativar' title='Tornar público'><span class='fa fa-product-hunt'></button>&nbsp;"+
                              "<button type='button' class='btn btn-danger' id='excluir' title='Excluir'><span class='fa fa-trash-o'></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-galeria-inactive').DataTable( {
    //serverSide: false,
    processing: true,
    responsive: true,
    ajax: {
        url: 'manter.php',
        type: "POST",
        data : {
            acao : "manterGaleria",
            tipoAcao: "listarAll",
            status: false
        },
        dataSrc: ''
    },
    columns: [
            { data: "gal_nome"  },
            { 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-info' id='acessar' title='Acessar'><span class='fa fa-folder-open-o'></button>&nbsp;"+
                              "<button type='button' class='btn btn-warning' id='ativar' title='Tornar privado'><span class='fa fa-product-hunt'></button>&nbsp;"+
                              "<button type='button' class='btn btn-danger' id='excluir' title='Excluir'><span class='fa fa-trash-o'></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-galeria-active tbody').on( 'click', 'button', function () {
    var data = tableAt.row( $(this).parents('tr') ).data();
    var idClick = $(this).attr('id');
    switch(idClick) {
      case 'atualizar':
          resetForm('formAtualizar');
          updateObj(data);
          break;
      case 'acessar':
          location.href='galerias-in.php?gal='+data.gal_id+'&n='+data.gal_nome;
          break;
      case 'desativar':
          enabDisabled(data.gal_id, tableAt, tableIn, 'I');
          break;
      case 'excluir':
          trash(data.gal_id, tableAt);
          break;
      default:
        $("#msg-erro").html("<strong id='msg-erro'>Opção não informada!</strong>");
        $('#alertaErro').show();
        setTimeout(function() {
          $('#alertaErro').hide();
        }, 2000);  
    }
    //console.log(data);
    //alert(data.id_admin);
    //table.fnClearTable();//table.clear().draw();
  });//onClick

  $('#datatable-galeria-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 'acessar':
          location.href='galerias-in.php?gal='+data.gal_id+'&n='+data.gal_nome;
          break;
      case 'ativar':
          enabDisabled(data.gal_id, tableAt, tableIn, 'A');
          break;
      case 'excluir':
          trash(data.gal_id, tableIn);
          break;
      default:
        $("#msg-erro").html("<strong id='msg-erro'>Opção não informada!</strong>");
        $('#alertaErro').show();
        setTimeout(function() {
          $('#alertaErro').hide();
        }, 2000);   
    }
    //console.log(data);
    //alert(data.id_admin);
    //table.fnClearTable();//table.clear().draw();
  });//onClick

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

  $('#formAtualizar').submit(function(){
    //alert('teste');
    var json = jQuery(this).serialize();
    //var formData = new FormData(this);
    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, table1, table2) {
  $('#loadPublicacao').show();
  var acao = 'manterGaleria';
  var tipoAcao = 'adicionar';             
  $.ajax({
    url:"manter.php",                    
    type:"post",                            
    data: json+"&acao="+acao+"&tipoAcao="+tipoAcao,
    success: function (result){             
      if(result==1){                      
        $('#loadPublicacao').hide();
        table1.ajax.reload();
        table2.ajax.reload();
        resetForm('formCadastrar');
        
        $("#msg-success").html("<strong id='msg-success'>Galeria Cadastrada</strong>");
        $('#alertaSucesso').show();

        setTimeout(function() {
          $('#alertaSucesso').hide();
        }, 2000);
      
      }if(result != 1){
        $('#loadPublicacao').hide();
        $("#msg-erro").html("<strong id='msg-erro'>Ocorreu um erro: "+result+"</strong>");
        $('#alertaErro').show();
        setTimeout(function() {
          $('#alertaErro').hide();
        }, 2000);                   
      }  
      return false;

    }//success
  });//ajax
}//cadastrar

function updateObj(obj) {
  $("#reloadAt").val('0');
  $("#idAt").val(obj.gal_id);
  $("#statusAt").val(obj.gal_visibilidade);
  $("#nomeAt").val(obj.gal_nome);
  $("#dataAt").val(obj.gal_date);

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

function submitUp(json) {
  $('#submitGif').show();
  $('#retornoAt').hide();
  var acao = 'manterGaleria';
  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 = "privado?";
  }if (status == 'I') {
    stName = "público?";
  }
  bootbox.confirm({
    message: "<h3 class='text-center'>Deseja mudar o status para "+stName+"</h3>",
    buttons: {
      confirm: {
        label: 'Sim!',
        className: 'btn-success'
      },
      cancel: {
        label: 'Cancelar!',
        className: 'btn-danger'
      }
    },
    callback: function (confirma) {
      if (confirma == true) {
        $('#loadPublicacao').show();
        var acao = 'manterGaleria';
        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();
              }, 2000);   
            }if (result !=1){
              $('#loadPublicacao').hide();
              $("#msg-erro").html("<strong id='msg-erro'>Ocorreu um erro: "+result+"</strong>");
              $('#alertaErro').show();
              setTimeout(function() {
                $('#alertaErro').hide();
              }, 2000);                     
            }
          }
        });
      }else{

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

function trash(idDelete, table) {
  bootbox.confirm({
    message: "<h3 class='text-center'>Deseja excluir esta Galeria?</h3>",
    buttons: {
      confirm: {
        label: 'Sim!',
        className: 'btn-success'
      },
      cancel: {
        label: 'Cancelar!',
        className: 'btn-danger'
      }
    },
    callback: function (confirma) {
      if (confirma == true) {
        $('#loadPublicacao').show();
        var acao = 'manterGaleria';
        var tipoAcao = 'trash'; 
        $.ajax({
          url:"manter.php",                    
          type:"post",                            
          data: "Id_Del="+idDelete+"&acao="+acao+"&tipoAcao="+tipoAcao,
          success: function (result){ 
            if (result == 1) {
              $('#loadPublicacao').hide();
              $("#msg-info").html("<strong id='msg-info'>Galeria excluida!</strong>");
              $('#alertaInfo').show();
              table.ajax.reload();
              setTimeout(function() {
                $('#alertaInfo').hide();
              }, 2000);   
            }if (result !=1){
              $('#loadPublicacao').hide();
              $("#msg-erro").html("<strong id='msg-erro'>Ocorreu um erro: "+result+"</strong>");
              $('#alertaErro').show();
              setTimeout(function() {
                $('#alertaErro').hide();
              }, 2000);                     
            }
          }
        });
      }else{

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