
var keybord_used = false;
var mouse_used = false;
var action_count = 0;
var trialCount = 1;
var font_value = allTrials[0].step_value;
var font_loaded = false;


$(document).ready(function() {


  var font_A = url_part.para + '_' + value_to_font(allTrials[0].lower);
  var font_B = url_part.para + '_' + value_to_font(allTrials[0].upper);
  var font_C = url_part.para + '_' + value_to_font(allTrials[0].step_value);

  var f_A = new FontFaceObserver('"' + font_A + '"');
  var f_B = new FontFaceObserver('"' + font_B + '"');
  var f_C = new FontFaceObserver('"' + font_C + '"');

  Promise.all([f_A.load(), f_B.load(), f_C.load()]).then(function () {
      font_loaded = true;
  });

  $('.A').css("font-family", '"' + font_A + '"');
  $('.B').css("font-family", '"' + font_B + '"');
  $('#C').css("font-family", '"' + font_C + '"');

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

  $('#set_value').mousedown(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) {

    var knob_val = $('#set_value');
    var value = Number(knob_val.val());
    var increment = 1;

    if (event.shiftKey) { increment = 7 + Math.floor(Math.random() * 7); }

    switch ( event.keyCode ) {
      case 37:
        if (keybord_used === false) { keybord_used = true; }
        make_active();
        knob_val.val( value - increment );
        action_count += 1;
        break;
      case 39:
        if (keybord_used === false) { keybord_used = true; }
        make_active();
        knob_val.val( value + increment );
        action_count += 1;
        break;
      case 13:
        $('#nextButton').click();
        break;
    }
  });

  $('#the_form').submit(function(e) {

      $("#nextButton").prop("disabled", true).css({"left" : "50%", "color" : "#efefef"});

      $.ajax({
          type: 'POST',
          url: '/study/' + url_part.exp + '/' + url_part.para + '/ajax',
          data: JSON.stringify({
            trialCount : trialCount,
            roundCount : roundCount,
            segment : segment,
            width : $(window).width(),
            height : $(window).height(),
            wordLeft: $('.A').html(),
            wordRight: $('.B').html(),
            wordCenter: $('#C').html(),
            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),
            keyboard: keybord_used,
            dragged: mouse_used,
            interactionCount: action_count,
            fontLeft: $('.A').css("font-family"),
            fontRight: $('.B').css("font-family"),
            fontCenter: $('#C').css("font-family"),
            fontLoaded: font_loaded,
            parameterLeft: axis_seg_low.map(0, 100, axis_para_min, axis_para_max),
            parameterRight: axis_seg_high.map(0, 100, axis_para_min, axis_para_max),
            parameterCenter: font_value.map(0, 100, axis_para_min, axis_para_max),
            parameterKnob: Number($('#valueKnob').val()).map_seg().map(0, 100, axis_para_min, axis_para_max),
            parameterAnswer: Number($('#set_value').val()).map_seg().map(0, 100, axis_para_min, axis_para_max),
            valueLeft: axis_seg_low,
            valueCenter: font_value, //Number(font_value).map(axis_seg_low, axis_seg_high, 0, 100),
            valueRight: axis_seg_high, //$('#set_value').prop('max'),
            valueKnob: Number($('#valueKnob').val()),
            valueAnswer: Number($('#set_value').val()),
            valueKnobMapped: Number($('#valueKnob').val()).map_seg(),
            valueAnswerMapped: Number($('#set_value').val()).map_seg(),
            end:
              (function () {
                if (trialCount == trials_amount) {
                  return collect;
                }
                else {
                  return false;
                }
              }())
            }),
          contentType: "application/json",
          dataType: 'json',
          success: update_the_task,
          error: function(jqXHR, textStatus, errorThrown) {
             console.log(textStatus, errorThrown);
        }
      });
      e.preventDefault();
  });
});



Number.prototype.map = function (in_min, in_max, out_min, out_max) {
  return (this - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
};

Number.prototype.map_seg = function () {
  if (url_part.para == 'aperture') { mapped_val = this.map(100, 0, axis_seg_low, axis_seg_high); }
  else { mapped_val = this.map(0, 100, axis_seg_low, axis_seg_high); }
  return mapped_val;
};

var axis_para_min = Number($('#axis_para_min').val());
var axis_para_max = Number($('#axis_para_max').val());
var step = Number($('#increments').val());

var init_time = new Date();


function value_to_para (a_number) {
    var user_val_mapped = Number(a_number).map(0, 100, axis_para_min, axis_para_max);
    return user_val_mapped;
}

function value_to_font (a_number) {
    var user_val_mapped_round = step * Math.round(value_to_para (a_number) / step);
    user_val_mapped_round = user_val_mapped_round.toFixed(decimals);
    return user_val_mapped_round;
}

function para_to_value (a_number) {
    var user_val_mapped = Number(a_number).map(axis_para_min, axis_para_max, 0, 100);
    return user_val_mapped;
}


function get_average(an_array) {
    var sum = 0;
    var i = an_array.length;
    while(i--) {
      sum += an_array[i];
    }
    return sum / an_array.length;
}

function average_json (a_json) {
  var collect_av = {};
  jQuery.each(a_json, function(i, val) {
    jQuery.each(val, function(j, val_) {
      collect_av[j] = get_average(val_);
    });
  });
  return collect_av;
}

function diff_json (a_json) {
  var collect_diff = [];
  for (i = 0; i < trial_array.length - 1; i += 1) {
      collect_diff[i] = {
        "lower" : trial_array[i],
        "upper" : trial_array[i + 1],
        "diff"  : Math.abs(a_json[trial_array[i+1]] - a_json[trial_array[i]]) };
  }
  return collect_diff;
}

function sorting_array(prop){
   return function(a,b) {
      if( a[prop] < b[prop]){
          return 1;
      }
      if( a[prop] > b[prop] ){
          return -1;
      }
      return 0;
   };
}

function update_the_task (response) {

  trialCount = response.trial_counter
  collect[segment][font_value].push(Number($('#set_value').val()).map_seg());

  action_count = 0;
  mouse_used = false;
  keybord_used = false;
  font_loaded = false;

  if(trialCount > trials_amount) {
    var collect_av = average_json(collect);
    var end_result = diff_json(collect_av).sort( sorting_array('diff'));

    $(".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='hidden' name='sorted_diffs' id='sorted_diffs' value=" + JSON.stringify(end_result) + "><input type='hidden' name='answers_av' id='answers_av' value=" + JSON.stringify(collect_av) + "><input type='submit' value='N E X T'> </form>");

  }
  else {

    segment = allTrials[trialCount - 1].seg;
    axis_seg_low    = allTrials[trialCount - 1].lower;
    font_value      = allTrials[trialCount - 1].step_value;
    axis_seg_high   = allTrials[trialCount - 1].upper;
    var random_knob = Math.floor( Math.random() * 100 );

    var font_A = url_part.para + '_' + value_to_font(axis_seg_low);
    var font_B = url_part.para + '_' + value_to_font(axis_seg_high);
    var font_C = url_part.para + '_' + value_to_font(font_value);

    var f_A = new FontFaceObserver('"' + font_A + '"');
    var f_B = new FontFaceObserver('"' + font_B + '"');
    var f_C = new FontFaceObserver('"' + font_C + '"');

    Promise.all([f_A.load(), f_B.load(), f_C.load()]).then(function () {
        font_loaded = true;
    });

    $('.A').html(response.A);
    $('.A').css("font-family", '"' + font_A + '"');
    $('.B').html(response.A);
    $('.B').css("font-family", '"' + font_B + '"');
    $('#C').html(response.C);
    $('#C').css("font-family", '"' + font_C + '"');

    $('#set_value').val(random_knob);
    $('#valueKnob').val(random_knob);
    // trialCount += 1;
    
    $('#count_').html(trialCount);
    init_time = new Date();
  }
}
