$(document).ready(function(){

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

});

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

  $("#iconeGabarito").fileinput({
    overwriteInitial: false,
    initialPreviewFileType: 'image', 
   'showUpload':false, 
    language: "pt-BR",
    allowedFileExtensions: ["pdf", "doc", "docx", "ppt", "pptx", "xls", "png", "jpg"],
    maxFilePreviewSize: 10240
  });

}//initPage

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


function initTable(tableAt, tableIn) {

  tableAt = 
  $('#datatable-gab-active').DataTable( {
    //serverSide: false,
    processing: true,
    responsive: true,
    ajax: {
        url: 'manter.php',
        type: "POST",
        data : {
            acao : "manterSimuGabarito",
            tipoAcao: "listarAll",
            status: true
        },
        dataSrc: ''
    },
    columns: [
            { data: "gabarito_titulo"  },
            { 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='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-gab-inactive').DataTable( {
    //serverSide: false,
    processing: true,
    responsive: true,
    ajax: {
        url: 'manter.php',
        type: "POST",
        data : {
            acao : "manterSimuGabarito",
            tipoAcao: "listarAll",
            status: false
        },
        dataSrc: ''
    },
    columns: [
            { data: "gabarito_titulo"  },
            { 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='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-gab-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 'desativar':
          enabDisabled(data.gabarito_id, tableAt, tableIn, 'I');
          break;
      case 'excluir':
          trash(data.gabarito_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-gab-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.gabarito_id, tableAt, tableIn, 'A');
          break;
      case 'excluir':
          trash(data.gabarito_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(formData, tableAt, tableIn);
    return false;
  });//CreateForm

  $('#formAtualizar').submit(function(){
    //var json = jQuery(this).serialize();
    var formData = new FormData(this);
    var status = $("#statusAt").val();
    if (status == '1') {
      submitUp(formData, tableAt);
    }if (status == '0') {
      submitUp(formData, 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(formData, table1, table2) {
  $('#loadPublicacao').show();
  var acao = 'manterSimuGabarito';
  var tipoAcao = 'adicionar';             
  $.ajax({
    url:"manter.php",                    
    type:"post",                            
    data: formData,
    cache: false,
    contentType: false,
    processData: false,
    success: function (result){             
      if(result==1){                      
        $('#loadPublicacao').hide();
        $("#msg-success").html("<strong id='msg-success'>Gabarito Cadastrado</strong>");
        $('#alertaSucesso').show();
        table1.ajax.reload();
        table2.ajax.reload();
        resetForm('formCadastrar');
        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);                   
      }  
    }//success
  });//ajax
  return false;
}//cadastrar

function updateObj(obj) {
  $('#loadPublicacao').show();
  $('#submitGif').hide();
  $('#retornoAt').hide();
  $("#reloadAt").val('0');
  $("#idAt").val(obj.gabarito_id);

  var extensao = obj.gabarito_file.split(".");
  var exts = extensao[extensao.length - 1];
  var ext = '';

  ext = (exts == 'png' || exts == 'jpg') ? 'image' : 
        (exts == 'pdf') ? 'pdf' : 'office';
  
  $("#office").hide();
  console.log(exts);
  console.log(ext);

  if (ext == 'office') {
      
      $("#iconeGabaritoAt").fileinput('refresh',{
        overwriteInitial: true,
        initialPreviewFileType: 'image', 
       'showUpload':false, 
        language: "pt-BR",
        allowedFileExtensions: ["pdf", "doc", "docx", "ppt", "pptx", "xls", "png", "jpg"],
        maxFilePreviewSize: 10240
      });
    
      $("button.fileinput-remove").trigger('click');
      var download = "<a href='../_files/gabaritos/"+obj.gabarito_file+"' download>Clique aqui para o Download </a>";

      $("#office").show();
      $("#office").html("<p id='office'> A visualização de arquivos desta extensão não é possível,<br>"+download+"</p>");
  }else{

    $("#iconeGabaritoAt").fileinput('refresh',{
      initialPreviewAsData: true, 
      initialPreview: [
            "../_files/gabaritos/"+obj.gabarito_file
            ],
          initialPreviewConfig: [
                            {
                              type: ext,
                              caption: "Arquivo", 
                              //size: 827000, width: "100px", 
                              key: 1
                            }
            ],
      overwriteInitial: true,
      initialPreviewFileType: ext, 
      'showDownload': true,
      'showUpload':false, 
      language: "pt-BR",
      allowedFileExtensions: ["pdf", "doc", "docx", "ppt", "pptx", "xls", "png", "jpg"],
      maxFilePreviewSize: 10240
    });
  }

  $("#idTipoAt").val(obj.gabarito_tipo);
  $("#statusAt").val(obj.gabarito_visibilidade);
  $("#nomeAt").val(obj.gabarito_titulo);
  $("#dataAt").val(obj.gabarito_date);
  $("#myModalAtualizar").modal({backdrop: false});
  $('#loadPublicacao').hide();
}//updateObj

function submitUp(formData) {
  $('#submitGif').show();
  $('#retornoAt').hide();
  $.ajax({
    url:"manter.php",                    
    type:"post",                            
    data: formData,
    cache: false,
    contentType: false,
    processData: false,

    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>");
      }
      return false;
    }//success
  });//ajax
}//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 = 'manterSimuGabarito';
        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 este gabarito?</h3>",
    buttons: {
      confirm: {
        label: 'Sim!',
        className: 'btn-success'
      },
      cancel: {
        label: 'Cancelar!',
        className: 'btn-danger'
      }
    },
    callback: function (confirma) {
      if (confirma == true) {
        $('#loadPublicacao').show();
        var acao = 'manterSimuGabarito';
        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'>Gabarito excluido!</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
