<commit_before>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(function() {
  $("#submission_deadline.datepicker").datepicker( {
    showOn: 'button',
    buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
    dateFormat: "mm/dd/yy",
    changeMonth: true,
    changeYear: true,
    numberOfMonths: 1
  });
});

$(function() {
  $('#comment_dialog_form').hide();
  $('.add_comments_link').click(function(event) {
    event.preventDefault();
    $('#comment_comment_type').attr('value', $(event.target).attr("data-comment-type"));
    $('#comment_dialog_form').dialog( {
      width: 600,
      height: 310,
      modal: true,
      closeOnEscape: true,
      draggable: true,
      resizable: false,
      title: "Add New Comments",
      show: {
        effect: "blind",
        duration: 1000
      },
      hide: {
        effect: "toggle",
        duration: 1000
      },
      open: function()
      {
        $("#comment_dialog_form").dialog("open");
      },
      close: function() {
        $('#comment_dialog-form').dialog("close");
        $(this).find('form')[0].reset();
        window.location.reload()
      }
    }).prev ().find(".ui-dialog-titlebar-close").show();
    return false
  });
});

$(function() {
  $("#cancel_action").bind("click",function() {
    $("#comment_dialog_form").reset();
  });
});

$(function() {
  $("#reviewer_comments, .hide-reviewer-comments").hide();
  $(".view-reviewer-comments").click(function(event){
    event.preventDefault();
    $("#reviewer_comments").show();
    $(".view-reviewer-comments").hide();
    $(".hide-reviewer-comments").show();
  });
});

$(function() {
  $(".hide-reviewer-comments").click(function(event){
    event.preventDefault();
    $("#reviewer_comments").hide();
    $(".hide-reviewer-comments").hide();
    $(".view-reviewer-comments").show();
  });
});

$(function() {
  $("#owner_comments, .hide-owner-comments").hide();
  $(".view-owner-comments").click(function(event){
    event.preventDefault();
    $("#owner_comments").show();
    $(".view-owner-comments").hide();
    $(".hide-owner-comments").show();
  });
});

$(function() {
  $(".hide-owner-comments").click(function(event){
    event.preventDefault();
    $("#owner_comments").hide();
    $(".hide-owner-comments").hide();
    $(".view-owner-comments").show();
  });
});

$(function() {
  $("#plan_history, .hide-plan-history").hide();
  $(".view-plan-history").click(function(event){
    event.preventDefault();
    $("#plan_history").show();
    $(".view-plan-history").hide();
    $(".hide-plan-history").show();
  });
});

$(function() {
  $(".hide-plan-history").click(function(event){
    event.preventDefault();
    $("#plan_history").hide();
    $(".hide-plan-history").hide();
    $(".view-plan-history").show();
  });
});

// share my dmp popup window
$(function() {
  $.ui.dialog.prototype._focusTabbable = function(){};
  $('#visibility_dialog_form').hide();
	$('#visibility_confirmation_dialog_form').hide();
  $('.change_visibility_link').click(function(event) {
    event.preventDefault();

    showVisibilityDialog(false);
    return false
  });
  $('.confirm_visibility_link').click(function(event) {
    event.preventDefault();

    showVisibilityDialog(true);
    return false
  });
});

$(function() {
  $('#visibility_dialog_form').parent().find('button:contains("Cancel")').bind("click",function() {
    $("#visibility_dialog_form").reset();
  });
});

$(function() {
  $(".change_visibility_link").bind("click",function() {
    var id= $(this).data('planid');
    var visibility = $(this).data('visibility');

    setInitialVisibilityOnDialog(this, id, visibility);
  });

	$(".confirm_visibility_link").click(function(e){
    var id= $(this).data('planid');
    var visibility = $(this).data('visibility');

		setInitialVisibilityOnDialog(this, id, visibility);
	});
});

$(function() {
  $('#reject_dialog_form').hide();
  $('#reject_with_comments_link').click(function(event) {
    event.preventDefault();
    $('#comment_comment_type').attr('value', $(event.target).attr("data-comment-type"));
    $('#reject_dialog_form').dialog( {
      width: 450,
      height: 270,
      modal: true,
      closeOnEscape: true,
      draggable: true,
      resizable: false,
      title: "Reason for rejection (mandatory)",
      show: {
        effect: "blind",
        duration: 1000
      },
      hide: {
        effect: "toggle",
        duration: 1000
      },
      open: function()
      {
        $("#reject_dialog_form").dialog("open");
      },
      close: function() {
        $('#reject_dialog-form').dialog("close");
        $(this).find('form')[0].reset();
      }
    }).prev ().find(".ui-dialog-titlebar-close").show();
    return false
  });
});

$(function() {
  $("#cancel_action").bind("click",function() {
    $("#reject_dialog_form").reset();
  });
});

function showVisibilityDialog(planConfirmation){
  var dlg = (planConfirmation ? '#visibility_confirmation_dialog_form' :
                                '#visibility_dialog_form')

console.log("Recevied request to display " + dlg);

  $(dlg).dialog( {
    width: 600,
    height: 300,
    modal: true,
    closeOnEscape: true,
    draggable: true,
    resizable: false,
    title: (planConfirmation ? "Confirm your DMP's visibility setting" : "Share my DMP"),

     buttons: {
      Cancel: function(){
        //$('#ui-id-1').unwrap();
        $(this).dialog( "close" );
      },
      Submit: function() {
        // If this is the final visibility confirmation, click the confirmation button
        if(planConfirmation){
          $("#confirm_visibility_form").submit();

        }else{
          $("#visibility_form").submit();
        }

        $(this).dialog( "close" );
      }
    },
    open: function()
    {
      $('.ui-widget-overlay').addClass('custom-overlay');

      $('#visibility_dialog_form').prev().css('color', '#4C4C4E');
      $('#visibility_dialog_form').prev().css('font-family', 'Helvetica, sans-serif');
      $('#visibility_dialog_form').prev().css('font-size', '12px');
      $('#visibility_dialog_form').prev().css('line-height', '1.3');

       $('#visibility_dialog_form').prev().addClass('modal-header');

      $('#visibility_dialog_form').parent().addClass(' in');

      $('#visibility_dialog_form').prev().find('button').addClass('custom-close');
      $('#visibility_dialog_form').prev().find('button').css('background','none');
      $('#visibility_dialog_form').prev().find('button').css('border','none');
      $('#visibility_dialog_form').prev().find('button').css('font-color','black');
      $('#visibility_dialog_form').prev().find('button').css('font-size','20');
      $('#visibility_dialog_form').prev().find('button').css('font-color','black');
      $('#visibility_dialog_form').prev().find('button').css('opacity','0.2');

      $(this).parent().find('button:contains("Cancel")').removeClass('ui-corner-all');
      $(this).parent().find('button:contains("Cancel")').removeClass('ui-widget');
      $(this).parent().find('button:contains("Cancel")').removeClass('ui-button');
      $(this).parent().find('button:contains("Cancel")').removeClass('ui-state-default');
      $(this).parent().find('button:contains("Cancel")').removeClass('ui-button-text-only');
      $(this).parent().find('button:contains("Cancel")').addClass('btn');

      $(this).parent().find('button:contains("Submit")').removeClass('ui-corner-all');
      $(this).parent().find('button:contains("Submit")').removeClass('ui-widget');
      $(this).parent().find('button:contains("Submit")').removeClass('ui-button');
      $(this).parent().find('button:contains("Submit")').removeClass('ui-state-default');
      $(this).parent().find('button:contains("Submit")').removeClass('ui-button-text-only');
      $(this).parent().find('button:contains("Submit")').removeClass('ui-button-text');
      $(this).parent().find('button:contains("Submit")').addClass('btn btn-green confirm');

      $('#ui-id-1').parent().removeClass('ui-widget-overlay');
      $('#ui-id-1').parent().removeClass('ui-widget-header');
      $('#ui-id-1').parent().removeClass('ui-dialog-title');
      $('#ui-id-1').parent().addClass('modal-header');

      // $('#ui-id-1').css('font-weight','bold');
      // $('#ui-id-1').css('font-family', 'Helvetica, sans-serif');
      // $('#ui-id-1').css('font-size', '12px');

      $('#ui-id-1').wrap("

");

      $('#visibility_dialog_form').next().removeClass('ui-dialog-buttonpane ui-widget-content ui-helper-clearfix');
      $('#visibility_dialog_form').next().addClass('modal-footer');

      $("#visibility_dialog_form").dialog("open");
      $(".copyright span7").hide();
    },
    close: function() {
      $('#ui-id-1').first().unwrap();
      $('#ui-id-1').first().unwrap();
      $('#visibility_dialog_form').dialog("close");

      //window.location.reload(true);
    }
  }).prev ().find(".ui-dialog-titlebar-close").show();
}

function setInitialVisibilityOnDialog(form, id, visibility){
	var form = $(this).closest('form');

  $(form).find("#shared_plan_id").val(id);

  if (visibility  == "institutional")
  {
    $(form).find("#visibility_institutional").click();
  }
  else if (visibility  == "public")
  {
    $(form).find("#visibility_public").click();
  }
  else if (visibility  == "test")
  {
    $(form).find("#visibility_test").click();
  }
  else if (visibility  == "private")
  {
    $(form).find("#visibility_private").click();
  }
  else if (visibility  == "unit")
  {
    $(form).find("#visibility_unit").click();
  }
}<commit_msg>Added js debug<commit_after>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(function() {
  $("#submission_deadline.datepicker").datepicker( {
    showOn: 'button',
    buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
    dateFormat: "mm/dd/yy",
    changeMonth: true,
    changeYear: true,
    numberOfMonths: 1
  });
});

$(function() {
  $('#comment_dialog_form').hide();
  $('.add_comments_link').click(function(event) {
    event.preventDefault();
    $('#comment_comment_type').attr('value', $(event.target).attr("data-comment-type"));
    $('#comment_dialog_form').dialog( {
      width: 600,
      height: 310,
      modal: true,
      closeOnEscape: true,
      draggable: true,
      resizable: false,
      title: "Add New Comments",
      show: {
        effect: "blind",
        duration: 1000
      },
      hide: {
        effect: "toggle",
        duration: 1000
      },
      open: function()
      {
        $("#comment_dialog_form").dialog("open");
      },
      close: function() {
        $('#comment_dialog-form').dialog("close");
        $(this).find('form')[0].reset();
        window.location.reload()
      }
    }).prev ().find(".ui-dialog-titlebar-close").show();
    return false
  });
});

$(function() {
  $("#cancel_action").bind("click",function() {
    $("#comment_dialog_form").reset();
  });
});

$(function() {
  $("#reviewer_comments, .hide-reviewer-comments").hide();
  $(".view-reviewer-comments").click(function(event){
    event.preventDefault();
    $("#reviewer_comments").show();
    $(".view-reviewer-comments").hide();
    $(".hide-reviewer-comments").show();
  });
});

$(function() {
  $(".hide-reviewer-comments").click(function(event){
    event.preventDefault();
    $("#reviewer_comments").hide();
    $(".hide-reviewer-comments").hide();
    $(".view-reviewer-comments").show();
  });
});

$(function() {
  $("#owner_comments, .hide-owner-comments").hide();
  $(".view-owner-comments").click(function(event){
    event.preventDefault();
    $("#owner_comments").show();
    $(".view-owner-comments").hide();
    $(".hide-owner-comments").show();
  });
});

$(function() {
  $(".hide-owner-comments").click(function(event){
    event.preventDefault();
    $("#owner_comments").hide();
    $(".hide-owner-comments").hide();
    $(".view-owner-comments").show();
  });
});

$(function() {
  $("#plan_history, .hide-plan-history").hide();
  $(".view-plan-history").click(function(event){
    event.preventDefault();
    $("#plan_history").show();
    $(".view-plan-history").hide();
    $(".hide-plan-history").show();
  });
});

$(function() {
  $(".hide-plan-history").click(function(event){
    event.preventDefault();
    $("#plan_history").hide();
    $(".hide-plan-history").hide();
    $(".view-plan-history").show();
  });
});

// share my dmp popup window
$(function() {
  $.ui.dialog.prototype._focusTabbable = function(){};
  $('#visibility_dialog_form').hide();
	$('#visibility_confirmation_dialog_form').hide();
  $('.change_visibility_link').click(function(event) {
    event.preventDefault();

    showVisibilityDialog(false);
    return false
  });
  $('.confirm_visibility_link').click(function(event) {
    event.preventDefault();

    showVisibilityDialog(true);
    return false
  });
});

$(function() {
  $('#visibility_dialog_form').parent().find('button:contains("Cancel")').bind("click",function() {
    $("#visibility_dialog_form").reset();
  });

	$("#visibility_confirmation_dialog_form").parent().find('button:contains("Cancel")').bind("click", function(){
		$("#visibility_confirmation_dialog_form").reset();
	});
});

$(function() {
  $(".change_visibility_link").bind("click",function() {
    var id= $(this).data('planid');
    var visibility = $(this).data('visibility');

    setInitialVisibilityOnDialog(this, id, visibility);
  });

	$(".confirm_visibility_link").click(function(e){
    var id= $(this).data('planid');
    var visibility = $(this).data('visibility');

		setInitialVisibilityOnDialog(this, id, visibility);
	});
});

$(function() {
  $('#reject_dialog_form').hide();
  $('#reject_with_comments_link').click(function(event) {
    event.preventDefault();
    $('#comment_comment_type').attr('value', $(event.target).attr("data-comment-type"));
    $('#reject_dialog_form').dialog( {
      width: 450,
      height: 270,
      modal: true,
      closeOnEscape: true,
      draggable: true,
      resizable: false,
      title: "Reason for rejection (mandatory)",
      show: {
        effect: "blind",
        duration: 1000
      },
      hide: {
        effect: "toggle",
        duration: 1000
      },
      open: function()
      {
        $("#reject_dialog_form").dialog("open");
      },
      close: function() {
        $('#reject_dialog-form').dialog("close");
        $(this).find('form')[0].reset();
      }
    }).prev ().find(".ui-dialog-titlebar-close").show();
    return false
  });
});

$(function() {
  $("#cancel_action").bind("click",function() {
    $("#reject_dialog_form").reset();
  });
});

function showVisibilityDialog(planConfirmation){
  var dlg = (planConfirmation ? '#visibility_confirmation_dialog_form' :
                                '#visibility_dialog_form')

console.log("Recevied request to display " + dlg);

  $(dlg).dialog( {
    width: 600,
    height: 300,
    modal: true,
    closeOnEscape: true,
    draggable: true,
    resizable: false,
    title: (planConfirmation ? "Confirm your DMP's visibility setting" : "Share my DMP"),

     buttons: {
      Cancel: function(){
        //$('#ui-id-1').unwrap();
        $(this).dialog( "close" );
      },
      Submit: function() {
        // If this is the final visibility confirmation, click the confirmation button
        if(planConfirmation){
          $("#confirm_visibility_form").submit();

        }else{
          $("#visibility_form").submit();
        }

        $(this).dialog( "close" );
      }
    },
    open: function()
    {
      $('.ui-widget-overlay').addClass('custom-overlay');

      $(dlg).prev().css('color', '#4C4C4E');
      $(dlg).prev().css('font-family', 'Helvetica, sans-serif');
      $(dlg).prev().css('font-size', '12px');
      $(dlg).prev().css('line-height', '1.3');

       $(dlg).prev().addClass('modal-header');

      $(dlg).parent().addClass(' in');

      $(dlg).prev().find('button').addClass('custom-close');
      $(dlg).prev().find('button').css('background','none');
      $(dlg).prev().find('button').css('border','none');
      $(dlg).prev().find('button').css('font-color','black');
      $(dlg).prev().find('button').css('font-size','20');
      $(dlg).prev().find('button').css('font-color','black');
      $(dlg).prev().find('button').css('opacity','0.2');

      $(this).parent().find('button:contains("Cancel")').removeClass('ui-corner-all');
      $(this).parent().find('button:contains("Cancel")').removeClass('ui-widget');
      $(this).parent().find('button:contains("Cancel")').removeClass('ui-button');
      $(this).parent().find('button:contains("Cancel")').removeClass('ui-state-default');
      $(this).parent().find('button:contains("Cancel")').removeClass('ui-button-text-only');
      $(this).parent().find('button:contains("Cancel")').addClass('btn');

      $(this).parent().find('button:contains("Submit")').removeClass('ui-corner-all');
      $(this).parent().find('button:contains("Submit")').removeClass('ui-widget');
      $(this).parent().find('button:contains("Submit")').removeClass('ui-button');
      $(this).parent().find('button:contains("Submit")').removeClass('ui-state-default');
      $(this).parent().find('button:contains("Submit")').removeClass('ui-button-text-only');
      $(this).parent().find('button:contains("Submit")').removeClass('ui-button-text');
      $(this).parent().find('button:contains("Submit")').addClass('btn btn-green confirm');

      $('#ui-id-1').parent().removeClass('ui-widget-overlay');
      $('#ui-id-1').parent().removeClass('ui-widget-header');
      $('#ui-id-1').parent().removeClass('ui-dialog-title');
      $('#ui-id-1').parent().addClass('modal-header');

      // $('#ui-id-1').css('font-weight','bold');
      // $('#ui-id-1').css('font-family', 'Helvetica, sans-serif');
      // $('#ui-id-1').css('font-size', '12px');

      $('#ui-id-1').wrap("

");

      $(dlg).next().removeClass('ui-dialog-buttonpane ui-widget-content ui-helper-clearfix');
      $(dlg).next().addClass('modal-footer');

      $(dlg).dialog("open");
      $(".copyright span7").hide();
    },
    close: function() {
      $('#ui-id-1').first().unwrap();
      $('#ui-id-1').first().unwrap();
      $(dlg).dialog("close");

      //window.location.reload(true);
    }
  }).prev ().find(".ui-dialog-titlebar-close").show();
}

function setInitialVisibilityOnDialog(form, id, visibility){
	var form = $(this).closest('form');

  $(form).find("#shared_plan_id").val(id);

  if (visibility  == "institutional")
  {
    $(form).find("#visibility_institutional").click();
  }
  else if (visibility  == "public")
  {
    $(form).find("#visibility_public").click();
  }
  else if (visibility  == "test")
  {
    $(form).find("#visibility_test").click();
  }
  else if (visibility  == "private")
  {
    $(form).find("#visibility_private").click();
  }
  else if (visibility  == "unit")
  {
    $(form).find("#visibility_unit").click();
  }
}<|endoftext|>


<commit_before>
/*----------------------------------------------------------------------------------------------------------------------------------*/

var places = [0, "first", "second", "third", "fouth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"];

var num_rounds = 2;
var grace_time = 10;

/*----------------------------------------------------------------------------------------------------------------------------------*/

notify_new = function(me) {

  var notify = {};

  notify.me = me;
  notify.call_backs = [];

  /*-------------------------------------------------------------------------------------------------------------------------------*/
  notify.notify = function () {

    for (var i=0; i<this.call_backs.length; i++) {

      var func = this.call_backs[i].func;
      var owner = this.call_backs[i].owner;

      func(owner, this.me);
    }
  }
  /*-------------------------------------------------------------------------------------------------------------------------------*/

  notify.add_notify = function(func, owner) {

    var data = {func: func, owner: owner};
    this.call_backs.push(data);
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  return notify;
}

/*----------------------------------------------------------------------------------------------------------------------------------*/

poet_new = function (name) {

  var poet = {};
  poet.name = name;
  poet.total_score = 0;
  poet.performances = [];
  poet.notify_score = notify_new(poet);
  poet.notify_name = notify_new(poet);

  /*-------------------------------------------------------------------------------------------------------------------------------*/

  poet.set_name = function(name) {

    this.name = name;

    for (var i=0; i<this.performances.length; i++)
      this.performances[i].name = name;

    this.notify_name.notify();
  }

  /*-------------------------------------------------------------------------------------------------------------------------------*/

  poet.add_performance = function(performance) {

    this.performances.push(performance);
    performance.add_notify_score(this.calculate, this)

  }
  /*-------------------------------------------------------------------------------------------------------------------------------*/
  poet.calculate = function(me) {

    if (typeof me === 'undefined')
      me = this;

    me.total_score = 0;
    for (var i=0; i< me.performances.length; i++) {
      me.total_score += me.performances[i].score;
      me.performances[i].subscore = me.total_score;
    }

    me.notify_score.notify();
  }
  /*-------------------------------------------------------------------------------------------------------------------------------*/

  return poet;
}

/*----------------------------------------------------------------------------------------------------------------------------------*/

performance_new = function (name, prev, time_limit, num_judges) {

  var performance = {};

  performance.id = makeid(20);
  performance.time_limit = time_limit;
  performance.num_judges = num_judges; // = 5;// to see if I refactored correctly
  /*--------------------------------------------------------------------------------------------------------------------------------*/
  // Notify that the score has been (re)calculated.

  performance.add_notify_score = function(func, owner) {

    var data = {func: func, owner: owner};
    this.call_backs_score.push(data);
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/
  // Notify that the rank has been (re)calculated.

  performance.add_notify_rank = function(func, owner) {

    var data = {func: func, owner: owner};
    this.call_backs_rank.push(data);
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.notify_score = function() {

    for (var i=0; i<this.call_backs_score.length; i++) {

      var func = this.call_backs_score[i].func;
      var owner = this.call_backs_score[i].owner;

      func(owner, this);
    }
  }
  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.notify_rank = function() {

    for (var i=0; i<this.call_backs_rank.length; i++) {

      var func = this.call_backs_rank[i].func;
      var owner = this.call_backs_rank[i].owner;

      func(owner, this);
    }
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.set_rank= function(rank) {
    this.rank = rank;
    this.notify_rank();
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.set_penalty = function(penalty) {

    this.penalty = penalty;
    this.calculate();
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.set_time = function(min, sec) {

    this.seconds = min * 60 + sec;
    this.calculate();
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/
  performance.calculate_time_penalty = function() {

    var over_time;
    var penalty;

    if (this.seconds <= this.time_limit + grace_time)
      return 0;

    over_time = this.seconds - this.time_limit;
    over_time = Math.floor(over_time / 10);
    penalty = over_time * 0.5;

    return penalty;
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/
  performance.judge = function (judge_num, score) {

    this.judges[judge_num] = score;
    this.calculate();

  }
  /*--------------------------------------------------------------------------------------------------------------------------------*/
  performance.find_min_judge = function() {

    var min_score = Infinity;
    var min_judge;

    for (var i=0; i<this.num_judges; i++)
      if (min_score > this.judges[i]) {
	min_score = this.judges[i];
	this.min_judge = i;
      }
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/
  // Precondition: find_min_judge was called before calling this function. This is because if all the judges have the same score
  // The minimum and maximum judges cannot be the same judges.
  performance.find_max_judge = function() {

    var max_score = -Infinity;
    var max_judge;

    for (var i=0; i<this.num_judges; i++)
      if (max_score < this.judges[i] && i != this.min_judge) {
	max_score = this.judges[i];
	this.max_judge = i;
      }
  }
  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.add_up_judges = function() {

    var sum = 0;

    this.find_min_judge();
    this.find_max_judge();

    for (var i=0; i<this.num_judges; i++)
      if (i != this.min_judge && i != this.max_judge)
	sum += this.judges[i];

    return sum;
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.calculate = function(me) {

    if (typeof me === 'undefined')
      me = this;

    me.score = 0;
    me.score += me.add_up_judges();
    me.score -= me.penalty;
    me.score -= me.calculate_time_penalty();

    me.notify_score();
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.init = function(name, prev) {

    if (prev == null)
      this.poet = poet_new(name);
    else
      this.poet = prev.poet;

    this.poet.add_performance(this);
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.name = name;
  performance.prev = prev;

  performance.penalty = 0;
  performance.seconds = 0;

  performance.judges = [];
  for (var i=0; i< performance.num_judges; i++)
    performance.judges[i] = 0;

  performance.score = 0;
  performance.rank = Infinity; // 1 = first place, 2, second place, etc...

  performance.subscore = 0;

  performance.call_backs_score = [];
  performance.call_backs_rank = [];

  performance.init(name, prev);

  return performance;
}

/*----------------------------------------------------------------------------------------------------------------------------------*/
round_new = function (num_places, round_number) {

  var round = {};

  round.num_places = num_places;
  round.round_number = round_number;
  round.performances = [];

  round.call_backs = [];
  /*--------------------------------------------------------------------------------------------------------------------------------*/

  round.rank = function(me) {

    if (typeof me === 'undefined')
      me = this;

    var rankings = [];

    for (var i=0; i<me.performances.length; i++)
      if (rankings.indexOf(me.performances[i].subscore) == -1) {

	// Turn subscore into an "integer" because "floats" don't work well with comparisons
	var subscore = Math.floor(me.performances[i].subscore * 10);
	rankings.push(subscore);
      }

    rankings.sort(function(a, b){return b - a;});

    for (var i=0; i<me.performances.length; i++) {

      // Turn subscore into an "integer" because "floats" don't work well with comparisons
      var subscore = Math.floor(me.performances[i].subscore * 10);
      var ranking = rankings.indexOf(subscore) + 1;
      me.performances[i].set_rank(ranking);
    }
    me.notify_rank();
  }

  /*-------------------------------------------------------------------------------------------------------------------------------*/

  round._get_winners = function() {

    var winners = [];
    var result = {};

    winners.push(null);
    for (var i=1; i<=this.num_places; i++)
      winners.push([]);

    for (var i=0; i<this.performances.length; i++) {

      var rank = this.performances[i].rank;
      if (rank <= this.num_places)
	winners[rank].push(this.performances[i]);
    }

    return winners;
  }
  /*-------------------------------------------------------------------------------------------------------------------------------*/

  // Returns a hash
  //
  //   So in the Winter Sesion of Vancouver Poetry Slam there are 5 winners unless there's a tie for 5th place.
  //   If that happens then there will be 6 winners.
  //
  //   result.winners: an array of winners
  //   result.result: 0 if successful, otherwise the number of the 'place' (1st place, 2nd place, etc) where there were too many ties.
  //   result.overflow: an array of 'place' containing too many ties.

  round.get_winners = function() {

    var result = {};
    var winners = this._get_winners();

    result.result = 0;
    result.winners = [];

    // Winners for all but the last 'place'
    for (var i=1; i<this.num_places && result.winners.length < this.num_places; i++)
      if (result.winners.length + winners[i].length <= this.num_places) {
	var _winners = result.winners.concat(winners[i]);
	result.winners = _winners;
      } else {
	// Too many ties....

	result.result = i;
	result.overflow = winners[i];
      }

    if (result.result == 0 && result.winners.length < this.num_places) {
      // In the event of a tie, this.num_places + 1 is acceptable....
      if (result.winners.length + winners[this.num_places].length <= this.num_places + 1) {

	var _winners = result.winners.concat(winners[this.num_places]);
	result.winners = _winners;
      }
      else {
	result.result = this.num_places;
	result.overflow = winners[this.num_places];
      }
    }

    return result;
  }
  /*-------------------------------------------------------------------------------------------------------------------------------*/

  round.add_performance = function(performance) {

    performance.add_notify_score(this.rank, this);
    this.performances.push(performance);

    performance.round = this;  // The performance knows which round it's in

  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/
  round.call_backs = [];
  /*--------------------------------------------------------------------------------------------------------------------------------*/
  // Notify that the rank has been (re)calculated.

  round.add_notify_rank = function(func, owner) {

    var data = {func: func, owner: owner};
    this.call_backs.push(data);
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  round.notify_rank = function() {

    for (var i=0; i<this.call_backs.length; i++) {

      var func = this.call_backs[i].func;
      var owner = this.call_backs[i].owner;

      func(owner, this);
    }
  }
  /*--------------------------------------------------------------------------------------------------------------------------------*/

  return round;

}

/*----------------------------------------------------------------------------------------------------------------------------------*/
<commit_msg>if two people tie for 4th then there is no longer a 5th place<commit_after>
/*----------------------------------------------------------------------------------------------------------------------------------*/

var places = [0, "first", "second", "third", "fouth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"];

var num_rounds = 2;
var grace_time = 10;

/*----------------------------------------------------------------------------------------------------------------------------------*/

notify_new = function(me) {

  var notify = {};

  notify.me = me;
  notify.call_backs = [];

  /*-------------------------------------------------------------------------------------------------------------------------------*/
  notify.notify = function () {

    for (var i=0; i<this.call_backs.length; i++) {

      var func = this.call_backs[i].func;
      var owner = this.call_backs[i].owner;

      func(owner, this.me);
    }
  }
  /*-------------------------------------------------------------------------------------------------------------------------------*/

  notify.add_notify = function(func, owner) {

    var data = {func: func, owner: owner};
    this.call_backs.push(data);
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  return notify;
}

/*----------------------------------------------------------------------------------------------------------------------------------*/

poet_new = function (name) {

  var poet = {};
  poet.name = name;
  poet.total_score = 0;
  poet.performances = [];
  poet.notify_score = notify_new(poet);
  poet.notify_name = notify_new(poet);

  /*-------------------------------------------------------------------------------------------------------------------------------*/

  poet.set_name = function(name) {

    this.name = name;

    for (var i=0; i<this.performances.length; i++)
      this.performances[i].name = name;

    this.notify_name.notify();
  }

  /*-------------------------------------------------------------------------------------------------------------------------------*/

  poet.add_performance = function(performance) {

    this.performances.push(performance);
    performance.add_notify_score(this.calculate, this)

  }
  /*-------------------------------------------------------------------------------------------------------------------------------*/
  poet.calculate = function(me) {

    if (typeof me === 'undefined')
      me = this;

    me.total_score = 0;
    for (var i=0; i< me.performances.length; i++) {
      me.total_score += me.performances[i].score;
      me.performances[i].subscore = me.total_score;
    }

    me.notify_score.notify();
  }
  /*-------------------------------------------------------------------------------------------------------------------------------*/

  return poet;
}

/*----------------------------------------------------------------------------------------------------------------------------------*/

performance_new = function (name, prev, time_limit, num_judges) {

  var performance = {};

  performance.id = makeid(20);
  performance.time_limit = time_limit;
  performance.num_judges = num_judges; // = 5;// to see if I refactored correctly
  /*--------------------------------------------------------------------------------------------------------------------------------*/
  // Notify that the score has been (re)calculated.

  performance.add_notify_score = function(func, owner) {

    var data = {func: func, owner: owner};
    this.call_backs_score.push(data);
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/
  // Notify that the rank has been (re)calculated.

  performance.add_notify_rank = function(func, owner) {

    var data = {func: func, owner: owner};
    this.call_backs_rank.push(data);
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.notify_score = function() {

    for (var i=0; i<this.call_backs_score.length; i++) {

      var func = this.call_backs_score[i].func;
      var owner = this.call_backs_score[i].owner;

      func(owner, this);
    }
  }
  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.notify_rank = function() {

    for (var i=0; i<this.call_backs_rank.length; i++) {

      var func = this.call_backs_rank[i].func;
      var owner = this.call_backs_rank[i].owner;

      func(owner, this);
    }
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.set_rank= function(rank) {
    this.rank = rank;
    this.notify_rank();
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.set_penalty = function(penalty) {

    this.penalty = penalty;
    this.calculate();
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.set_time = function(min, sec) {

    this.seconds = min * 60 + sec;
    this.calculate();
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/
  performance.calculate_time_penalty = function() {

    var over_time;
    var penalty;

    if (this.seconds <= this.time_limit + grace_time)
      return 0;

    over_time = this.seconds - this.time_limit;
    over_time = Math.floor(over_time / 10);
    penalty = over_time * 0.5;

    return penalty;
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/
  performance.judge = function (judge_num, score) {

    this.judges[judge_num] = score;
    this.calculate();

  }
  /*--------------------------------------------------------------------------------------------------------------------------------*/
  performance.find_min_judge = function() {

    var min_score = Infinity;
    var min_judge;

    for (var i=0; i<this.num_judges; i++)
      if (min_score > this.judges[i]) {
	min_score = this.judges[i];
	this.min_judge = i;
      }
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/
  // Precondition: find_min_judge was called before calling this function. This is because if all the judges have the same score
  // The minimum and maximum judges cannot be the same judges.
  performance.find_max_judge = function() {

    var max_score = -Infinity;
    var max_judge;

    for (var i=0; i<this.num_judges; i++)
      if (max_score < this.judges[i] && i != this.min_judge) {
	max_score = this.judges[i];
	this.max_judge = i;
      }
  }
  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.add_up_judges = function() {

    var sum = 0;

    this.find_min_judge();
    this.find_max_judge();

    for (var i=0; i<this.num_judges; i++)
      if (i != this.min_judge && i != this.max_judge)
	sum += this.judges[i];

    return sum;
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.calculate = function(me) {

    if (typeof me === 'undefined')
      me = this;

    me.score = 0;
    me.score += me.add_up_judges();
    me.score -= me.penalty;
    me.score -= me.calculate_time_penalty();

    me.notify_score();
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.init = function(name, prev) {

    if (prev == null)
      this.poet = poet_new(name);
    else
      this.poet = prev.poet;

    this.poet.add_performance(this);
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  performance.name = name;
  performance.prev = prev;

  performance.penalty = 0;
  performance.seconds = 0;

  performance.judges = [];
  for (var i=0; i< performance.num_judges; i++)
    performance.judges[i] = 0;

  performance.score = 0;
  performance.rank = Infinity; // 1 = first place, 2, second place, etc...

  performance.subscore = 0;

  performance.call_backs_score = [];
  performance.call_backs_rank = [];

  performance.init(name, prev);

  return performance;
}

/*----------------------------------------------------------------------------------------------------------------------------------*/
round_new = function (num_places, round_number) {

  var round = {};

  round.num_places = num_places;
  round.round_number = round_number;
  round.performances = [];

  round.call_backs = [];
  /*--------------------------------------------------------------------------------------------------------------------------------*/

  round.rank = function(me) {

    if (typeof me === 'undefined')
      me = this;

    var rankings = [];

    for (var i=0; i<me.performances.length; i++)
      /*if (rankings.indexOf(me.performances[i].subscore) == -1)*/ {

	// Turn subscore into an "integer" because "floats" don't work well with comparisons
	var subscore = Math.floor(me.performances[i].subscore * 10);
	rankings.push(subscore);
      }

    rankings.sort(function(a, b){return b - a;});

    for (var i=0; i<me.performances.length; i++) {

      // Turn subscore into an "integer" because "floats" don't work well with comparisons
      var subscore = Math.floor(me.performances[i].subscore * 10);
      var ranking = rankings.indexOf(subscore) + 1;
      me.performances[i].set_rank(ranking);
    }
    me.notify_rank();
  }

  /*-------------------------------------------------------------------------------------------------------------------------------*/

  round._get_winners = function() {

    var winners = [];
    var result = {};

    winners.push(null);
    for (var i=1; i<=this.num_places; i++)
      winners.push([]);

    for (var i=0; i<this.performances.length; i++) {

      var rank = this.performances[i].rank;
      if (rank <= this.num_places)
	winners[rank].push(this.performances[i]);
    }

    return winners;
  }
  /*-------------------------------------------------------------------------------------------------------------------------------*/

  // Returns a hash
  //
  //   So in the Winter Sesion of Vancouver Poetry Slam there are 5 winners unless there's a tie for 5th place.
  //   If that happens then there will be 6 winners.
  //
  //   result.winners: an array of winners
  //   result.result: 0 if successful, otherwise the number of the 'place' (1st place, 2nd place, etc) where there were too many ties.
  //   result.overflow: an array of 'place' containing too many ties.

  round.get_winners = function() {

    var result = {};
    var winners = this._get_winners();

    result.result = 0;
    result.winners = [];

    // Winners for all but the last 'place'
    for (var i=1; i<this.num_places && result.winners.length < this.num_places; i++)
      if (result.winners.length + winners[i].length <= this.num_places) {
	var _winners = result.winners.concat(winners[i]);
	result.winners = _winners;
      } else {
	// Too many ties....

	result.result = i;
	result.overflow = winners[i];
      }

    if (result.result == 0 && result.winners.length < this.num_places) {
      // In the event of a tie, this.num_places + 1 is acceptable....
      if (result.winners.length + winners[this.num_places].length <= this.num_places + 1) {

	var _winners = result.winners.concat(winners[this.num_places]);
	result.winners = _winners;
      }
      else {
	result.result = this.num_places;
	result.overflow = winners[this.num_places];
      }
    }

    return result;
  }
  /*-------------------------------------------------------------------------------------------------------------------------------*/

  round.add_performance = function(performance) {

    performance.add_notify_score(this.rank, this);
    this.performances.push(performance);

    performance.round = this;  // The performance knows which round it's in

  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/
  round.call_backs = [];
  /*--------------------------------------------------------------------------------------------------------------------------------*/
  // Notify that the rank has been (re)calculated.

  round.add_notify_rank = function(func, owner) {

    var data = {func: func, owner: owner};
    this.call_backs.push(data);
  }

  /*--------------------------------------------------------------------------------------------------------------------------------*/

  round.notify_rank = function() {

    for (var i=0; i<this.call_backs.length; i++) {

      var func = this.call_backs[i].func;
      var owner = this.call_backs[i].owner;

      func(owner, this);
    }
  }
  /*--------------------------------------------------------------------------------------------------------------------------------*/

  return round;

}

/*----------------------------------------------------------------------------------------------------------------------------------*/
<|endoftext|>


<commit_before>table = function () {
  // $(".js-vertical-tab-content").hide();
  // $(".js-vertical-tab-content:first").show();

  /* if in tab mode */
  $(".js-vertical-tab").click(function(event) {
    event.preventDefault();

    $(".js-vertical-tab-content").hide();
    var activeTab = $(this).attr("rel");
    $("#"+activeTab).show();

    $(".js-vertical-tab").removeClass("is-active");
    $(this).addClass("is-active");

    $(".js-vertical-tab-accordion-heading").removeClass("is-active");
    $(".js-vertical-tab-accordion-heading[rel^='"+activeTab+"']").addClass("is-active");
  });
}<commit_msg>Show content of first skill<commit_after>table = function () {
  $(".js-vertical-tab-content").hide();
  $(".js-vertical-tab-content:first").show();

  $(".js-vertical-tab").click(function(event) {
    event.preventDefault();

    $(".js-vertical-tab-content").hide();
    var activeTab = $(this).attr("rel");
    $("#"+activeTab).show();

    $(".js-vertical-tab").removeClass("is-active");
    $(this).addClass("is-active");

    $(".js-vertical-tab-accordion-heading").removeClass("is-active");
    $(".js-vertical-tab-accordion-heading[rel^='"+activeTab+"']").addClass("is-active");
  });
}<|endoftext|>


<commit_before>var myTaskObject;
var currentPositionInTime;
var numOfAllTaskEvents = 5;
// var numOfAllTaskEvents;
// var currentTaskId = window.location.href.split("/").pop()
// $(document).ready(function(){

    // var url = '/tasks/' + currentTaskId + '/'
    // $.ajax({
    //   url: url,
    //   type: 'get',
    // }).done(function(response){
    //   console.log(response)
    //   // debugger;
    // });
// var GetNumOfAllTaskEvents = (function (){
// })();

// debugger;

var Task = function(taskName) {
  this.taskName = taskName;
  this.positionInTime = 0;
  this.allStatusElements = (function(){
    var arrayOfAllStatusElements = new Array();
    for (var i = 0; i <= numOfAllTaskEvents; i++){
      arrayOfAllStatusElements.push(new StatusElement(i))
    };
    return arrayOfAllStatusElements;
  })();
};
Task.prototype.advanceInTime = function(){
  this.positionInTime++;
};
Task.prototype.gobackInTime = function(){
  this.positionInTime--;
};

var Board = function(task){
  this.boardLength = task.allStatusElements.length - 1;
  this.task = task;
};
Board.prototype.drawBoard = function() {
  for (var i = 0; i <= this.boardLength; i++) {
    if (this.task.positionInTime === i) {
      this.printCurrentPositionInTime(i);
    } else {
      this.printEmptyPositionInTime(i);
    };
  };
};
Board.prototype.eraseBoard = function() {
  $("tr.progress_line").empty();
};
Board.prototype.printCurrentPositionInTime = function(numInOrder){
  $("tr.progress_line").append('' + this.task.taskName + '	')
};
Board.prototype.printEmptyPositionInTime = function(numInOrder){
  $("tr.progress_line").append('' + numInOrder + '	');
};
Board.prototype.printLogElement = function(){
  this.task.allStatusElements[this.task.positionInTime].printStatusElement();
};
Board.prototype.eraseLogElement = function(){
  $('div.task_log_container div:last-child').remove()
};

var StatusElement = function(statusPosition){
  this.statusPosition = statusPosition;
}
StatusElement.prototype.printStatusElement = function(){
  // debugger;
  var url = '/tasks/' + window.location.href.split("/").pop() + '/'
  currentPositionInTime = this.statusPosition;
  $.ajax({
    url: url,
    type: 'get',
    dataType: 'JSON',
    data: {"position_in_time": currentPositionInTime}
  }).done(function(response) {
    // debugger;
    $("div.task_log_container").append('

' + "Step " + currentPositionInTime + '

' + "Assigned to: " + response.assignee + '

' + "Status: " + response.current_status  + '
'); //+'
' + "Why: " + response.why + '

');
  });
}

myTaskObject = new Task('My Task', numOfAllTaskEvents);

$(document).ready(function(){

  var display = new Board(myTaskObject);
  display.drawBoard();
  $('body').on("click", 'button.time_travel_next', function(event){
    if (display.task.positionInTime < display.boardLength) {
      myTaskObject.advanceInTime();
      display.eraseLogElement();
      display.printLogElement();
      // debugger;
      display.eraseBoard();
      display.drawBoard();
    };
  });
  $('body').on("click", 'button.time_travel_back', function(event){
    if (display.task.positionInTime > 0) {
      myTaskObject.gobackInTime();
      display.eraseLogElement();
      display.printLogElement();
      display.eraseBoard();
      display.drawBoard();
    };
  });
  $('body').on("click","tr.progress_line",function(event){
    // alert(event.target.id);
    myTaskObject.positionInTime = event.target.id;
    display.eraseLogElement();
    display.printLogElement();
    display.eraseBoard();
    display.drawBoard();
  });
});<commit_msg>Last status not working bug fixed<commit_after>var myTaskObject;
var currentPositionInTime;
var numOfAllTaskEvents = 9;
// var numOfAllTaskEvents;
// var currentTaskId = window.location.href.split("/").pop()
// $(document).ready(function(){

    // var url = '/tasks/' + currentTaskId + '/'
    // $.ajax({
    //   url: url,
    //   type: 'get',
    // }).done(function(response){
    //   console.log(response)
    //   // debugger;
    // });
// var GetNumOfAllTaskEvents = (function (){
// })();

// debugger;

var Task = function(taskName) {
  this.taskName = taskName;
  this.positionInTime = 0;
  this.allStatusElements = (function(){
    var arrayOfAllStatusElements = new Array();
    for (var i = 0; i <= numOfAllTaskEvents; i++){
      arrayOfAllStatusElements.push(new StatusElement(i))
    };
    return arrayOfAllStatusElements;
  })();
};
Task.prototype.advanceInTime = function(){
  this.positionInTime++;
};
Task.prototype.gobackInTime = function(){
  this.positionInTime--;
};

var Board = function(task){
  this.boardLength = task.allStatusElements.length;
  this.task = task;
};
Board.prototype.drawBoard = function() {
  for (var i = 1; i < this.boardLength; i++) {
    if (this.task.positionInTime === i) {
      this.printCurrentPositionInTime(i);
    } else {
      this.printEmptyPositionInTime(i);
    };
  };
};
Board.prototype.eraseBoard = function() {
  $("tr.progress_line").empty();
};
Board.prototype.printCurrentPositionInTime = function(numInOrder){
  $("tr.progress_line").append('' + this.task.taskName + '	')
};
Board.prototype.printEmptyPositionInTime = function(numInOrder){
  $("tr.progress_line").append('' + numInOrder + '	');
};
Board.prototype.printLogElement = function(){
  this.task.allStatusElements[this.task.positionInTime].printStatusElement();
};
Board.prototype.eraseLogElement = function(){
  $('div.task_log_container div:last-child').remove()
};

var StatusElement = function(statusPosition){
  this.statusPosition = statusPosition;
}
StatusElement.prototype.printStatusElement = function(){
  var url = '/tasks/' + window.location.href.split("/").pop() + '/'
  currentPositionInTime = this.statusPosition;
  // debugger;
  $.ajax({
    url: url,
    type: 'get',
    dataType: 'JSON',
    data: {"position_in_time": currentPositionInTime}
  }).done(function(response) {
    // debugger;
    $("div.task_log_container").append('

' + "Step " + currentPositionInTime + '

' + "Assigned to: " + response.assignee + '

' + "Status: " + response.current_status  + '
');
  });
}

myTaskObject = new Task('My Task', numOfAllTaskEvents);

$(document).ready(function(){

  var display = new Board(myTaskObject);
  display.drawBoard();
  $('body').on("click", 'button.time_travel_next', function(event){
    if (display.task.positionInTime < display.boardLength) {
      myTaskObject.advanceInTime();
      display.eraseLogElement();
      display.printLogElement();
      display.eraseBoard();
      display.drawBoard();
    };
  });
  $('body').on("click", 'button.time_travel_back', function(event){
    if (display.task.positionInTime > 0) {
      myTaskObject.gobackInTime();
      display.eraseLogElement();
      display.printLogElement();
      display.eraseBoard();
      display.drawBoard();
    };
  });
  $('body').on("click","tr.progress_line",function(event){
    myTaskObject.positionInTime = parseInt(event.target.id);
    display.eraseLogElement();
    display.printLogElement();
    display.eraseBoard();
    display.drawBoard();
  });
});<|endoftext|>


<commit_before>import { merge } from '@ember/polyfills';
import { get } from '@ember/object';
import { Promise as EmberPromise } from 'rsvp';
import { inject as service } from '@ember/service';
import JwtTokenAuthenticator from 'ember-simple-auth-token/authenticators/jwt';

export default JwtTokenAuthenticator.extend({
  commonAjax: service(),
  /**
    Extend the JwtTokenAuthenticator to accept a token in liu of credentials
    This allows authentication of an already existing session.
    @method authenticate
    @param {Object} credentials The credentials to authenticate the session with
    @param {Object} headers Request headers.
    @return {Ember.RSVP.Promise} A promise that resolves when an auth token is
                                 successfully acquired from the server and rejects
                                 otherwise
  */
  authenticate(credentials, headers) {
    return new EmberPromise((resolve, reject) => {
      if(this.tokenPropertyName in credentials){
        const token = get(credentials, this.tokenPropertyName);
        const tokenData = this.getTokenData(token);
        const expiresAt = get(tokenData, this.tokenExpireName);

        this.scheduleAccessTokenRefresh(expiresAt, token);

        let response  = {};
        response[this.tokenPropertyName] = token;
        response[this.tokenExpireName] = expiresAt;

        resolve(response);
      } else {
        this.makeRequest(this.serverTokenEndpoint, credentials, headers).then(response => {
          const token = get(response, this.tokenPropertyName);
          const tokenData = this.getTokenData(token);
          const expiresAt = get(tokenData, this.tokenExpireName);
          const tokenExpireData = {};
          this.scheduleAccessTokenRefresh(expiresAt, token);
          tokenExpireData[this.tokenExpireName] = expiresAt;
          response = merge(response, tokenExpireData);
          resolve(response);
        }, e => {
          let error = {
            'message': e.message,
            'keys': e.payload.errors || [],
          };
          reject(error);
        });
      }
    });
  },

  /**
   * Extend the default make request in order to user our own commonAjax service
   * Using our service allows us to use a custom hostname instead of just '/'
   *
   * @method makeRequest
   * @param {string} url The URL to post to.
   * @param {Object} data The POST data.
   * @param {Object} providedHeaders Request headers.
   * @return {Ember.RSVP.Promise} The result of the request.
  */
  makeRequest(url, data, providedHeaders) {
    const commonAjax = this.get('commonAjax');
    let headers = this.headers;
    if (providedHeaders) {
      Object.keys(headers).forEach((key) => {
        headers[key] = providedHeaders[key];
      });
    }

    return commonAjax.post(url, {
      data: JSON.stringify(data),
      dataType: 'json',
      contentType: 'application/json',
      headers,
    });
  },
});
<commit_msg>Remove duplicate authenticator<commit_after><|endoftext|>


<commit_before>/*--------------------------------------------------------
 * Copyright (c) 2011, The Dojo Foundation
 * This software is distributed under the "Simplified BSD license",
 * the text of which is available at http://www.winktoolkit.org/licence.txt
 * or see the "license.txt" file for more details.
 *--------------------------------------------------------*/

/**
 * @fileOverview math matrix library - a wink.math extension.
 *
 * @compatibility Iphone OS2, Iphone OS3, Iphone OS4, Android 2.1, Android 2.2, Android 2.3, Android 3.0, Android 3.1, BlackBerry 6, BlackBerry 7, Bada 1.0
 * @author Sylvain LALANDE
 */
define(['../../../_amd/core'], function(wink)
{
	/**
	 * Creates a transformation matrix with the given css transform
	 *
	 * @param {string|WebKitCSSMatrix} [cssTransform] The css transform which will initialize the matrix
	 *
	 * @returns {wink.math.Matrix} The corresponding wink.math.Matrix
	 *
	 * @example
	 *
	 * var rotationMatrix = wink.math.createTransformMatrix();
	 * rotationMatrix.rotateAxisAngle(0, 1, 0, 45);
	 *
	 */
	wink.math.createTransformMatrix = function(cssTransform)
	{
		var matrix = new wink.math.Matrix({});
		if (wink.isSet(cssTransform))
		{
			matrix.loadCssTransform(cssTransform);
		}
		return matrix;
	};

	/**
	 * @class Implements a matrix encapsulation object (of order 4) that is representative of a 3d transformation.
	 *
	 * @param {object} properties The properties object
	 * @param {array} [properties.values] The matrix values as an array of 16 elements
	 */
	wink.math.Matrix = function(properties)
	{
		/**
		 * Unique identifier
		 *
		 * @property
		 * @type integer
		 */
		this.uId = wink.getUId();

		this._properties		= properties;
		this._values			= [];
		this._cssMatrix			= null;

		this._test				= (wink.ua.isBlackBerry && wink.ua.browserVersion == 7 && wink.ua.browserMinorVersion == 1);

		if (this._validateProperties() === false) return;

		this._initProperties();
	};

	wink.math.Matrix.prototype =
	{
		/**
		 * Apply a scale operation to the matrix.
		 *
		 * @param {number} x The x scale component
		 * @param {number} y The y scale component
		 * @param {number} z The z scale component
		 */
		scale: function(x, y, z)
		{
			var resultMatrix = this._cssMatrix.scale(x, y, z);
			var values = this._cssMatrixToValues(resultMatrix);
			this._load(values);
		},
		/**
		 * Apply a translate operation to the matrix.
		 *
		 * @param {number} x The x translation component
		 * @param {number} y The y translation component
		 * @param {number} z The z translation component
		 */
		translate: function(x, y, z)
		{
			var resultMatrix = this._cssMatrix.translate(x, y, z);
			var values = this._cssMatrixToValues(resultMatrix);
			this._load(values);
		},
		/**
		 * Apply a rotation operation to the matrix.
		 *
		 * @param {number} x The x rotation component
		 * @param {number} y The y rotation component
		 * @param {number} z The z rotation component
		 * @param {number} angleDeg The rotation angle in degree
		 */
		rotateAxisAngle: function(x, y, z, angleDeg)
		{
			var resultMatrix = this._cssMatrix.rotateAxisAngle(x, y, z, angleDeg);
			var values = this._cssMatrixToValues(resultMatrix);
			this._load(values);
		},
		/**
		 * Multiply the current matrix by an other one.
		 *
		 * @param {wink.math.Matrix} otherWinkMatrix The other matrix
		 */
		multiply: function(otherWinkMatrix)
		{
			var m1 = otherWinkMatrix.getCssMatrix();
			var m2 = this._cssMatrix;
			if (wink.has("css-matrix-stack-inversed")) {
				var tmp = m1;
				m1 = m2;
				m2 = tmp;
			}
			var resultMatrix = m1.multiply(m2);
			var values = this._cssMatrixToValues(resultMatrix);
			this._load(values);
		},
		/**
		 * Clones the current Wink Matrix
		 *
		 * @returns {wink.math.Matrix} The cloned matrix
		 */
		clone: function()
		{
			return new wink.math.Matrix({ values: this._values });
		},
		/**
		 * Load the given transformation
		 *
		 * @param {string|WebKitCSSMatrix} transformation The css transform
		 */
		loadCssTransform: function(transformation)
		{
			var result = null;

			if (isString(transformation))
			{
				var search = "matrix3d";
				var chaine = transformation;
				var index = chaine.indexOf(search);
				if (index != -1)
				{
					var matriceS = chaine.substring((search.length + 1), (chaine.length - 1));
					var matValues = matriceS.split(", ");
					var m = [];
					for ( var i = 0; i < matValues.length; i++) {
						m[i] = matValues[i] * 1;
					}
					this._load(m);
				}
			}
			else
			{
				try {
					var values = this._cssMatrixToValues(transformation); // WebKitCSSMatrix
					this._load(values);
				} catch (e) {
					wink.log('[Matrix] Error: bad WebKitCSSMatrix');
				}
			}
		},
		/**
		 * Returns the matrix values
		 *
		 * @returns {array} The matrix values
		 */
		getValues: function()
		{
			return this._values;
		},
		/**
		 * Return the corresponding WebKitCSSMatrix
		 *
		 * @returns {WebkitCSSMatrix} The WebKitCSSMatrix
		 */
		getCssMatrix: function()
		{
			return this._cssMatrix;
		},

		/**
		 * Return the string value of the WebKitCSSMatrix
		 *
		 * @returns {String} The value of the matrix
		 */
		toString: function()
		{
			if ( !this._test )
			{
				return this._cssMatrix.toString();
			} else
			{
				return 'matrix3d(' + this._values.join(',') + ')';
			}
		},
		/**
		 * Validate the properties of the component
		 * @returns {boolean} True if the properties are valid, false otherwise
		 */
		_validateProperties: function()
		{
			if (wink.isSet(this._properties.values) && this._properties.values.length != 16)
			{
				wink.log('[Matrix] Error: values should be number 16');
				return false;
			}
			return true;
		},
		/**
		 * Initialize datas with given properties
		 */
		_initProperties: function()
		{
			if (wink.isSet(this._properties.values))
			{
				this._load(this._properties.values);
			}
			else
			{
				this._loadIdentity();
			}
		},
		/**
		 * Load the identity matrix
		 */
		_loadIdentity: function()
		{
			this._load([
				1, 0, 0, 0,
				0, 1, 0, 0,
				0, 0, 1, 0,
				0, 0, 0, 1
			]);
		},
		/**
		 * Load the given values
		 *
		 * @param {array} values An array of 16 matrix values
		 */
		_load: function(values)
		{
			if (!wink.isSet(values) || values.length != 16)
			{
				wink.log('[Matrix] Error: values should be number 16');
				return false;
			}
			this._values = values;
			this._cssMatrix = this._valuesToCssMatrix(this._values);
		},
		/**
		 * Returns a WebKitCSSMatrix with the given array of values
		 *
		 * @param {array} values An array of 16 matrix values
		 *
		 * @returns {WebkitCSSMatrix} The WebKitCSSMatrix
		 */
		_valuesToCssMatrix: function(values)
		{
			var cssMatrix = new WebKitCSSMatrix();

			cssMatrix.m11 = values[0];
			cssMatrix.m12 = values[1];
			cssMatrix.m13 = values[2];
			cssMatrix.m14 = values[3];

			cssMatrix.m21 = values[4];
			cssMatrix.m22 = values[5];
			cssMatrix.m23 = values[6];
			cssMatrix.m24 = values[7];

			cssMatrix.m31 = values[8];
			cssMatrix.m32 = values[9];
			cssMatrix.m33 = values[10];
			cssMatrix.m34 = values[11];

			cssMatrix.m41 = values[12];
			cssMatrix.m42 = values[13];
			cssMatrix.m43 = values[14];
			cssMatrix.m44 = values[15];

			return cssMatrix;
		},
		/**
		 * Returns an array of values with the given WebKitCSSMatrix
		 *
		 * @param {WebkitCSSMatrix} cssMatrix The WebKitCSSMatrix
		 *
		 * @returns {array} The value of the Matrix
		 */
		_cssMatrixToValues: function(cssMatrix)
		{
			var values = [];
			values[0] = cssMatrix.m11;
			values[1] = cssMatrix.m12;
			values[2] = cssMatrix.m13;
			values[3] = cssMatrix.m14;

			values[4] = cssMatrix.m21;
			values[5] = cssMatrix.m22;
			values[6] = cssMatrix.m23;
			values[7] = cssMatrix.m24;

			values[8] = cssMatrix.m31;
			values[9] = cssMatrix.m32;
			values[10] = cssMatrix.m33;
			values[11] = cssMatrix.m34;

			values[12] = cssMatrix.m41;
			values[13] = cssMatrix.m42;
			values[14] = cssMatrix.m43;
			values[15] = cssMatrix.m44;
			return values;
		}
	};

	return wink.math;
});<commit_msg>Hack to avoid the BB playbook problem on the float to string conversion<commit_after>/*--------------------------------------------------------
 * Copyright (c) 2011, The Dojo Foundation
 * This software is distributed under the "Simplified BSD license",
 * the text of which is available at http://www.winktoolkit.org/licence.txt
 * or see the "license.txt" file for more details.
 *--------------------------------------------------------*/

/**
 * @fileOverview math matrix library - a wink.math extension.
 *
 * @compatibility Iphone OS2, Iphone OS3, Iphone OS4, Android 2.1, Android 2.2, Android 2.3, Android 3.0, Android 3.1, BlackBerry 6, BlackBerry 7, Bada 1.0
 * @author Sylvain LALANDE
 */
define(['../../../_amd/core'], function(wink)
{
	/**
	 * Creates a transformation matrix with the given css transform
	 *
	 * @param {string|WebKitCSSMatrix} [cssTransform] The css transform which will initialize the matrix
	 *
	 * @returns {wink.math.Matrix} The corresponding wink.math.Matrix
	 *
	 * @example
	 *
	 * var rotationMatrix = wink.math.createTransformMatrix();
	 * rotationMatrix.rotateAxisAngle(0, 1, 0, 45);
	 *
	 */
	wink.math.createTransformMatrix = function(cssTransform)
	{
		var matrix = new wink.math.Matrix({});
		if (wink.isSet(cssTransform))
		{
			matrix.loadCssTransform(cssTransform);
		}
		return matrix;
	};

	/**
	 * @class Implements a matrix encapsulation object (of order 4) that is representative of a 3d transformation.
	 *
	 * @param {object} properties The properties object
	 * @param {array} [properties.values] The matrix values as an array of 16 elements
	 */
	wink.math.Matrix = function(properties)
	{
		/**
		 * Unique identifier
		 *
		 * @property
		 * @type integer
		 */
		this.uId = wink.getUId();

		this._properties          = properties;
		this._values              = [];
		this._cssMatrix           = null;
		this._matrixConversionBug = (wink.ua.isBlackBerry && wink.ua.browserVersion == 7 && wink.ua.browserMinorVersion == 1);

		if (this._validateProperties() === false) return;

		this._initProperties();
	};

	wink.math.Matrix.prototype =
	{
		/**
		 * Apply a scale operation to the matrix.
		 *
		 * @param {number} x The x scale component
		 * @param {number} y The y scale component
		 * @param {number} z The z scale component
		 */
		scale: function(x, y, z)
		{
			var resultMatrix = this._cssMatrix.scale(x, y, z);
			var values = this._cssMatrixToValues(resultMatrix);
			this._load(values);
		},
		/**
		 * Apply a translate operation to the matrix.
		 *
		 * @param {number} x The x translation component
		 * @param {number} y The y translation component
		 * @param {number} z The z translation component
		 */
		translate: function(x, y, z)
		{
			var resultMatrix = this._cssMatrix.translate(x, y, z);
			var values = this._cssMatrixToValues(resultMatrix);
			this._load(values);
		},
		/**
		 * Apply a rotation operation to the matrix.
		 *
		 * @param {number} x The x rotation component
		 * @param {number} y The y rotation component
		 * @param {number} z The z rotation component
		 * @param {number} angleDeg The rotation angle in degree
		 */
		rotateAxisAngle: function(x, y, z, angleDeg)
		{
			var resultMatrix = this._cssMatrix.rotateAxisAngle(x, y, z, angleDeg);
			var values = this._cssMatrixToValues(resultMatrix);
			this._load(values);
		},
		/**
		 * Multiply the current matrix by an other one.
		 *
		 * @param {wink.math.Matrix} otherWinkMatrix The other matrix
		 */
		multiply: function(otherWinkMatrix)
		{
			var m1 = otherWinkMatrix.getCssMatrix();
			var m2 = this._cssMatrix;
			if (wink.has("css-matrix-stack-inversed")) {
				var tmp = m1;
				m1 = m2;
				m2 = tmp;
			}
			var resultMatrix = m1.multiply(m2);
			var values = this._cssMatrixToValues(resultMatrix);
			this._load(values);
		},
		/**
		 * Clones the current Wink Matrix
		 *
		 * @returns {wink.math.Matrix} The cloned matrix
		 */
		clone: function()
		{
			return new wink.math.Matrix({ values: this._values });
		},
		/**
		 * Load the given transformation
		 *
		 * @param {string|WebKitCSSMatrix} transformation The css transform
		 */
		loadCssTransform: function(transformation)
		{
			var result = null;

			if (isString(transformation))
			{
				var search = "matrix3d";
				var chaine = transformation;
				var index = chaine.indexOf(search);
				if (index != -1)
				{
					var matriceS = chaine.substring((search.length + 1), (chaine.length - 1));
					var matValues = matriceS.split(", ");
					var m = [];
					for ( var i = 0; i < matValues.length; i++) {
						m[i] = matValues[i] * 1;
					}
					this._load(m);
				}
			}
			else
			{
				try {
					var values = this._cssMatrixToValues(transformation); // WebKitCSSMatrix
					this._load(values);
				} catch (e) {
					wink.log('[Matrix] Error: bad WebKitCSSMatrix');
				}
			}
		},
		/**
		 * Returns the matrix values
		 *
		 * @returns {array} The matrix values
		 */
		getValues: function()
		{
			return this._values;
		},
		/**
		 * Return the corresponding WebKitCSSMatrix
		 *
		 * @returns {WebkitCSSMatrix} The WebKitCSSMatrix
		 */
		getCssMatrix: function()
		{
			return this._cssMatrix;
		},

		/**
		 * Return the string value of the WebKitCSSMatrix
		 *
		 * @returns {String} The value of the matrix
		 */
		toString: function()
		{
			if ( !this._matrixConversionBug )
			{
				return this._cssMatrix.toString();
			} else
			{
				return 'matrix3d(' + this._values.join(',') + ')';
			}
		},
		/**
		 * Validate the properties of the component
		 * @returns {boolean} True if the properties are valid, false otherwise
		 */
		_validateProperties: function()
		{
			if (wink.isSet(this._properties.values) && this._properties.values.length != 16)
			{
				wink.log('[Matrix] Error: values should be number 16');
				return false;
			}
			return true;
		},
		/**
		 * Initialize datas with given properties
		 */
		_initProperties: function()
		{
			if (wink.isSet(this._properties.values))
			{
				this._load(this._properties.values);
			}
			else
			{
				this._loadIdentity();
			}
		},
		/**
		 * Load the identity matrix
		 */
		_loadIdentity: function()
		{
			this._load([
				1, 0, 0, 0,
				0, 1, 0, 0,
				0, 0, 1, 0,
				0, 0, 0, 1
			]);
		},
		/**
		 * Load the given values
		 *
		 * @param {array} values An array of 16 matrix values
		 */
		_load: function(values)
		{
			if (!wink.isSet(values) || values.length != 16)
			{
				wink.log('[Matrix] Error: values should be number 16');
				return false;
			}
			this._values = values;
			this._cssMatrix = this._valuesToCssMatrix(this._values);
		},
		/**
		 * Returns a WebKitCSSMatrix with the given array of values
		 *
		 * @param {array} values An array of 16 matrix values
		 *
		 * @returns {WebkitCSSMatrix} The WebKitCSSMatrix
		 */
		_valuesToCssMatrix: function(values)
		{
			var cssMatrix = new WebKitCSSMatrix();

			cssMatrix.m11 = values[0];
			cssMatrix.m12 = values[1];
			cssMatrix.m13 = values[2];
			cssMatrix.m14 = values[3];

			cssMatrix.m21 = values[4];
			cssMatrix.m22 = values[5];
			cssMatrix.m23 = values[6];
			cssMatrix.m24 = values[7];

			cssMatrix.m31 = values[8];
			cssMatrix.m32 = values[9];
			cssMatrix.m33 = values[10];
			cssMatrix.m34 = values[11];

			cssMatrix.m41 = values[12];
			cssMatrix.m42 = values[13];
			cssMatrix.m43 = values[14];
			cssMatrix.m44 = values[15];

			return cssMatrix;
		},
		/**
		 * Returns an array of values with the given WebKitCSSMatrix
		 *
		 * @param {WebkitCSSMatrix} cssMatrix The WebKitCSSMatrix
		 *
		 * @returns {array} The value of the Matrix
		 */
		_cssMatrixToValues: function(cssMatrix)
		{
			var values = [];
			values[0] = cssMatrix.m11;
			values[1] = cssMatrix.m12;
			values[2] = cssMatrix.m13;
			values[3] = cssMatrix.m14;

			values[4] = cssMatrix.m21;
			values[5] = cssMatrix.m22;
			values[6] = cssMatrix.m23;
			values[7] = cssMatrix.m24;

			values[8] = cssMatrix.m31;
			values[9] = cssMatrix.m32;
			values[10] = cssMatrix.m33;
			values[11] = cssMatrix.m34;

			values[12] = cssMatrix.m41;
			values[13] = cssMatrix.m42;
			values[14] = cssMatrix.m43;
			values[15] = cssMatrix.m44;
			return values;
		}
	};

	return wink.math;
});<|endoftext|>


<commit_before><commit_msg>rewrite the datetime in the api<commit_after><|endoftext|>


<commit_before>var ActivityService = new ActivityService();

SMARTREAD = {};

$(document).ready(function(){

    var checkReadiumTimer = setInterval(function(){checkReadium()}, 1);
    var checkReadium = function(){

        // if it is loaded, then bind events to elements inside iframe
        if(window._epubController &&
            window._epubController.paginator &&
            window._epubController.paginator.v &&
            window._epub){

            clearInterval(checkReadiumTimer);

            // INIT book configuration
            SMARTREAD.book = {
                id: window._epub.attributes.id,
                key: window._epub.attributes.key,
                name: window._epub.attributes.title,
                numPages: window._epubController.paginator.v.pages.attributes.num_pages,
                status : {
                    currentPage: window._epubController.paginator.v.pages.attributes.current_page,
                    previousPage: null
                }
            }

            var pageChanged = function(model, newPage){
                var oldPage = model._previousAttributes.current_page;
                SMARTREAD.book.status.currentPage = newPage;
                SMARTREAD.book.status.previousPage = oldPage;

                // activity_type_id = 3  --->  page_changed
                ActivityService.newActivity({
                    activity_type_id: '3',
                    activity_content: "{old: '" + oldPage + "', new: '" + newPage + "'}",
                    book_name : '1',
                    user_id : '1'
                }, function(){})
            }

            // attach a function to page change event
            window._epubController.paginator.v.pages.on("change:current_page", pageChanged, this);

            // TELL SERVER that user started reading a book
            ActivityService.newActivity({
                activity_type_id: '1',
                activity_content: '',
                book_name : '1',
                user_id : '1'
            }, function(){})

        }
    }
});
<commit_msg>track.js - have all the functions in one file<commit_after>// need to lood this first, image search api
google.load('search', '1');

SMARTREAD = {};

SMARTREAD = new function() {

    // BOOK model
    this.book = {
        id: '',
        key: '',
        name: '',
        numPages: '',
        status : {
            currentPage: '',
            previousPage: ''
        }
    }

    // init SMARTREAD object, assign required variables
    this.init = function () {

        var checkReadiumTimer = setInterval(function(){checkReadium()}, 1);

        var checkReadium = function(){

            // if it is loaded, then bind events to elements inside iframe
            if(window._epubController &&
                window._epubController.paginator &&
                window._epubController.paginator.v &&
                window._epubController.paginator.v.pages &&
                window._epub){

                clearInterval(checkReadiumTimer);

                var current_page = window._epubController.paginator.v.pages.get("current_page");

                // INIT book configuration
                SMARTREAD.book = {
                    id: window._epub.attributes.id,
                    key: window._epub.attributes.key,
                    name: window._epub.attributes.title,
                    numPages: window._epubController.paginator.v.pages.attributes.num_pages,
                    status : {
                        currentPage: current_page,
                        previousPage: null
                    }
                }

                var pageChanged = function(){
                    var previousPage = null;
                    var currentPage = window._epubController.paginator.v.pages.get("current_page");

                    SMARTREAD.book.status.previousPage = previousPage;
                    SMARTREAD.book.status.currentPage = currentPage;

                    // activity_type_id = 3  --->  page_changed
                    SMARTREAD.services.ActivityService.newActivity({
                        activity_type_id: '3',
                        activity_content: "{old: '" + previousPage + "', new: '" + currentPage + "'}"
                    }, function(){})
                }

                // attach a function to page change event
                $( "#next-page-button" ).click(function() {
                    pageChanged();
                });

                $( "#prev-page-button" ).click(function() {
                    pageChanged();
                });

                // this is called when chapter has been changed
                window._epubController.on("change:spine_position", function(){}, this);

                // TELL SERVER that user started reading a book
                SMARTREAD.services.ActivityService.newActivity({
                    activity_type_id: '1',
                    activity_content: ''
                }, function(){})

            }
        }
    }

    this.services = {

        // makes calls to the server
        CallService : new function() {
            this.makeRequest = function (method, path, data, callback) {
                chrome.storage.local.get('user', function (result) {

                    var user = result.user;

                    if(!user)
                        alert('Cannot tracking reading activity. Please log-in from main page to use this application.');

                    else {
                        chrome.storage.local.get('server', function (result) {
                            if(!result.server.url)
                                alert('Error while getting server options, please restart the application and go to main page.');
                            else {

                                data.user_id = user.user_id;

                                $.ajax({
                                    type: method,
                                    url: result.server.url + path,
                                    data: data
                                }).done(function(result) {
                                        callback(result);
                                    });
                            }
                        });
                    }
                });
            }
        },

        // activity operations
        ActivityService : new function() {
            this.newActivity = function (activity, callback) {
                var data = {
                    activity_type_id: activity.activity_type_id,
                    activity_content: activity.activity_content,
                    book_name : SMARTREAD.book.name,
                    user_id : activity.user_id
                };

                SMARTREAD.services.CallService.makeRequest('POST', 'activity/', data, function(result){
                    callback(result);
                });
            }
        },

        // word lookup requests
        LookupService : new function() {
            this.wordLookup = function (word, callback) {
                // Handles AJAX response (google dictionary API request)
                var handleResponse = function(){
                    if(ajax.readyState==4 && ajax.status==200){
                        var massaged = ajax.responseText.replace(/^[^(]+\(|[^}]+$/g, ''), res;
                        try {
                            res = JSON.parse( massaged );
                        } catch( e ) {
                            res = new Function( 'return ' + massaged )();
                        }

                        var result = process(res);
                        callback(result);
                    }
                }

                // process the json response, creates result object
                var process = function(json_obj){
                    var result = {
                        word : json_obj.query,
                        type : null,
                        sound : null,
                        pronunciation : null,
                        primary_means : null
                    };

                    for (var prop in json_obj){
                        if(prop=="primaries"){
                            var stuff = json_obj["primaries"][0];

                            // get pronunciation and sound
                            var isa = "";
                            var sound = '';
                            var wordType = '';
                            var pro = stuff["terms"];
                            for(var i=0;i<pro.length;i++){
                                if(pro[i]["type"]=="phonetic"){
                                    isa+=pro[i]["text"];
                                    isa+=" ";
                                }
                                else if(pro[i]["type"]=="sound"){
                                    sound = pro[i]["text"];
                                }
                                else if(pro[i]["type"]=="text"){
                                    wordType += pro[i]["labels"][0]['text'];
                                    wordType += " ";
                                }
                            }

                            result.sound = sound;
                            result.type = wordType;
                            result.pronunciation = isa;

                            // get meaning array
                            var primary_mean = stuff["entries"];
                            var primary_mean_list = [];
                            var k=0;
                            for(var i=0;i<primary_mean.length;i++){
                                if(primary_mean[i]["type"]=="meaning"){
                                    primary_mean_list[k]=primary_mean[i]["terms"][0]["text"];
                                    k++;
                                }
                            }
                            result.primary_means = primary_mean_list;
                        }
                        else
                            continue;
                    }

                    return result;
                }

                // if selected string is empty, do nothing
                if(word == "" || word == " ")    return;

                // now, make a call to google dictionary api, and get the meaning
                var ajax = new XMLHttpRequest();
                ajax.onreadystatechange	= handleResponse;
                ajax.open("GET","http://www.google.com/dictionary/json?callback=process&sl=en&tl=en&restrict=pr,de&client=te&q=" + word,true);
                ajax.send();
            }
        },

        // image search api
        ImageService : new function() {
            this.getImage = function (keyword, callback) {
                var imageSearch;

                // this is called after we get the response back from google search api
                function searchComplete() {
                    callback(imageSearch.results );
                }

                // makes the call, returns the response
                function imageCall(keyword) {
                    imageSearch = new google.search.ImageSearch();
                    imageSearch.setSearchCompleteCallback(this, searchComplete, null);
                    imageSearch.execute(keyword);
                }

                // make an ajax call to google img api
                imageCall(keyword);
            }
        }
    }
};

$(document).ready(function(){
    SMARTREAD.init();
});
<|endoftext|>