@extends('layouts.master')

@section('navigation')
    @if(Auth::user()->role==1)
      @include('local.managers.admins._navigation')
    @elseif(Auth::user()->role==2)
      @include('local.managers.sCoords._navigation')
    @elseif(Auth::user()->role==3)
      @include('local.managers.pCoords._navigation')
    @elseif(Auth::user()->role==4)
      @include('local.professors._navigation')
    @endif
@stop

@section('main')
  {{-- TODO: look where to place this script.
          if placed inside .ready() or before it,
            an error that the function is not defined occurs. --}}
  {{-- TODO: no reconoce acentos --}}
  <script type="text/javascript">
  function filterObjectives() {
    // Declare variables
    var input, filter, div, li, i, objectiveText;
    input = document.getElementById('userInput');
    filter = input.value.toUpperCase();
    div = document.getElementById("list");
    li = div.getElementsByTagName('li');

    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
      objectiveText = li[i].textContent;
      if (objectiveText.toUpperCase().indexOf(filter) > -1) {
        li[i].style.display = "";
      } else {
        li[i].style.display = "none";
      }
    }
  }
  </script>

  <div class="row">
    <div class="col-md-3">
      <input class="form-control" type="text" id="userInput" onkeyup="filterObjectives()" placeholder="Search for Learning Outcomes..">
      <div class="list-group" id='list'>
        @foreach ($objectives as $objective)
          <li data-objective-id="{{ $objective->id }}"class="list-group-item">{{ $objective->text }}</li>
        @endforeach
      </div>
    </div>

    <div class="col-md-9">
      <div id="objective-display" class="panel panel-default">
        <div class="panel-heading">
          <h4 class=" panel-title" style="cursor:auto!important;">
          </h4>
        </div>
        <div class="panel-body">
          <p class="objective-definition "></p>
          <label for="">View Criterions with </label>
          <select class="view-scales input-sm" name=""></select>
          <label for="">Scales</label>
            <div class="table-responsive table-responsive-0">
                <table class="table table-striped table-condensed datatable">
                  <thead id="theHead">
                    <th>Criteria</th>
                                    <tfoot>
                     
                  </tfoot>
                  <tbody>
                  </tbody>
                </table>
            </div>

        </div>
      </div>
    </div>

    <div class="col-md-9">
      <div class="no-objective alert alert-info">
        <p>Select a Learning Objective to view its information</p>
      </div>
    </div>

  </div>
  <script>
 
</script>
@stop

@section('included-js')
    @include('global._datatables_js')
@stop

@section('javascript')

 $(document).ready(function()
{
  // --------------------------------------------------------------------------
  // Page load
  // --------------------------------------------------------------------------

  // Hide accordion panel contents by default
  $('.panel-group .panel-body').hide();-

  $('#objective-display').parent().hide();

  // --------------------------------------------------------------------------
  // Functions
  // --------------------------------------------------------------------------
/*

  */
function fetchObjectiveForCriteria(li){
  {
    
    var id = $(li).data('objective-id');

    $.post(
    "{{ URL::action('ObjectivesController@fetchObjectiveForCriteria') }}",
    { id: id,
    },
    function(json)
    {
      var tables = [];
        // Retrieve datatable instance
        //var table = $('.table-responsive-0').;

        var name = json.objective.text;
        //var definition = json.objective.program.name;
        var criteria =json.objective.criteria;

        $('#objective-display').parent().show();
        $('.no-objective').parent().hide();

        //Display title and definition
        $('#objective-display .panel-title').html(name);
       // $('#objective-display .objective-definition').html(definition);

        //Empty table
       $('.table-responsive-0').empty();

        // Add new criteria
        if(Object.keys(criteria).length !== 0)
        {
          var selector = $('.view-scales');
        selector.empty();
        
        $.each(criteria, function(num_scales){
          var criterions_levels = num_scales;
          var new_option = $('<option />');
          new_option.attr('value',criterions_levels).html(criterions_levels);
          new_option.appendTo(selector);
          var dataset = Array();

          $.each(criteria[num_scales], function(index, criterion_info){
            var row = Array();
            criterion_name = criterion_info.name;
            criterion_scales = criterion_info.scales;
            criterion_programs = criterion_info.programs;
            var program_html ='';

            row.push(criterion_name);
              $.each(criterion_scales, function(index, scale){
                  //
                 // var title = scale.title;
                  var description = scale.description;

                  //var cell_text = description;
                  row.push(description);
              });
              howManyPrograms = 0;
              $.each(criterion_programs, function(index, program){

              program_html += (index+1) +'. '+program.name+'<br>\n';
              howManyPrograms++;
              });
              row.push(program_html);
              role = {{{Auth::user()->role}}};
              
              switch (role) {
                case 1:
                if(!criterion_info.deleted_at) row.push('<a onclick = "statusClick(this)" data-criterion-id="'+criterion_info.criterion_id+'" href="#" class = "status">Active</a>');
              else row.push('<a href="#" onclick = "statusClick(this)" data-criterion-id="'+criterion_info.criterion_id+'" class = "status">Deactivated</a>');
                  break;
                case 2:
                if(!criterion_info.deleted_at) row.push('<a onclick = "statusClick(this)" data-criterion-id="'+criterion_info.criterion_id+'" href="#" class = "status">Active</a>');
              else row.push('<a href="#" onclick = "statusClick(this)" data-criterion-id="'+criterion_info.criterion_id+'" class = "status">Deactivated</a>');
              break;
              case 3:
                if(howManyPrograms<=1){
              if(!criterion_info.deleted_at) row.push('<a onclick = "statusClick(this)" data-criterion-id="'+criterion_info.criterion_id+'" href="#" class = "status">Active</a>');
              else row.push('<a href="#" onclick = "statusClick(this)" data-criterion-id="'+criterion_info.criterion_id+'" class = "status">Deactivated</a>');
                }

                else{
                  if(!criterion_info.deleted_at) row.push('<p>Active</p>');
              else row.push('<p>Deactivated</p>');
                }
                break;
                case 4:
                if(!criterion_info.deleted_at) row.push('<p>Active</p>');
              else row.push('<p>Deactivated</p>');
                  break;
              }
              dataset.push(row);

          })
          var columns_titles = Array();
          columns_titles.push({title: "Criterion"})
          var i = 0;
          while(i < criterions_levels){
            columns_titles.push({title: "Level "+(i+1)})
            i++;
          }
          columns_titles.push({title: "Program"});
          columns_titles.push({title: "Status"});

          var table_id = 'table-'+criterions_levels;
          var new_table_div = $('<div />').attr('class','table-responsive table-div '+table_id);
          new_table_div.append('<hr>');

          new_table_div.append('<hr>');
          new_table_div.append('<p><b class="h3">Criterions with '+criterions_levels+' levels</b></p>');
          new_table_div.append('<table id="'+table_id+'" class="table table-striped table-condensed" width="100%"></table>');

          new_table_div.appendTo('.table-responsive-0');
          var table2 = $('#'+table_id).DataTable( {
            order : [[parseInt(criterions_levels)+2, "asc"]],
            buttons: [
            {
              lengthMenu: [5, 10, 25, 50],
              autoWidth: false,
              retrieve: true,
              pageLength: 10,
              extend: 'collection',
              text: 'Export <span class="caret"></span>',
              buttons: [
              {
                extend: 'print',
                exportOptions: {
                  columns: ':visible'
                },
                text: 'Print',
              },
              {
                extend: 'excelHtml5',
                exportOptions: {
                  columns: ':visible'
                }
              },
              {
                extend: 'pdfHtml5',
                exportOptions: {
                  columns: ':visible',
                  stripNewlines: false,
                },
                customize: function(doc){
                  //$('#loadingModal').modal('show');

                  doc.pageSize = 'LEGAL';
                  doc.pageOrientation ='landscape';
                  doc.defaultStyle.fontSize = 10;
                  doc.styles.tableHeader.fillColor = '#E70033';

                  // doc.content[1].layout= 'lightHorizontalLines';
                  doc.content[1].layout = {
                    hLineWidth: function (i, node) {
                      if(i === 1){
                        return 2;
                      }
                      else if(i > 1){
                        return 1;
                      }
                      else {
                        return 0;
                      }
                    },
                    vLineWidth: function (i, node) {
                      return 0;
                    },
                    hLineColor: function (i, node) {
                      if(i === 1){
                        return '#000';
                      }
                      else if(i > 1){
                        return '#ccc';
                      }
                      else {
                        return 'transparent';
                      }
                    },
                    // vLineColor: function (i, node) {
                      //     return (i === 0 || i === node.table.widths.length) ? 'black' : 'gray';
                      // },
                      paddingLeft: function(i, node) { return 5; },
                      paddingRight: function(i, node) { return 5; },
                      paddingTop: function(i, node) { return 5; },
                      paddingBottom: function(i, node) { return 5; }
                    };

                    doc.content.splice( 0, 0, {
                      margin: [ 0, 0, 0, 12 ],
                      alignment: 'center',
                      width: 150,
                      image: 'data:image/png;base64,[encoded data, 31780 characters]'
                    } );

                  }
                },
                ]
              },
              {
                extend: 'colvis',
                columns: ':gt(0)',
                text: 'Column visibility <span class="caret"></span>',
              }
              ],
              data: dataset,
              columns: columns_titles,
            } );

            $('.col-sm-6:eq(0)', table2.table().container()).before(table2.buttons().container());


            $(document).on('click', '.buttons-columnVisibility', function(){
              console.log('visibility toggled');
              table2.columns.adjust().responsive.recalc();
            });

          tables.push(table2);
          
          

        })
        $('.table')
        var first_table = '.table-'+Object.keys(criteria)[0];

        $('.table-responsive').hide();
        $('.table-responsive-0').show();
        $(first_table).show();


         // $('table').show();
          /*$.each(criteria, function(index, value)
          {
              table.row.add([
                value.name,
                value.description12,
                value.description34,
                value.description56,
                value.description78
              ]);
          });*/
        }
        //else
        //{
         // $('table').hide();
        //}

        // Update display
        //table.draw();
    },
    'json'
    );

  }
}
  // --------------------------------------------------------------------------
  // Events
  // --------------------------------------------------------------------------

  // When list item is clicked, load corresponding info
  $('.list-group-item').on('click', function()
  {
    fetchObjectiveForCriteria(this);
  })
});

$('.view-scales').on('click', function()
  {
    var number_of_scales = this.value;

    $('.table-responsive').hide();
    $('.table-responsive-0').show();
    $('.table-'+number_of_scales).show();
  })

@stop
