@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')
<!-- View criterion info -->
<div class="modal fade" id="modal-view-criterion">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
                <table class="table table-bordered">
                    <thead id = "criteria-header">;
                        @for($i=0; $i<$rubric->num_scales; $i++)
                        <th>{{$rubric->titles[$i]}} ({{1+($i*($rubric->max_score/$rubric->num_scales))}} - {{(1+$i)*($rubric->max_score/$rubric->num_scales)}})</th>
                        @endfor
                        <th>Notes</th>
                    </thead>
                    <tbody>
                        <tr>
                            
                            
                        </tr>
                    </tbody>
                </table>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->


<div class="row">
    <div class="col-md-12">
        <div class="well">
            <button id="button-language" class="btn btn-default btn-sm pull-right">Change language / Cambiar idioma</button>

            <div id="english-instructions">
                <h4>Instructions:</h4>
                <ol>
                    <li>Fill in the scores per criterion for each student. You can see the student's final score in the last column.</li>
                    <li>Click 'Publish Assessment' if you are done. Click 'Save as Draft' if you have not finished assessing the activity. You can come back later if you need to make any updates.
                    <li>Unpublished results will be isolated. That is, they <strong>will not</strong> be aggregated to other results.</li>
                </ol>

                <h4>Notes:</h4>
                <ul>
                    <li>If a particular criterion cannot be assessed for a student, select "N/A" (Not Applicable). This <strong>will not</strong> affect the student's score.</li>
                    <li>If a particular criterion was assessed but the student did not complete the necessary work, you must select "0". This <strong>will</strong> affect the student's score.</li>
                    <li>If a student did not complete any work for this activity, select "0" for all columns in that student's row.</li>
                    <li>If a student dropped the class, select "N/A" (Not Applicable) for all columns in that student's row.</li>
                    <li>Cells with "N/A" <strong>will not</strong> be used to determine whether a criterion is achieved. Only scores from 0 to {{$rubric->max_score}} will be considered for this purpose.</li>
                    <li>For this activity, <strong>at least one score must be from 1-{{$rubric->max_score}}.</strong> Otherwise, the 'Publish Assessment' and 'Save as Draft' buttons will be <strong>disabled</strong>. If you want to delete previously saved scores, go back to the activity and click the "Delete Assessment" button.</li>
                    <li>If some criterion has more weight on the student's final percentage, you can add it in the 'Weight' box above the criterion but be sure that the sum of criteria weights is equal to 100 (or aproximates it).
                </ul>
            </div>

            <div id="spanish-instructions">
                <h4>Instrucciones:</h4>
                <ol>
                    <li>Seleccione la puntuación por criterio para cada estudiante. Puede ver la puntuación final en la última columna.</li>
                    <li>Oprima 'Publish Assessment' una vez termine. Si no ha terminado, oprima 'Save as Draft' (guardar como borrador). Puede volver a esta página luego si desea hacer cambios.</li>
                    <li>Los resultados guardados como borrador estarán asilados. Es decir, <strong>no</strong> se agregarán a los demás resultados.</li>

                </ol>

                <h4>Notas:</h4>
                <ul>
                    <li>Si un criterio particular no puede ser evaluado, seleccione "N/A" (No Aplica). Esto <strong>no</strong> afectará la puntuación final del estudiante.</li>
                    <li>Si un criterio particular fue evaluado, pero el estudiante no completó el trabajo necesario, debe seleccionar "0". Esto <strong>sí</strong> afectará la puntuación final del estudiante.</li>
                    <li>Si un estudiante no completó el trabajo para esta actividad, seleccione "0" en todas las columnas de la fila de ese estudiante.</li>
                    <li>Si un estudiante se dio de baja, seleccione "N/A" (No Aplica) en todas las columnas de la fila de ese estudiante.</li>
                    <li>Las celdas con "N/A" <strong>no</strong> serán utilizadas para determinar si un criterio se alcanzó o no. Solamente las puntuaciones del 0 al {{$rubric->max_score}} serán consideradas.</li>
                    <li>Para esta actividad, <strong>al menos una puntuación deber ser del 1 al {{$rubric->max_score}}.</strong> De otra manera, el botón para guardar <strong>se desactivará</strong>. Si quiere borrar los resultados del avalúo, vuelva a la actividad y oprima el botón que dice "Delete Assessment".</li>
                    <li>Si algún criterio tiene más peso en el porcentaje final del estudiante, puedes añadirlo en la caja de "Weight" arriba del criterio deseado, pero debe asegurarse que la suma de los criterios sea igual a cien, o se aproxime. 

                </ul>
            </div>

        </div>
        <input type='hidden' id='max' name= 'max' value='{{$rubric->max_score}}'>
        <input type ='hidden' id='num_of_scales' name ='num_of_scales' value ='{{$rubric->num_scales}}'>
        <p id="course">Course: {{{ $course->code }}} {{{ $course->number }}}</p>
        <p id="section">Section: {{{ $course->section }}}</p>
        {{ HTML::linkAction('ActivitiesController@show', 'Back to Activity', array($activity->id), array('class'=>'btn btn-default btn-sm pull-right')) }}
        <p id="activity" data-activity-id="{{{ $activity->id }}}">Activity: {{{ $activity->name}}} </p>
        <p>Passing Criteria: <span id="expected_percentage">{{{ $rubric->expected_percentage }}}% of students must obtain at least </span><span id="expected_points">{{{$rubric->expected_points}}}</span> points </p>

        <table data-rubric-id="{{{ $rubric->id }}}" id="assessment-table" class="table table-striped table-condensed table-bordered">
            <thead>
                <tr>
                    <th>
                    </th>
                    @foreach ($rubric_criterion as $index => $criterion)
                    <th  data-criterion-id="{{{ $criterion->criterion_id }}}" ><div class="th-box">
                        
                        Weight<input class="form-control" id="weight-{{$index}}" name='weight[]' type="text"  value="{{$criterion->weight}}" data-activity-criterion-id="{{$criterion->activity_criterion_id}}">
                        </div></th>
                @endforeach
                <th colspan=3>
                <div class="th-box">
                        
                        Total<input class="form-control" id="total" name='total' type="text"  value="{{$total_weights}}" readonly>
                        </div>
                </th>
                </tr>
                    <tr>
                        <th>
                            <div class="th-box">
                                Student
                            </div>
                        </th>
                        @foreach ($rubric_criterion as $criterion)
                            <th class="criterion-field" data-activity-criterion-id = "{{$criterion->activity_criterion_id}}"data-rubric-criterion-id = "{{$criterion->rubric_criterion_id}}" data-criterion-id="{{{ $criterion->criterion_id }}}" ><div class="th-box">{{ $criterion->name}}</div></th>
                        @endforeach
                        <th>Student Percentage</th>
                        <th>Student % per Weight</th>
                        <th>Comments</th>
                    </tr>
            </thead>
            <tbody>

            <!-- If the activity was assessed, load the assessment. Otherwise load empty sheet -->
            @if(sizeof($assessments)!=0)
                <!-- For each assessment -->
                @foreach ($students as $student)
                    <tr class="student-row">
                        <!-- Fetch student name -->
                        <td class="student-field" data-student-id="{{ $student->id }}">
                            {{{ $student->name }}}
                        </td>

                        <!-- For each criterion in the rubric, there's a score field -->
                        @for ($i = 0; $i<sizeof($rubric_criterion); $i++)
                            <td class="score-field">
                                <select name="" id="" class="form-control" data-toggle="tooltip" data-placement="right" title="{{{ $student->name }}} 
{{{ $rubric_criterion[$i]->name }}}">
                                <!-- Option from 0-8 -->
                                
                                @for ($j=0; $j<=$rubric->max_score; $j++)
                                    <!-- If the decoded scores with index as the assessment id and second index as criterion id equals the loop index, mark it as selected -->

                                    @if(array_key_exists($student->id, $scores_array) && isset($scores_array[$student->id][$rubric_criterion[$i]->activity_criterion_id]) && $j ==  $scores_array[$student->id][$rubric_criterion[$i]->activity_criterion_id])
                                        <option value="{{$j}}" selected="selected">{{ $j }}</option>
                                    @else
                                        <option value="{{$j}}">{{ $j }}</option>
                                    @endif
                                @endfor

                                <!-- N/A option -->
                                @if( !array_key_exists($student->id, $scores_array)|| !isset($scores_array[$student->id][$rubric_criterion[$i]->activity_criterion_id]))
                                    <option value="N/A" selected="selected">N/A</option>
                                @else
                                    <option value="N/A">N/A</option>
                                @endif
                                </select>
                            </td>
                        @endfor
                        <td class="percentage"></td>
                        <td class="percentage-per-weight"></td>
                        <td class="">
                            <textarea class="comments full-textarea" placeholder="Max. 255 characters" maxLength="255" >
                            
                                @if(array_key_exists($student->id, $scores_array))
                                {{ $scores_array[$student->id]["comments"] }}
                                @endif
                            </textarea>
                        </td>
                     </tr>
                @endforeach
            @else
                @foreach ($students as $student)
                    <tr class="student-row">
                        <td class="student-field" data-student-id={{ $student->id }}>{{{ $student->name }}}</td>
                        @for ($i = 0; $i<sizeof($rubric_criterion); $i++)
                            <td class="score-field" data-weight = '1'>
                                <select name="" id="" class="form-control" data-toggle="tooltip" data-placement="right" title="{{{ $student->name }}}">
                                    @for($j=0; $j<=$rubric->max_score; $j++)
                                    <option value ='{{$j}}'>{{$j}}</option>
                                    @endfor
                                    <option selected="selected" value="N/A">N/A</option>
                                </select>
                            </td>
                        @endfor
                        <td class="percentage"></td>
                        <td class="percentage-per-weight"></td>
                        <td class="comments"><textarea class="comments full-textarea" placeholder="Max. 255 characters" maxLength="255" ></textarea></td>
                     </tr>
                @endforeach
            @endif
            </tbody>
            <tfoot>
                <tr>
                    <td>
                        <strong>Passed Criteria Percentage </strong>
                    </td>
                    @for ($i = 0; $i<sizeof($rubric_criterion); $i++)
                        <td class="total"><strong><span class="total-value"></span><span class="percent-sign">%</span></strong>
                        </td>
                    @endfor
                    <td></td>

                 </tr>
            </tfoot>
        </table>

        <div class="text-center">
            <button id="button-submit-assessment" class="btn btn-primary btn-lg publish">Publish Assessment</button>
            <button id="button-diagnostic-assessment" class="btn btn-primary btn-lg diagnostic">Save as Diagnostic Test</button>
            <button id="button-draft-assessment" class="btn btn-primary btn-lg draft">Save as Draft</button>
   
        </div>
    </div>
</div>
<script>

$('#button-submit-assessment, #button-draft-assessment, #button-diagnostic-assessment').on('click', function(e)
{

    var draft = 0;
    var diagnostic=0

    if($(this).hasClass('draft'))
        draft = 1;
    if($(this).hasClass('diagnostic'))
        diagnostic = 1;

    var expected_points = parseInt($('#expected_points').text());
    var expected_percentage = parseInt($('#expected_percentage').text());

    //Prevent page refresh
    e.preventDefault();

    // Row in the database
    var activity_id   =  $('#activity').data('activity-id');

    var student_info = new Object();

    // Object to hold the score sum of each criterion
    var criteriaSumObject = new Object();

    // Object to hold % of students that passed each criterion
    var CriteriaAchievedPercentage = new Object();

    // Object to hold all student evaluations
    var studentAssessments = new Array();

    var weights = new Object();

    $('input[name="weight[]"]').each(function (index){
        activity_criterion_id = $(this).data('activity-criterion-id');
        weight = $(this).val();
        
        weights[activity_criterion_id] = weight;
    });

    // Iterate through all students
    $('#assessment-table tbody tr').each(function( index )
    {   

        student_info[index] = new Object()
        student_info[index].studentId = $(this).find('.student-field').data('student-id');
        student_info[index].activity_crit_id = new Object();

       /* var ScoresObject     = new Object();        // Scores column in database
        var CriterionObject = new Object();     // Objects inside ScoresObject
        var SingleStudentAssessment = new Object();
        SingleStudentAssessment.student_id = $(this).find('.student-field').data('student-id');
        */
        // For each criterion, store the score in array
        $(this).children('td.score-field').each(function(index2)
        {
            // Table cell with a score
            var scoreField = $(this);

            // Criterion being evaluated in current iteration
            activity_criterion_id = $('.criterion-field').eq(index2).data('activity-criterion-id');
            score = scoreField.children('select').find(':selected').val();
            if(score != "N/A")
            student_info[index].activity_crit_id[activity_criterion_id] = score;
            // Score in the cell
            //var score = scoreField.children('select').find(':selected').val();

            // Store the score in the scores Object
            //ScoresObject[criterion_id]=score;

            // Initialize the index for the sum object, if it's undefined
            //if(typeof(criteriaSumObject[criterion_id]) == 'undefined')
            //{
            //    criteriaSumObject[criterion_id]=0;
            //}

            // Add to this criterion's total
            //criteriaSumObject[criterion_id]+=parseInt(score);
        });
        student_info[index].comments = $.trim($(this).find('.comments').val());

        //SingleStudentAssessment.scores = ScoresObject;
        //SingleStudentAssessment.percentage = $(this).find('.percentage').text();
        //SingleStudentAssessment.comments = $.trim($(this).find('.comments').val());
        // console.log('comment '+index+': '+SingleStudentAssessment.comments);
        // console.log('student object: '+JSON.stringify(SingleStudentAssessment));

        //var clone = jQuery.extend({}, SingleStudentAssessment);
        //studentAssessments.push(clone);


    });

    // console.log('students: '+JSON.stringify(studentAssessments));
    // console.log('total points per criteria: '+JSON.stringify(criteriaSumObject));

    // Iterate through all evaluated criteria, determining which were achieved
    // by comparing the completion percentage to the expected percentage
    /*var CriteriaAchievedResults = new Object();


    $('.total').each(function(index)
    {
        var id = $('.criterion-field').eq(index).data('criterion-id');

        CriteriaAchievedPercentage[id] = parseFloat($(this).find('span').text());

        //Set whether criterion was achieved (1) or not (0)
        if(CriteriaAchievedPercentage[id] >= expected_percentage)
        {
            CriteriaAchievedResults[id]=1;
        }
        else if (CriteriaAchievedPercentage[id] < expected_percentage)
        {
            CriteriaAchievedResults[id]=0;
        }
        else
        {
            CriteriaAchievedResults[id]=null;
        }

    });
*/
    // console.log('criteria percentages: '+JSON.stringify(CriteriaAchievedPercentage));
    // console.log('criteria achieved results: '+JSON.stringify(CriteriaAchievedResults));


    // Save activity to the database
    $.post
    (
        "{{ URL::action('ActivitiesController@saveAssessment') }}",
        {
            activity_id: activity_id,
            draft: draft,
            weights: JSON.stringify(weights),
        
            student_info: JSON.stringify(student_info),
            diagnostic:diagnostic
        },
        function(data)
        {
            location.replace(data);
        }
    );

});
    </script>
@stop

@section('included-js')

<!-- StickyTableHeaders js -->
<script src="{{ asset('vendor/stickyTableHeaders/js/jquery.stickytableheaders.min.js') }}"></script>

@stop


@section ('javascript')

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


// Enable fixed headers
//$('#assessment-table').stickyTableHeaders();


// Hide spanish instructions by default
$('#spanish-instructions').toggle();


$('.total').each(function(index)
{
    percentagePerCriterion(index+1);
});

$('.student-row').each(function(index)
{
    percentagePerStudent($(this));

});

// Highlight student names on hover
$('.student-row td').on('mouseover', function()
{
    $('.student-field').css(
    {
        'color': 'black',
    });

    $(this).siblings('.student-field').css(
    {
        'color': '#DD0026',
    });
});

toggleSaveButton();

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

// Calculate average of students that passed a specific criterion
function percentagePerCriterion(columnIndex)
{
    // Object to hold the score sum of each criterion
    var sum = 0 ;
    var total = 0;

    columnIndex+=1;

    // Iterate through rows of column
    $('table tbody tr td:nth-child('+columnIndex+')').each(function( index )
    {
        var val = parseInt($(this).children('select').find(':selected').val());

        /* If N/A or 0 are chosen, they are ignored in the calculation.  */
        if(val % 1 === 0)
        {
            if(val >= parseInt($('#expected_points').text()))
            {
                sum+=1;
            }

            total+=1;
        }
    });

    var percentage= (sum/total*100).toFixed(2);

    // If no criteria were assessed, set the percentage to 0.
    // This is to avoid show NaN%
    if(total==0)
    {
        percentage="N/A";
        $('.total:nth-child('+columnIndex+') span.total-value').html(percentage);
        $('.total:nth-child('+columnIndex+') span.percent-sign').hide();
    }
    else
    {
        $('.total:nth-child('+columnIndex+') span.total-value').html(percentage);
        $('.total:nth-child('+columnIndex+') span.percent-sign').show();
    }
}


// Calculate total for a specific student
function percentagePerStudent(row)
{
    // Object to hold the score student's total score
    var sum = 0 ;
    var total = 0;
    var percentage = 0;
    var max_score = parseInt($('#max').val());
    sum_of_weight = 0;
    per_of_weight =0;
	var sum_of_weight_fixed=0.0;
    row.find('td.score-field').each(function(index)
    {	
    	sum_of_weight_fixed+=parseFloat($('#weight-'+index).val());
        var val = parseInt($(this).children('select').find(':selected').val());
        if(val % 1 === 0) //If number is integer
        {
            sum += val;
            total+=1;
            per_of_weight += val * parseInt($('#weight-'+index).val()); 
            sum_of_weight += parseInt($('#weight-'+index).val());
        }

    });
    $('#total').val(sum_of_weight_fixed.toFixed(2));
<!--     console.log(sum_of_weight_fixed); -->

    percentage_per_weight = (100 *(per_of_weight/(max_score*sum_of_weight))).toFixed(2);
    percentage =((sum/(total*max_score))*100).toFixed(2);

    //If percentage is not a number, set it to 0.
    if(isNaN(percentage))
    {
        percentage="N/A";
        row.find('.percentage').html('<strong>'+percentage+'</strong>');
    }
    else
    {
        row.find('.percentage').html('<strong>'+percentage+'%</strong>');
    }
    if(isNaN(percentage_per_weight)){
        percentage_per_weight="N/A";
        row.find('.percentage-per-weight').html('<strong>'+percentage_per_weight+'</strong>');
    }
    else{
        row.find('.percentage-per-weight').html('<strong>'+percentage_per_weight+'%</strong>');
    }


}

function toggleSaveButton()
{
    // Check at least one total criterion percentage is not zero
    var all_zeros_criteria = true;

    $('.total-value').each(function(index)
    {
        if(Number($(this).text())>0.00)
            all_zeros_criteria = false;
    });


    // Check at least one total student percentage is not zero
    var all_zeros_students = true;

    $('.percentage').each(function(index)
    {
        var value = $(this).text().replace('%', '');
        if(Number(value)>0.00)
            all_zeros_students = false;
    });


    if(all_zeros_criteria && all_zeros_students)
    {
        $('#button-submit-assessment').prop('disabled', true);
        $('#button-draft-assessment').prop('disabled', true);
    }
    else
    {
        $('#button-submit-assessment').prop('disabled', false);
        $('#button-draft-assessment').prop('disabled', false);
    }

    return;
}


// --------------------------------------------------------------------------
// Events
// --------------------------------------------------------------------------


$('input[name="weight[]"]').on('change', function(e){
    $('.student-row').each(function(index)
    {
        percentagePerStudent($(this));
    
    });
});
// When any score changes, calculate percentages
$('select').on('change', function(e)
{
    percentagePerCriterion($(this).parent().index());
    percentagePerStudent($(this).closest('tr'));
    toggleSaveButton();
});
//LA LINEA DONDE VA, 410
// Submit button is clicked


// Language button is clicked
$('#button-language').on('click', function(e)
{
    $('#english-instructions').stop().toggle();
    $('#spanish-instructions').stop().toggle();

});

// Criterion name is clicked
$('.criterion-field').on('click', function()
{
    $.ajax({
        type: 'POST',
        url: "{{ URL::action('RubricsController@fetchRubricCriterion') }}",
        data: {
            criterion_id: $(this).data('criterion-id')
        },
        success: function(data)
        {
            data = JSON.parse(data);
            $('.modal-title').html(data.criteria.name);
            descriptions = '';
            $('.modal-body tbody tr').empty();
            for(i =0; i<{{$rubric->num_scales}}; i++){
                descriptions += '<td>'+data[i].description+'</td>'
            }
            $('.modal-body tbody tr').append
            (
                descriptions
            );

            if(data.criteria.notes!=null)
                $('.modal-body tbody tr').append('<td>'+data.criteria.notes+'</td>');
            else
                $('.modal-body tbody tr').append('<td></td>');

        },
        async:true
    });
    $('#modal-view-criterion').modal();
});


$(window).load(function(){
    $(".tableFloatingHeader").each(function(){
        $(this).remove();
    })
});

@stop