var keybord_used = false;
var mouse_used = false;
var action_count = 0;
var trialCount = 0;
var init_time = new Date();

var font_loaded = false;
var choices = ['A', 'B'];


$(document).ready(function() {

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

  var font_base = url_part.para + '_' + tp_0;
  var font_changing = url_part.para + '_' + sp_0;

  var f_b = new FontFaceObserver('"' + font_base + '"');
  var f_c = new FontFaceObserver('"' + font_changing + '"');

  Promise.all([f_b.load(), f_c.load()]).then(function () {
      font_loaded = true;
  });

  $('.' + base).css("font-family", '"' + font_base + '"'); 
  $('.' + changing).css("font-family",  '"' + font_changing + '"'); 

  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) {
      $("#next_j").prop("disabled", true).css({"color" : "#efefef"});
      $.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),
            trialCount : trialCount,
            wordLeft: $('.A').html(),
            wordRight: $('.B').html(),
            choice: $("input:radio[name=choose]:checked").val(),
            keyboard: keybord_used,
            dragged: mouse_used,
            interactionCount: action_count,
            fontLoaded: font_loaded,
            fontLeft: $('.A').css("font-family"),
            fontRight: $('.B').css("font-family"),
            // 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) {
 
  if (response['trialsEnd']) {
    $(".range-slider").html("<p>You finished the trials! <br> Please click the <span class='letter_spaced'>NEXT</span> button to finish.</p> <form id='end_first_round' action='./feedback' method='post'> <input type='submit' value='N E X T'> </form>");
  }

  else {

    $('#left').prop('checked', false);
    $('#right').prop('checked', false);

    action_count = 0;
    mouse_used = false;
    keybord_used = false;
    font_loaded = false;
    
    $('.A').html(response['A']);
    $('.B').html(response['B']);

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

    var font_base = url_part.para + '_' + response['tp'];
    var font_changing = url_part.para + '_' + response['sp'];

    var f_b = new FontFaceObserver('"' + font_base + '"');
    var f_c = new FontFaceObserver('"' + font_changing + '"');

    Promise.all([f_b.load(), f_c.load()]).then(function () {
        font_loaded = true;
    });

    $('.' + base).css("font-family", '"' + font_base + '"'); 
    $('.' + changing).css("font-family",  '"' + font_changing + '"'); 

    trialCount += 1;  
    $('#count_').html(trialCount);
    init_time = new Date();
  }
};

