var tipoUsuario = '<?php echo $_SESSION[\'UsuarioTipo\']?>';
if (tipoUsuario == "COORDENADOR" || tipoUsuario == "ACADEMICO") {
  var btn = +"<button type='button' class='btn btn-danger' id='del' title='Excluir'><span class='fa fa-ban'></button>";
}else{
  var btn = '';
}
$(document).ready(function(){

    var tableAt;
    var tableIn;
    initPage();
    initTable(tableAt, tableIn);
  
  });
  
  function initPage() {
    $('#loadPublicacao').hide();
    $('#btmCancelar').click(function(){
      resetForm('formCadastrar');
    }); 
  
    $("#iconeAula").fileinput({
      overwriteInitial: false,
      initialPreviewFileType: 'image', 
     'showUpload':false, 
      language: "pt-BR",
      allowedFileExtensions: ["pdf", "doc", "docx", "ppt", "pptx", "xls", "png", "jpg"],
      maxFilePreviewSize: 10240
    });
  
  }//initPage pdf, doc, docx, ppt, pptx, xls, xls, png e jpg.
  
  function resetForm(form) {
    $('#'+form).each(function(){
      this.reset(); 
    });
  }//ResetForm
  
  
  function initTable(tableAt, tableIn) {
    var teste = "ok";
    tableAt = 
    $('#datatable-aulas-active').DataTable( {
      //serverSide: false,
      processing: true,
      responsive: true,
      ajax: {
          url: 'manter.php',
          type: "POST",
          data : {
              acao : "manterAulas",
              tipoAcao: "listarAll",
              status: true,
              tipo: "A"
          },
          dataSrc: ''
      },
      columns: [
              { data: "aula_titulo"  },
              { data: "data_formatada"  },
              { 
                //data: "id_admin", 
                defaultContent: "<button type='button' class='btn btn-success' id='download' title='Download'><span class='fa fa-download'></button>"+
                "<button type='button' class='btn btn-danger' id='del' title='Excluir'><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-aulas-inactive').DataTable( {
      //serverSide: false,
      processing: true,
      responsive: true,
      ajax: {
          url: 'manter.php',
          type: "POST",
          data : {
              acao : "manterAulas",
              tipoAcao: "listarAll",
              status: false
          },
          dataSrc: ''
      },
      columns: [
              { data: "aula_titulo"  },
              { data: "data_formatada" },
              { 
                //data: "id_admin", 
                defaultContent: "<button type='button' class='btn btn-success' id='download' title='Download'><span class='fa fa-download'></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-aulas-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.aula_id, tableAt, tableIn, 'I');
            break;
        case 'del':
            Del(data.aula_id, tableAt, tableIn, 'I');
            break;
        case 'excluir':
            trash(data.aula_id, tableAt);
            break;
        case 'download':
            window.open('http://paivacursos.com.br/portal/system/_files/aulas/'+data.aula_file);
            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-aulas-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.aula_id, tableAt, tableIn, 'A');
            break;
        case 'excluir':
            trash(data.aula_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(){
      //alert('teste');
      //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 = 'manterAulas';
    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'>Aula Cadastrado</strong>");
          $('#alertaSucesso').show();
          table1.ajax.reload();
          table2.ajax.reload();
          resetForm('formCadastrar');
          setTimeout(function() {
            $('#alertaSucCateg').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 Del(idDelete, tableAt, tableIn, status) {
    if (status == 'A') {
      stName = "excluir";
    }if (status == 'I') {
      stName = "excluir";
    }
    bootbox.confirm({
      message: "<h3 class='text-center'>Deseja "+stName+" este arquivo?</h3>",
      buttons: {
        confirm: {
          label: 'Sim!',
          className: 'btn-success'
        },
        cancel: {
          label: 'Cancelar!',
          className: 'btn-danger'
        }
      },
      callback: function (confirma) {
        if (confirma == true) {
          $('#loadPublicacao').show();
          var acao = 'manterAulas';
          var tipoAcao = 'del'; 
          $.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
  function updateObj(obj) {
    $('#loadPublicacao').show();
    $('#submitGif').hide();
    $('#retornoAt').hide();
    $("#reloadAt").val('0');
    $("#idAt").val(obj.aula_id);
  
    var extensao = obj.aula_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') {
        
        $("#iconeAulaAt").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/aulas/"+obj.aula_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{
  
      $("#iconeAulaAt").fileinput('refresh',{
        initialPreviewAsData: true, 
        initialPreview: [
              "../_files/aulas/"+obj.aula_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
      });
  
    }
  
    $("#statusAt").val(obj.aula_visibilidade);
    $("#nomeAt").val(obj.aula_titulo);
    $("#dataAt").val(obj.aula_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 = 'manterAulas';
          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 Aula?</h3>",
      buttons: {
        confirm: {
          label: 'Sim!',
          className: 'btn-success'
        },
        cancel: {
          label: 'Cancelar!',
          className: 'btn-danger'
        }
      },
      callback: function (confirma) {
        if (confirma == true) {
          $('#loadPublicacao').show();
          var acao = 'manterAulas';
          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'>Aula 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
  