@extends('layouts.master')

@section('navigation')
        @include('local.professors._navigation')
@stop

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

<div class="row">
  <div class="col-md-12">
    <div class="well">
      <label>Expected Criteria Outcome</label>
      <form class="form-inline">
          <input id="activity_id" type="hidden" value="{{{ $activity->id}}}">
          <div class="form-group">
            <!-- Select percentage. If there is a rubric, select the saved value -->
            <select id="expected_percentage" class="form-control">
              @for($i = 1; $i <= 20; $i++)
                @if($rubric!=NULL && $rubric->expected_percentage == $i*5)
                  <option selected="selected" value="{{ $i*5 }}">{{ $i*5 }}</option>
                @elseif($rubric==NULL && $i*5==70)
                  <option selected="selected" value="{{ $i*5 }}">{{ $i*5 }}</option>
                @else
                  <option value="{{ $i*5 }}">{{ $i*5 }}</option>
                @endif
              @endfor
            </select>
            % of all students must score at least
            <!-- Select points. If there is a rubric, select the saved value -->
            <select id="expected_points" class="form-control">
              @for($i = 1; $i <= 8; $i++)
                @if($rubric!=NULL && $rubric->expected_points == $i)
                  <option selected="selected" value="{{ $i }}">{{ $i }}</option>
                @elseif($rubric==NULL && $i==6)
                  <option selected="selected" value="{{ $i }}">{{ $i }}</option>
                @else
                  <option value="{{ $i }}">{{ $i }}</option>
                @endif
              @endfor
            </select>
            point(s) in a criterion for it to pass.
          </div>
        </form>
        <div class="form-group">
          <label>Select a Template, or create your own Rubric</label>
          <select id="select-template" class="form-control">
            <option data-template-id="0">Custom</option>
            <optgroup label="Templates">
              @foreach ($templates as $template)
              <option data-template-id="{{ $template->id }}" class="template">{{ $template->name }}</option>
              @endforeach
            </optgroup>
            <optgroup label="Your Rubrics">
              @foreach ($rubrics as $rubric)
                <!-- If a rubric already exists for this activity, select it for loading -->
                @if ($activity->rubric_id == $rubric->id)
                  <option selected="selected" data-rubric-id="{{ $rubric->id }}" class="rubric">{{ $rubric->name }}</option>
                @else
                  <option data-rubric-id="{{ $rubric->id }}" class="rubric">{{ $rubric->name }}</option>
                @endif
              @endforeach
            </optgroup>

          </select>
        </div>
        <div class="form-group">
          <label>Select a Learning Outcome</label>
          <select id="select-outcome" class="form-control">
            @foreach ($outcomes as $outcome)
            <option data-outcome-id="{{ $outcome->id }}">{{ $outcome->name }}</option>
            @endforeach
          </select>
        </div>
        <div class="form-group">
          <label>Select a Criterion</label>
          <select id="select-criterion" class="form-control">
          </select>
        </div>
        <button id="button-add-criterion" class="btn btn-md btn-primary center-block">Add Criterion to Rubric</button>
      </form>
    </div>
  </div>
</div>

<div id="rubric-container" class="row">
  <div class="col-md-12">
    @if($activity->rubric_id!=NULL)
      <span id="assigned_rubric" class="hidden" data-assigned-rubric="{{{ $activity->rubric_id }}}"></span>
    @endif
    <table class="table editable-table">
      <thead><tr><th colspan="6 "><input id="rubric-name" type="text" class="form-control input-lg" placeholder="Rubric Name"></th></tr></thead>
      <thead><tr><th>Criterion</th><th>Beginning (1-2)</th><th>In Progress (3-4)</th><th>Good (5-6)</th><th>Excellent (7-8)</th><th></th></tr></thead>
      <tbody>

      </tbody>
    </table>

    <div class="text-center">
        <button id="button-save-rubric" class="btn btn-lg btn-primary save">Save</button>
    </div>
  </div>
</div>
@stop

@section('javascript')

// --------------------------------------------------------------------------
// Page load
// --------------------------------------------------------------------------

// Fetch criteria of first outcome
fetchCriteria($('#select-outcome'));

//
if($('#select-template').find(':selected').data('template-id') == '0')
{
  // Hide table
  $('#rubric-container').hide();
}
else
{
  alert('else');
  loadRubric();
}

// Find way to get the original name for use farther below. This doesn't work.
var originalName = $('#rubric-name').val();
alert(originalName);

// --------------------------------------------------------------------------
// 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);
    }
  );
}

// Add a new criterion to the rubric
function addCriterion()
{

  if(!$('tbody').children().length)
  {
    $('#rubric-container').show();
  }

  var id= parseInt($('#select-criterion').find(':selected').data('criterion-id'));

  // If criterion already exists in the db
  if(id!=0)
  {

    // Check for duplicates
    var duplicates=false;
    $('tbody tr').each(function()
    {
      if ($(this).data('criterion-id') == id)
      {
        duplicates=true;
      }
    });

    if(duplicates)
    {
      $('#js-error-row').show();
      $('#js-error-row').find('#error-message').text('Error: The selected criterion was already added.');
      return;
    }
    else
    {
      $('#js-error-row').hide();
    }

    $.post
    (
      "{{ URL::route('fetchCriterion') }}",
      { id: id},
      function(data)
      {
        // If saved criterion is not custom, it can be removed but not edited
        if(data.user_id==null)
        {
          $('table tbody')
            .append('<tr data-assoc-outcome-id="'+data.outcome_id+'"'
            +'data-criterion-id="'+data.id+'">'
            +'<td>'+data.name+'</td>'
            +'<td>'+data.description12+'</td>'
            +'<td>'+data.description34+'</td>'
            +'<td>'+data.description56+'</td>'
            +'<td>'+data.description78+'</td>'
            +'<th><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></th></tr>');
        }
        // If saved criterion is custom, it can be removed and edited
        else
        {
          $('table tbody')
            .append('<tr data-assoc-outcome-id="'+data.outcome_id+'"'
            +'data-criterion-id="0">'
            +'<td class="editable" data-type="textarea">Custom</td>'
            +'<td class="editable" data-type="textarea"></td>'
            +'<td class="editable" data-type="textarea"></td>'
            +'<td class="editable" data-type="textarea"></td>'
            +'<td class="editable" data-type="textarea"></td>'
            +'<th><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></th></tr>');
        }

        // Enable X-Edtable on this new row
        $('.editable').editable({
          unsavedclass: null,
          rows: "4"
        });
      }
    );
  }
  // If criterion is completely new and custom
  else
  {

    $('table tbody')
      .append('<tr data-assoc-outcome-id="'+$('#select-outcome').find(':selected').data('outcome-id')+'"'
      +'data-criterion-id="0">'
      +'<td class="editable" data-type="textarea">Custom</td>'
      +'<td class="editable" data-type="textarea"></td>'
      +'<td class="editable" data-type="textarea"></td>'
      +'<td class="editable" data-type="textarea"></td>'
      +'<td class="editable" data-type="textarea"></td>'
      +'<th><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></th></tr>');

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

  }
}

// Fetch single criterion
function fetchCriterion(criterion)
{
  $.post
  (
    "{{ URL::route('fetchCriterion') }}",
    { id: outcome.find(':selected').data('outcome-id')},
    function(data)
    {
      $('#select-criterion').empty();

      data.forEach( function (arrayItem)
      {
        $('#select-criterion')
          .append('<option data-criterion-id="'+arrayItem.id+'" >'+arrayItem.name+'</option>');
      });

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

// Load a template
function loadTemplate()
{
  // Set expected values to the default 70 / 5
  $('#expected_percentage option[value="70"]').prop('selected', true);
  $('#expected_points option[value="5"]').prop('selected', true);

  $.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.name);

      // Set the contents of the rubric
      var contents = JSON.parse(data.contents);
      contents.forEach(function (criterion)
      {
        $('table tbody')
          .append('<tr data-assoc-outcome-id="'+criterion.outcome_id+'"'
          +'data-criterion-id="'+criterion.id+'">'
          +'<td>'+criterion.name+'</td>'
          +'<td>'+criterion.description12+'</td>'
          +'<td>'+criterion.description34+'</td>'
          +'<td>'+criterion.description56+'</td>'
          +'<td>'+criterion.description78+'</td>'
          +'<th></th></tr>');

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

// Load a rubric
function loadRubric()
{
  $.post
  (
    "{{ URL::to('professor/loadRubric') }}",
    { id: $('#select-template').find(':selected').data('rubric-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.name);

      // Set the contents of the rubric
      var contents = JSON.parse(data.contents);
      contents.forEach(function (criterion)
      {

        // If saved criterion is not custom, it can be removed but not edited
        if(criterion.user_id==null)
        {
          $('table tbody')
            .append('<tr data-assoc-outcome-id="'+criterion.outcome_id+'"'
            +'data-criterion-id="'+criterion.id+'">'
            +'<td>'+criterion.name+'</td>'
            +'<td>'+criterion.description12+'</td>'
            +'<td>'+criterion.description34+'</td>'
            +'<td>'+criterion.description56+'</td>'
            +'<td>'+criterion.description78+'</td>'
            +'<th><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></th></tr>');
        }
        // If saved criterion is custom, it can be removed and edited
        else
        {
          $('table tbody')
            .append('<tr data-assoc-outcome-id="'+criterion.outcome_id+'"'
            +'data-criterion-id="0">'
            +'<td class="editable" data-type="textarea">Custom</td>'
            +'<td class="editable" data-type="textarea"></td>'
            +'<td class="editable" data-type="textarea"></td>'
            +'<td class="editable" data-type="textarea"></td>'
            +'<td class="editable" data-type="textarea"></td>'
            +'<th><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></th></tr>');
        }

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

    }
  );
}

// Checks whether the user wants to save a rubric with a name that already exists
function nameExists()
{
  var duplicates = false;
  $('#select-template option').each(function()
  {
    if($('#rubric-name').val().trim()===$(this).text().trim())
    {
      duplicates = true;
      return;
    }
  });
  return duplicates;
}

// --------------------------------------------------------------------------
// 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()
{
  // If changing to custom template, reset
  if($('#select-template').find(':selected').data('template-id')=='0')
  {
    $('#rubric-container').hide();
    $('#rubric-name').val('');
    $('tbody').empty();
  }
  // Otherwise, load the selected template/rubric
  else
  {
    if($('#select-template').find(':selected').hasClass('template'))
    {
      loadTemplate();
    }
    else
    {
      loadRubric();
    }
  }

});

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

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

  //Add new criterion
  addCriterion();
});

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

  // Empty field validation
  var emptyFields=false;
  $('td').each(function()
  {
    if ($(this).text() == "" || $(this).text() == "Empty")
    {
      emptyFields=true;
    }
  });

  // If any fields are empty, display error and return
  if(emptyFields || $.trim($('#rubric-name').val())=='')
  {
    $('#js-error-row').show();
    $('#js-error-row').find('#error-message').text('Error: Please fill all the fields.');
    return;
  }
  else
  {
      $('#js-error-row').hide();
  }



//---------------------------------------------------vvv-------------------------------------------------------------------
//TODO update assessments


  var criterionObject = new Object();
  var criteriaArray = new Array();

  // For each criterion in the rubric, get its value and put it into an array
  $('tbody tr').each(function( index )
  {
      criterionObject.id = $(this).data('criterion-id');
      criterionObject.outcome_id = $(this).data('assoc-outcome-id');
      criterionObject.name = $(this).children('td:nth-child(1)').text();
      criterionObject.description12 = $(this).children('td:nth-child(2)').text();
      criterionObject.description34 = $(this).children('td:nth-child(3)').text();
      criterionObject.description56 = $(this).children('td:nth-child(4)').text();
      criterionObject.description78 = $(this).children('td:nth-child(5)').text();

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

  });

  // If activity does not have a rubric, create it
  if($('#assigned_rubric').length === 0)
  {
    // Check whether a rubric with the written name already exists
    // If it does, display an error.
    if(nameExists())
    {
      $('#js-error-row').show();
      $('#js-error-row').find('#error-message').text('Error: A rubric or template with that name already exists.');
      return;
    }

    $('#js-error-row').hide();

    // Create
    $.post
    (
      "{{ URL::to('professor/saveRubric') }}",
      {
        name: $('#rubric-name').val(),
        activity_id: parseInt($('#activity_id').val()),
        contents: JSON.stringify(criteriaArray),
        expected_percentage: $('#expected_percentage').find(':selected').val(),
        expected_points: $('#expected_points').find(':selected').val()

      },
      function(data)
      {
        location.reload(true);
      }
    );
  }
  // Else, update it
  else
  {
    // Check whether a rubric with the written name already exists and if the
    // selected template's id equals assigned id. If the name exists, but the
    // ids don't match, show error

    alert(originalName);
    if(originalName != $('#rubric-name').val() &&  nameExists())
    {
      $('#js-error-row').show();
      $('#js-error-row').find('#error-message').text('Error: You must change the name of the rubric.');
      return;
    }

    $('#js-error-row').hide();

    // Update database
    $.post
    (
      "{{ URL::to('professor/updateRubric') }}",
      {
        id: $('#assigned_rubric').data('assigned-rubric'),
        name: $('#rubric-name').val(),
        contents: JSON.stringify(criteriaArray),
        expected_percentage: $('#expected_percentage').find(':selected').val(),
        expected_points: $('#expected_points').find(':selected').val()
      },
      function(data)
      {
        location.reload();
      }
    );
  }
});

//-----------------------------------------------------^^^------------------------------------------------------------------

// TODO Move this somewhere else
// When the delete button is clicked
$('#button-delete-rubric').on('click', function(e)
{

  // Delete from database
  $.post
  (
    "{{ URL::to('professor/deleteRubric') }}",
    {
      id: $('#select-template').find(':selected').data('rubric-id')
    },
    function(data)
    {
      location.reload();

    }
  );
});


// Remove a criterion and hide the table if it was the only one
$('table').on('click', '.glyphicon-remove', function(e)
{
  $(this).closest('tr').remove();

  if(!$('tbody').children().length)
  {
    $('#rubric-container').hide();
  }
});

@stop
