$(document).ready( function () {

  $.ajax({
    type: "POST",
    url: "views/home.html",
    dats_Accommodation: 'text',
    success: function(result){
      $('#conteudo').html(result);
      $('#pageHome_buttonActivityConfiguration').on('click', function(){
        $.ajax({
          type: "POST",
          url: "views/configuration/years.html",
          dats_Accommodation: 'text',
          success: function(result){
            $('#conteudo').html(result);
            activityConfigurationYears();
          }
        });
      });
      $('#pageHome_buttonActivityManagement').on('click', function(){
        $.ajax({
          type: "POST",
          url: "views/management/activities.html",
          dats_Accommodation: 'text',
          success: function(result){
            $('#conteudo').html(result);
            activityManagementActivities();
            //activityManagementYears();
          }
        });
      });
      $('#pageHome_buttonActivityRegistration').on('click', function(){
        $.ajax({
          type: "POST",
          url: "views/registration/activities.html",
          dats_Accommodation: 'text',
          success: function(result){
            $('#conteudo').html(result);
            activityRegistrationActivities();
            //activityRegistrationYears();
            }
        });
      });
    }
  });

  //********************************************************************
  //********************************************************************
  // ACTIVITY - CONFIGURATION
  //********************************************************************
  //********************************************************************

  //--------------------------------------------------------------------
  // Years
  //--------------------------------------------------------------------
  function activityConfigurationYears() {
    var dtable;
    var year;
    $('#breadcrumbYears').text("Anos com atividades");
    dtable = $('#tableYears').DataTable( {
      paginate: false,
      select : true,
      columns: [
        { title: "Ano" }
      ],
      columnDefs: [
        { targets: 0, className: 'dt-center' }
      ]
    });

    $.ajax({
      type: "POST",
      url: "server/tableyears.php",
      dats_Accommodation: 'json',
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $('#tableYears tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      year = data[0];
      $.ajax({
        type: "POST",
        url: "views/configuration/activities.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityConfigurationActivities(dtable,year);
        }
      });   
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });

    $('#modalYearCreate_button').click(function (){
      $.ajax({
          type: "POST",
          url: "server/tableyears.php",
          dats_Accommodation: 'json',
          data: {"year_create": $('#modalYearCreate_input').val()},
          success: function(result){
              dtable.clear();
              dtable.rows.add(result);
              dtable.draw();
              $('#modalYearCreate').modal('hide');
          },
          error: function (jqXHR, exception) {
              var msg = '';
              if (jqXHR.status === 0) {
                  msg = 'Not connect.\n Verify Network.';
              } else if (jqXHR.status === 400) {
                  msg = 'Valor do ano é inválido!';
              } else if (jqXHR.status === 403) {
                  msg = 'Não foi possível criar o diretório!';
              } else if (jqXHR.status == 404) {
                  msg = 'Requested page not found. [404]';
              } else if (jqXHR.status === 409) {
                  msg = 'O diretório já existe!';
              } else if (jqXHR.status == 500) {
                  msg = 'Internal Server Error [500].';
              } else {
                  msg = 'Uncaught Error.\n' + jqXHR.responseText;
              }
              $('#modalYearCreate_pErrorInfo').html(msg);
              $('#modalYearCreate_divErrorInfo').removeClass('hide');
              $('#modalYearCreate_divErrorInfo').addClass('show');
          }
      });     
    });  

    $('#modalYears_buttonDelete').click(function (){
      $.ajax({
          type: "POST",
          url: "server/tableyears.php",
          async: false, 
          dats_Accommodation: 'json',
          data: {"year_delete": year},
          success: function(result){
            dtable.clear();
            dtable.rows.add(result);
            dtable.draw();
            $('#modalYears').modal('hide');
        },
          error: function (jqXHR, exception) {
              var msg = '';
              if (jqXHR.status === 0) {
                  msg = 'Not connect.\n Verify Network.';
              } else if (jqXHR.status === 400) {
                  msg = 'Valor do ano é inválido!';
              } else if (jqXHR.status === 403) {
                  msg = 'Não foi possível eliminar o diretório!';
              } else if (jqXHR.status == 404) {
                  msg = 'Requested page not found. [404]';
              } else if (jqXHR.status === 409) {
                  msg = 'O diretório não está vazio!';
              } else if (jqXHR.status == 500) {
                  msg = 'Internal Server Error [500].';
              } else {
                  msg = 'Uncaught Error.\n' + jqXHR.responseText;
              }
              $('#modalYears_pErrorInfo').html(msg);
              $('#modalYears_divErrorInfo').removeClass('hide');
              $('#modalYears_divErrorInfo').addClass('show');
          }
      });     
    });  

    $('#modalYears_buttonActivitiesList').on('click', function(){
      $.ajax({
        type: "POST",
        url: "views/configuration/activities.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#modalYears').modal('hide');
          $('#conteudo').html(result);
          activityConfigurationActivities(dtable,year);
        }
      });   
    });
  }

  //--------------------------------------------------------------------
  // Activities
  //--------------------------------------------------------------------
  function activityConfigurationActivities(dtable,year) {
    var archive;
    var activity;
    var title;
    var badge_title;
    var date_begin;
    var date_end;
    $('#breadcrumbYears').text("Anos com atividades");
    $('#breadcrumbActivities').text("Atividades em "+year);
    dtable = $('#tableActivities').DataTable( {
      orderCellsHome: true,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Atividade", width: "4%" },
        { title: "Arquivo", width: "10%" },
        { title: "Início", width: "13%" },
        { title: "Fim", width: "13%" },
        { title: "Título", width: "30%" },
        { title: "Título do passe", width: "20%" }
      ],
      columnDefs: [
        {
          targets: [0,1,2,3],
          className: 'dt-center'
        }
      ],
      initComplete: function () {
        $('#tableActivities thead tr')
          .clone(true)
          .addClass('filters')
          .appendTo('#tableActivities thead');
        $('#tableActivities thead tr.filters th')
          .off('click')
          .removeClass('sorting')
          .removeClass('sorting_asc');
        var api = this.api();
        api
          .columns()
          .eq(0)
          .each(function (colIdx) {
            var cell = $('.filters th').eq(
              $(api.column(colIdx).header()).index()
            );
            var title = $(cell).text();
            $(cell).html('<input type="text" name="filter" style="width: 100%" />');
            $('input', $('.filters th').eq($(api.column(colIdx).header()).index()))
              .off('keyup change')
              .on('keyup change', function (e) {
                e.stopPropagation();
                $(this).attr('title', $(this).val());
                var regexr = '({search})';
                var cursorPosition = this.selectionStart;
                api
                  .column(colIdx)
                  .search(
                    this.value != ''
                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                        : '',
                    this.value != '',
                    this.value == ''
                  )
                  .draw();
                $(this)
                  .focus()[0]
                  .setSelectionRange(cursorPosition, cursorPosition);
              });
          });
      }  
    });

    $.ajax({
      type: "POST",
      url: "server/tableactivities.php",
      dats_Accommodation: 'json',
      data: {"year": year},
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });

    $('#breadcrumbYears').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/configuration/years.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityConfigurationYears();
        }
      });   
    });
    
    $('#tableActivities tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      activity = data[0];
      archive = data[1];
      title = data[4];
      /*
      date_begin = data[2];
      date_end = data[3];
      title = data[4];
      badge_title = data[5];
      $('#modalActivities_value').text(title);
      $('#modalActivities').modal('show');
      */
      $.ajax({
        type: "POST",
        url: "views/configuration/activitydetails.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityConfigurationActivityDetails(dtable,year,archive,activity,title);
        }
      });   
    } );

    $('#modalActivities_buttonBookingsList').on('click', function(){
      $.ajax({
        type: "POST",
        url: "views/configuration/bookings.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#modalActivities').modal('hide');
          $('#conteudo').html(result);
          activityConfigurationBookings(dtable,year,archive,activity,date_begin,date_end,title,badge_title);
        }
      });   
    });
  }

  //--------------------------------------------------------------------
  // Activity Info
  //--------------------------------------------------------------------
  function activityConfigurationActivityDetails(dtable,year,archive,activity,title) {
    $('#breadcrumbYears').text("Anos com atividades");
    $('#breadcrumbActivities').text("Atividades em "+year);
    $('#breadcrumbBookings').text("Inscrições para "+title);
    // Nested demo
    var nestedSortables = [].slice.call(document.querySelectorAll('.nested-sortable'));

    // Loop through each nested sortable element
    for (var i = 0; i < nestedSortables.length; i++) {
      new Sortable(nestedSortables[i], {
        group: 'nested',
        animation: 150,
        fallbackOnBody: true,
        swapThreshold: 0.65,
        removeOnSpill: true
      });
      /*
      new Sortable(nestedSortables[i], {
        group: 'nested',
        animation: 150,
        fallbackOnBody: true,
        swapThreshold: 0.65
      });
      */
    }


  	example3Left = document.getElementById('example3-left'),
    new Sortable(example3Left, {
      group: 'shared',
      animation: 150
    });
    
    var example3Right = document.getElementById('example3-right');
    new Sortable(example3Right, {
      group: {
        name: 'shared',
        pull: 'clone'
      },
      sort: false, // To disable sorting: set sort to false
      animation: 150
    });
    
  }
  
  //--------------------------------------------------------------------
  // Bookings
  //--------------------------------------------------------------------
  function activityConfigurationBookings(dtable,year,archive,activity,date_begin,date_end,title,badge_title) {
    $('#breadcrumbYears').text("Anos com atividades");
    $('#breadcrumbActivities').text("Atividades em "+year);
    $('#breadcrumbBookings').text("Inscrições para "+title);
    dtable = $('#tableBookings').DataTable( {
      orderCellsHome: true,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Id", width: "4%" },
        { title: "Número", width: "4%" },
        { title: "Data", width: "11%" },
        { title: "Nome", width: "13%" },
        { title: "Concessão", width: "6%" },
        { title: "Cartão", width: "%6" },
        { title: "Total", width: "%4" },
        { title: "Pago", width: "%4" },
        { title: "Dívida", width: "%4" },
        { title: "Modalidade", width: "%10" },
        { title: "Sessões", width: "%10" },
        { title: "Tradução", width: "%4" },
        { title: "Refeições", width: "%10" },
        { title: "Alojamento", width: "%10" }
      ],
      columnDefs: [
        { targets: [0,1,2,4,5,6,7,8,9,10,11,12,13], className: 'dt-center' }
      ],
      initComplete: function () {
        $('#tableBookings thead tr')
          .clone(true)
          .addClass('filters')
          .appendTo('#tableBookings thead');
        $('#tableBookings thead tr.filters th')
          .off('click')
          .removeClass('sorting')
          .removeClass('sorting_asc');
        var api = this.api();
        api
          .columns()
          .eq(0)
          .each(function (colIdx) {
            var cell = $('.filters th').eq(
              $(api.column(colIdx).header()).index()
            );
            var title = $(cell).text();
            $(cell).html('<input type="text" name="filter" style="width: 100%" />');
            $(
              'input',
              $('.filters th').eq($(api.column(colIdx).header()).index())
            )
              .off('keyup change')
              .on('keyup change', function (e) {
                e.stopPropagation();
                $(this).attr('title', $(this).val());
                var regexr = '({search})';
                var cursorPosition = this.selectionStart;
                api
                  .column(colIdx)
                  .search(
                    this.value != ''
                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                        : '',
                    this.value != '',
                    this.value == ''
                  )
                  .draw();
                $(this)
                  .focus()[0]
                  .setSelectionRange(cursorPosition, cursorPosition);
              });
          });
      }  
    });

    $.ajax({
      type: "POST",
      url: "server/tablebookings.php",
      dats_Accommodation: 'json',
      data: {"year" : year, "archive" : archive, "activity" : activity},
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });

    $('#breadcrumbYears').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/configuration/years.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityConfigurationYears();
        }
      });   
    });
    
    $('#breadcrumbActivities').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/configuration/activities.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityConfigurationActivities(dtable,year);
        }
      });   
    });

    $('#tableBookings tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      title = data[3];
    } );
  }

  //********************************************************************
  //********************************************************************
  // ACTIVITY - MANAGEMENT
  //********************************************************************
  //********************************************************************

  //--------------------------------------------------------------------
  // Years
  //--------------------------------------------------------------------
  function activityManagementYears() {
    var dtable;
    var year;
    //$('#breadcrumbYears').text("Anos com atividades");
    dtable = $('#tableYears').DataTable( {
      paginate: false,
      select : true,
      columns: [
        { title: "Ano" }
      ],
      columnDefs: [
        { targets: 0, className: 'dt-center' }
      ]
    });

    $.ajax({
      type: "POST",
      url: "server/tableyears.php",
      dats_Accommodation: 'json',
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $('#tableYears tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      year = data[0];
      $.ajax({
        type: "POST",
        url: "views/management/activities.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#modalYears').modal('hide');
          $('#conteudo').html(result);
          activityManagementActivities(dtable,year);
        }
      });   
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });

  }

  //--------------------------------------------------------------------
  // Activities
  //--------------------------------------------------------------------
  function activityManagementActivities() {
    var dtable;
    var archive;
    var activity;
    var title;
    var badge_title;
    var date_begin;
    var date_end;
    
    //$('#breadcrumbYears').text("Anos com atividades");
    $('#breadcrumbActivities').text("Atividades");

    dtable = $('#tableActivities').DataTable( {
      orderCellsHome: true,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Atividade", width: "5%" },
        { title: "Tipo", width: "30%" },
        { title: "Ano", width: "5%" },
        { title: "Mês", width: "5%" },
        { title: "Dia", width: "5%" },
        { title: "Título", width: "50%" }
      ],
      columnDefs: [
        {
          targets: [0,1,2,3],
          className: 'dt-center'
        }
      ],
      initComplete: function () {
        $('#tableActivities thead tr')
          .clone(true)
          .addClass('filters')
          .appendTo('#tableActivities thead');
        $('#tableActivities thead tr.filters th')
          .off('click')
          .removeClass('sorting')
          .removeClass('sorting_asc');
        var api = this.api();
        api
          .columns()
          .eq(0)
          .each(function (colIdx) {
            var cell = $('.filters th').eq(
              $(api.column(colIdx).header()).index()
            );
            var title = $(cell).text();
            $(cell).html('<input type="text" name="filter" style="width: 100%" />');
            $('input', $('.filters th').eq($(api.column(colIdx).header()).index()))
              .off('keyup change')
              .on('keyup change', function (e) {
                e.stopPropagation();
                $(this).attr('title', $(this).val());
                var regexr = '({search})';
                var cursorPosition = this.selectionStart;
                api
                  .column(colIdx)
                  .search(
                    this.value != ''
                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                        : '',
                    this.value != '',
                    this.value == ''
                  )
                  .draw();
                $(this)
                  .focus()[0]
                  .setSelectionRange(cursorPosition, cursorPosition);
              });
          });
      }  
    });

    $.ajax({
      type: "POST",
      url: "tableactivities.php",
      dats_Accommodation: 'json',
      //data: {"year": year},
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });

    /*
    $('#breadcrumbYears').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/management/years.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityManagementYears();
        }
      });   
    });
    */
    
    $('#tableActivities tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      activity = data[0];
      archive = data[1];
      date_begin = data[2];
      date_end = data[3];
      title = data[4];
      badge_title = data[5];
      $.ajax({
        type: "POST",
        url: "views/management/activitydetails.html",
        async: true,
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          //$('#breadcrumbYears').text("Anos com atividades");
          $('#breadcrumbActivities').text("Atividades em "+year);
          $('#breadcrumbActivityDetails').text(title);
          activityManagementActivityInfo(dtable,year,archive,activity,date_begin,date_end,title);
          activityManagementBookings(dtable,year,archive,activity,date_begin,date_end,title,badge_title);
        }
      });   
    });


    /*
    $('#tableActivities tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      activity = data[0];
      archive = data[1];
      date_begin = data[2];
      date_end = data[3];
      title = data[4];
      badge_title = data[5];
      $('#modalActivities_value').text(title);
      $('#modalActivities').modal('show');
    } );

    $('#modalActivities_buttonBookingsList').on('click', function(){
      $.ajax({
        type: "POST",
        url: "views/management/bookings.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#modalActivities').modal('hide');
          $('#conteudo').html(result);
          activityManagementBookings(dtable,year,archive,activity,date_begin,date_end,title,badge_title);
        }
      });   
    });

    $('#modalActivities_buttonActivityInfo').on('click', function(){
      $.ajax({
        type: "POST",
        url: "views/management/activityinfo.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#modalActivities').modal('hide');
          $('#conteudo').html(result);
          activityManagementActivityInfo(dtable,year,archive,activity,date_begin,date_end,title);
        }
      });   
    });
    */
    /*
    $('#tableActivities tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      activity = data[0];
      archive = data[1];
      date_begin = data[2];
      date_end = data[3];
      title = data[4];
      badge_title = data[5];
      $.ajax({
        type: "POST",
        url: "views/management/bookings.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#modalActivities').modal('hide');
          $('#conteudo').html(result);
          activityManagementBookings(dtable,year,archive,activity,date_begin,date_end,title,badge_title);
        }
      });   
    } );
    */
  }

  //--------------------------------------------------------------------
  // Activity Info
  //--------------------------------------------------------------------
  function activityManagementActivityInfo(dtable,year,archive,activity,date_begin,date_end,title) {
    /*
    var days = [];
    var date_first = new Date.parse(date_begin);
    var date_last  = new Date.parse(date_end);
    for (var d = date_first ; d <= date_last; d.setDate(d.getDate() + 1)) {
      days.push(new Date(d));
    }
    */
    //$('#breadcrumbYears').text("Anos com atividades");
    //$('#breadcrumbActivities').text("Atividades em "+year);
    //$('#breadcrumbActivityDetails').text(title);

    $('#tableActivityInfoSessions').append('<tfoot><tr><td></td><td></td><td class="columnTotal"></td><td class="columnSum"></td></tr></tfoot>');
    dtable = $('#tableActivityInfoSessions').DataTable( {
      ordering: false,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Tipo de inscrição em sessões", width: "50%" },
        { title: "Modalidade", width: "10%" },
        { title: "Tradução", width: "10%" },
        { title: "Quantidade de inscrições", width: "30%" },
        /*
        { title: days[0].toISOString().split('T')[0], width: "20%" },
        { title: days[1].toISOString().split('T')[0], width: "20%" },
        { title: days[2].toISOString().split('T')[0], width: "20%" },
        */
      ],
      columnDefs: [
        { targets: [1,2,3], className: 'dt-center' }
      ],
      footerCallback: function ( row, data, start, end, display ) {
        var api = this.api();

        $( api.column( 2 ).footer() ).html('Total: ');
        total = api
            .column( 3 )
            .data()
            .reduce( function (a, b) {
              if ( typeof(a) === "undefined" && a === null) a = 0;
              if ( typeof(b) === "undefined" && b === null) b = 0;
              return parseInt(a) + parseInt(b);
            }, 0 );
        $( api.column( 3 ).footer() ).html( parseInt(total) || 0 );
      }
    });

    $.ajax({
      type: "POST",
      url: "server/tablesessionsinfo.php",
      dats_Accommodation: 'json',
      data: {"year" : year, "archive" : archive, "activity" : activity},
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $('#tableActivityInfoMeals').append('<tfoot><tr><td></td><td class="columnTotal"></td><td class="columnSum"></td></tr></tfoot>');
    dtable2 = $('#tableActivityInfoMeals').DataTable( {
      ordering: false,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Tipo de inscrição em refeições", width: "60%" },
        { title: "Refeição", width: "10%" },
        { title: "Quantidade de inscrições", width: "30%" },
        /*
        { title: days[0].toISOString().split('T')[0], width: "20%" },
        { title: days[1].toISOString().split('T')[0], width: "20%" },
        { title: days[2].toISOString().split('T')[0], width: "20%" },
        */
      ],
      columnDefs: [
        { targets: [1,2], className: 'dt-center' }
      ],
      footerCallback: function ( row, data, start, end, display ) {
        var api = this.api();

        $( api.column( 1 ).footer() ).html('Total: ');
        total = api
            .column( 2 )
            .data()
            .reduce( function (a, b) {
              if ( typeof(a) === "undefined" && a === null || a=="") a = 0;
              if ( typeof(b) === "undefined" && b === null || b=="") b = 0;
              return parseInt(a) + parseInt(b);
            }, 0 );
        $( api.column( 2 ).footer() ).html( parseInt(total) || 0 );
      }
    });

    $.ajax({
      type: "POST",
      url: "server/tablemealsinfo.php",
      dats_Accommodation: 'json',
      data: {"year" : year, "archive" : archive, "activity" : activity},
      success: function(result){
        dtable2.clear();
        dtable2.rows.add(result);
        dtable2.draw();
      }
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });
    /*
    $('#breadcrumbYears').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/management/years.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityManagementYears();
        }
      });   
    });
    */
    $('#breadcrumbActivities').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/management/activities.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityManagementActivities(dtable,year);
        }
      });   
    });

  }

  //--------------------------------------------------------------------
  // Bookings
  //--------------------------------------------------------------------
  function activityManagementBookings(dtable,year,archive,activity,date_begin,date_end,title,badge_title) {
    //$('#breadcrumbYears').text("Anos com atividades");
    //$('#breadcrumbActivities').text("Atividades em "+year);
    //$('#breadcrumbBookings').text("Inscrições para "+title);
    dtable = $('#tableBookings').DataTable( {
      orderCellsHome: true,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Id", width: "4%" },
        { title: "Número", width: "4%" },
        { title: "Data", width: "11%" },
        { title: "Nome", width: "13%" },
        { title: "Nome Completo", width: "12%" },
        { title: "Concessão", width: "6%" },
        { title: "Cartão", width: "%6" },
        { title: "Total", width: "%4" },
        { title: "Pago", width: "%4" },
        { title: "Dívida", width: "%4" },
        { title: "Modalidade", width: "%10" },
        { title: "Sessões", width: "%6" },
        { title: "Tradução", width: "%4" },
        { title: "Refeições", width: "%6" },
        { title: "Alojamento", width: "%6" }
      ],
      columnDefs: [
        { targets: [0,1,2,5,6,7,8,9,10,11,12,13,14], className: 'dt-center' },
        { targets: [0,2,4,5,6], visible: false}
      ],
      initComplete: function () {
        $('#tableBookings thead tr')
          .clone(true)
          .addClass('filters')
          .attr('id', 'rowFilter')
          .appendTo('#tableBookings thead');
        $('#tableBookings thead tr.filters th')
          .off('click')
          .removeClass('sorting')
          .removeClass('sorting_asc');
        var api = this.api();
        api
          .columns()
          .eq(0)
          .each(function (colIdx) {
            var cell = $('.filters th').eq(
              $(api.column(colIdx).header()).index()
            );
            var title = $(cell).text();
            $(cell).html('<input type="text" name="filter" style="width: 100%" />');
            $(
              'input',
              $('.filters th').eq($(api.column(colIdx).header()).index())
            )
              .off('keyup change')
              .on('keyup change', function (e) {
                e.stopPropagation();
                $(this).attr('title', $(this).val());
                var regexr = '({search})';
                var cursorPosition = this.selectionStart;
                api
                  .column(colIdx)
                  .search(
                    this.value != ''
                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                        : '',
                    this.value != '',
                    this.value == ''
                  )
                  .draw();
                $(this)
                  .focus()[0]
                  .setSelectionRange(cursorPosition, cursorPosition);
              });
          });
      }  
    });

    $.ajax({
      type: "POST",
      url: "server/tablebookings.php",
      dats_Accommodation: 'json',
      data: {"year" : year, "archive" : archive, "activity" : activity},
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });

    $('#buttonCompactExpand').on('click', function(){
      if( dtable.column(0).visible()==true) {
        dtable.column(0).visible(false);
        dtable.column(2).visible(false);
        dtable.column(4).visible(false);
        dtable.column(5).visible(false);
        dtable.column(6).visible(false);
      } else {
        dtable.column(0).visible(true);
        dtable.column(2).visible(true);
        dtable.column(4).visible(true);
        dtable.column(5).visible(true);
        dtable.column(6).visible(true);
      }
      $('#rowFilter').remove();
      $('#tableBookings thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tableBookings thead');
      $('#tableBookings thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      dtable
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('.filters th').eq(
            $(dtable.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $(
            'input',
            $('.filters th').eq($(dtable.column(colIdx).header()).index())
          )
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              dtable
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    });

    /*
    $('#breadcrumbYears').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/management/years.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityManagementYears();
        }
      });   
    });
    
    $('#breadcrumbActivities').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/management/activities.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityManagementActivities(dtable,year);
        }
      });   
    });
    */

    $('#tableBookings tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      booking_id = data[0];
      booking_number = data[1];
      booking_name = data[3];
      $.ajax({
        type: "POST",
        url: "views/management/payments.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityManagementPayments(dtable,year,archive,activity,date_begin,date_end,title,badge_title,booking_id,booking_number,booking_name);
        }
      });   
    } );


    $('#pageBookings_buttonGenerateBadges').on('click', function(){
      $('#modalBadges_pInfo').html( 'Estão selecionadas '+dtable.rows( {search:'applied'} ).count()+' inscrições. Verifique as seguintes opções para a geração dos passes em PDF.<br /><i>Nota: Requer uma conta gratuita em </i><a href="https://www.overleaf.com" target="_blank">https://www.overleaf.com</a>' );
      $('#modalBadges_pInfoSets').html( '<i>Valor recomendado (>0): <strong>'+Math.ceil(dtable.rows( {search:'applied'} ).count()/10)+'</strong></i>' );
      $('#modalBadges_inputTitle').val(badge_title);
      $('#modalBadges_inputSets').val(Math.ceil(dtable.rows( {search:'applied'} ).count()/10));
    });
    $('#pageBookings_buttonGenerateEmptyBadges').on('click', function(){
      $('#modalEmptyBadges_pInfoSessions').html( 'Sessões (' + date_begin + ' - ' + date_end + '):');
      $('#modalEmptyBadges_pInfoMeals').html( 'Refeições (' + date_begin + ' - ' + date_end + '):');
      $('#modalEmptyBadges_inputTitle').val(badge_title);
    });
    $('#pageBookings_buttonGenerateCSV').on('click', function(){
      $('#modalCSV_pInfo').html( 'Estão selecionadas '+dtable.rows( {search:'applied'} ).count()+' inscrições.' );
    });

    $('#modalBadges_buttonCreateOverleaf').on('click', function(){
      $.ajax({
        type: "POST",
        url: "server/badges.php",
        async: false, 
        dats_Accommodation: 'json',
        data: {"badge_title": $('#modalBadges_inputTitle').val(), "date_begin": date_begin, "date_end": date_end, "sets": $('#modalBadges_inputSets').val(), "data": JSON.stringify(dtable.rows({search:'applied'}).data().toArray())},
        success: function(result){
          $("#modalBadges").modal('hide');
          window.open(result.url, '_blank');
        }
      });     
    });

    $('#modalBadges_buttonCreateLatex').on('click', function(){
      $.ajax({
        type: "POST",
        url: "server/badges.php",
        async: false, 
        dats_Accommodation: 'json',
        data: {"option": "latex", "badge_title": $('#modalBadges_inputTitle').val(), "date_begin": date_begin, "date_end": date_end, "sets": $('#modalBadges_inputSets').val(), "data": JSON.stringify(dtable.rows({search:'applied'}).data().toArray())},
        success: function(result){
          $("#modalBadges").modal('hide');
          window.open(result.url, '_blank');
        }
      });     
    });
    
    $('#modalEmptyBadges_buttonCreateOverleaf').on('click', function(){
      $.ajax({
        type: "POST",
        url: "server/badges.php",
        async: false, 
        dats_Accommodation: 'json',
        data: {"badge_title": $('#modalEmptyBadges_inputTitle').val(), "date_begin": date_begin, "date_end": date_end, "sessionsDay1": $('#sessionsDay1').prop("checked"), "sessionsDay2": $('#sessionsDay2').prop("checked"), "sessionsDay3": $('#sessionsDay3').prop("checked"), "mealsDay1": $('#mealsDay1').prop("checked"), "mealsDay2": $('#mealsDay2').prop("checked"), "mealsDay3": $('#mealsDay3').prop("checked")},
        success: function(result){
          $("#modalEmptyBadges").modal('hide');
          window.open(result.url, '_blank');
        }
      });     
    });

    $('#modalEmptyBadges_buttonCreateLatex').on('click', function(){
      var sd1,sd2,sd3,sd4,sd5,sd6,sd7;
      var md1,md2,md3,md4,md5,md6,md7;
      if ($("#sessionsDay1").prop("checked")) sd1=1;
      if ($("#sessionsDay2").prop("checked")) sd2=1;
      if ($("#sessionsDay3").prop("checked")) sd3=1;
      if ($("#sessionsDay4").prop("checked")) sd4=1;
      if ($("#sessionsDay5").prop("checked")) sd5=1;
      if ($("#sessionsDay6").prop("checked")) sd6=1;
      if ($("#sessionsDay7").prop("checked")) sd7=1;
      if ($("#mealsDay1").prop("checked")) md1=1;
      if ($("#mealsDay2").prop("checked")) md2=1;
      if ($("#mealsDay3").prop("checked")) md3=1;
      if ($("#mealsDay4").prop("checked")) md4=1;
      if ($("#mealsDay5").prop("checked")) md5=1;
      if ($("#mealsDay6").prop("checked")) md6=1;
      if ($("#mealsDay7").prop("checked")) md7=1;
      $.ajax({
        type: "POST",
        url: "server/badges.php",
        async: false, 
        dats_Accommodation: 'json',
        data: {"option": "latex", "badge_title": $('#modalEmptyBadges_inputTitle').val(), "date_begin": date_begin, "date_end": date_end, "sessionsDay1": sd1, "sessionsDay2": sd2, "sessionsDay3": sd3, "mealsDay1": md1, "mealsDay2": md2, "mealsDay3": md3},
        success: function(result){
          $("#modalEmptyBadges").modal('hide');
          window.open(result.url, '_blank');
        }
      });     
    });

    $('#modalCSV_buttonCreate').click(function (){
      $.ajax({
        type: "POST",
        url: "server/csv.php",
        async: false, 
        dats_Accommodation: 'json',
        data: {"data": JSON.stringify(dtable.rows({search:'applied'}).data().toArray())},
        success: function(result){
          $("#modalCSV").modal('hide');
          window.open(result.url, '_blank');
        }
      });     
    });
  }


  //--------------------------------------------------------------------
  // Payments
  //--------------------------------------------------------------------
  function activityManagementPayments(dtable,year,archive,activity,date_begin,date_end,title,badge_title,booking_id,booking_number,booking_name) {
    var dtable2;
    //$('#breadcrumbYears').text("Anos com atividades");
    $('#breadcrumbActivities').text("Atividades em "+year);
    $('#breadcrumbActivityDetails').text(title);
    $('#breadcrumbPayments').text("Pagamentos de "+booking_name+" ("+booking_number+")");
    $('#tableBookingDetails').append('<tfoot><tr><td></td><td class="columnTotal"></td><td></td><td></td><td class="columnSum"></td></tr></tfoot>');
    dtable = $('#tableBookingDetails').DataTable( {
      ordering: false,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Campo da inscrição", width: "20%" },
        { title: "Opção selecionada", width: "50%" },
        { title: "Preço", width: "10%" },
        { title: "Desconto", width: "10%" },
        { title: "A pagar", width: "10%" },
      ],
      columnDefs: [
        { targets: [2,3,4], className: 'dt-center' }
      ],
      footerCallback: function ( row, data, start, end, display ) {
        var api = this.api();

        $( api.column( 1 ).footer() ).html('Total: ');
        soma = api
            .column( 2 )
            .data()
            .reduce( function (a, b) {
              if ( typeof(a) === "undefined" && a === null) a = 0;
              if ( typeof(b) === "undefined" && b === null) b = 0;
              return a + b;
            }, 0 );
        $( api.column( 2 ).footer() ).html(parseFloat(soma).toFixed(2));
        /*
          new Intl.NumberFormat('pt-PT', { style: 'currency', currency: 'EUR' }).format(soma)
        );
        */
        desconto = api
            .column( 3 )
            .data()
            .reduce( function (a, b) {
              if ( typeof(a) === "undefined" && a === null) a = 0;
              if ( typeof(b) === "undefined" && b === null) b = 0;
              return a + b;
            }, 0 );
        $( api.column( 3 ).footer() ).html(parseFloat(desconto).toFixed(2));
        /*
          new Intl.NumberFormat('pt-PT', { style: 'currency', currency: 'EUR' }).format(desconto)
        );
        */
        total = api
            .column( 4 )
            .data()
            .reduce( function (a, b) {
              if ( typeof(a) === "undefined" && a === null) a = 0;
              if ( typeof(b) === "undefined" && b === null) b = 0;
              return a + b;
            }, 0 );
        $( api.column( 4 ).footer() ).html(parseFloat(total).toFixed(2));
        /*
          new Intl.NumberFormat('pt-PT', { style: 'currency', currency: 'EUR' }).format(total)
        );
        */
      }
    });
    $('#tablePackPayments').append('<tfoot><tr><td></td><td></td><td class="columnTotal"></td><td class="columnSum"></td></tr></tfoot>');
    dtable2 = $('#tablePackPayments').DataTable( {
      ordering: false,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Número", width: "20%" },
        { title: "Forma do pagamento", width: "50%" },
        { title: "Data", width: "20%" },
        { title: "Pago", width: "10%" },
      ],
      columnDefs: [
        { targets: [0,2,3], className: 'dt-center' }
      ],
      footerCallback: function ( row, data, start, end, display ) {
        var api = this.api();

        $( api.column( 2 ).footer() ).html(
          'Total: '
        );
        soma = api
            .column( 3 )
            .data()
            .reduce( function (a, b) {
                return a + b;
            }, 0 );
        $( api.column( 3 ).footer() ).html(
          new Intl.NumberFormat('pt-PT', { style: 'currency', currency: 'EUR' }).format(soma)
        );
      }
    });

    $.ajax({
      type: "POST",
      url: "server/tablepayments.php",
      dats_Accommodation: 'json',
      data: {"year" : year, "archive" : archive, "activity" : activity, "booking_id" : booking_id},
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $.ajax({
      type: "POST",
      url: "server/tablepayments.php",
      dats_Accommodation: 'json',
      data: {"booking_id" : booking_id},
      success: function(result){
        dtable2.clear();
        dtable2.rows.add(result);
        dtable2.draw();
      }
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });
    /*
    $('#breadcrumbYears').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/management/years.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          dtable2.destroy();
          $('#conteudo').html(result);
          activityManagementYears();
        }
      });   
    });
    */
    $('#breadcrumbActivities').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/management/activities.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          dtable2.destroy();
          $('#conteudo').html(result);
          activityManagementActivities(dtable,year);
        }
      });   
    });

    $('#breadcrumbActivityDetails').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/management/activitydetails.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          dtable2.destroy();
          $('#conteudo').html(result);
          //$('#breadcrumbYears').text("Anos com atividades");
          $('#breadcrumbActivities').text("Atividades em "+year);
          $('#breadcrumbActivityDetails').text(title);
          $('#pillsActivityDetails_tabInfo').removeClass('show');
          $('#pillsActivityDetails_tabInfo').removeClass('active');
          $('#pillsActivityDetails_tabBookings').addClass('show');
          $('#pillsActivityDetails_tabBookings').addClass('active');
          activityManagementBookings(dtable,year,archive,activity,date_begin,date_end,title,badge_title);
          activityManagementActivityInfo(dtable,year,archive,activity,date_begin,date_end,title);
        }
      });   
    });

    $('#tableBookingDetails tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
    } );

    $('#tablePackPayments tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
    } );

  }

  //********************************************************************
  //********************************************************************
  // ACTIVITY - REGISTRATION
  //********************************************************************
  //********************************************************************

  //--------------------------------------------------------------------
  // Years
  //--------------------------------------------------------------------
  function activityRegistrationYears() {
    var dtable;
    var year;
    //$('#breadcrumbYears').text("Anos com atividades");
    dtable = $('#tableYears').DataTable( {
      paginate: false,
      select : true,
      columns: [
        { title: "Ano" }
      ],
      columnDefs: [
        { targets: 0, className: 'dt-center' }
      ]
    });

    $.ajax({
      type: "POST",
      url: "server/tableyears.php",
      dats_Accommodation: 'json',
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $('#tableYears tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      year = data[0];
      $.ajax({
        type: "POST",
        url: "views/registration/activities.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#modalYears').modal('hide');
          $('#conteudo').html(result);
          activityRegistrationActivities(dtable,year);
        }
      });   
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });

  }

  //--------------------------------------------------------------------
  // Activities
  //--------------------------------------------------------------------
  function activityRegistrationActivities(year) {
    var dtable;
    var archive;
    var activity;
    var title;
    var badge_title;
    var date_begin;
    var date_end;
    //$('#breadcrumbYears').text("Anos com atividades");
    $('#breadcrumbActivities').text("Atividades em "+year);
    dtable = $('#tableActivities').DataTable( {
      orderCellsHome: true,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Atividade", width: "4%" },
        { title: "Arquivo", width: "10%" },
        { title: "Início", width: "13%" },
        { title: "Fim", width: "13%" },
        { title: "Título", width: "30%" },
        { title: "Título do passe", width: "20%" }
      ],
      columnDefs: [
        {
          targets: [0,1,2,3],
          className: 'dt-center'
        }
      ],
      initComplete: function () {
        $('#tableActivities thead tr')
          .clone(true)
          .addClass('filters')
          .appendTo('#tableActivities thead');
        $('#tableActivities thead tr.filters th')
          .off('click')
          .removeClass('sorting')
          .removeClass('sorting_asc');
        var api = this.api();
        api
          .columns()
          .eq(0)
          .each(function (colIdx) {
            var cell = $('.filters th').eq(
              $(api.column(colIdx).header()).index()
            );
            var title = $(cell).text();
            $(cell).html('<input type="text" name="filter" style="width: 100%" />');
            $('input', $('.filters th').eq($(api.column(colIdx).header()).index()))
              .off('keyup change')
              .on('keyup change', function (e) {
                e.stopPropagation();
                $(this).attr('title', $(this).val());
                var regexr = '({search})';
                var cursorPosition = this.selectionStart;
                api
                  .column(colIdx)
                  .search(
                    this.value != ''
                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                        : '',
                    this.value != '',
                    this.value == ''
                  )
                  .draw();
                $(this)
                  .focus()[0]
                  .setSelectionRange(cursorPosition, cursorPosition);
              });
          });
      }  
    });

    $.ajax({
      type: "POST",
      url: "server/tableactivities.php",
      dats_Accommodation: 'json',
      data: {"year": year},
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });
    /*
    $('#breadcrumbYears').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/registration/years.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityRegistrationYears();
        }
      });   
    });
    */
    $('#tableActivities tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      activity = data[0];
      archive = data[1];
      date_begin = data[2];
      date_end = data[3];
      title = data[4];
      badge_title = data[5];
      $.ajax({
        type: "POST",
        url: "views/registration/bookings.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#modalActivities').modal('hide');
          $('#conteudo').html(result);
          activityRegistrationBookings(dtable,year,archive,activity,date_begin,date_end,title,badge_title);
        }
      });   
    } );
  }

  //--------------------------------------------------------------------
  // Bookings
  //--------------------------------------------------------------------
  function activityRegistrationBookings(dtable,year,archive,activity,date_begin,date_end,title,badge_title) {
    var booking_id;
    //$('#breadcrumbYears').text("Anos com atividades");
    $('#breadcrumbActivities').text("Atividades em "+year);
    $('#breadcrumbBookings').text("Inscrições para "+title);
    dtable = $('#tableBookings').DataTable( {
      orderCellsHome: true,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Id", width: "4%" },
        { title: "Número", width: "4%" },
        { title: "Data", width: "11%" },
        { title: "Nome", width: "13%" },
        { title: "Nome Completo", width: "12%" },
        { title: "Concessão", width: "6%" },
        { title: "Cartão", width: "%6" },
        { title: "Total", width: "%4" },
        { title: "Pago", width: "%4" },
        { title: "Dívida", width: "%4" },
        { title: "Modalidade", width: "%10" },
        { title: "Sessões", width: "%6" },
        { title: "Tradução", width: "%4" },
        { title: "Refeições", width: "%6" },
        { title: "Alojamento", width: "%6" }
      ],
      columnDefs: [
        { targets: [0,1,2,5,6,7,8,9,10,11,12,13,14], className: 'dt-center' },
        { targets: [0,2,4,5,6], visible: false}
      ],
      initComplete: function () {
        $('#tableBookings thead tr')
          .clone(true)
          .addClass('filters')
          .attr('id', 'rowFilter')
          .appendTo('#tableBookings thead');
        $('#tableBookings thead tr.filters th')
          .off('click')
          .removeClass('sorting')
          .removeClass('sorting_asc');
        var api = this.api();
        api
          .columns()
          .eq(0)
          .each(function (colIdx) {
            var cell = $('.filters th').eq(
              $(api.column(colIdx).header()).index()
            );
            var title = $(cell).text();
            $(cell).html('<input type="text" name="filter" style="width: 100%" />');
            $(
              'input',
              $('.filters th').eq($(api.column(colIdx).header()).index())
            )
              .off('keyup change')
              .on('keyup change', function (e) {
                e.stopPropagation();
                $(this).attr('title', $(this).val());
                var regexr = '({search})';
                var cursorPosition = this.selectionStart;
                api
                  .column(colIdx)
                  .search(
                    this.value != ''
                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                        : '',
                    this.value != '',
                    this.value == ''
                  )
                  .draw();
                $(this)
                  .focus()[0]
                  .setSelectionRange(cursorPosition, cursorPosition);
              });
          });
      }  
    });

    $.ajax({
      type: "POST",
      url: "server/tablebookings.php",
      dats_Accommodation: 'json',
      data: {"year" : year, "archive" : archive, "activity" : activity},
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });

    $('#buttonCompactExpand').on('click', function(){
      if( dtable.column(0).visible()==true) {
        dtable.column(0).visible(false);
        dtable.column(2).visible(false);
        dtable.column(4).visible(false);
        dtable.column(5).visible(false);
        dtable.column(6).visible(false);
      } else {
        dtable.column(0).visible(true);
        dtable.column(2).visible(true);
        dtable.column(4).visible(true);
        dtable.column(5).visible(true);
        dtable.column(6).visible(true);
      }
      $('#rowFilter').remove();
      $('#tableBookings thead tr')
        .clone(true)
        .addClass('filters')
        .attr('id', 'rowFilter')
        .appendTo('#tableBookings thead');
      $('#tableBookings thead tr.filters th')
        .off('click')
        .removeClass('sorting')
        .removeClass('sorting_asc');
      dtable
        .columns()
        .eq(0)
        .each(function (colIdx) {
          var cell = $('.filters th').eq(
            $(dtable.column(colIdx).header()).index()
          );
          var title = $(cell).text();
          $(cell).html('<input type="text" name="filter" style="width: 100%" />');
          $(
            'input',
            $('.filters th').eq($(dtable.column(colIdx).header()).index())
          )
            .off('keyup change')
            .on('keyup change', function (e) {
              e.stopPropagation();
              $(this).attr('title', $(this).val());
              var regexr = '({search})';
              var cursorPosition = this.selectionStart;
              dtable
                .column(colIdx)
                .search(
                  this.value != ''
                      ? regexr.replace('{search}', '(((' + this.value + ')))')
                      : '',
                  this.value != '',
                  this.value == ''
                )
                .draw();
              $(this)
                .focus()[0]
                .setSelectionRange(cursorPosition, cursorPosition);
            });
        });
    });
    /*
    $('#breadcrumbYears').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/registration/years.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityRegistrationYears();
        }
      });   
    });
    */
    $('#breadcrumbActivities').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/registration/activities.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityRegistrationActivities(dtable,year);
        }
      });   
    });

    $('#tableBookings tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
      booking_id = data[0];
      booking_number = data[1];
      booking_name = data[3];
      $.ajax({
        type: "POST",
        url: "views/registration/payments.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          $('#conteudo').html(result);
          activityRegistrationPayments(dtable,year,archive,activity,date_begin,date_end,title,badge_title,booking_id,booking_number,booking_name);
        }
      });   
    } );
  }

  //--------------------------------------------------------------------
  // Payments
  //--------------------------------------------------------------------
  function activityRegistrationPayments(dtable,year,archive,activity,date_begin,date_end,title,badge_title,booking_id,booking_number,booking_name) {
    var dtable2;
    //$('#breadcrumbYears').text("Anos com atividades");
    $('#breadcrumbActivities').text("Atividades em "+year);
    $('#breadcrumbBookings').text("Inscrições para "+title);
    $('#breadcrumbPayments').text("Pagamentos de "+booking_name+" ("+booking_number+")");
    $('#tableBookingDetails').append('<tfoot><tr><td></td><td class="columnTotal"></td><td></td><td></td><td class="columnSum"></td></tr></tfoot>');
    dtable = $('#tableBookingDetails').DataTable( {
      ordering: false,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Campo da inscrição", width: "20%" },
        { title: "Opção selecionada", width: "50%" },
        { title: "Preço", width: "10%" },
        { title: "Desconto", width: "10%" },
        { title: "A pagar", width: "10%" },
      ],
      columnDefs: [
        { targets: [2,3,4], className: 'dt-center' }
      ],
      footerCallback: function ( row, data, start, end, display ) {
        var api = this.api();

        $( api.column( 1 ).footer() ).html('Total: ');
        soma = api
            .column( 2 )
            .data()
            .reduce( function (a, b) {
              return parseFloat(a) + parseFloat(b);
            }, 0 );
        $( api.column( 2 ).footer() ).html(parseFloat(soma).toFixed(2));
        /*
          new Intl.NumberFormat('pt-PT', { style: 'currency', currency: 'EUR' }).format(soma)
        );
        */
        desconto = api
            .column( 3 )
            .data()
            .reduce( function (a, b) {
              return parseFloat(a) + parseFloat(b);
            }, 0 );
        $( api.column( 3 ).footer() ).html(parseFloat(desconto).toFixed(2));
        /*
          new Intl.NumberFormat('pt-PT', { style: 'currency', currency: 'EUR' }).format(desconto)
        );
        */
        total = api
            .column( 4 )
            .data()
            .reduce( function (a, b) {
              return parseFloat(a) + parseFloat(b);
            }, 0 );
        $( api.column( 4 ).footer() ).html(parseFloat(total).toFixed(2));
        /*
          new Intl.NumberFormat('pt-PT', { style: 'currency', currency: 'EUR' }).format(total)
        );
        */
      }
    });
    $('#tablePackPayments').append('<tfoot><tr><td></td><td></td><td class="columnTotal"></td><td class="columnSum"></td></tr></tfoot>');
    dtable2 = $('#tablePackPayments').DataTable( {
      ordering: false,
      fixedHeader: true,
      paginate: false,
      select : true,
      columns: [
        { title: "Número", width: "20%" },
        { title: "Forma do pagamento", width: "50%" },
        { title: "Data", width: "20%" },
        { title: "Pago", width: "10%" },
      ],
      columnDefs: [
        { targets: [0,2,3], className: 'dt-center' }
      ],
      footerCallback: function ( row, data, start, end, display ) {
        var api = this.api();

        $( api.column( 2 ).footer() ).html(
          'Total: '
        );
        soma = api
            .column( 3 )
            .data()
            .reduce( function (a, b) {
                return parseFloat(a) + parseFloat(b);
            }, 0 );
        $( api.column( 3 ).footer() ).html(parseFloat(total).toFixed(2));
      }
    });

    $.ajax({
      type: "POST",
      url: "server/tablepayments.php",
      dats_Accommodation: 'json',
      data: {"year" : year, "archive" : archive, "activity" : activity, "booking_id" : booking_id},
      success: function(result){
        dtable.clear();
        dtable.rows.add(result);
        dtable.draw();
      }
    });

    $.ajax({
      type: "POST",
      url: "server/tablepayments.php",
      dats_Accommodation: 'json',
      data: {"booking_id" : booking_id},
      success: function(result){
        dtable2.clear();
        dtable2.rows.add(result);
        dtable2.draw();
      }
    });

    $('#clearFilter').on('click', function(){
      dtable
          .search( '' )
          .columns().search( '' )
          .draw();
      $('input[name="filter"]').val( '' );
    });
    /*
    $('#breadcrumbYears').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/registration/years.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          dtable2.destroy();
          $('#conteudo').html(result);
          activityRegistrationYears();
        }
      });   
    });
    */
    $('#breadcrumbActivities').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/registration/activities.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          dtable2.destroy();
          $('#conteudo').html(result);
          activityRegistrationActivities(dtable,year);
        }
      });   
    });

    $('#breadcrumbBookings').click(function(e) {
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: "views/registration/bookings.html",
        dats_Accommodation: 'text',
        success: function(result){
          dtable.destroy();
          dtable2.destroy();
          $('#conteudo').html(result);
          activityRegistrationBookings(dtable,year,archive,activity,date_begin,date_end,title,badge_title);
        }
      });   
    });

    $('#tableBookingDetails tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
    } );

    $('#tablePackPayments tbody').on('click', 'tr', function () {
      var data = dtable.row( this ).data();
    } );

  }
  
} );
  