<commit_before>// The ConversationPanel module is designed to handle
// all display and behaviors of the conversation column of the app.
/* eslint no-unused-vars: "off" */
/* global Api: true, Common: true*/

var ConversationPanel = (function() {

  var settings = {
    selectors: {
      chatBox: '#scrollingChat',
      fromUser: '.from-user',
      fromWatson: '.from-watson',
      latest: '.latest'
    },
    authorTypes: {
      user: 'user',
      watson: 'watson'
    }
  };

  // Publicly accessible methods defined
  return {
    init: init,
    inputKeyDown: inputKeyDown
  };

  // Initialize the module
  function init() {
    Api.sendRequest( 'initial message', null );
    chatUpdateSetup();
    setupInputBox();

    //Setting the sessionID
    //localStorage.clear();
    if(!localStorage){
      localStorage.setItem("sessionID", "0");
      localStorage.setItem("questionID", "0");
    }
    else
    {
      var temp = localStorage.getItem("sessionID");
      temp++;
      localStorage.setItem("sessionID", temp);
      localStorage.setItem("questionID", 1);
    }
  }

  // Set up callbacks on payload setters in Api module
  // This causes the displayMessage function to be called when messages are sent / received
  function chatUpdateSetup() {
    var currentRequestPayloadSetter = Api.setRequestPayload;
    Api.setRequestPayload = function(newPayloadStr) {
      currentRequestPayloadSetter.call(Api, newPayloadStr);
      displayMessage(JSON.parse(newPayloadStr), settings.authorTypes.user);
    };

    var currentResponsePayloadSetter = Api.setResponsePayload;
    Api.setResponsePayload = function(newPayloadStr) {
      currentResponsePayloadSetter.call(Api, newPayloadStr);
      displayMessage(JSON.parse(newPayloadStr), settings.authorTypes.watson);
    };
  }

// Set up the input box to underline text as it is typed
  // This is done by creating a hidden dummy version of the input box that
  // is used to determine what the width of the input text should be.
  // This value is then used to set the new width of the visible input box.
  function setupInputBox() {
    var input = document.getElementById('textInput');
    var dummy = document.getElementById('textInputDummy');
    var minFontSize = 14;
    var maxFontSize = 16;
    var minPadding = 4;
    var maxPadding = 6;

    // If no dummy input box exists, create one
    if (dummy === null) {
      var dummyJson = {
        'tagName': 'div',
        'attributes': [{
          'name': 'id',
          'value': 'textInputDummy'
        }]
      };

      dummy = Common.buildDomElement(dummyJson);
      document.body.appendChild(dummy);
    }

    function adjustInput() {
      if (input.value === '') {
        // If the input box is empty, remove the underline
        input.classList.remove('underline');
        input.setAttribute('style', 'width:' + '100%');
        input.style.width = '100%';
      } else {
        // otherwise, adjust the dummy text to match, and then set the width of
        // the visible input box to match it (thus extending the underline)
        input.classList.add('underline');
        var txtNode = document.createTextNode(input.value);
        ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height',
          'text-transform', 'letter-spacing'].forEach(function(index) {
            dummy.style[index] = window.getComputedStyle(input, null).getPropertyValue(index);
          });
        dummy.textContent = txtNode.textContent;

        var padding = 0;
        var htmlElem = document.getElementsByTagName('html')[0];
        var currentFontSize = parseInt(window.getComputedStyle(htmlElem, null).getPropertyValue('font-size'), 10);
        if (currentFontSize) {
          padding = Math.floor((currentFontSize - minFontSize) / (maxFontSize - minFontSize) * (maxPadding - minPadding) + minPadding);
        } else {
          padding = maxPadding;
        }

        var widthValue = ( dummy.offsetWidth + padding) + 'px';
        input.setAttribute('style', 'width:' + widthValue);
        input.style.width = widthValue;
      }
    }

    // Any time the input changes, or the window resizes, adjust the size of the input box
    input.addEventListener('input', adjustInput);
    window.addEventListener('resize', adjustInput);

    // Trigger the input event once to set up the input box and dummy element
    Common.fireEvent(input, 'input');
  }

  // Display a user or Watson message that has just been sent/received
  function displayMessage(newPayload, typeValue) {
    var isUser = isUserMessage(typeValue);
    var textExists = (newPayload.input && newPayload.input.text) || (newPayload.output && newPayload.output.text);
    if (isUser !== null && textExists) {
      // Create new message DOM element
      var messageDivs = buildMessageDomElements(newPayload, isUser);
      var chatBoxElement = document.querySelector(settings.selectors.chatBox);
      var previousLatest = chatBoxElement.querySelectorAll((isUser ? settings.selectors.fromUser : settings.selectors.fromWatson) + settings.selectors.latest);
      // Previous "latest" message is no longer the most recent
      if (previousLatest) {
        Common.listForEach(previousLatest, function(element) {
          element.classList.remove('latest');
        });
      }

      messageDivs.forEach(function(currentDiv) {
        chatBoxElement.appendChild(currentDiv);
        // Class to start fade in animation
        currentDiv.classList.add('load');
      });

      // Move chat to the most recent messages when new messages are added
      scrollToChatBottom();
      console.log(localStorage);
    }
  }

  // Checks if the given typeValue matches with the user "name", the Watson "name", or neither
  // Returns true if user, false if Watson, and null if neither
  // Used to keep track of whether a message was from the user or Watson
  function isUserMessage(typeValue) {
    if (typeValue === settings.authorTypes.user) {
      return true;
    } else if (typeValue === settings.authorTypes.watson) {
      return false;
    }
    return null;
  }

  // Constructs new DOM element from a message payload
  function buildMessageDomElements(newPayload, isUser) {
    var textArray = isUser ? newPayload.input.text : newPayload.output.text;
    if (Object.prototype.toString.call( textArray ) !== '[object Array]') {
      textArray = [textArray];
    }
    var messageArray = [];

    textArray.forEach(function(currentText) {
      if (currentText) {
        var messageJson = {
          //

          'tagName': 'div',
          'classNames': ['segments'],
          'children': [{
            //

            'tagName': 'div',
            'classNames': [(isUser ? 'from-user' : 'from-watson'), 'latest', ((messageArray.length === 0) ? 'top' : 'sub')],
            'children': [{
              //

              'tagName': 'div',
              'classNames': ['message-inner'],
              'children': [{
                //
{messageText}

                'tagName': 'p',
                'text': currentText
              }]
            }]
          }]
        };

        function extraOutput(newHtml){
          var messageJson2 = {
            //

            'tagName': 'div',
            'classNames': ['segments'],
            'children': [{
              //

              'tagName': 'div',
              'classNames': [(isUser ? 'from-user' : 'from-watson'), 'latest', ((messageArray.length === 0) ? 'top' : 'sub')],
              'children': [{
                //

                'tagName': 'div',
                'classNames': ['message-inner'],
                'children': [{
                  //  html injection
                  'html': newHtml
                }]
              }]
            }]
          };
          return messageJson2;
        }

        messageArray.push(Common.buildDomElement(messageJson));
      }

      //display the scrum diagram
      if(isUser==false){
        if(currentText=="The scrum diagram displays an overview of scrum."){
          messageArray.push(Common.buildDomElement(extraOutput("")));
        }
      }

      //Function for disabling buttons
      var disableButtons = function(){
        var elems = document.getElementsByClassName("myButtons");
        for(var i = 0; i < elems.length; i++) {
            elems[i].disabled = true;
        }
      }

      //daily scrum list
      if(isUser==false){
        if(currentText == "The Daily Scrum is a 15-minute time-boxed event for the Development Team to synchronize activities and create a plan for the next 24 hours. This is done by inspecting the work since the last Daily Scrum and forecasting the work that could be done before the next one. The Daily Scrum is held at the same time and place each day to reduce complexity. During the meeting, the Development Team members explain:"){
          var dailyScrum = "

What did I do yesterday that helped the Development Team meet the Sprint Goal?

What will I do today to help the Development Team meet the Sprint Goal?

Do I see any impediment that prevents me or the Development Team from meeting the Sprint Goal?

";
          messageArray.push(Common.buildDomElement(extraOutput(dailyScrum)));
        }
      }

      //display lists based on Watson's context (Watson doesn't have this functionality)
      if(isUser==false){

        if(Api.getResponsePayload().context.list.length>0){
          var list = Api.getResponsePayload().context.list;
          var htmlString = "
";
          var htmlString1 = "
";
          var htmlString2 = "
";
          var htmlString3 = "
";
          for (var i=0;i<list.length;i++){
            htmlString = htmlString.concat(htmlString1+list[i]+htmlString2);
          }
          htmlString = htmlString.concat(htmlString3);
          messageArray.push(Common.buildDomElement(extraOutput(htmlString)));

        }
      }

      //Log user input
      if(isUser == true && newPayload.input.text!="initial message"){
        //Setting the questionID
        var localQuestionID = localStorage.getItem("questionID");
        //Get the session ID
        var localSessionID = localStorage.getItem("sessionID") - 1;
        //Concat the input temaplte
        var questionTemplate = localSessionID + "_" + localQuestionID + "_question";
        //Store the input in local storage
        localStorage.setItem(questionTemplate, newPayload.input.text);

        //localQuestionID++;
        localStorage.setItem("questionID", localQuestionID);
      }

      //Log answer/question level
      if(isUser == false && Api.getResponsePayload().output.text[0]!="Hi, I'm ScrumBot, you can ask me about the scrum methodology"){
        //Setting the questionID
        var localQuestionID = localStorage.getItem("questionID");
        //Get the session ID
        var localSessionID = localStorage.getItem("sessionID") - 1;
        //Concat the level temaplte
        var levelTemplate = localSessionID + "_" + localQuestionID + "_level";
        //Store the level in local storage
        localStorage.setItem(levelTemplate, Api.getResponsePayload().context.level[0]);

      }

      //Log Watson response
      if(isUser == false && Api.getResponsePayload().output.text[0]!="Hi, I'm ScrumBot, you can ask me about the scrum methodology"){
        //Get the questionID
        var localQuestionID = localStorage.getItem("questionID");
        //Get the session ID
        var localSessionID = localStorage.getItem("sessionID") - 1;
        //Concat the answer temaplte
        var answerTemplate = localSessionID + "_" + localQuestionID + "_answer";
        //Store the answer in local storage
        localStorage.setItem(answerTemplate, Api.getResponsePayload().output.text[0]);

        //Increment the questionID
        localQuestionID++;
        //Store it again in local storage
        localStorage.setItem("questionID", localQuestionID);

      }

      // //display buttons based on Watson's context
      // if(isUser==false){
      //   disableButtons();

      //   if(Api.getResponsePayload().context.buttonsLabel.length>0){
      //     var buttons = Api.getResponsePayload().context.buttonsLabel;
      //     var onclicklist = Api.getResponsePayload().context.onclick;
      //     var htmlString1 = "<button type=\"button\" class='btn btn-default myButtons' onclick=\"suggested();Api.sendRequest('";
      //     var htmlString2 = "', null);\">";
      //     var htmlString3 = "</button>";
      //     var htmlString = "";
      //     for (var i=0;i<buttons.length;i++){
      //       htmlString = htmlString.concat(htmlString1+onclicklist[i]+htmlString2+buttons[i]+htmlString3);
      //     }
      //     messageArray.push(Common.buildDomElement(extraOutput(htmlString)));

      //   }
      // }

    });
    return messageArray;
  }

  // Scroll to the bottom of the chat window (to the most recent messages)
  function scrollToChatBottom() {
    var scrollingChat = document.querySelector('#scrollingChat');
    scrollingChat.scrollTop = scrollingChat.scrollHeight;
  }

  var questionID = 1;

  // Handles the submission of input
  function inputKeyDown(event, inputBox) {
    // Submit on enter key, dis-allowing blank messages
    if (event.keyCode === 13 && inputBox.value) {
      // Retrieve the context from the previous server response
      var context;
      var latestResponse = Api.getResponsePayload();
      if (latestResponse) {
        context = latestResponse.context;
      }

      // Send the user message
      Api.sendRequest(inputBox.value, context);

      // Clear input box for further messages
      inputBox.value = '';
      Common.fireEvent(inputBox, 'input');

      //Get the questionID
      var localQuestionID = localStorage.getItem("questionID");
      //Get the sessionID
      var localSessionID = localStorage.getItem("sessionID") - 1;
      //Concat the template
      var suggestedTemplate = localSessionID + "_" + localQuestionID + "_suggested";
      //Store it in local storage
      localStorage.setItem(suggestedTemplate, "Not suggested");
    }
  }
}());
<commit_msg>Fix learning analytics<commit_after>// The ConversationPanel module is designed to handle
// all display and behaviors of the conversation column of the app.
/* eslint no-unused-vars: "off" */
/* global Api: true, Common: true*/

var ConversationPanel = (function() {

  var settings = {
    selectors: {
      chatBox: '#scrollingChat',
      fromUser: '.from-user',
      fromWatson: '.from-watson',
      latest: '.latest'
    },
    authorTypes: {
      user: 'user',
      watson: 'watson'
    }
  };

  // Publicly accessible methods defined
  return {
    init: init,
    inputKeyDown: inputKeyDown
  };

  // Initialize the module
  function init() {
    Api.sendRequest( 'initial message', null );
    chatUpdateSetup();
    setupInputBox();

    //Setting the sessionID
    //localStorage.clear();
    if(!localStorage){
      localStorage.setItem("sessionID", "0");
      localStorage.setItem("questionID", "0");
    }
    else
    {
      var temp = localStorage.getItem("sessionID");
      temp++;
      localStorage.setItem("sessionID", temp);
      localStorage.setItem("questionID", 1);
    }
  }

  // Set up callbacks on payload setters in Api module
  // This causes the displayMessage function to be called when messages are sent / received
  function chatUpdateSetup() {
    var currentRequestPayloadSetter = Api.setRequestPayload;
    Api.setRequestPayload = function(newPayloadStr) {
      currentRequestPayloadSetter.call(Api, newPayloadStr);
      displayMessage(JSON.parse(newPayloadStr), settings.authorTypes.user);
    };

    var currentResponsePayloadSetter = Api.setResponsePayload;
    Api.setResponsePayload = function(newPayloadStr) {
      currentResponsePayloadSetter.call(Api, newPayloadStr);
      displayMessage(JSON.parse(newPayloadStr), settings.authorTypes.watson);
    };
  }

// Set up the input box to underline text as it is typed
  // This is done by creating a hidden dummy version of the input box that
  // is used to determine what the width of the input text should be.
  // This value is then used to set the new width of the visible input box.
  function setupInputBox() {
    var input = document.getElementById('textInput');
    var dummy = document.getElementById('textInputDummy');
    var minFontSize = 14;
    var maxFontSize = 16;
    var minPadding = 4;
    var maxPadding = 6;

    // If no dummy input box exists, create one
    if (dummy === null) {
      var dummyJson = {
        'tagName': 'div',
        'attributes': [{
          'name': 'id',
          'value': 'textInputDummy'
        }]
      };

      dummy = Common.buildDomElement(dummyJson);
      document.body.appendChild(dummy);
    }

    function adjustInput() {
      if (input.value === '') {
        // If the input box is empty, remove the underline
        input.classList.remove('underline');
        input.setAttribute('style', 'width:' + '100%');
        input.style.width = '100%';
      } else {
        // otherwise, adjust the dummy text to match, and then set the width of
        // the visible input box to match it (thus extending the underline)
        input.classList.add('underline');
        var txtNode = document.createTextNode(input.value);
        ['font-size', 'font-style', 'font-weight', 'font-family', 'line-height',
          'text-transform', 'letter-spacing'].forEach(function(index) {
            dummy.style[index] = window.getComputedStyle(input, null).getPropertyValue(index);
          });
        dummy.textContent = txtNode.textContent;

        var padding = 0;
        var htmlElem = document.getElementsByTagName('html')[0];
        var currentFontSize = parseInt(window.getComputedStyle(htmlElem, null).getPropertyValue('font-size'), 10);
        if (currentFontSize) {
          padding = Math.floor((currentFontSize - minFontSize) / (maxFontSize - minFontSize) * (maxPadding - minPadding) + minPadding);
        } else {
          padding = maxPadding;
        }

        var widthValue = ( dummy.offsetWidth + padding) + 'px';
        input.setAttribute('style', 'width:' + widthValue);
        input.style.width = widthValue;
      }
    }

    // Any time the input changes, or the window resizes, adjust the size of the input box
    input.addEventListener('input', adjustInput);
    window.addEventListener('resize', adjustInput);

    // Trigger the input event once to set up the input box and dummy element
    Common.fireEvent(input, 'input');
  }

  // Display a user or Watson message that has just been sent/received
  function displayMessage(newPayload, typeValue) {
    var isUser = isUserMessage(typeValue);
    var textExists = (newPayload.input && newPayload.input.text) || (newPayload.output && newPayload.output.text);
    if (isUser !== null && textExists) {
      // Create new message DOM element
      var messageDivs = buildMessageDomElements(newPayload, isUser);
      var chatBoxElement = document.querySelector(settings.selectors.chatBox);
      var previousLatest = chatBoxElement.querySelectorAll((isUser ? settings.selectors.fromUser : settings.selectors.fromWatson) + settings.selectors.latest);
      // Previous "latest" message is no longer the most recent
      if (previousLatest) {
        Common.listForEach(previousLatest, function(element) {
          element.classList.remove('latest');
        });
      }

      messageDivs.forEach(function(currentDiv) {
        chatBoxElement.appendChild(currentDiv);
        // Class to start fade in animation
        currentDiv.classList.add('load');
      });

      // Move chat to the most recent messages when new messages are added
      scrollToChatBottom();
      console.log(localStorage);
    }
  }

  // Checks if the given typeValue matches with the user "name", the Watson "name", or neither
  // Returns true if user, false if Watson, and null if neither
  // Used to keep track of whether a message was from the user or Watson
  function isUserMessage(typeValue) {
    if (typeValue === settings.authorTypes.user) {
      return true;
    } else if (typeValue === settings.authorTypes.watson) {
      return false;
    }
    return null;
  }

  // Constructs new DOM element from a message payload
  function buildMessageDomElements(newPayload, isUser) {
    var textArray = isUser ? newPayload.input.text : newPayload.output.text;
    if (Object.prototype.toString.call( textArray ) !== '[object Array]') {
      textArray = [textArray];
    }
    var messageArray = [];

    textArray.forEach(function(currentText) {
      if (currentText) {
        var messageJson = {
          //

          'tagName': 'div',
          'classNames': ['segments'],
          'children': [{
            //

            'tagName': 'div',
            'classNames': [(isUser ? 'from-user' : 'from-watson'), 'latest', ((messageArray.length === 0) ? 'top' : 'sub')],
            'children': [{
              //

              'tagName': 'div',
              'classNames': ['message-inner'],
              'children': [{
                //
{messageText}

                'tagName': 'p',
                'text': currentText
              }]
            }]
          }]
        };

        function extraOutput(newHtml){
          var messageJson2 = {
            //

            'tagName': 'div',
            'classNames': ['segments'],
            'children': [{
              //

              'tagName': 'div',
              'classNames': [(isUser ? 'from-user' : 'from-watson'), 'latest', ((messageArray.length === 0) ? 'top' : 'sub')],
              'children': [{
                //

                'tagName': 'div',
                'classNames': ['message-inner'],
                'children': [{
                  //  html injection
                  'html': newHtml
                }]
              }]
            }]
          };
          return messageJson2;
        }

        messageArray.push(Common.buildDomElement(messageJson));
      }

      //display the scrum diagram
      if(isUser==false){
        if(currentText=="The scrum diagram displays an overview of scrum."){
          messageArray.push(Common.buildDomElement(extraOutput("")));
        }
      }

      //Function for disabling buttons
      var disableButtons = function(){
        var elems = document.getElementsByClassName("myButtons");
        for(var i = 0; i < elems.length; i++) {
            elems[i].disabled = true;
        }
      }

      //daily scrum list
      if(isUser==false){
        if(currentText == "The Daily Scrum is a 15-minute time-boxed event for the Development Team to synchronize activities and create a plan for the next 24 hours. This is done by inspecting the work since the last Daily Scrum and forecasting the work that could be done before the next one. The Daily Scrum is held at the same time and place each day to reduce complexity. During the meeting, the Development Team members explain:"){
          var dailyScrum = "

What did I do yesterday that helped the Development Team meet the Sprint Goal?

What will I do today to help the Development Team meet the Sprint Goal?

Do I see any impediment that prevents me or the Development Team from meeting the Sprint Goal?

";
          messageArray.push(Common.buildDomElement(extraOutput(dailyScrum)));
        }
      }

      //display lists based on Watson's context (Watson doesn't have this functionality)
      if(isUser==false){

        if(Api.getResponsePayload().context.list.length>0){
          var list = Api.getResponsePayload().context.list;
          var htmlString = "
";
          var htmlString1 = "
";
          var htmlString2 = "
";
          var htmlString3 = "
";
          for (var i=0;i<list.length;i++){
            htmlString = htmlString.concat(htmlString1+list[i]+htmlString2);
          }
          htmlString = htmlString.concat(htmlString3);
          messageArray.push(Common.buildDomElement(extraOutput(htmlString)));

        }
      }

      //Log user input
      if(isUser == true && newPayload.input.text!="initial message"){
        //Setting the questionID
        var localQuestionID = localStorage.getItem("questionID");
        //Get the session ID
        var localSessionID = localStorage.getItem("sessionID") - 1;
        //Concat the input temaplte
        var questionTemplate = localSessionID + "_" + localQuestionID + "_question";
        //Store the input in local storage
        localStorage.setItem(questionTemplate, newPayload.input.text);

        //localQuestionID++;
        localStorage.setItem("questionID", localQuestionID);
      }

      //Log answer/question level
      if(isUser == false && Api.getResponsePayload().output.text[0]!="Hi, I'm your Scrum Assistant, you can ask me about the scrum methodology"){
        //Setting the questionID
        var localQuestionID = localStorage.getItem("questionID");
        //Get the session ID
        var localSessionID = localStorage.getItem("sessionID") - 1;
        //Concat the level temaplte
        var levelTemplate = localSessionID + "_" + localQuestionID + "_level";
        //Store the level in local storage
        localStorage.setItem(levelTemplate, Api.getResponsePayload().context.level[0]);

      }

      //Log Watson response
      if(isUser == false && Api.getResponsePayload().output.text[0]!="Hi, I'm your Scrum Assistant, you can ask me about the scrum methodology"){
        //Get the questionID
        var localQuestionID = localStorage.getItem("questionID");
        //Get the session ID
        var localSessionID = localStorage.getItem("sessionID") - 1;
        //Concat the answer temaplte
        var answerTemplate = localSessionID + "_" + localQuestionID + "_answer";
        //Store the answer in local storage
        localStorage.setItem(answerTemplate, Api.getResponsePayload().output.text[0]);

        //Increment the questionID
        localQuestionID++;
        //Store it again in local storage
        localStorage.setItem("questionID", localQuestionID);

      }

      // //display buttons based on Watson's context
      // if(isUser==false){
      //   disableButtons();

      //   if(Api.getResponsePayload().context.buttonsLabel.length>0){
      //     var buttons = Api.getResponsePayload().context.buttonsLabel;
      //     var onclicklist = Api.getResponsePayload().context.onclick;
      //     var htmlString1 = "<button type=\"button\" class='btn btn-default myButtons' onclick=\"suggested();Api.sendRequest('";
      //     var htmlString2 = "', null);\">";
      //     var htmlString3 = "</button>";
      //     var htmlString = "";
      //     for (var i=0;i<buttons.length;i++){
      //       htmlString = htmlString.concat(htmlString1+onclicklist[i]+htmlString2+buttons[i]+htmlString3);
      //     }
      //     messageArray.push(Common.buildDomElement(extraOutput(htmlString)));

      //   }
      // }

    });
    return messageArray;
  }

  // Scroll to the bottom of the chat window (to the most recent messages)
  function scrollToChatBottom() {
    var scrollingChat = document.querySelector('#scrollingChat');
    scrollingChat.scrollTop = scrollingChat.scrollHeight;
  }

  var questionID = 1;

  // Handles the submission of input
  function inputKeyDown(event, inputBox) {
    // Submit on enter key, dis-allowing blank messages
    if (event.keyCode === 13 && inputBox.value) {
      // Retrieve the context from the previous server response
      var context;
      var latestResponse = Api.getResponsePayload();
      if (latestResponse) {
        context = latestResponse.context;
      }

      // Send the user message
      Api.sendRequest(inputBox.value, context);

      // Clear input box for further messages
      inputBox.value = '';
      Common.fireEvent(inputBox, 'input');

      //Get the questionID
      var localQuestionID = localStorage.getItem("questionID");
      //Get the sessionID
      var localSessionID = localStorage.getItem("sessionID") - 1;
      //Concat the template
      var suggestedTemplate = localSessionID + "_" + localQuestionID + "_suggested";
      //Store it in local storage
      localStorage.setItem(suggestedTemplate, "Not suggested");
    }
  }
}());
<|endoftext|>


<commit_before>'use strict';

angular.module('bitcoincom.services').service('cameraPreviewService', function(
  $log
  , platformInfo
  , $rootScope
  , $window
  ) {

  var isDesktop = !platformInfo.isCordova;
  var CameraPreview = $window.CameraPreview;
  var lightEnabled = false;
  var backCamera = true; // the plugin defaults to the back camera

  // Initalize known capabilities
  // Assume camera is available. If init fails, we'll set this to false.
  var isAvailable = true;
  var hasPermission = false;
  var isDenied = false;
  var isRestricted = false;
  var canEnableLight = false;
  var canChangeCamera = false;
  var canOpenSettings = false;

  function _checkCapabilities(status) {
    $log.debug('scannerService is reviewing platform capabilities...');
    // Permission can be assumed on the desktop builds
    hasPermission = (isDesktop || status.authorized) ? true : false;
    isDenied = status.denied ? true : false;
    isRestricted = status.restricted ? true : false;
    canEnableLight = status.canEnableLight ? true : false;
    canChangeCamera = status.canChangeCamera ? true : false;
    canOpenSettings = status.canOpenSettings ? true : false;
    _logCapabilities();
  }

  var defaultCameraSettings = {
    x: 0
    , y: 0
    , width: $window.screen.width
    , height: $window.screen.height
    , camera: CameraPreview ? CameraPreview.CAMERA_DIRECTION.BACK : 0
    , toBack: true
    , tapPhoto: false
    , tapFocus: true
    , previewDrag: false
  };

  var defaultDocumentSettings = {
    x: 0
    , y: 0
    , width: $window.screen.width
    , height: $window.screen.height
    , camera: CameraPreview ? CameraPreview.CAMERA_DIRECTION.BACK : 0
    , toBack: true
    , tapPhoto: false
    , tapFocus: true
    , previewDrag: false
  }

  this.startCamera = function () {
    var options = defaultCameraSettings;
    if (isDesktop) {
      this.startDesktopCamera();
      return;
    }

    CameraPreview.startCamera(options, [function onStartCameraSuccess() {
      console.log('Camera Preview Started!');
      return;
    }, function onStartCameraError(err) {
      $log.debug('Camera Preview Failed to start on request');
    }]);
  }

  this.startSelfieCamera = function() {
    var options = defaultCameraSettings;
    if (isDesktop) {
      this.startDesktopCamera();
      return;
    }

    options.camera = CameraPreview.CAMERA_DIRECTION.FRONT;
    this.startCamera(options) ;
  }

  this.startDocumentCamera = function() {
    var options = defaultDocumentSettings;
    if (isDesktop) {
      this.startDesktopCamera();
      return;
    }

    options.camera = CameraPreview.CAMERA_DIRECTION.BACK;
    this.startCamera(options);
  }

  this.startDesktopCamera = function () {
    var constraints = {
      video: true
    };

    var elements = document.querySelectorAll('video');
    console.log(elements);
    var video = elements[elements.length - 1];

    navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
      $rootScope.$apply(function () {
        video.srcObject = stream;
      });
    });
  }

  this.stopCamera = function () {
    if (isDesktop) return;
    return CameraPreview.stopCamera(
      function onStopCameraSuccess() {
        return;
      },
      function onCameraStopError(err) {
        $log.debug('Camera Preview Failed to stop on request');
      }
    );
  }

  this.takePicture = function (options, callback) {
    if (isDesktop) {
      var elements = document.querySelectorAll('video');
      var video = elements[elements.length - 1];
      var canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas.getContext('2d').drawImage(video, 0, 0);
      var base64PictureData = canvas.toDataURL('image/jpeg', 0.8);
      return callback(base64PictureData);
    }
    CameraPreview.takePicture(options, function(base64PictureData){
      callback('data:image/jpeg;base64,' + base64PictureData);
    });
  }

  function setPreviewSize() {

  }

  // getCameraCharacteristics

});
<commit_msg>Fix default options<commit_after>'use strict';

angular.module('bitcoincom.services').service('cameraPreviewService', function(
  $log
  , platformInfo
  , $rootScope
  , $window
  ) {

  var isDesktop = !platformInfo.isCordova;
  var CameraPreview = $window.CameraPreview;
  var lightEnabled = false;
  var backCamera = true; // the plugin defaults to the back camera

  // Initalize known capabilities
  // Assume camera is available. If init fails, we'll set this to false.
  var isAvailable = true;
  var hasPermission = false;
  var isDenied = false;
  var isRestricted = false;
  var canEnableLight = false;
  var canChangeCamera = false;
  var canOpenSettings = false;

  function _checkCapabilities(status) {
    $log.debug('scannerService is reviewing platform capabilities...');
    // Permission can be assumed on the desktop builds
    hasPermission = (isDesktop || status.authorized) ? true : false;
    isDenied = status.denied ? true : false;
    isRestricted = status.restricted ? true : false;
    canEnableLight = status.canEnableLight ? true : false;
    canChangeCamera = status.canChangeCamera ? true : false;
    canOpenSettings = status.canOpenSettings ? true : false;
    _logCapabilities();
  }

  var defaultCameraSettings = {
    x: 0
    , y: 0
    , width: $window.screen.width
    , height: $window.screen.height
    , camera: CameraPreview ? CameraPreview.CAMERA_DIRECTION.BACK : 0
    , toBack: true
    , tapPhoto: false
    , tapFocus: true
    , previewDrag: false
  };

  var defaultDocumentSettings = {
    x: 0
    , y: 0
    , width: $window.screen.width
    , height: $window.screen.height
    , camera: CameraPreview ? CameraPreview.CAMERA_DIRECTION.BACK : 0
    , toBack: true
    , tapPhoto: false
    , tapFocus: true
    , previewDrag: false
  }

  this.startCamera = function (options) {
    if (isDesktop) {
      this.startDesktopCamera();
      return;
    }

    CameraPreview.startCamera(options, [function onStartCameraSuccess() {
      console.log('Camera Preview Started!');
      return;
    }, function onStartCameraError(err) {
      $log.debug('Camera Preview Failed to start on request');
    }]);
  }

  this.startSelfieCamera = function() {
    var options = defaultCameraSettings;
    if (isDesktop) {
      this.startDesktopCamera();
      return;
    }

    options.camera = CameraPreview.CAMERA_DIRECTION.FRONT;
    this.startCamera(options);
  }

  this.startDocumentCamera = function() {
    var options = defaultDocumentSettings;
    if (isDesktop) {
      this.startDesktopCamera();
      return;
    }

    options.camera = CameraPreview.CAMERA_DIRECTION.BACK;
    this.startCamera(options);
  }

  this.startDesktopCamera = function () {
    var constraints = {
      video: true
    };

    var elements = document.querySelectorAll('video');
    console.log(elements);
    var video = elements[elements.length - 1];

    navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
      $rootScope.$apply(function () {
        video.srcObject = stream;
      });
    });
  }

  this.stopCamera = function () {
    if (isDesktop) return;
    return CameraPreview.stopCamera(
      function onStopCameraSuccess() {
        return;
      },
      function onCameraStopError(err) {
        $log.debug('Camera Preview Failed to stop on request');
      }
    );
  }

  this.takePicture = function (options, callback) {
    if (isDesktop) {
      var elements = document.querySelectorAll('video');
      var video = elements[elements.length - 1];
      var canvas = document.createElement('canvas');
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      canvas.getContext('2d').drawImage(video, 0, 0);
      var base64PictureData = canvas.toDataURL('image/jpeg', 0.8);
      return callback(base64PictureData);
    }
    CameraPreview.takePicture(options, function(base64PictureData){
      callback('data:image/jpeg;base64,' + base64PictureData);
    });
  }

  function setPreviewSize() {

  }

  // getCameraCharacteristics

});
<|endoftext|>


<commit_before>/*
	Utility Functions
*/

// Set the width of the side navigation to show
function openNav() {
  $('#mySidenav').css('width', '25%');
}

// Set the width of the side navigation to 0
function closeNav() {
  $('#mySidenav').css('width','0px');
}

function getIDFromPokemonURL(url){
  /*
    Grabs the value between the last two /'s
    (i.e http://pokeapi.co/api/v2/pokemon/1/ => 1)
  */
  // var id = url.replace(/(.*)(pokemon|pokemon\-species)\/(.*)\//, '$3');
  var id = url.replace(/.*\/.*\/(.*?)\//, '$1');
  return id;
}

function showSection(sectionName){
  sectionName = sectionName.trim();

  if ($( "#" + sectionName ).hasClass("hidden")) {
    $('.' + sectionName + ' button').html('–');
    $('#' + sectionName).removeClass("hidden").addClass("expanded");
    $('#' + sectionName).focus();
  }else {
    $('.' + sectionName + ' button').html('+');
    $('#' + sectionName).addClass("hidden").removeClass("expanded");
  }
}

function setAutoComplete(results, searchBox, passedArray) {
  $.each(results, function(index, value){
    var name = value.name;
    passedArray.push(name);
  });
  var options = {
    data        :   passedArray,
    theme       :   'square',
    adjustWidth : false,

    list        :   {
      match          : {
        enabled: true
      },
      onChooseEvent   :   function(){

        var pokemonName = $("#" + searchBox).getSelectedItemData();
        newFunction(pokemonName, passedArray);
        // changePage(pokemonName, passedArray);
      }
    }
  }

  $('#' + searchBox).easyAutocomplete(options);

}

function newFunction(pokemonName, passedArray) {
  showSearch();
}

function changePage(pokemonID, passedArray) {
  console.log(pokemonID);
  if (pokemonID !== null) {
    pokemonID = pokemonID.toLowerCase();
    //make sure that pokemon name exists
    if(passedArray.indexOf(pokemonID) > -1){
      loadOverlay();
      window.location = "./" + pokemonID;
    }
  };
};

function showSearch(){
  if ($( "#searchContainer" ).hasClass("hidden")) {
    $('#searchContainer').removeClass("hidden");
    $('#pokemonSearchBox').focus();
  }else {
    $('#searchContainer').addClass("hidden");
  }
}

// Call Page Change Animation
function loadOverlay(){
  // alert('load overlay');
  $('#loadingAnimation').removeClass('hidden');
  console.log('loading new page...');
  $('#searchContainer').addClass('hidden');
  $('#loadingDiv').removeClass('hidden');
  // $('#loadingAnimation').removeClass('hidden');
}

function getQS(object){
  /*
  Query string values get returned back to the object
  Use object.key|object[key] //returns value
  */
  var pl     = /\+/g;  // Regex for replacing addition symbol with a space
  var search = /([^&=]+)=?([^&]*)/g;
  var decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); };
  var query  = window.location.search.substring(1);
  var match;

  while (match = search.exec(query)){
    object[decode(match[1])] = decode(match[2]);
  }
}
<commit_msg>testing overlay function<commit_after>/*
	Utility Functions
*/

// Set the width of the side navigation to show
function openNav() {
  $('#mySidenav').css('width', '25%');
}

// Set the width of the side navigation to 0
function closeNav() {
  $('#mySidenav').css('width','0px');
}

function getIDFromPokemonURL(url){
  /*
    Grabs the value between the last two /'s
    (i.e http://pokeapi.co/api/v2/pokemon/1/ => 1)
  */
  // var id = url.replace(/(.*)(pokemon|pokemon\-species)\/(.*)\//, '$3');
  var id = url.replace(/.*\/.*\/(.*?)\//, '$1');
  return id;
}

function showSection(sectionName){
  sectionName = sectionName.trim();

  if ($( "#" + sectionName ).hasClass("hidden")) {
    $('.' + sectionName + ' button').html('–');
    $('#' + sectionName).removeClass("hidden").addClass("expanded");
    $('#' + sectionName).focus();
  }else {
    $('.' + sectionName + ' button').html('+');
    $('#' + sectionName).addClass("hidden").removeClass("expanded");
  }
}

function setAutoComplete(results, searchBox, passedArray) {
  $.each(results, function(index, value){
    var name = value.name;
    passedArray.push(name);
  });
  var options = {
    data        :   passedArray,
    theme       :   'square',
    adjustWidth : false,

    list        :   {
      match          : {
        enabled: true
      },
      onChooseEvent   :   function(){

        var pokemonName = $("#" + searchBox).getSelectedItemData();
        // newFunction(pokemonName, passedArray);
        changePage(pokemonName, passedArray);
      }
    }
  }

  $('#' + searchBox).easyAutocomplete(options);

}

function newFunction(pokemonName, passedArray) {
  showSearch();
}

function changePage(pokemonID, passedArray) {
  console.log(pokemonID);
  if (pokemonID !== null) {
    pokemonID = pokemonID.toLowerCase();
    //make sure that pokemon name exists
    if(passedArray.indexOf(pokemonID) > -1){
      loadOverlay();
      window.location = "./" + pokemonID;
    }
  };
};

function showSearch(){
  if ($( "#searchContainer" ).hasClass("hidden")) {
    $('#searchContainer').removeClass("hidden");
    $('#pokemonSearchBox').focus();
  }else {
    $('#searchContainer').addClass("hidden");
  }
}

// Call Page Change Animation
function loadOverlay(){
  // alert('load overlay');
  $('#loadingAnimation').removeClass('hidden');
  console.log('loading new page...');
  $('#searchContainer').addClass('hidden');
  $('#loadingDiv').removeClass('hidden');
  // $('#loadingAnimation').removeClass('hidden');
}

function getQS(object){
  /*
  Query string values get returned back to the object
  Use object.key|object[key] //returns value
  */
  var pl     = /\+/g;  // Regex for replacing addition symbol with a space
  var search = /([^&=]+)=?([^&]*)/g;
  var decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); };
  var query  = window.location.search.substring(1);
  var match;

  while (match = search.exec(query)){
    object[decode(match[1])] = decode(match[2]);
  }
}
<|endoftext|>


<commit_before>// Variables :
var number = 0;
var color = "#000000";
var painting = false;
var started = false;
var size_min = 5;
var width_brush = 5;
var cursorX, cursorY;
var restoreCanvasArray = [];
var restoreCanvasIndex = 0;
var context;
var nbCanvas = 0;

function createNew() {
    number = number + 1;

    var sizeW = document.getElementById('postItGenerate').offsetWidth;
    var sizeH = document.getElementById('postItGenerate').offsetHeight;

    console.log(sizeH)

    //div principale
    let postIt = document.createElement('div');
    postIt.setAttribute('id', 'postIt' + number);
    //postIt.setAttribute('draggable', true);
    postIt.setAttribute('ondragstart', 'drag(event)');
    postIt.classList.add('postIt');
    postIt.style.width = sizeW + 'px';
    postIt.style.height = sizeH + 'px';
    console.log(postIt.style.height);

    //div des boutons
    let navigation = document.createElement('div');
    navigation.classList.add('boutons');
    navigation.style.width = 100 + '%';
    navigation.style.height = 30 + 'px';
    navigation.backgroundColor = '#F0E000';
    postIt.appendChild(navigation);
    console.log(navigation.style.height);

    //bouton Hide -> Cacher tous les autres
    let hide = document.createElement('img');
    hide.type = "button";
    hide.value = "Hide";
    hide.addEventListener("mousedown", mouseDown);
    hide.addEventListener("mouseup", mouseUp);
    hide.setAttribute('class', 'buttonHide');
    hide.setAttribute('onclick', 'hide()');
    hide.setAttribute('src', 'image/buttons/hideH.png');

    navigation.appendChild(hide);

    //bouton poubelle
    let trash = document.createElement('img');
    trash.type = "button";
    trash.addEventListener("mousedown", mouseDown);
    trash.addEventListener("mouseup", mouseUp);
    trash.setAttribute('class','buttonApp');
    trash.setAttribute('onclick', 'Trash("postIt' + number + '")');
    trash.setAttribute('src', 'image/buttons/trashH.png');
    navigation.appendChild(trash);

    trash.style.visibility = "hidden";

    //bouton full screen
    let fullscreen = document.createElement('img');
    fullscreen.addEventListener("mousedown", mouseDown);
    fullscreen.addEventListener("mouseup", mouseUp);
    fullscreen.type = "button";
    fullscreen.setAttribute('class', 'buttonApp');
    fullscreen.setAttribute('onclick', 'fullscreen(' + postIt.id + ')');
    fullscreen.setAttribute('src', 'image/buttons/fullScreenH.png');
    navigation.appendChild(fullscreen);

    fullscreen.style.visibility = "hidden";

    //bouton turn
    let turn = document.createElement('img');
    turn.addEventListener("mousedown", mouseDownS);
    turn.addEventListener("mouseup", mouseUpS);
    turn.type = "button";
    turn.setAttribute('class', 'buttonApp');
    //turn.setAttribute('onclick','Turn()');
    turn.addEventListener('click', startRotation);
    turn.setAttribute('src', 'image/buttons/turnH.png');
    navigation.appendChild(turn);

    turn.style.visibility = "hidden";

    //bouton save
    let save = document.createElement('img');
    save.addEventListener("mousedown", mouseDown);
    save.addEventListener("mouseup", mouseUp);
    save.type = "button";
    save.setAttribute('class', 'buttonApp');
    // save.setAttribute('onclick', 'Save()');
    save.setAttribute('src', 'image/buttons/saveH.png');
	save.addEventListener('click', download);
    navigation.appendChild(save);

    save.style.visibility = "hidden";

    //bouton full change
    let change = document.createElement('img');
    change.addEventListener("mousedown", mouseDown);
    change.addEventListener("mouseup", mouseUp);
    change.type = "button";
    change.setAttribute('class', 'buttonApp');
    change.setAttribute('onclick', 'replace("postIt"+number+"")');
    change.setAttribute('src', 'image/buttons/styloH.png');
    navigation.appendChild(change);

    change.style.visibility = "hidden";

    //bouton move
    let move = document.createElement('img');
    move.addEventListener("mousedown", mouseDownS);
    move.addEventListener("mouseup", mouseUpS);
    move.type = "button";
    move.setAttribute('class', 'buttonApp');
    move.setAttribute('onclick', 'Move("postIt' + number + '")');
    move.setAttribute('src', 'image/buttons/moveOKH.png');
    navigation.appendChild(move);

    move.style.visibility = "hidden";

    let text = document.createElement('textarea');
    text.setAttribute('type', 'text');
    postIt.appendChild(text);
    VKI_attach(text);
    text.setAttribute('style.resize', 'none');
    text.style.width = 70 + '%';
    text.style.height = 70 + '%';
    text.style.bottom = 0 + '%';
    console.log("top du text");
    console.log(text.offsetTop);
    console.log(text.style.height);
    console.log(postIt.style.height);

    // bouton bleu
    let color = document.createElement('div');
    color.classList.add('color');
    let blue = document.createElement('button');
    blue.setAttribute('id', 'blue');
    blue.setAttribute('onclick', 'changeColor("blue")');
    navigation.appendChild(blue);
    color.appendChild(blue);

    //bouton rouge
    let red = document.createElement('button');
    red.setAttribute('id', 'red');
    red.setAttribute('onclick', 'changeColor("red")');
    navigation.appendChild(red);
    color.appendChild(red);

    //bouton noir
    let black = document.createElement('button');
    black.setAttribute('id', 'black');
    black.setAttribute('onclick', 'changeColor("black")');
    navigation.appendChild(black);
    color.appendChild(black);

    //bouton jaune
    let yellow = document.createElement('button');
    yellow.setAttribute('id', 'yellow');
    yellow.setAttribute('onclick', 'changeColor("yellow")');
    navigation.appendChild(yellow);
    color.appendChild(yellow);

    //bouton purple
    let purple = document.createElement('button');
    purple.setAttribute('id', 'purple');
    purple.setAttribute('onclick', 'changeColor("purple")');
    navigation.appendChild(purple);
    color.appendChild(purple);

    //bouton rose
    let pink = document.createElement('button');
    pink.setAttribute('id', 'pink');
    pink.setAttribute('onclick', 'changeColor("pink")');
    navigation.appendChild(pink);
    color.appendChild(pink);

    //bouton marron
    let brown = document.createElement('button');
    brown.setAttribute('id', 'brown');
    brown.setAttribute('onclick', 'changeColor("brown")');
    navigation.appendChild(brown);
    color.appendChild(brown);

    // bouton green
    let green = document.createElement('button');
    green.setAttribute('id', 'green');
    green.setAttribute('onclick', 'changeColor("green")');
    navigation.appendChild(green);
    color.appendChild(green);

    // bouton blanc
    let white = document.createElement('button');
    white.setAttribute('id', 'white');
    white.setAttribute('onclick', 'changeColor("white")');
    navigation.appendChild(white);
    color.appendChild(white);

    color.style.visibility = 'hidden';
    postIt.appendChild(color);

    document.getElementById('page').appendChild(postIt);

}

function replace(id) {
    var parent = document.getElementById(id);
    var color = parent.getElementsByClassName('color')[0];
    var text = parent.getElementsByTagName("textarea")[0];
    var canvas = parent.getElementsByTagName("canvas")[0];

    if (text === undefined) {
        color.style.visibility = "hidden";
        canvas.remove();
        //  bouton.hide();
        text = document.createElement("textarea");
        text.setAttribute('type', 'text');
        parent.appendChild(text);
    } else {
        color.style.visibility = 'visible';
        text.remove();
        canvas = document.createElement("canvas");
        var div = document.createElement("div");
        canvas.appendChild(div);
        canvas.setAttribute("id", "postIt'+number+'");
        canvas.setAttribute("onclick", "createCanvas()");
        parent.appendChild(canvas);
    }
}

function Trash(id) {
    document.getElementById(id).remove();
}

function mouseDown(event){
  this.src='image/buttons/'+event.target.getAttribute('src').match(/[a-zA-Z]+(?=[HB]\.png)/g)+'B.png';
}

function mouseUp(event){
  this.src='image/buttons/'+event.target.getAttribute('src').match(/[a-zA-Z]+(?=[HB]\.png)/g)+'H.png';
}

function mouseDownS(event) {
  if(event.target.getAttribute('src').match(/OK/g) !== null)
    this.src='image/buttons/'+event.target.getAttribute('src').match(/[a-zA-Z]+(?=OK[HB]\.png)/g)+'OKB.png';
  else
    this.src='image/buttons/'+event.target.getAttribute('src').match(/[a-zA-Z]+(?=[HB]\.png)/g)+'B.png';
}
function mouseUpS(event) {
  if(event.target.getAttribute('src').match(/OK/g) !== null)
    this.src='image/buttons/'+event.target.getAttribute('src').match(/[a-zA-Z]+(?=OK[HB]\.png)/g)+'H.png';
  else
    this.src='image/buttons/'+event.target.getAttribute('src').match(/[a-zA-Z]+(?=[HB]\.png)/g)+'OKH.png';
}
<commit_msg>postIt are now draggable at beginning<commit_after>// Variables :
var number = 0;
var color = "#000000";
var painting = false;
var started = false;
var size_min = 5;
var width_brush = 5;
var cursorX, cursorY;
var restoreCanvasArray = [];
var restoreCanvasIndex = 0;
var context;
var nbCanvas = 0;

function createNew() {
    number = number + 1;

    var sizeW = document.getElementById('postItGenerate').offsetWidth;
    var sizeH = document.getElementById('postItGenerate').offsetHeight;

    console.log(sizeH)

    //div principale
    let postIt = document.createElement('div');
    postIt.setAttribute('id', 'postIt' + number);
    postIt.setAttribute('draggable', true);
    postIt.setAttribute('ondragstart', 'drag(event)');
    postIt.classList.add('postIt');
    postIt.style.width = sizeW + 'px';
    postIt.style.height = sizeH + 'px';
    console.log(postIt.style.height);

    //div des boutons
    let navigation = document.createElement('div');
    navigation.classList.add('boutons');
    navigation.style.width = 100 + '%';
    navigation.style.height = 30 + 'px';
    navigation.backgroundColor = '#F0E000';
    postIt.appendChild(navigation);
    console.log(navigation.style.height);

    //bouton Hide -> Cacher tous les autres
    let hide = document.createElement('img');
    hide.type = "button";
    hide.value = "Hide";
    hide.addEventListener("mousedown", mouseDown);
    hide.addEventListener("mouseup", mouseUp);
    hide.setAttribute('class', 'buttonHide');
    hide.setAttribute('onclick', 'hide()');
    hide.setAttribute('src', 'image/buttons/hideH.png');

    navigation.appendChild(hide);

    //bouton poubelle
    let trash = document.createElement('img');
    trash.type = "button";
    trash.addEventListener("mousedown", mouseDown);
    trash.addEventListener("mouseup", mouseUp);
    trash.setAttribute('class', 'buttonApp');
    trash.setAttribute('onclick', 'Trash("postIt' + number + '")');
    trash.setAttribute('src', 'image/buttons/trashH.png');
    navigation.appendChild(trash);

    trash.style.visibility = "hidden";

    //bouton full screen
    let fullscreen = document.createElement('img');
    fullscreen.addEventListener("mousedown", mouseDown);
    fullscreen.addEventListener("mouseup", mouseUp);
    fullscreen.type = "button";
    fullscreen.setAttribute('class', 'buttonApp');
    fullscreen.setAttribute('onclick', 'fullscreen(' + postIt.id + ')');
    fullscreen.setAttribute('src', 'image/buttons/fullScreenH.png');
    navigation.appendChild(fullscreen);

    fullscreen.style.visibility = "hidden";

    //bouton turn
    let turn = document.createElement('img');
    turn.addEventListener("mousedown", mouseDownS);
    turn.addEventListener("mouseup", mouseUpS);
    turn.type = "button";
    turn.setAttribute('class', 'buttonApp');
    //turn.setAttribute('onclick','Turn()');
    turn.addEventListener('click', startRotation);
    turn.setAttribute('src', 'image/buttons/turnH.png');
    navigation.appendChild(turn);

    turn.style.visibility = "hidden";

    //bouton save
    let save = document.createElement('img');
    save.addEventListener("mousedown", mouseDown);
    save.addEventListener("mouseup", mouseUp);
    save.type = "button";
    save.setAttribute('class', 'buttonApp');
    // save.setAttribute('onclick', 'Save()');
    save.setAttribute('src', 'image/buttons/saveH.png');
    save.addEventListener('click', download);
    navigation.appendChild(save);

    save.style.visibility = "hidden";

    //bouton full change
    let change = document.createElement('img');
    change.addEventListener("mousedown", mouseDown);
    change.addEventListener("mouseup", mouseUp);
    change.type = "button";
    change.setAttribute('class', 'buttonApp');
    change.setAttribute('onclick', 'replace("postIt"+number+"")');
    change.setAttribute('src', 'image/buttons/styloH.png');
    navigation.appendChild(change);

    change.style.visibility = "hidden";

    //bouton move
    let move = document.createElement('img');
    move.addEventListener("mousedown", mouseDownS);
    move.addEventListener("mouseup", mouseUpS);
    move.type = "button";
    move.setAttribute('class', 'buttonApp');
    move.setAttribute('onclick', 'Move("postIt' + number + '")');
    move.setAttribute('src', 'image/buttons/moveOKH.png');
    navigation.appendChild(move);

    move.style.visibility = "hidden";

    let text = document.createElement('textarea');
    text.setAttribute('type', 'text');
    postIt.appendChild(text);
    VKI_attach(text);
    text.setAttribute('style.resize', 'none');
    text.style.width = 70 + '%';
    text.style.height = 70 + '%';
    text.style.bottom = 0 + '%';
    console.log("top du text");
    console.log(text.offsetTop);
    console.log(text.style.height);
    console.log(postIt.style.height);

    // bouton bleu
    let color = document.createElement('div');
    color.classList.add('color');
    let blue = document.createElement('button');
    blue.setAttribute('id', 'blue');
    blue.setAttribute('onclick', 'changeColor("blue")');
    navigation.appendChild(blue);
    color.appendChild(blue);

    //bouton rouge
    let red = document.createElement('button');
    red.setAttribute('id', 'red');
    red.setAttribute('onclick', 'changeColor("red")');
    navigation.appendChild(red);
    color.appendChild(red);

    //bouton noir
    let black = document.createElement('button');
    black.setAttribute('id', 'black');
    black.setAttribute('onclick', 'changeColor("black")');
    navigation.appendChild(black);
    color.appendChild(black);

    //bouton jaune
    let yellow = document.createElement('button');
    yellow.setAttribute('id', 'yellow');
    yellow.setAttribute('onclick', 'changeColor("yellow")');
    navigation.appendChild(yellow);
    color.appendChild(yellow);

    //bouton purple
    let purple = document.createElement('button');
    purple.setAttribute('id', 'purple');
    purple.setAttribute('onclick', 'changeColor("purple")');
    navigation.appendChild(purple);
    color.appendChild(purple);

    //bouton rose
    let pink = document.createElement('button');
    pink.setAttribute('id', 'pink');
    pink.setAttribute('onclick', 'changeColor("pink")');
    navigation.appendChild(pink);
    color.appendChild(pink);

    //bouton marron
    let brown = document.createElement('button');
    brown.setAttribute('id', 'brown');
    brown.setAttribute('onclick', 'changeColor("brown")');
    navigation.appendChild(brown);
    color.appendChild(brown);

    // bouton green
    let green = document.createElement('button');
    green.setAttribute('id', 'green');
    green.setAttribute('onclick', 'changeColor("green")');
    navigation.appendChild(green);
    color.appendChild(green);

    // bouton blanc
    let white = document.createElement('button');
    white.setAttribute('id', 'white');
    white.setAttribute('onclick', 'changeColor("white")');
    navigation.appendChild(white);
    color.appendChild(white);

    color.style.visibility = 'hidden';
    postIt.appendChild(color);

    document.getElementById('page').appendChild(postIt);

}

function replace(id) {
    var parent = document.getElementById(id);
    var color = parent.getElementsByClassName('color')[0];
    var text = parent.getElementsByTagName("textarea")[0];
    var canvas = parent.getElementsByTagName("canvas")[0];

    if (text === undefined) {
        color.style.visibility = "hidden";
        canvas.remove();
        //  bouton.hide();
        text = document.createElement("textarea");
        text.setAttribute('type', 'text');
        parent.appendChild(text);
    } else {
        color.style.visibility = 'visible';
        text.remove();
        canvas = document.createElement("canvas");
        var div = document.createElement("div");
        canvas.appendChild(div);
        canvas.setAttribute("id", "postIt'+number+'");
        canvas.setAttribute("onclick", "createCanvas()");
        parent.appendChild(canvas);
    }
}

function Trash(id) {
    document.getElementById(id).remove();
}

function mouseDown(event) {
    this.src = 'image/buttons/' + event.target.getAttribute('src').match(/[a-zA-Z]+(?=[HB]\.png)/g) + 'B.png';
}

function mouseUp(event) {
    this.src = 'image/buttons/' + event.target.getAttribute('src').match(/[a-zA-Z]+(?=[HB]\.png)/g) + 'H.png';
}

function mouseDownS(event) {
    if (event.target.getAttribute('src').match(/OK/g) !== null)
        this.src = 'image/buttons/' + event.target.getAttribute('src').match(/[a-zA-Z]+(?=OK[HB]\.png)/g) + 'OKB.png';
    else
        this.src = 'image/buttons/' + event.target.getAttribute('src').match(/[a-zA-Z]+(?=[HB]\.png)/g) + 'B.png';
}

function mouseUpS(event) {
    if (event.target.getAttribute('src').match(/OK/g) !== null)
        this.src = 'image/buttons/' + event.target.getAttribute('src').match(/[a-zA-Z]+(?=OK[HB]\.png)/g) + 'H.png';
    else
        this.src = 'image/buttons/' + event.target.getAttribute('src').match(/[a-zA-Z]+(?=[HB]\.png)/g) + 'OKH.png';
}<|endoftext|>


<commit_before>define(['jquery', 'inheritance', 'bind', 'domReady!'], function($, inheritance) {

    var Throb = Class.extend({
        init: function (throbber, brand) {
            var that = this;

            this.throbber = $(throbber);
            this.brand = $(brand);

            this.active = 0;

            $(document).ajaxSend(function () {
                if (that.active == 0) {
                    that.start();
                }

                that.active++;
            });

            $(document).ajaxComplete(function () {
                that.active--;

                setTimeout(function () {
                    if (that.active == 0) {
                        that.stop();
                    }
                }, 500);
            });
        },
        stop: function () {
            this.throbber.hide();
            this.brand.show();
        },
        start: function () {
            this.throbber.show();
            this.brand.hide();
        }
    });

    var instance = null;

    /**
     * This one listens to click events and loads the href in the content div
     * instead of reloading the full page.
     */
    var Ajaxify = Class.extend({
        init: function () {
            if (instance !== null) {
                throw Error('Only one instance of Ajaxify allowed!');
            }

            var that = this;

            this.throb = new Throb('.throbber', '.brand');

            this.contents = ['#main', '#top'];

            if ($(this.contents[0]).length == 0) {
                return;
            }

            this.selector = '#top, #queue, #main';

            this.initialURL = document.location.href;

            this.activeRequest = null;

            // setTimeout hack to ignore initial popstate that at least chrome fires,
            // but not firefox
            setTimeout(function () {
                $(window).bind('popstate', function (event) {

                    href = document.location.pathname + document.location.search;

                    if (that.activeRequest !== null) {
                        that.activeRequest.abort();
                    }

                    if (href !== null) {
                        that.loadPage(href);
                    }
                });
            });

            this.internalInit();
        },
        internalInit: function () {
            this.load(this.selector);
        },
        load: function (element) {
            var that = this;

            $(element).find('a')
                .unbind('click.ajaxify')
                .bind('click.ajaxify', function (event) {
                var href = $(this).attr('href');

                if (!event.ctrlKey && that.isRelative(href)) {
                    that.setPage(href);
                } else {
                    // open external and ctrl-click in new window/tab
                    window.open(href, "_blank");
                }

                // continue propagation if the link has said attribute
                return $(this).is("[data-ajaxify=continue]");
            });

            $(element).trigger('ajaxifyInit');
        },
        loadPage: function (href) {
            var that = this;
            var contents = that.contents.join(',');

            that.disableElements(contents);

            this.activeRequest = $.ajax(href, {
                success: function (data, textStatus, xhr) {
                    that.setPageInDom(data);
                    that.enableElements(contents);
                    that.activeRequest = null;
                },
                error: function (xhr) {
                    if (xhr.statusText != 'abort') {
                        that.setPageInDom(xhr.responseText);
                    }
                    that.enableElements(contents);
                    that.activeRequest = null;
                },
            });
        },
        setPageInDom: function (data) {
            var html = $($.parseHTML(data));

            document.title = $.trim(html.find("#title").text());

            for (var index in this.contents) {
                var content = this.contents[index];
                $(content).children().remove();
                $(content).append(html.find(content).children());
                $(window).scrollTop(0);
            }

            this.internalInit();
        },
        disableElements: function (element) {
            $(element).addClass('ajaxify-disabled');

            $(element).find("input, textarea, select").attr("disabled", "disabled");
            $(element).find('.btn, a, input').addClass('disabled');

            $(element).find("*").bind(
                'click.ajaxify_disabled ' +
                'dblclick.ajaxify_disabled ' +
                'dragstart.ajaxify_disabled',
                function(event) {
                    return false;
                }
            ).unbind('click.ajaxify');
        },
        enableElements: function (element) {
            $(element).removeClass('ajaxify-disabled');

            $(element).find("input, textarea, select").removeAttr("disabled");

            $(element).find('.btn, a, input').removeClass('disabled');

            $(element).find("*").unbind(
                'click.ajaxify_disabled ' +
                'dblclick.ajaxify_disabled ' +
                'dragstart.ajaxify_disabled'
            );
        },
        getPage: function (href) {
            if (!this.isRelative(href)) {
                href = this.getPathComponent(href);
            }

            return href;
        },
        setPage: function (href) {
            href = this.getPage(href);

            history.pushState({}, "", href);

            this.loadPage(href);
        },
        getPathComponent: function (href) {
            return href.match(/^http(s)?:\/\/[^\/]+(.*)/)[2];
        },
        isRelative: function (href) {
            return !/^http(s)?:\/\//.test(href);
        },
    });

    return (function() {
        if (instance === null) {
            instance = new Ajaxify();
        }

        return instance;
    })();
});
<commit_msg>use replaceWith() to replace whole element instead of just children<commit_after>define(['jquery', 'inheritance', 'bind', 'domReady!'], function($, inheritance) {

    var Throb = Class.extend({
        init: function (throbber, brand) {
            var that = this;

            this.throbber = $(throbber);
            this.brand = $(brand);

            this.active = 0;

            $(document).ajaxSend(function () {
                if (that.active == 0) {
                    that.start();
                }

                that.active++;
            });

            $(document).ajaxComplete(function () {
                that.active--;

                setTimeout(function () {
                    if (that.active == 0) {
                        that.stop();
                    }
                }, 500);
            });
        },
        stop: function () {
            this.throbber.hide();
            this.brand.show();
        },
        start: function () {
            this.throbber.show();
            this.brand.hide();
        }
    });

    var instance = null;

    /**
     * This one listens to click events and loads the href in the content div
     * instead of reloading the full page.
     */
    var Ajaxify = Class.extend({
        init: function () {
            if (instance !== null) {
                throw Error('Only one instance of Ajaxify allowed!');
            }

            var that = this;

            this.throb = new Throb('.throbber', '.brand');

            this.contents = ['#main', '#top'];

            if ($(this.contents[0]).length == 0) {
                return;
            }

            this.selector = '#top, #queue, #main';

            this.initialURL = document.location.href;

            this.activeRequest = null;

            // setTimeout hack to ignore initial popstate that at least chrome fires,
            // but not firefox
            setTimeout(function () {
                $(window).bind('popstate', function (event) {

                    href = document.location.pathname + document.location.search;

                    if (that.activeRequest !== null) {
                        that.activeRequest.abort();
                    }

                    if (href !== null) {
                        that.loadPage(href);
                    }
                });
            });

            this.internalInit();
        },
        internalInit: function () {
            this.load(this.selector);
        },
        load: function (element) {
            var that = this;

            $(element).find('a')
                .unbind('click.ajaxify')
                .bind('click.ajaxify', function (event) {
                var href = $(this).attr('href');

                if (!event.ctrlKey && that.isRelative(href)) {
                    that.setPage(href);
                } else {
                    // open external and ctrl-click in new window/tab
                    window.open(href, "_blank");
                }

                // continue propagation if the link has said attribute
                return $(this).is("[data-ajaxify=continue]");
            });

            $(element).trigger('ajaxifyInit');
        },
        loadPage: function (href) {
            var that = this;
            var contents = that.contents.join(',');

            that.disableElements(contents);

            this.activeRequest = $.ajax(href, {
                success: function (data, textStatus, xhr) {
                    that.setPageInDom(data);
                    that.enableElements(contents);
                    that.activeRequest = null;
                },
                error: function (xhr) {
                    if (xhr.statusText != 'abort') {
                        that.setPageInDom(xhr.responseText);
                    }
                    that.enableElements(contents);
                    that.activeRequest = null;
                },
            });
        },
        setPageInDom: function (data) {
            var html = $($.parseHTML(data));

            document.title = $.trim(html.find("#title").text());

            for (var index in this.contents) {
                var content = this.contents[index];
                $(content).replaceWith(html.find(content));
                $(window).scrollTop(0);
            }

            this.internalInit();
        },
        disableElements: function (element) {
            $(element).addClass('ajaxify-disabled');

            $(element).find("input, textarea, select").attr("disabled", "disabled");
            $(element).find('.btn, a, input').addClass('disabled');

            $(element).find("*").bind(
                'click.ajaxify_disabled ' +
                'dblclick.ajaxify_disabled ' +
                'dragstart.ajaxify_disabled',
                function(event) {
                    return false;
                }
            ).unbind('click.ajaxify');
        },
        enableElements: function (element) {
            $(element).removeClass('ajaxify-disabled');

            $(element).find("input, textarea, select").removeAttr("disabled");

            $(element).find('.btn, a, input').removeClass('disabled');

            $(element).find("*").unbind(
                'click.ajaxify_disabled ' +
                'dblclick.ajaxify_disabled ' +
                'dragstart.ajaxify_disabled'
            );
        },
        getPage: function (href) {
            if (!this.isRelative(href)) {
                href = this.getPathComponent(href);
            }

            return href;
        },
        setPage: function (href) {
            href = this.getPage(href);

            history.pushState({}, "", href);

            this.loadPage(href);
        },
        getPathComponent: function (href) {
            return href.match(/^http(s)?:\/\/[^\/]+(.*)/)[2];
        },
        isRelative: function (href) {
            return !/^http(s)?:\/\//.test(href);
        },
    });

    return (function() {
        if (instance === null) {
            instance = new Ajaxify();
        }

        return instance;
    })();
});
<|endoftext|>


<commit_before>/* ========================================================================
* Phonon: ripple.js v0.0.2
* http://phonon.quarkdev.com
* ========================================================================
* Licensed under MIT (http://phonon.quarkdev.com)
* Inspiration: http://www.cssscript.com/demo/android-l-ripple-click-effect-with-javascript-and-css3/
* ======================================================================== */
(function (window, document) {

	'use strict';

	var ripple = function (evt) {
		var target = evt.target;

		if (target.getAttribute('no-ripple') !== null) return false;

		if (target.tagName.toLowerCase() !== 'button' && !target.classList.contains('btn')) return false;

		if (target.classList.contains('btn-action') || target.classList.contains('flg-action')) return false;

		if (target.disabled === true) return false;

		var rect = target.getBoundingClientRect();
		var ripple = target.querySelector('.ripple');
		if (!ripple) {
			ripple = document.createElement('span');
			ripple.className = 'ripple';
			ripple.style.height = ripple.style.width = Math.max(rect.width, rect.height) + 'px';
			target.appendChild(ripple);
		}
		ripple.classList.remove('show');

		var top = (evt.changedTouches ? evt.changedTouches[0].pageY : evt.pageY) - rect.top - ripple.offsetHeight / 2 - document.body.scrollTop;
		var left = (evt.changedTouches ? evt.changedTouches[0].pageX : evt.pageX) - rect.left - ripple.offsetWidth / 2 - document.body.scrollLeft;
		ripple.style.top = top + 'px';
		ripple.style.left = left + 'px';
		ripple.classList.add('show');
		return false;
	}

	document.addEventListener('touchend', ripple, false);

}(window, document));<commit_msg>ripple animation removed on floating actions<commit_after>/* ========================================================================
* Phonon: ripple.js v0.0.2
* http://phonon.quarkdev.com
* ========================================================================
* Licensed under MIT (http://phonon.quarkdev.com)
* Inspiration: http://www.cssscript.com/demo/android-l-ripple-click-effect-with-javascript-and-css3/
* ======================================================================== */
(function (window, document) {

	'use strict';

	var ripple = function (evt) {
		var target = evt.target;

		if (target.getAttribute('no-ripple') !== null) return false;

		if (target.tagName.toLowerCase() !== 'button' && !target.classList.contains('btn')) return false;

		if (target.classList.contains('btn-action') || target.classList.contains('floating-action')) return false;

		if (target.disabled === true) return false;

		var rect = target.getBoundingClientRect();
		var ripple = target.querySelector('.ripple');
		if (!ripple) {
			ripple = document.createElement('span');
			ripple.className = 'ripple';
			ripple.style.height = ripple.style.width = Math.max(rect.width, rect.height) + 'px';
			target.appendChild(ripple);
		}
		ripple.classList.remove('show');

		var top = (evt.changedTouches ? evt.changedTouches[0].pageY : evt.pageY) - rect.top - ripple.offsetHeight / 2 - document.body.scrollTop;
		var left = (evt.changedTouches ? evt.changedTouches[0].pageX : evt.pageX) - rect.left - ripple.offsetWidth / 2 - document.body.scrollLeft;
		ripple.style.top = top + 'px';
		ripple.style.left = left + 'px';
		ripple.classList.add('show');
		return false;
	}

	document.addEventListener('touchend', ripple, false);

}(window, document));<|endoftext|>


<commit_before>//Running BB Router and immediately extending itself
window.TodoApp = new (Backbone.Router.extend({
	routes: { '' : 'index'}, //when base route ('') run the index function/controller
	initialize: function() { //init the following
		this.todoItems = new TodoItems();
		this.todosView = new TodosView({collection: this.todoItems});
		this.todosView.render();// start everything off with a first Render

		//using JQ outside of app render view. Btn is in index so we have to handle somehow.
		$('.btn-clear').click(function(e) {
			window.TodoApp.todosView.filterCompleted()
		});
	},

	index: function() {
		//Add fixture data
		var fixtures = [
		{ val: "Apples", completed: true},
		{ val: "Bananna", completed: false},
		{ val: "Pear", completed: true},
		{ val: "Peach", completed: false}
		];

		$('#app').html(this.todosView.el);
		this.todoItems.reset(fixtures); //Reset will just fill out with updated model
	},

	start: function() { // To load all BB first
		Backbone.history.start(); //then track html history. Html push states.
	}
}));<commit_msg>Add item and clear input now functional<commit_after>//Running BB Router and immediately extending itself
window.TodoApp = new (Backbone.Router.extend({
	routes: { '' : 'index'}, //when base route ('') run the index function/controller
	initialize: function() { //init the following
		this.todoItems = new TodoItems();
		this.todosView = new TodosView({collection: this.todoItems});
		this.todosView.render();// start everything off with a first Render

		//using JQ outside of app render view. Btn is in index so we have to handle somehow.
		$('.btn-clear').click(function(e) {
			window.TodoApp.todosView.filterCompleted()
		});

		$('.btn-success').click(function() {
			window.TodoApp.todoItems.add({val:$("#newTodo").val(), completed: false}); //Add new value in todo on click
			$("#newTodo").val(''); //clear it out
		});
	},

	index: function() {
		//Add fixture data
		var fixtures = [
		{ val: "Apples", completed: true},
		{ val: "Bananna", completed: false},
		{ val: "Pear", completed: true},
		{ val: "Peach", completed: false}
		];

		$('#app').html(this.todosView.el);
		this.todoItems.reset(fixtures); //Reset will just fill out with updated model
	},

	start: function() { // To load all BB first
		Backbone.history.start(); //then track html history. Html push states.
	}
}));
<|endoftext|>


<commit_before>const chai = require('chai');
const expect = chai.expect;
const _ = require('lodash');
const {enrichment} = require('../../../../src/server/enrichment-map/enrichment');

// object keys are unordered
const objectEquality = (obj1, obj2) => {
  _.forEach(obj1, property => {
    if (!obj2.has(property)) { return false; }
    if (obj1.get(property) != obj2.get(property)) { return false; }
  });
  return true;
};

describe('test enrichment', function() {
  this.timeout(500000);
  it('it should return an object', function() {
    return (enrichment('AFF4')).then(function(res) {
      const result = {
        'GO:0006354':
         { signf: '!',
           pvalue: '8.70e-03',
           T: '124',
           Q: '1',
           c: '1',
           'Q&T/Q': '1.000',
           'Q&T/T': '0.008',
           't type': 'BP',
           't group': '3',
           't name': '   DNA-templated transcription, elongation',
           't depth': '1',
           'Q&T list': 'AFF4' },
        'GO:0006368':
         { signf: '!',
           pvalue: '8.70e-03',
           T: '100',
           Q: '1',
           'Q&T': '1',
           'Q&T/Q': '1.000',
           'Q&T/T': '0.010',
           't type': 'BP',
           't group': '3',
           't name': '   transcription elongation from RNA polymerase II promoter',
           't depth': '1',
           'Q&T list': 'AFF4' },
        'REAC:75955':
         { signf: '!',
           pvalue: '7.75e-03',
           T: '61',
           Q: '1',
           'Q&T': '1',
           'Q&T/Q': '1.000',
           'Q&T/T': '0.016',
           't type': 'rea',
           't group': '5',
           't name': '   RNA Polymerase II Transcription Elongation',
           't depth': '1',
           'Q&T list': 'AFF4' },
        'REAC:112382':
         { signf: '!',
           pvalue: '7.75e-03',
           T: '61',
           Q: '1',
           'Q&T': '1',
           'Q&T/Q': '1.000',
           'Q&T/T': '0.016',
           't type': 'rea',
           't group': '5',
           't name': '    Formation of RNA Pol II elongation complex ',
           't depth': '2',
           'Q&T list': 'AFF4' },
        'REAC:674695':
         { signf: '!',
           pvalue: '7.75e-03',
           T: '83',
           Q: '1',
           'Q&T': '1',
           'Q&T/Q': '1.000',
           'Q&T/T': '0.012',
           't type': 'rea',
           't group': '2',
           't name': '   RNA Polymerase II Pre-transcription Events',
           't depth': '1',
           'Q&T list': 'AFF4' } };
        expect(objectEquality(result, res)).to.equal(true);
    });
  });
});<commit_msg>use _.isEqual in enrichment-test.js relates to #481 point 6 pr #494<commit_after>const chai = require('chai');
const expect = chai.expect;
const _ = require('lodash');
const {enrichment} = require('../../../../src/server/enrichment-map/enrichment');

// object keys are unordered
// t group changes
const objectEquality = (obj1, obj2) => {
  return _.isEqualWith(obj1, obj2, (val1, val2, key) => {
      if (key === "signf" || key === "pvalue" || key === "T" || key === "Q" || key === "Q&T" || key === "Q&T/Q" || key === "Q&T/T" || key === "t type" || key === "t name" || key === "t depth" || key === "Q&T list") {
        return val1.key === val2.key;
      }
      return true;
  });
};

describe('test enrichment', function() {
  this.timeout(500000);
  it('it should return an object', function() {
    return (enrichment('AFF4')).then(function(res) {
      const result = {
        'GO:0006354':
         { signf: '!',
           pvalue: '8.70e-03',
           T: '124',
           Q: '1',
           'Q&T': '1',
           'Q&T/Q': '1.000',
           'Q&T/T': '0.008',
           't type': 'BP',
           't group': '3',
           't name': '   DNA-templated transcription, elongation',
           't depth': '1',
           'Q&T list': 'AFF4' },
        'GO:0006368':
         { signf: '!',
           pvalue: '8.70e-03',
           T: '100',
           Q: '1',
           'Q&T': '1',
           'Q&T/Q': '1.000',
           'Q&T/T': '0.010',
           't type': 'BP',
           't group': '3',
           't name': '   transcription elongation from RNA polymerase II promoter',
           't depth': '1',
           'Q&T list': 'AFF4' },
        'REAC:75955':
         { signf: '!',
           pvalue: '7.75e-03',
           T: '61',
           Q: '1',
           'Q&T': '1',
           'Q&T/Q': '1.000',
           'Q&T/T': '0.016',
           't type': 'rea',
           't group': '5',
           't name': '   RNA Polymerase II Transcription Elongation',
           't depth': '1',
           'Q&T list': 'AFF4' },
        'REAC:112382':
         { signf: '!',
           pvalue: '7.75e-03',
           T: '61',
           Q: '1',
           'Q&T': '1',
           'Q&T/Q': '1.000',
           'Q&T/T': '0.016',
           't type': 'rea',
           't group': '5',
           't name': '    Formation of RNA Pol II elongation complex ',
           't depth': '2',
           'Q&T list': 'AFF4' },
        'REAC:674695':
         { signf: '!',
           pvalue: '7.75e-03',
           T: '83',
           Q: '1',
           'Q&T': '1',
           'Q&T/Q': '1.000',
           'Q&T/T': '0.012',
           't type': 'rea',
           't group': '2',
           't name': '   RNA Polymerase II Pre-transcription Events',
           't depth': '1',
           'Q&T list': 'AFF4' } };
        expect(objectEquality(result, res)).to.equal(true);
    });
  });
});<|endoftext|>