
var keybord_used = false;
var mouse_used = false;
var action_count = 0;
var trialCount = 1;
var init_time = new Date();
var collect = [];
var answer = true;
var value_count = 0;

var font_0 = trial_values[value_count].toFixed(decimals);
var font_1 = (trial_values[value_count] + (increments * 10)).toFixed(decimals);
var choices = ['A', 'B'];

var choice, base, changing;


$(document).ready(function() {

  choice = (Math.round(Math.random()));
  base = choices[choice];
  changing = choices[Math.abs(choice-1)];

  $('.' + base).css("font-family", '"' + url_part.para + '_' + font_0 + '"'); 
  $('.' + changing).css("font-family",  '"' + url_part.para + '_' + font_1 + '"'); 

  function make_active() { 
    if ($('#next_j').prop('disabled') == true) {
      $('#next_j').prop('disabled', false).css({'visibility' : 'visible', 'color' : 'black'});
    }
  };

  $("input:radio[name=choose]").click(function() {
      if (mouse_used == false) { mouse_used = true; }
      action_count += 1;
      make_active();
  });

  $('body').keydown(function (event) {
    if (event.keyCode == 37 || event.keyCode == 39) {
    event.preventDefault(); 
    }
  });


  $('body').keyup(function (event) {
  
    switch ( event.keyCode ) {
      case 37: 
        if (keybord_used == false) { keybord_used = true; } 
        make_active();
        $("#left").prop("checked", true);
        action_count += 1;
        break;
      case 39: 
        if (keybord_used == false) { keybord_used = true; } 
        make_active();
        $("#right").prop("checked", true);
        action_count += 1;
        break;
      case 13:
        $('#next_j').click();
        break;
    };


  });

  $('#the_form').submit(function(e) {
      $.ajax({
          type: 'POST',
          url: '/study/' + url_part.exp + '/' + url_part.para + '/ajax',
          data: JSON.stringify({
            width : $(window).width(),
            height : $(window).height(),
            startTime: init_time.toISOString().slice(0, 23).replace('T', ' '),
            endTime: new Date().toISOString().slice(0, 23).replace('T', ' '),
            timeDelta: Math.abs(new Date() - init_time),
            roundCount : value_count,
            trialCount : trialCount,
            wordLeft: $('.A').html(),
            wordRight: $('.B').html(),
            choice: $("input:radio[name=choose]:checked").val(),
            keyboard: keybord_used,
            dragged: mouse_used,
            interactionCount: action_count,
            fontLeft: $('.A').css("font-family"),
            fontRight: $('.B').css("font-family"),
            parameterLeft: Number($('.A').css("font-family").slice(1, -1).split("_")[1]),
            parameterRight: Number($('.B').css("font-family").slice(1, -1).split("_")[1]),
            parameterAnswer: Number($('.' + $("input:radio[name=choose]:checked").val()).css("font-family").slice(1, -1).split("_")[1]),
            end: 
              (function () {
                if (trialCount == trials_amount) { return collect; }
                else { false; }
              })(),
            }),
          contentType: "application/json",
          dataType: 'json',
          success: update_the_task,
          error: function(jqXHR, textStatus, errorThrown) {
             console.log(textStatus, errorThrown);
        }
      });
      e.preventDefault();
  });
});


function update_the_task (response) {
 
  action_count = 0;
  mouse_used = false;
  keybord_used = false;
  
  if (collect.length >= 8) {
    // console.log(collect.slice(-8));
    var collect_sum = collect.slice(-8).reduce(function(a, b) { return a + b; });
    var collect_sum_av = collect_sum / 8;
    console.log(collect_sum_av);
  }

  
  if (value_count == trial_values.length) {
    $(".range-slider").html("<p>End of the trials. <br> Please click <a href='./feedback'>next</a> to start the next round.</p>");
  }
  else {  
    if(trialCount >= trials_amount) {
      value_count += 1;
      console.log(trial_values[value_count]);
      font_0 = trial_values[value_count].toFixed(decimals);
      font_1 = (trial_values[value_count] + (increments * 10)).toFixed(decimals);
      trialCount = 0;
      collect = [];

      // var end_result = diff_json(collect_av).sort( sorting_array('diff'));
    }
    else {
      
      answer = $("input:radio[name=choose]:checked").val() 

      if (answer != base) {
          font_1 = (Number(font_1) - increments).toFixed(decimals);
          collect.push(1);  
      }
      else {
          font_1 = (Number(font_1) + (3 * increments)).toFixed(decimals); 
          collect.push(0);  
      }

    }

    $('.A').html(response['A']);
    $('.B').html(response['B']);

    choice = (Math.round(Math.random()));
    base = choices[choice];
    changing = choices[Math.abs(choice-1)];

    $('.' + base).css("font-family", '"' + url_part.para + '_' + font_0 + '"'); 
    $('.' + changing).css("font-family",  '"' + url_part.para + '_' + font_1 + '"'); 

    console.log('A: ', $('.A').css("font-family"));
    console.log('B: ', $('.B').css("font-family"));

    trialCount += 1;    

    $("input:radio[name=choose]").prop('checked', false);
    $("#next_j").prop("disabled", true).css({"left" : "45%", "color" : "#efefef"});
    init_time = new Date();
    
  }
};
