@extends('layouts.master')

@section('navigation')
  @if($role==1)
    @include('local.managers.admins._new_navigation')
  @elseif($role==2)
    @include('local.managers.sCoords._new_navigation')
  @elseif($role==3)
    @include('local.managers.pCoords._new_navigation')
  @else
    @include('local.professors._navigation')
  @endif
@stop

@section('main')

<!-- No rubric modal -->
<div class="modal fade" id="modal-no-rubric">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">No Rubric Available</h4>
      </div>
        <div class="modal-body">
          There are no existing rubrics for your School. Please contact your Program's Coordinator. You will be redirected to the previous page.
        </div>
      <div class="modal-footer">
        <button id="button-redirect" class="btn btn-primary">Ok</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->


<div class="row">
  <div class="col-md-12">
    <div>
      {{ HTML::linkAction('ActivitiesController@show', 'Back to Activity', array($activity->id), array('class'=>'btn btn-default btn-sm pull-right')) }}
      <br>
      <br>
    </div>


    <div class="well">
      @if(count($activity->rubric)!=0)
        <span id="assigned_rubric" class="hidden" data-assigned-rubric="{{{ $activity->rubric[0]->id }}}"></span>
      @endif
      <input id="activity_id" type="hidden" value="{{{ $activity->id}}}">

      <div class="form-group">
        @if($activity->draft)
        <label>Select a Rubric:</label>
        <select id="select-template" class="form-control selectpicker">
        @else
        <label>Rubric (Assessment was published):</label>
        <select id="select-template" class="form-control selectpicker" disabled>
        @endif
          @foreach ($templates as $template)
            @if(count($activity->rubric)!=0 && $template->name == Rubric::find($activity->rubric[0]->id)->name)
              <option data-template-id="{{ $template->id }}" class="template" selected="selected">{{ $template->name }}</option>
            @else
              <option data-template-id="{{ $template->id }}" class="template">{{ $template->name }}</option>
            @endif
          @endforeach
        </select>
      </div>
      <input type='hidden' id='max' name= 'max' value="0">
      <input type ='hidden' id='num_of_scales' name ='num_of_scales' value ='0'>
      <div class="form-group">
        <label>Expected Criteria Outcome: </label>
        <!-- Select percentage. If there is a rubric, select the saved value -->
        <strong>
          <span id="expected_percentage">

          </span>%
        </strong> of all students must score at least
        <!-- Select points. If there is a rubric, select the saved value -->
        <strong>
          <span id="expected_points">

          </span>
        </strong>
        points in a criterion for it to pass.
      </div>
    </div>
  </div>
</div>

<div id="rubric-container" class="row">
  <div class="col-md-12">

<!--     <table class="table" style="table-layout: fixed"> -->
    <table class="table  table-striped table-condensed">
      <thead><tr><th colspan="6 "><h3 id="rubric-name"></h3></th></tr></thead>
      <thead><tr id ="criterion-header"><th>Criterion</th><th>Beginning (1-2)</th><th>In Progress (3-4)</th><th>Good (5-6)</th><th>Excellent (7-8)</th></tr></thead>
      <tbody>

      </tbody>
    </table>

    <div id="copyright-info">
      

      <hr>
      <p class="small"><strong>Copyright Information</strong></p>
      <ul id="copyright-list" class="list-unstyled small">
      </ul>
      <hr>
    </div>
    

    @if($activity->outcomes_attempted!=NULL)
    <div class="alert alert-info" role="alert">This activity has already been assessed. Changing the rubric will delete all saved scores.</div>
    @endif
    <div class="text-center">
        <button id="button-save-rubric" class="btn btn-lg btn-primary save"><span class="glyphicon glyphicon-floppy-disk"></span> Save</button>
    </div>
  </div>
</div>

<script>
  
function changeTable(data){
    
 
            amount_of_scales = parseInt($('#num_of_scales').val());
            counter2 = 0;
            maximum = parseInt($('#max').val());
            
           
            newScaleHeaders = '<th>Criterion</th>';
            counter = 0;
            division = maximum/amount_of_scales;
            if(amount_of_scales==1){
                newScaleHeaders+= "<th class ='titles' data-title-id  ="+data.titles[counter].title_id+">"+data.titles[counter].text+" (1 - "+maximum+")</th>";
            }
            else if(maximum!= amount_of_scales){
            while(counter <amount_of_scales){
                
                minimumScore = 1+(counter*division);
                maximumScore = (1+counter)*division;
                newScaleHeaders+= "<th class ='titles' data-title-id = "+data.titles[counter].title_id+">"+data.titles[counter].text+"  ("+minimumScore+" - "+maximumScore+")</th>";
                counter++;
            }
            }else{
                while(counter <amount_of_scales){
                
       
                newScaleHeaders+= "<th class ='titles' data-title-id  ="+data.titles[counter].title_id+"> "+data.titles[counter].text+ " </th>";
                counter++;
            }
            }
            newScaleHeaders += '<th>Outcomes</th>';
            
            $("#criterion-header").html(newScaleHeaders);
            
}

  </script>
@stop

@section('javascript')

// --------------------------------------------------------------------------
// Page load
// --------------------------------------------------------------------------
console.log({{ $activity }});

//If there are no rubrics to show, alert user and redirect.
if($('#select-template').children().length)
  loadTemplate();
else
{
  $('#modal-no-rubric').modal({
    backdrop: 'static'
  });
}

// --------------------------------------------------------------------------
// Functions
// --------------------------------------------------------------------------

// Fetch criteria associated to a specific learning outcome
function fetchCriteria(outcome)
{
  $.post
  (
    "{{ URL::route('fetchCriteria') }}",
    { id: outcome.find(':selected').data('outcome-id')},
    function(data)
    {
      $('#select-criterion').empty();

      data.forEach( function (arrayItem)
      {
        // If criterion does not belong to a user, display it
        if(arrayItem.user_id==null)
        {
          $('#select-criterion')
            .append('<option data-criterion-id="'+arrayItem.id+'" >'+arrayItem.name+'</option>');
        }
        // If it does, but the user is the one logged on, display.
        // Otherwise, ignore
        else if(arrayItem.user_id!="" && {{{Auth::id()}}}==arrayItem.user_id )
        {
          $('#select-criterion')
            .append('<option data-criterion-id="'+arrayItem.id+'" >'+arrayItem.name+'</option>');
        }

      });

      // Add custom option
      $('#select-criterion')
          .append('<option data-criterion-id="0">Custom</option>');

      $('#select-criterion').prop('disabled', false);
      $('#button-add-criterion').prop('disabled', false);
    }
  );
}

// Build list from copyright info in rubric
function buildCopyrightList()
{
    // Empty the copyright list
    $('#copyright-list').empty();

    $('tbody tr').each(function( index )
    {
        var criterion = $(this);
        // If there's copyright info
        if(criterion.data('criterion-copyright')!=null){
            var copyright = criterion.data('criterion-copyright');
            if($('#copyright-list li').length>0)
            {
                var found = false;
                $('#copyright-list li').each(function()
                {
                    // If found, give the string its number
                    if(copyright==$(this).find('span').text())
                    {

                        copyrightNumber = Number.parseInt($(this).find('sup').text());

                        console.log('a: '+copyrightNumber);

                        criterion.children('td:nth-child(2)').find('sup').text(copyrightNumber);
                        found =true;

                        //to break
                        return false;
                    }
                });

                // Otherwise, give it the next number and append a new item to the
                // list
                if(!found)
                {
                    var copyrightNumber = $('#copyright-list li').length+1;

                    console.log('b: '+copyrightNumber);
                    console.log(criterion.children('td:nth-child(2)').find('sup').length);

                    criterion.children('td:nth-child(2)').find('sup').text(copyrightNumber);
                    $('#copyright-list').append('<li><sup>'+copyrightNumber+' </sup><span>'+copyright+'<span></li>');
                }
            }
            else
            {
                criterion.children('td:nth-child(2)').find('sup').text('1');
                $('#copyright-list').append('<li><sup>1 </sup><span>'+copyright+'<span></li>');
            }
        }
    });

    if($('#copyright-info li').length>0)
    {
    $('#copyright-info').show();
    }
    else
    {
       $('#copyright-info').hide();
}}

// Load a template

function loadTemplate()
{
    $.post
    (
        "{{ URL::to('loadTemplate') }}",
        { id: $('#select-template').find(':selected').data('template-id')},
        function(data)
        {
            // Show the container and empty all rows
            $('#rubric-container').show();
            $('tbody').empty();

            //Set the name of the rubric
            $('#rubric-name').val(data.template.name);

            $('#expected_percentage').text(data.template.expected_percentage);
            $('#expected_points').text(data.template.expected_points)
            $('#max').val(data.template.max_score);
            $('#num_of_scales').val(data.template.num_scales);
            changeTable(data);


            // Set the contents of the rubric
            var temp_criterion = data.criterion;
            for(temp_c in temp_criterion){
                var str = '<tr data-criterion-id="'+temp_criterion[temp_c].criterion_id+'" data-criterion-copyright="'+temp_criterion[temp_c].copyright+'" data-criterion-notes="'+temp_criterion[temp_c].notes+'" data-outcomes = "'+temp_criterion[temp_c].outcomes+'">';
                current_criterion = temp_criterion[temp_c]
                var subcriteria ='';
                if(current_criterion.subcriteria){
                    var subcriteria_array = JSON.parse(current_criterion.subcriteria);
                    subcriteria = '<ul class="subcriteria list-unstyled">';
                    subcriteria_array.forEach(function (value) {
                        subcriteria += '<li>'+value+'</li>';
                    });
                    subcriteria += '</ul>';
                }
                if(current_criterion.notes)
                {
                    str+='<td><span><em data-toggle="tooltip" data-placement="top" title="'+current_criterion.notes+'">'+current_criterion.name+'</em></span><sup></sup>'+subcriteria+'</td>';
                }
                else
                {
                    str+='<td><span>'+current_criterion.name+'</span><sup></sup>'+subcriteria+'</td>';
                }
                
                
                for(scaleIndex in current_criterion.scales){

                  scale = current_criterion.scales[scaleIndex];

                  str+='<td>'+scale.description+'</td>';

              }
 str+= '<td>'+current_criterion.outcomes+'</td>';
                str+='</tr>';
               
    $('table tbody').append(str);

    buildCopyrightList();

                

                // Turn on tooltips again (because content is dynamic)
                $('[data-toggle="tooltip"]').tooltip();


                
            

            
            }
            /*
            var contents = JSON.parse(data.contents);
            contents.forEach(function (data)
            {
                // Append the fetched data
                var str ='<tr data-criterion-id="'+data.id+'" data-criterion-copyright="'+data.copyright+'" data-criterion-notes="'+data.notes+'"><th><span class="glyphicon glyphicon-move"></span></th><td>';


                var subcriteria = '';
                if(data.subcriteria){

                    var subcriteria_array = data.subcriteria;
                    subcriteria = '<ul class="subcriteria list-unstyled">';
                    subcriteria_array.forEach(function (value) {
                        subcriteria += '<li>'+value+'</li>';
                    });
                    subcriteria += '</ul>';

                }

                if(data.notes)
                {
                    str+='<span><em data-toggle="tooltip" data-placement="top" title="'+data.notes+'">'+data.name+'</em></span><sup></sup>'+subcriteria;
                }
                else
                {
                    str+='<span>'+data.name+'</span><sup></sup>'+subcriteria;
                }

                str+='</td><td class="editable" data-type="textarea">'+data.description12+'</td>'
                    +'<td class="editable" data-type="textarea">'+data.description34+'</td>'
                    +'<td class="editable" data-type="textarea">'+data.description56+'</td>'
                    +'<td class="editable" data-type="textarea">'+data.description78+'</td>'
                    +'<th><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></th></tr>';

                $('table tbody').append(str);

                // Build copyright list
                buildCopyrightList();

                // Enable X-Edtable on this new row
                $('.editable').editable({
                    unsavedclass: null,
                    rows: 4
                });

                // Turn on tooltips again (because content is dynamic)
                $('[data-toggle="tooltip"]').tooltip();


               
            }); */

          

            // Build Copyright List
            buildCopyrightList();
        }, 
        'json',
    );
}


/*
      console.log($('#expected_percentage').text());
      console.log($('#expected_points').text());

      // Set expected values
      $('#expected_percentage').text(data.expected_percentage);
      $('#expected_points').text(data.expected_points);

      // Set the contents of the rubric
      var contents = JSON.parse(data.contents);


      contents.forEach(function (criterion)
      {
        var str ='<tr data-assoc-outcome-id="'+criterion.outcome_id+'"'
          +'data-criterion-id="'+criterion.id+'" data-criterion-copyright="'+criterion.copyright+'" data-criterion-notes="'+criterion.notes+'">';


        var subcriteria = '';
        if(criterion.subcriteria){

            var subcriteria_array = criterion.subcriteria;
            subcriteria = '<ul class="subcriteria list-unstyled">';
            subcriteria_array.forEach(function (value) {
                subcriteria += '<li>'+value+'</li>';
            });
            subcriteria += '</ul>';

        }

        // If the criterion has notes, set the tooltip with them
        if(criterion.notes)
        {
          str+='<td><span><em data-toggle="tooltip" data-placement="top" title="'+criterion.notes+'">'+criterion.name+'</em></span><sup></sup>'+subcriteria+'</td>';
        }
        else
        {
          str+='<td><span>'+criterion.name+'</span><sup></sup>'+subcriteria+'</td>';
        }

        // Add the descriptions
        str+='<td>'+criterion.description12.replace(/\n/gi, '<br>')+'</td>'
          +'<td>'+criterion.description34.replace(/\n/gi, '<br>')+'</td>'
          +'<td>'+criterion.description56.replace(/\n/gi, '<br>')+'</td>'
          +'<td>'+criterion.description78.replace(/\n/gi, '<br>')+'</td></tr>';

        // Append the string to the table
        $('table tbody').append(str);

        // Turn on tooltips again (because content is dynamic)
        $('[data-toggle="tooltip"]').tooltip();
      });

      // Build Copyright List
      buildCopyrightList();
    }
  );
}
*/
// --------------------------------------------------------------------------
// Events
// --------------------------------------------------------------------------

// When trying to change the template, ask the user to confirm and reset the
// rubric if s/he does
$('#select-template').on('change', function()
{
      loadTemplate();
});

// When a learning outcome changes, update its criteria
$('#select-outcome').on('change', function()
{
  fetchCriteria($(this));
});

// When save button is clicked
$('#button-save-rubric').on('click', function(e)
{
  //Prevent page refresh
  e.preventDefault();

  var criteria = [];
  var titles =  [];
  max_score = $('#max').val();

  // For each criterion in the rubric, get its value and put it into an array
  $('tbody tr').each(function( index )
  {

    criteria.push($(this).data('criterion-id'));

    
    /*
      criterionObject.id = $(this).data('criterion-id');
      criterionObject.outcome_id = $(this).data('assoc-outcome-id');
      criterionObject.name = $(this).children('td:nth-child(1)').find('span').text();

      var subcriteriaArray = new Array();
      $(this).children('td:nth-child(1)').find('.subcriteria li').each(function(index){
          subcriteriaArray.push($(this).text());
      });
      criterionObject.subcriteria = subcriteriaArray;


      criterionObject.description12 = $(this).children('td:nth-child(2)').html().replace(/<br>/gi, '\n');
      criterionObject.description34 = $(this).children('td:nth-child(3)').html().replace(/<br>/gi, '\n');
      criterionObject.description56 = $(this).children('td:nth-child(4)').html().replace(/<br>/gi, '\n');
      criterionObject.description78 = $(this).children('td:nth-child(5)').html().replace(/<br>/gi, '\n');
      criterionObject.copyright = $(this).data('criterion-copyright');
      criterionObject.notes = $(this).data('criterion-notes');

      // Clone the object and push it into the array
      var clone = jQuery.extend({}, criterionObject);
      criteriaArray.push(clone);
*/

  });

  $('.titles').each(function(index){
    titles.push($(this).data('title-id'));
  });


  

  // If activity does not have a rubric, create it
  if($('#assigned_rubric').length === 0)
  {
    $('#js-error-row').hide();

    // Create
    $.post
    (
      "{{ URL::to('professor/saveRubric') }}",
      {
        name: $('#select-template').find(':selected').text(),
        activity_id: parseInt($('#activity_id').val()),
        
        expected_percentage: $('#expected_percentage').text(),
        expected_points: $('#expected_points').text(),
        criteria: criteria,
        titles:titles,
        max_score:max_score


      },
      function(data)
      {
        location.replace(data);
      }
    );
  }
  // Else, update it
  else
  {
    // Update database
    $.post
    (
      "{{ URL::to('professor/updateRubric') }}",
      {
        id: $('#assigned_rubric').data('assigned-rubric'),
        name: $('#select-template').find(':selected').text(),
        activity_id: parseInt($('#activity_id').val()),
        
        expected_percentage: $('#expected_percentage').text(),
        expected_points: $('#expected_points').text(),
        criteria: criteria,
        titles:titles,
        max_score:max_score
      },
      function(data)
      {
        location.replace(data);
      }
    );
  }
});

// When Ok button is clicked, redirect to previous page
// When save button is clicked
$('#button-redirect').on('click', function(e)
{
  e.preventDefault();
  history.go(-1);
});


@stop
