<commit_before>/* globals dom file KellyColorPicker palettes */

// Initialize
const canvas = document.querySelector('#canvas');
canvas.setAttribute('width', document.body.clientWidth + 'px');
canvas.setAttribute('height', document.body.clientHeight + 'px');
const colorpaletteselect = document.querySelector('.colorpalette');
palettes.forEach((p,i) => {
  let opt = document.createElement('option');
  opt.setAttribute('value', i);
  opt.innerText = p.name;
  colorpaletteselect.append(opt);
});
colorpaletteselect.addEventListener('change', setPalette);
// Color picker
const colorpicker = new KellyColorPicker(
  {
    place : document.querySelector('.popup-colour'),
    input : '.js-colour',
    size : 200,
    color : '#ffffff',
    method : 'square',
    input_color : false, // or inputColor (sice v1.15)
    input_format : 'mixed', // or inputFormat (since v1.15)
    alpha : 1,
    alpha_slider : false, // or alphaSlider (since v1.15)
    colorSaver : false,
    resizeWith : true, // auto redraw canvas on resize window
    popupClass: 'popup-colour',
    userEvents : {
      // change : function(self) {
      //   // set background color for 'input' to current color of color picker
      //   if(self.getCurColorHsv().v < 0.5){
      //   self.getInput().style.color = "#FFF";
      // } else {
      //   self.getInput().style.color = "#000";
      // }
      // self.getInput().style.background = self.getCurColorHex();
    // }
  }
  });
setPalette({target: colorpaletteselect});

const mouse = {};

function setPalette(evt){
  let palette = palettes[parseInt(evt.target.value)];
  let wells = document.querySelectorAll('.js-miniwell');
  for (let i = 0; i < 5; i++){
    colorButton(wells[i], '#' + palette.colors[i]);
  }
}

class Pen{
  constructor(){
    this.drawing = false;
  }
  start(evt){
    console.log('start evt button: ', evt.button);
    if (evt.button === 0){
      // button 0 is the main button, we're not interested in others
      // can't test for truthiness, because touch events have button=undefined
      return;
    }
    let {x,y} = getXY(evt);
    startPath(x,y);
    this.drawing = true;
  }

  move(evt){
    console.log('move %s', this.drawing);
    if (!this.drawing) return;
    let {x,y} = getXY(evt);
    if (inBounds(x,y)){
        appendToPath(x,y);
    }
  }

  stop(evt){
    console.log('stop %s', this.drawing);
    if (!this.drawing) return;
    let {x,y} = getXY(evt);
    // FIXME: draw a dot if we haven't moved
    if (currentPath){
      dom.simplifyPath(currentPath);
      currentPath = null;
    }
    this.drawing = false;
  }

  cancel(){
    // remove the path in progress
  }

}

class Pan{
  constructor(){
    this.dragging = false;
  }

  start(evt){
    if (evt.button !== 0){
      // button 0 is the main button, we're not interested in others
      return;
    }
    let {x,y} = getXY(evt);
    this.matrix = currentFrame().get
    startPath(x,y);
    this.drawing = true;
  }

  move(evt){

  }

  stop(evt){

  }

  cancel(){

  }

}

class Rotate{
  constructor(){

  }

  start(evt){

  }

  move(evt){

  }

  stop(evt){

  }

  cancel(evt){

  }
}

class ZoomIn{
  constructor(){

  }

  start(evt){

  }

  move(evt){

  }

  stop(evt){

  }

  cancel(evt){

  }
}

class ZoomOut{
  constructor(){

  }

  start(evt){

  }

  move(evt){

  }

  stop(evt){

  }

  cancel(evt){

  }
}

let tools = {
  pen: new Pen(canvas),
  pan: new Pan(canvas),
  rotate: new Rotate(canvas),
  zoomin: new ZoomIn(canvas),
  zoomout: new ZoomOut(canvas)
}

let currentTool = tools.pen;
let currentStrokeWidth = 1;
let currentDoOnionskin = true;

function selectTool(button){
  let name = button.getAttribute('title').toLowerCase();
  document.querySelector('.js-tool.active').classList.remove('active');
  button.classList.add('active');
  switch(name){
    case 'pen': currentTool = tools.pen; break;
    case 'pan': currentTool = tools.pan; break;
    case 'rotate': currentTool = tools.rotate; break;
    case 'zoom in':  currentTool = tools.zoomin; break;
    case 'zoom out': currentTool = tools.zoomout; break;
    default: console.error('unrecognized tool name: %s', name);
  }
}

let currentColor = '#000000';
let currentFrameDelay = 30; // milliseconds

function setFrameRate(input){
  currentFrameDelay = Math.floor(1000 / Number(input.value));
}

function colorPopup(input){
  let popup = document.querySelector('.popup-colour');
  let colorwell = document.querySelector('.colourwell');
  if (popup.style.display === 'none'){
    colorpicker.setColor(input.value);
    popup.style.display = 'block';
  }else{
    let color = colorpicker.getCurColorHex();
    colorButton(colorwell, color);
    colorButton(input, color);
    currentColor = color;
    popup.style.display = 'none';
  }
}

function colorButton(button, color){
  button.value = color;
  button.style.backgroundColor = color;
  if (hexToValue(color) < 0.5){
    button.style.color = '#FFF';
  }else{
    button.style.color = '#000';
  }
}

function hexToValue(hex){
  return colorpicker.rgbToHsv(colorpicker.hexToRgb(hex)).v;
}

function selectColor(input){
  let popup = document.querySelector('.popup-colour');
  let colorwell = document.querySelector('.colourwell');
  if (popup.style.display === 'block'){
    let color = colorpicker.getCurColorHex();
    colorButton(colorwell, color);
    colorButton(input, color);
    currentColor = color;
    popup.style.display = 'none';
  }else{
    colorButton(colorwell, input.value);
    currentColor = input.value;
  }
}

var drawing = false;
var WIDTH = document.body.clientWidth;
var HEIGHT = document.body.clientHeight;

// Prevent control clicks from passing through to svg
function swallowClicks(evt){
  evt.stopPropagation();
}
document.querySelector('.buttonbar.animation').addEventListener('mousedown', swallowClicks);
document.querySelector('.buttonbar.tools').addEventListener('mousedown', swallowClicks);
document.querySelector('.buttonbar.animation').addEventListener('touchstart', swallowClicks);
document.querySelector('.buttonbar.tools').addEventListener('touchstart', swallowClicks);

function inBounds(x,y){
  return !(x < 0 || x > WIDTH || y < 0 || y > HEIGHT);
}

function getXY(evt){
   if (evt.cancelable) {
      evt.preventDefault();
    }

    const rect = this.canvas.getBoundingClientRect();
    const position = evt.changedTouches && evt.changedTouches[0] || evt;
    let x = position.offsetX;
    let y = position.offsetY;

    if (typeof x === 'undefined') {
      x = position.clientX - rect.left;
    }
    if (typeof y === 'undefined') {
      y = position.clientY - rect.top;
    }
    return {x,y};
}

const toolStart = evt => currentTool.start(evt);
const toolMove = evt => currentTool.move(evt);
const toolStop = evt => currentTool.stop(evt);
const toolCancel = evt => currentTool.cancel();
const escCancel = evt => {
  if (evt.code && evt.code === 'Escape'){
    currentTool.cancel();
  }
}

document.body.addEventListener('mousedown', toolStart);
document.body.addEventListener('touchstart', toolStart);
document.body.addEventListener('mousemove', toolMove);
document.body.addEventListener('touchmove', toolMove);
document.body.addEventListener('touchend', toolStop);
document.body.addEventListener('mouseup', toolStop);
document.body.addEventListener('touchcancel', toolCancel);
document.body.addEventListener('keydown', escCancel);

function currentFrame(){
  return document.querySelector('.frame.selected');
}

function playingFrame(){
  return document.querySelector('.frame.play-frame');
}

var currentPath = null;

function startPath(x,y){

  currentPath = currentFrame().appendChild(dom.svg('path', {
      d: 'M ' + x + ',' + y,
      stroke: currentColor,
      'stroke-width': currentStrokeWidth
  }));
  file.onChange();
}

function appendToPath(x,y){
  var path = document.querySelector('.selected path:last-child');
  var d = path.getAttribute('d');
  path.setAttribute('d', `${d} L${x} ${y}`);
}

/***************************************
*
*  MANAGE FRAMES
*
***************************************/

function isOnionskinOn(){
  return currentDoOnionskin;
}

function currentOnionskinFrame(){
  return document.querySelector('.frame.onionskin');
}

function updateOnionskin(){
  if (!isOnionskinOn()) return;
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  dom.addClass(currentFrame().previousElementSibling, 'onionskin');
}

function addFrame(){
  dom.insertAfter(dom.svg('g', {'class': 'frame selected'}), currentFrame());
  currentFrame().classList.remove('selected');
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function cloneFrame(){
  dom.insertAfter(currentFrame().cloneNode(true), currentFrame());
  currentFrame().classList.remove('selected');
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function deleteFrame(){
  var frameToDelete = currentFrame();
  if (frameToDelete.nextElementSibling){
      incrementFrame();
  }else if (frameToDelete.previousElementSibling){
      decrementFrame();
  }
  if (frameToDelete.parentNode.children.length > 1){
    dom.remove(frameToDelete);
  }else{
    dom.clear(frameToDelete); // don't delete the last frame, just its children
  }
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function clear(){
  dom.clear(currentFrame());
}

function toggleOnionskin(){
  if (isOnionskinOn()){
      dom.addClass(currentFrame().previousElementSibling, 'onionskin');
  }else{
      dom.removeClass(currentOnionskinFrame(), 'onionskin');
  }
}

function incrementFrame(){
  var curr = currentFrame();
  if (curr.nextElementSibling){
      curr.classList.remove('selected');
      curr.nextElementSibling.classList.add('selected');
  }
  updateOnionskin();
  updateFrameCount();
}

function decrementFrame(){
  var curr = currentFrame();
  if (curr.previousElementSibling){
      curr.classList.remove('selected');
      curr.previousElementSibling.classList.add('selected');
  }
  updateOnionskin();
  updateFrameCount();
}

function gotoFirstFrame(){
  currentFrame().classList.remove('selected');
  document.querySelector('.frame').classList.add('selected');
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  updateFrameCount();
}

function gotoLastFrame(){
  currentFrame().classList.remove('selected');
  document.querySelector('.frame:last-child').classList.add('selected');
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  dom.addClass(currentFrame().previousElementSibling, 'onionskin');
  updateFrameCount();
}

var _lastFrameTime = 0;
var _frameDelay = 0;

function play(){
  document.body.classList.add('playing');
  // turn play button into stop button
  // disable all other controls
  // temporarily turn off onionskin (remember state)
  // start at beginning of document (remember state)
  document.querySelector('.frame').classList.add('play-frame');
  // add SVG SMIL animation
  // Unless looping, call stop() when animation is finished
  // How much of this can I do by adding "playing" class to body?
  setTimeout(function(){
      _frameDelay = currentFrameDelay;
      _lastFrameTime = Date.now();
      requestAnimationFrame(playNextFrame);
  }, 500);
}

function stop(){
  // remove SMIL animation
  // re-enable all controls
  // return to the frame we were on
  // re-enable onionskin if needed
  // turn stop button into play button
  dom.removeClass(playingFrame(), 'play-frame');
  document.body.classList.remove('playing');
}

function playNextFrame(){
  var time = Date.now();
  if ((time - _lastFrameTime) < _frameDelay){
      requestAnimationFrame(playNextFrame);
      return;
  }
  var currFrame = playingFrame();
  _lastFrameTime = time;
  if (currFrame.nextElementSibling){
      currFrame.classList.remove('play-frame');
      currFrame.nextElementSibling.classList.add('play-frame');
      requestAnimationFrame(playNextFrame);
  }else{
      stop();
  }
}

function updateFrameCount(){
  try{
      var frames = currentFrame().parentElement.children.length;
      var index = dom.indexOf(currentFrame());
      document.querySelector('.framecount').textContent = 'Frame ' + (index+1) + ' of ' + frames;
  }catch(e){
      // wait for the file to load, probably
  }
}

function undoLine(){
  dom.remove(currentFrame().lastElementChild);
  file.onChange();
}

function keydownHandler(evt){
  if ((evt.key || evt.keyIdentifier) === 'Control'){
      document.body.classList.add('usefiles');
  }
}

function keyupHandler(evt){
  if ((evt.key || evt.keyIdentifier) === 'Control'){
      document.body.classList.remove('usefiles');
  }
}

window.app = {
  updateFrameCount: updateFrameCount,
  play: play
};

// document.querySelector('#canvas-undo').addEventListener('click', undoLine, false);
// document.querySelector('#canvas-onionskin').addEventListener('change', toggleOnionskin, false);
document.addEventListener('keydown', keydownHandler, false);
document.addEventListener('keyup', keyupHandler, false);

<commit_msg>🎇🐝 Checkpoint ./js/script.js:739936/2<commit_after>/* globals dom file KellyColorPicker palettes */

// Initialize
const canvas = document.querySelector('#canvas');
canvas.setAttribute('width', document.body.clientWidth + 'px');
canvas.setAttribute('height', document.body.clientHeight + 'px');
const colorpaletteselect = document.querySelector('.colorpalette');
palettes.forEach((p,i) => {
  let opt = document.createElement('option');
  opt.setAttribute('value', i);
  opt.innerText = p.name;
  colorpaletteselect.append(opt);
});
colorpaletteselect.addEventListener('change', setPalette);
// Color picker
const colorpicker = new KellyColorPicker(
  {
    place : document.querySelector('.popup-colour'),
    input : '.js-colour',
    size : 200,
    color : '#ffffff',
    method : 'square',
    input_color : false, // or inputColor (sice v1.15)
    input_format : 'mixed', // or inputFormat (since v1.15)
    alpha : 1,
    alpha_slider : false, // or alphaSlider (since v1.15)
    colorSaver : false,
    resizeWith : true, // auto redraw canvas on resize window
    popupClass: 'popup-colour',
    userEvents : {
      // change : function(self) {
      //   // set background color for 'input' to current color of color picker
      //   if(self.getCurColorHsv().v < 0.5){
      //   self.getInput().style.color = "#FFF";
      // } else {
      //   self.getInput().style.color = "#000";
      // }
      // self.getInput().style.background = self.getCurColorHex();
    // }
  }
  });
setPalette({target: colorpaletteselect});

const mouse = {};

function setPalette(evt){
  let palette = palettes[parseInt(evt.target.value)];
  let wells = document.querySelectorAll('.js-miniwell');
  for (let i = 0; i < 5; i++){
    colorButton(wells[i], '#' + palette.colors[i]);
  }
}

class Pen{
  constructor(){
    this.drawing = false;
  }
  start(evt){
    console.log('start evt button: ', evt.button);
    if (evt.button !== 0){
      // button 0 is the main button, we're not interested in others
      // can't test for truthiness, because touch events have button=undefined
      return;
    }
    let {x,y} = getXY(evt);
    startPath(x,y);
    this.drawing = true;
  }

  move(evt){
    console.log('move %s', this.drawing);
    if (!this.drawing) return;
    let {x,y} = getXY(evt);
    if (inBounds(x,y)){
        appendToPath(x,y);
    }
  }

  stop(evt){
    console.log('stop %s', this.drawing);
    if (!this.drawing) return;
    let {x,y} = getXY(evt);
    // FIXME: draw a dot if we haven't moved
    if (currentPath){
      dom.simplifyPath(currentPath);
      currentPath = null;
    }
    this.drawing = false;
  }

  cancel(){
    // remove the path in progress
  }

}

class Pan{
  constructor(){
    this.dragging = false;
  }

  start(evt){
    if (evt.button !== 0){
      // button 0 is the main button, we're not interested in others
      return;
    }
    let {x,y} = getXY(evt);
    this.matrix = currentFrame().get
    startPath(x,y);
    this.drawing = true;
  }

  move(evt){

  }

  stop(evt){

  }

  cancel(){

  }

}

class Rotate{
  constructor(){

  }

  start(evt){

  }

  move(evt){

  }

  stop(evt){

  }

  cancel(evt){

  }
}

class ZoomIn{
  constructor(){

  }

  start(evt){

  }

  move(evt){

  }

  stop(evt){

  }

  cancel(evt){

  }
}

class ZoomOut{
  constructor(){

  }

  start(evt){

  }

  move(evt){

  }

  stop(evt){

  }

  cancel(evt){

  }
}

let tools = {
  pen: new Pen(canvas),
  pan: new Pan(canvas),
  rotate: new Rotate(canvas),
  zoomin: new ZoomIn(canvas),
  zoomout: new ZoomOut(canvas)
}

let currentTool = tools.pen;
let currentStrokeWidth = 1;
let currentDoOnionskin = true;

function selectTool(button){
  let name = button.getAttribute('title').toLowerCase();
  document.querySelector('.js-tool.active').classList.remove('active');
  button.classList.add('active');
  switch(name){
    case 'pen': currentTool = tools.pen; break;
    case 'pan': currentTool = tools.pan; break;
    case 'rotate': currentTool = tools.rotate; break;
    case 'zoom in':  currentTool = tools.zoomin; break;
    case 'zoom out': currentTool = tools.zoomout; break;
    default: console.error('unrecognized tool name: %s', name);
  }
}

let currentColor = '#000000';
let currentFrameDelay = 30; // milliseconds

function setFrameRate(input){
  currentFrameDelay = Math.floor(1000 / Number(input.value));
}

function colorPopup(input){
  let popup = document.querySelector('.popup-colour');
  let colorwell = document.querySelector('.colourwell');
  if (popup.style.display === 'none'){
    colorpicker.setColor(input.value);
    popup.style.display = 'block';
  }else{
    let color = colorpicker.getCurColorHex();
    colorButton(colorwell, color);
    colorButton(input, color);
    currentColor = color;
    popup.style.display = 'none';
  }
}

function colorButton(button, color){
  button.value = color;
  button.style.backgroundColor = color;
  if (hexToValue(color) < 0.5){
    button.style.color = '#FFF';
  }else{
    button.style.color = '#000';
  }
}

function hexToValue(hex){
  return colorpicker.rgbToHsv(colorpicker.hexToRgb(hex)).v;
}

function selectColor(input){
  let popup = document.querySelector('.popup-colour');
  let colorwell = document.querySelector('.colourwell');
  if (popup.style.display === 'block'){
    let color = colorpicker.getCurColorHex();
    colorButton(colorwell, color);
    colorButton(input, color);
    currentColor = color;
    popup.style.display = 'none';
  }else{
    colorButton(colorwell, input.value);
    currentColor = input.value;
  }
}

var drawing = false;
var WIDTH = document.body.clientWidth;
var HEIGHT = document.body.clientHeight;

// Prevent control clicks from passing through to svg
function swallowClicks(evt){
  evt.stopPropagation();
}
document.querySelector('.buttonbar.animation').addEventListener('mousedown', swallowClicks);
document.querySelector('.buttonbar.tools').addEventListener('mousedown', swallowClicks);
document.querySelector('.buttonbar.animation').addEventListener('touchstart', swallowClicks);
document.querySelector('.buttonbar.tools').addEventListener('touchstart', swallowClicks);

function inBounds(x,y){
  return !(x < 0 || x > WIDTH || y < 0 || y > HEIGHT);
}

function getXY(evt){
   if (evt.cancelable) {
      evt.preventDefault();
    }

    const rect = this.canvas.getBoundingClientRect();
    const position = evt.changedTouches && evt.changedTouches[0] || evt;
    let x = position.offsetX;
    let y = position.offsetY;

    if (typeof x === 'undefined') {
      x = position.clientX - rect.left;
    }
    if (typeof y === 'undefined') {
      y = position.clientY - rect.top;
    }
    return {x,y};
}

const toolStart = evt => currentTool.start(evt);
const toolMove = evt => currentTool.move(evt);
const toolStop = evt => currentTool.stop(evt);
const toolCancel = evt => currentTool.cancel();
const escCancel = evt => {
  if (evt.code && evt.code === 'Escape'){
    currentTool.cancel();
  }
}

document.body.addEventListener('mousedown', toolStart);
document.body.addEventListener('touchstart', toolStart);
document.body.addEventListener('mousemove', toolMove);
document.body.addEventListener('touchmove', toolMove);
document.body.addEventListener('touchend', toolStop);
document.body.addEventListener('mouseup', toolStop);
document.body.addEventListener('touchcancel', toolCancel);
document.body.addEventListener('keydown', escCancel);

function currentFrame(){
  return document.querySelector('.frame.selected');
}

function playingFrame(){
  return document.querySelector('.frame.play-frame');
}

var currentPath = null;

function startPath(x,y){

  currentPath = currentFrame().appendChild(dom.svg('path', {
      d: 'M ' + x + ',' + y,
      stroke: currentColor,
      'stroke-width': currentStrokeWidth
  }));
  file.onChange();
}

function appendToPath(x,y){
  var path = document.querySelector('.selected path:last-child');
  var d = path.getAttribute('d');
  path.setAttribute('d', `${d} L${x} ${y}`);
}

/***************************************
*
*  MANAGE FRAMES
*
***************************************/

function isOnionskinOn(){
  return currentDoOnionskin;
}

function currentOnionskinFrame(){
  return document.querySelector('.frame.onionskin');
}

function updateOnionskin(){
  if (!isOnionskinOn()) return;
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  dom.addClass(currentFrame().previousElementSibling, 'onionskin');
}

function addFrame(){
  dom.insertAfter(dom.svg('g', {'class': 'frame selected'}), currentFrame());
  currentFrame().classList.remove('selected');
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function cloneFrame(){
  dom.insertAfter(currentFrame().cloneNode(true), currentFrame());
  currentFrame().classList.remove('selected');
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function deleteFrame(){
  var frameToDelete = currentFrame();
  if (frameToDelete.nextElementSibling){
      incrementFrame();
  }else if (frameToDelete.previousElementSibling){
      decrementFrame();
  }
  if (frameToDelete.parentNode.children.length > 1){
    dom.remove(frameToDelete);
  }else{
    dom.clear(frameToDelete); // don't delete the last frame, just its children
  }
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function clear(){
  dom.clear(currentFrame());
}

function toggleOnionskin(){
  if (isOnionskinOn()){
      dom.addClass(currentFrame().previousElementSibling, 'onionskin');
  }else{
      dom.removeClass(currentOnionskinFrame(), 'onionskin');
  }
}

function incrementFrame(){
  var curr = currentFrame();
  if (curr.nextElementSibling){
      curr.classList.remove('selected');
      curr.nextElementSibling.classList.add('selected');
  }
  updateOnionskin();
  updateFrameCount();
}

function decrementFrame(){
  var curr = currentFrame();
  if (curr.previousElementSibling){
      curr.classList.remove('selected');
      curr.previousElementSibling.classList.add('selected');
  }
  updateOnionskin();
  updateFrameCount();
}

function gotoFirstFrame(){
  currentFrame().classList.remove('selected');
  document.querySelector('.frame').classList.add('selected');
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  updateFrameCount();
}

function gotoLastFrame(){
  currentFrame().classList.remove('selected');
  document.querySelector('.frame:last-child').classList.add('selected');
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  dom.addClass(currentFrame().previousElementSibling, 'onionskin');
  updateFrameCount();
}

var _lastFrameTime = 0;
var _frameDelay = 0;

function play(){
  document.body.classList.add('playing');
  // turn play button into stop button
  // disable all other controls
  // temporarily turn off onionskin (remember state)
  // start at beginning of document (remember state)
  document.querySelector('.frame').classList.add('play-frame');
  // add SVG SMIL animation
  // Unless looping, call stop() when animation is finished
  // How much of this can I do by adding "playing" class to body?
  setTimeout(function(){
      _frameDelay = currentFrameDelay;
      _lastFrameTime = Date.now();
      requestAnimationFrame(playNextFrame);
  }, 500);
}

function stop(){
  // remove SMIL animation
  // re-enable all controls
  // return to the frame we were on
  // re-enable onionskin if needed
  // turn stop button into play button
  dom.removeClass(playingFrame(), 'play-frame');
  document.body.classList.remove('playing');
}

function playNextFrame(){
  var time = Date.now();
  if ((time - _lastFrameTime) < _frameDelay){
      requestAnimationFrame(playNextFrame);
      return;
  }
  var currFrame = playingFrame();
  _lastFrameTime = time;
  if (currFrame.nextElementSibling){
      currFrame.classList.remove('play-frame');
      currFrame.nextElementSibling.classList.add('play-frame');
      requestAnimationFrame(playNextFrame);
  }else{
      stop();
  }
}

function updateFrameCount(){
  try{
      var frames = currentFrame().parentElement.children.length;
      var index = dom.indexOf(currentFrame());
      document.querySelector('.framecount').textContent = 'Frame ' + (index+1) + ' of ' + frames;
  }catch(e){
      // wait for the file to load, probably
  }
}

function undoLine(){
  dom.remove(currentFrame().lastElementChild);
  file.onChange();
}

function keydownHandler(evt){
  if ((evt.key || evt.keyIdentifier) === 'Control'){
      document.body.classList.add('usefiles');
  }
}

function keyupHandler(evt){
  if ((evt.key || evt.keyIdentifier) === 'Control'){
      document.body.classList.remove('usefiles');
  }
}

window.app = {
  updateFrameCount: updateFrameCount,
  play: play
};

// document.querySelector('#canvas-undo').addEventListener('click', undoLine, false);
// document.querySelector('#canvas-onionskin').addEventListener('change', toggleOnionskin, false);
document.addEventListener('keydown', keydownHandler, false);
document.addEventListener('keyup', keyupHandler, false);

<|endoftext|>


<commit_before>'use strict';

var allShops = [];

var clockHours = ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'];
var tableElement = document.getElementById('superTable');

function makeHeader(){

  var tableRow = document.createElement('tr');
  var tableHeader = document.createElement('th');
  tableHeader.textContent = 'Store';
  tableRow.appendChild(tableHeader);

  for(var k=0; k<clockHours.length; k++){
    tableHeader = document.createElement('th');
    tableHeader.textContent = clockHours[k];
    tableRow.appendChild(tableHeader);
  }

  tableHeader = document.createElement('th');
  tableHeader.textContent = 'Daily Location Total';
  tableRow.appendChild(tableHeader);
  tableElement.appendChild(tableRow);
}
makeHeader();

function Shop(nameOfShop, minCustomersPerHour, maxCustomersPerHour, averageCookiesPerCustomer){

  this.nameOfShop = nameOfShop;
  this.cookiesSoldEachHour = [];
  this.totalCookies = 0;
  this.minCustomersPerHour = minCustomersPerHour;
  this.maxCustomersPerHour = maxCustomersPerHour;
  this.averageCookiesPerCustomer = averageCookiesPerCustomer;

  this.randCustomersPerHour = function (){
    return Math.floor(Math.random()*(this.maxCustomersPerHour-this.minCustomersPerHour+1)+this.minCustomersPerHour);
  }

  this.fillCookiesSoldEachHour = function (){
    for(var i=0; i<clockHours.length; i++) {
      this.cookiesSoldEachHour.push(Math.ceil(this.averageCookiesPerCustomer * (this.randCustomersPerHour())));
      this.totalCookies += this.cookiesSoldEachHour[i];
    }
  }

  this.render = function (){
    this.fillCookiesSoldEachHour();

    var tableRow = document.createElement('tr');
    var tableData = document.createElement('td');
    tableData.textContent = this.nameOfShop;
    tableRow.appendChild(tableData);
    tableElement.appendChild(tableRow);

    for(var i = 0; i < clockHours.length; i++){
      tableData = document.createElement('td');
      tableData.textContent = this.cookiesSoldEachHour[i];
      tableRow.appendChild(tableData);
      tableElement.appendChild(tableRow);
    }
    tableData = document.createElement('td');
    tableData.textContent = this.totalCookies;
    tableRow.appendChild(tableData);
    tableElement.appendChild(tableRow);
  }
  this.render();
  allShops.push(this);
}

new Shop('First And Pike', 23, 65, 6.3);
new Shop('SeaTac Airport', 3, 24, 1.2);
new Shop('Seattle Center', 11, 38, 3.7);
new Shop('Capitol Hill', 20, 38, 2.3);
new Shop('Alki', 2, 16, 4.6);

function makeFooter(){

  var tableRow = document.createElement('tr');
  var tableHeader = document.createElement('th');
  tableHeader.textContent = 'Total';
  tableRow.appendChild(tableHeader);

  for(var k=0; k<allShops[1].cookiesSoldEachHour.length; k++){

    var allShopsTotal = 0;
    for(var p=0; p<allShops.length; p++){
      allShopsTotal += allShops[p].cookiesSoldEachHour[k];
    }
    tableHeader = document.createElement('th');
    tableHeader.textContent = allShopsTotal;
    tableRow.appendChild(tableHeader);
  }

  var superTotal = 0;
  for(var o=0; o<allShops.length; o++){
    superTotal+=allShops[o].totalCookies;
  }
  tableHeader = document.createElement('th');
  tableHeader.textContent = superTotal;
  tableRow.appendChild(tableHeader);
  tableElement.appendChild(tableRow);
}
makeFooter();
<commit_msg>Super Total<commit_after>'use strict';

var allShops = [];

var clockHours = ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'];
var tableElement = document.getElementById('superTable');

function makeHeader(){

  var tableRow = document.createElement('tr');
  var tableHeader = document.createElement('th');
  tableHeader.textContent = 'Store';
  tableRow.appendChild(tableHeader);

  for(var k=0; k<clockHours.length; k++){
    tableHeader = document.createElement('th');
    tableHeader.textContent = clockHours[k];
    tableRow.appendChild(tableHeader);
  }

  tableHeader = document.createElement('th');
  tableHeader.textContent = 'Daily Location Total';
  tableRow.appendChild(tableHeader);
  tableElement.appendChild(tableRow);
}
makeHeader();

function Shop(nameOfShop, minCustomersPerHour, maxCustomersPerHour, averageCookiesPerCustomer){

  this.nameOfShop = nameOfShop;
  this.cookiesSoldEachHour = [];
  this.totalCookies = 0;
  this.minCustomersPerHour = minCustomersPerHour;
  this.maxCustomersPerHour = maxCustomersPerHour;
  this.averageCookiesPerCustomer = averageCookiesPerCustomer;

  this.randCustomersPerHour = function (){
    return Math.floor(Math.random()*(this.maxCustomersPerHour-this.minCustomersPerHour+1)+this.minCustomersPerHour);
  }

  this.fillCookiesSoldEachHour = function (){
    for(var i=0; i<clockHours.length; i++) {
      this.cookiesSoldEachHour.push(Math.ceil(this.averageCookiesPerCustomer * (this.randCustomersPerHour())));
      this.totalCookies += this.cookiesSoldEachHour[i];
    }
  }

  this.render = function (){
    this.fillCookiesSoldEachHour();

    var tableRow = document.createElement('tr');
    var tableData = document.createElement('td');
    tableData.textContent = this.nameOfShop;
    tableRow.appendChild(tableData);
    tableElement.appendChild(tableRow);

    for(var i = 0; i < clockHours.length; i++){
      tableData = document.createElement('td');
      tableData.textContent = this.cookiesSoldEachHour[i];
      tableRow.appendChild(tableData);
      tableElement.appendChild(tableRow);
    }
    tableData = document.createElement('td');
    tableData.textContent = this.totalCookies;
    tableRow.appendChild(tableData);
    tableElement.appendChild(tableRow);
  }
  this.render();
  allShops.push(this);
}

new Shop('First And Pike', 23, 65, 6.3);
new Shop('SeaTac Airport', 3, 24, 1.2);
new Shop('Seattle Center', 11, 38, 3.7);
new Shop('Capitol Hill', 20, 38, 2.3);
new Shop('Alki', 2, 16, 4.6);

function makeFooter(){

  var tableRow = document.createElement('tr');
  var tableHeader = document.createElement('th');
  tableHeader.textContent = 'Total';
  tableRow.appendChild(tableHeader);

  for(var k=0; k<allShops[1].cookiesSoldEachHour.length; k++){

    var allShopsTotal = 0;
    for(var p=0; p<allShops.length; p++){
      allShopsTotal += allShops[p].cookiesSoldEachHour[k];
    }
    tableHeader = document.createElement('th');
    tableHeader.textContent = allShopsTotal;
    tableRow.appendChild(tableHeader);
  }

  var superTotal = 0;
  for(var o=0; o<allShops.length; o++){
    superTotal+=allShops[o].totalCookies;
  }
  tableHeader = document.createElement('th');
  tableHeader.textContent = 'Super Total '+superTotal;
  tableRow.appendChild(tableHeader);
  tableElement.appendChild(tableRow);
}
makeFooter();
<|endoftext|>


<commit_before>/**
 * Created by Lucas on 30/01/2017.
 */

document.addEventListener('contextmenu', function (event) {
    event.preventDefault()
});

$(document).ready(function () {

    $('button#validate').click(function () {
        if ($('#largeur').val() != "" && $('hauteur').val() != "" && $('#bombs').val() != "") {
            largeur = parseInt($('#largeur').val());
            hauteur = parseInt($('#hauteur').val());
            bombs = parseInt($('#bombs').val());

            if (!isNaN(largeur) && !isNaN(hauteur) && !isNaN(bombs)){
                if (testParameters(largeur,hauteur,bombs)) {
                    initGameboard();
                }
            }
        }
    });

});

function testParameters(largeur, hauteur, bombs) {

    if ( ((largeur * hauteur)/3)*2 >= bombs ){
        if (largeur <= 40 && hauteur <= 50){
            return true;
        }
    }
    return false;
}

function initGameboard() {
    generateLayout(largeur, hauteur);
    grid = new Grid(largeur, hauteur);
    grid.addBombs(bombs);
    $('#nbbombes').text(grid.bombs + ' bombes');

    $('#menu').css('display', 'none');
    $('#gameboard').css('display', 'block');

    document.oncontextmenu = function () {
        return false;
    };

    $('.reset').each(function () {
        $(this).click(function () {
            $('#modal-lost').modal('hide');
            $('#modal-win').modal('hide');

            generateLayout(largeur, hauteur);
            grid = new Grid(largeur, hauteur);
            grid.addBombs(bombs);
            $('#nbbombes').text(grid.flags + ' bombes');

            $('td').each(function () {
                initEvents($(this));
            });

        });
    });

    $('td').each(function () {
        initEvents($(this));
    });
}

function generateLayout(width, height) {
    $('table tbody').html('');
    for (var y = 0; y < height; y++) {
        var row = $("

");
        for (var x = 0; x < width; x++) {
            row.append($('	'))
        }
        $('table tbody').append(row);
    }
}

function initEvents(elem){

    elem.mousedown(function (event) {

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (event.button == 0) {

            if (grid.cells[x][y].flagged) {
                console.log('Erreur, il y a un drapeau');
            } else {
                if (!grid.cells[x][y].isShown()) {
                    if (grid.cells[x][y].isBomb()) {
                        elem.addClass("bomb");
                    } else if (grid.cells[x][y].value == 0) {
                        elem.addClass("empty");
                        cases = grid.reveal(x,y);
                        cases.forEach(function (el) {
                            if (el.value == 0) {
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('empty');
                            } else {
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('number');
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').html(el.getValue());
                            }
                        })
                    } else {
                        elem.addClass("number");
                        elem.html(grid.cells[x][y].getValue())
                    }
                    grid.cells[x][y].shown = true;
                    gameOverLose(grid.cells[x][y].getValue());
                    gameOverWin();
                }
            }

        } else if (event.button == 2) {
            console.log('clic du bouton droit');
            if (!grid.cells[x][y].isShown()) {
                if (grid.cells[x][y].isFlagged()) {
                    grid.cells[x][y].setFlagged(false);
                    elem.removeClass('flag');
                    grid.flags += 1;
                } else if (grid.flags > 0) {
                    grid.cells[x][y].setFlagged(true);
                    elem.addClass('flag');
                    grid.flags -= 1;
                } else if (grid.flags == 0) {
                    console.log('Nombre max de drapeau atteint !');
                }
                $('#nbbombes').text(grid.flags + ' bombes');
                console.log('Nombre de bombes : ' + grid.flags);
            }
        }
    });

    elem.dblclick(function () {
        console.log("test");

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (grid.cells[x][y].flagged) {
            console.log('Erreur, il y a un drapeau');
        } else {
            if (grid.cells[x][y].isShown())
            {
                result = grid.quickReveal(x,y);
                console.log(result.cases);

                result.cases.forEach(function (el) {
                    if (el.value == 0) {
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('empty');
                    }
                    else if (el.flagged && !el.isBomb()) {
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').removeClass('flag');
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('flagError');
                    }
                    else if (el.isBomb()) {
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('bomb');
                    }
                    else {
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('number');
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').html(el.value);
                    }
                });

                if (result.lost){
                    // Perdu!
                }
            }
        }

    })

}

function gameOverLose(elem) {
    if (elem == 'B') {
        $('#modal-lost').modal('show');
        return true;
    }
}

function gameOverWin() {
    var i = 0;
    $('td').each(function () {
        if ($(this).hasClass('bomb')) {
            return false
        } else if (!$(this).hasClass('empty') && !$(this).hasClass('number')) {
            i += 1;
        } else if ($(this).hasClass('flag')) {
            i += 1;
        }
    });
    if (i == grid.bombs) {
        console.log(i);
        $('#modal-win').modal('show');
        return true;
    }
}
<commit_msg>Fixes gameover<commit_after>/**
 * Created by Lucas on 30/01/2017.
 */

document.addEventListener('contextmenu', function (event) {
    event.preventDefault()
});

$(document).ready(function () {

    $('button#validate').click(function () {
        if ($('#largeur').val() != "" && $('hauteur').val() != "" && $('#bombs').val() != "") {
            largeur = parseInt($('#largeur').val());
            hauteur = parseInt($('#hauteur').val());
            bombs = parseInt($('#bombs').val());

            if (!isNaN(largeur) && !isNaN(hauteur) && !isNaN(bombs)) {
                if (testParameters(largeur, hauteur, bombs)) {
                    initGameboard();
                }
            }
        }
    });

});

function testParameters(largeur, hauteur, bombs) {

    if (((largeur * hauteur) / 3) * 2 >= bombs) {
        if (largeur <= 40 && hauteur <= 50) {
            return true;
        }
    }
    return false;
}

function initGameboard() {
    generateLayout(largeur, hauteur);
    grid = new Grid(largeur, hauteur);
    grid.addBombs(bombs);
    $('#nbbombes').text(grid.bombs + ' bombes');

    $('#menu').css('display', 'none');
    $('#gameboard').css('display', 'block');

    document.oncontextmenu = function () {
        return false;
    };

    $('.reset').each(function () {
        $(this).click(function () {
            $('#modal-lost').modal('hide');
            $('#modal-win').modal('hide');

            generateLayout(largeur, hauteur);
            grid = new Grid(largeur, hauteur);
            grid.addBombs(bombs);
            $('#nbbombes').text(grid.flags + ' bombes');

            $('td').each(function () {
                initEvents($(this));
            });

        });
    });

    $('td').each(function () {
        initEvents($(this));
    });
}

function generateLayout(width, height) {
    $('table tbody').html('');
    for (var y = 0; y < height; y++) {
        var row = $("

");
        for (var x = 0; x < width; x++) {
            row.append($('	'))
        }
        $('table tbody').append(row);
    }
}

function initEvents(elem) {

    elem.mousedown(function (event) {

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (event.button == 0) {

            if (grid.cells[x][y].flagged) {
                console.log('Erreur, il y a un drapeau');
            } else {
                if (!grid.cells[x][y].isShown()) {
                    if (grid.cells[x][y].isBomb()) {
                        elem.addClass("bomb");
                        gameOverLose();
                    } else if (grid.cells[x][y].value == 0) {
                        elem.addClass("empty");
                        cases = grid.reveal(x, y);
                        cases.forEach(function (el) {
                            if (el.value == 0) {
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('empty');
                            } else {
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('number');
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').html(el.getValue());
                            }
                        })
                    } else {
                        elem.addClass("number");
                        elem.html(grid.cells[x][y].getValue())
                    }
                    grid.cells[x][y].shown = true;
                    gameOverWin();
                }
            }

        } else if (event.button == 2) {
            console.log('clic du bouton droit');
            if (!grid.cells[x][y].isShown()) {
                if (grid.cells[x][y].isFlagged()) {
                    grid.cells[x][y].setFlagged(false);
                    elem.removeClass('flag');
                    grid.flags += 1;
                } else if (grid.flags > 0) {
                    grid.cells[x][y].setFlagged(true);
                    elem.addClass('flag');
                    grid.flags -= 1;
                } else if (grid.flags == 0) {
                    console.log('Nombre max de drapeau atteint !');
                }
                $('#nbbombes').text(grid.flags + ' bombes');
                console.log('Nombre de bombes : ' + grid.flags);
            }
        }
    });

    elem.dblclick(function () {
        console.log("test");

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (grid.cells[x][y].flagged) {
            console.log('Erreur, il y a un drapeau');
        } else {
            if (grid.cells[x][y].isShown()) {
                result = grid.quickReveal(x, y);
                console.log(result.cases);

                result.cases.forEach(function (el) {
                    if (el.value == 0) {
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('empty');
                    }
                    else if (el.flagged && !el.isBomb()) {
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').removeClass('flag');
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('flagError');
                    }
                    else if (el.isBomb()) {
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('bomb');
                    }
                    else {
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('number');
                        $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').html(el.value);
                    }
                });

                if (result.lost) {
                    gameOverLose()
                }
            }
        }

    })

}

function gameOverLose(elem) {
    $('#modal-lost').modal('show');
    return true;
}

function gameOverWin() {
    var i = 0;
    $('td').each(function () {
        if ($(this).hasClass('bomb')) {
            return false
        } else if (!$(this).hasClass('empty') && !$(this).hasClass('number')) {
            i += 1;
        } else if ($(this).hasClass('flag')) {
            i += 1;
        }
    });
    if (i == grid.bombs) {
        console.log(i);
        $('#modal-win').modal('show');
        return true;
    }
}
<|endoftext|>


<commit_before>var hours = ['6:00am', '7:00am', '8:00am', '9:00am', '10:00am', '11:00am', '12:00pm', '1:00pm', '2:00pm', '3:00pm', '4:00pm', '5:00pm', '6:00pm', '7:00pm', '8:00pm'];
var pikePlace = new CoffeeKiosk('Pike Place Market', 14, 35, 1.2, .34);
var capHill = new CoffeeKiosk('Capitol Hill', 12, 28, 3.2, .03);
var spl = new CoffeeKiosk('Seattle Public Library', 9, 45, 2.6, .02);
var slu = new CoffeeKiosk('South Lake Union', 5, 18, 1.3, .04);
var sta = new CoffeeKiosk('Sea-Tac Airport', 28, 44, 1.1, .41);
var kioskTable = document.getElementById('kioskTable');
var employeesTable = document.getElementById('employeesTable');
var newTable = document.getElementById('newTable');
var newLocationForm = document.getElementById('rowForm');
var headings = [' '] + hours;
var allKiosks = [pikePlace, capHill, spl, slu, sta];
var baristaHoursTotals = [];
var beansNeededHourTotals = [];

function CoffeeKiosk (locationName, minCustomersHour, maxCustomersHour, avgCupsPerCustomer, avgPoundsPerCustomer){
  this.locationName = locationName;
  this.minCustomersHour = minCustomersHour;
  this.maxCustomersHour = maxCustomersHour;
  this.avgCupsPerCustomer = avgCupsPerCustomer;
  this.avgPoundsPerCustomer = avgPoundsPerCustomer;
  this.customersPerHour = [];
  this.beansPerHour = [];
  this.poundPackagesPerHour = [];
  this.dailyCustomersTotal = 0;
  this.dailyCupsTotal = 0;
  this.dailyPoundPackagesTotal = 0;
  this.dailyBeansNeeded = 0;
  this.customersPerHour = function(){
    var custPerHour = [];
    for (var i = 0; i < hours.length; i++ ) {
      var customers = Math.floor(Math.random() * (this.maxCustomersHour - this.minCustomersHour + 1)) + this.minCustomersHour;
      custPerHour.push(customers);
    }
    return custPerHour;
  };
  this.cupsPerHour = function(){
    var cupsHrArray = [];
    for (var i = 0; i < hours.length; i++){
      var cupsSold = Math.ceil(this.customersPerHour()[i] * this.avgCupsPerCustomer);
      cupsHrArray.push(cupsSold);
    }
    return cupsHrArray;
  };
  this.beansNeededForCupsPerHour = function(){
    // beans needed for cups = (num cups per hour) / 16
    var beansForCups = [];
    for (var i = 0; i < hours.length; i++){
      var beansCup = Math.round((this.cupsPerHour()[i] / 16) * 10) / 10;
      beansForCups.push(beansCup);
    }
    return beansForCups;
  };
  this.poundPackagesPerHour = function(){
    //lbs needed per hour =  average pounds per customer * num of customers per hour
    var dailyPoundsSold = [];
    for (var i = 0; i < hours.length; i++){
      var lbsHour = Math.round((this.customersPerHour()[i] * this.avgPoundsPerCustomer) * 10) / 10;
      dailyPoundsSold.push(lbsHour);
    }
    return dailyPoundsSold;
  };
  this.beansPerHour = function (){
    // lbs of beans sold per hour = number of customers per hour * average pounds per customer + the beans needed for cups.
    var beansPerHour = [];
    for (var i = 0; i < hours.length; i++){
      var allBeans = Math.round((this.beansNeededForCupsPerHour()[i] + this.poundPackagesPerHour()[i]) * 10) / 10;
      beansPerHour.push(allBeans);
    }
    return beansPerHour;
  };
  this.employeesNeeded = function(){
    var numEmployees = [];
    for (var i = 0; i < hours.length; i++){
      var employees = Math.ceil((customersPerHour[i] * 2) / 60);
      numEmployees.push(employees);
    }
    return numEmployees;
  };
  this.dailyHourlyBeans = function(){
    var total = 0;
    for (var i = 0; i < this.beansPerHour().length; i++){
      var total = total + this.beansPerHour()[i];
    }
    return parseFloat((total).toFixed(1));
  };
};

function calcLocTotDaily(arrayInput){
  var total = 0;
  for (var i = 0; i < arrayInput.length; i++){
    var total = total + arrayInput[i];
  }
  beansNeededHourTotals.push(total);
  return parseFloat((total).toFixed(1));
}
function calcLocTotDailyBaristas(arrayInput){
  var total = 0;
  for (var i = 0; i < arrayInput.length; i++){
    var total = total + arrayInput[i];
  }
  baristaHoursTotals.push(total);
  return parseFloat((total / 7.5).toFixed(1));
}
function totalsDailyPerHour (){
  // two loops:
  // loop through the rows - one to grab the line
  // one to grab the first item of the line
}

function printTable (){
  var trElement = document.createElement('tr');
  var thElement = document.createElement('th');
  trElement.appendChild(thElement);

  var thElement = document.createElement('th');
  trElement.appendChild(thElement);
  thElement.textContent = 'Totals';

  for (var i = 0; i < headings.length; i++){
    var thElement = document.createElement('th');
    thElement.textContent = hours[i];
    trElement.appendChild(thElement);
  }
  newTable.appendChild(trElement);

  for ( var j = 0; j < allKiosks.length; j++){
    var trElement = document.createElement('tr');
    var thElement = document.createElement('th');
    thElement.textContent = allKiosks[j].locationName;
    trElement.appendChild(thElement);

    var thElement = document.createElement('th');
    trElement.appendChild(thElement);
    thElement.textContent = allKiosks[j].dailyHourlyBeans();

    for (var i = 0; i < hours.length; i++){
      var thElement = document.createElement ('th');
      thElement.textContent = allKiosks[j].beansPerHour()[i];
      trElement.appendChild(thElement);
    }
    newTable.appendChild(trElement);
  }
}

function submitRowToTable(event) {
  console.log(event);
  event.preventDefault();

  var locationName = event.target.locName.value;
  var minHr = event.target.minHr.value;
  var maxHr = event.target.maxHr.value;
  var cupsCust = event.target.cupsCust.value;
  var pounds = event.target.pounds.value;

  if (locationName === null){ locationName = 0; }
  if (minHr === null){ minHr = 0; }
  if (maxHr === null){ maxHr = 0; }
  if (cupsCust === null){ cupsCust = 0;}
  if (pounds === null){ pounds = 0; }

  var formKiosk = new CoffeeKiosk(locationName, minHr, maxHr, cupsCust, pounds);
  console.log(formKiosk);

  allKiosks.push(formKiosk);
  printTable();
  //create function to print all kiosks from an array of kiosks
}

printTable();

rowForm.addEventListener('submit', submitRowToTable);
<commit_msg>updates<commit_after>var hours = ['6:00am', '7:00am', '8:00am', '9:00am', '10:00am', '11:00am', '12:00pm', '1:00pm', '2:00pm', '3:00pm', '4:00pm', '5:00pm', '6:00pm', '7:00pm', '8:00pm'];
var pikePlace = new CoffeeKiosk('Pike Place Market', 14, 35, 1.2, .34);
var capHill = new CoffeeKiosk('Capitol Hill', 12, 28, 3.2, .03);
var spl = new CoffeeKiosk('Seattle Public Library', 9, 45, 2.6, .02);
var slu = new CoffeeKiosk('South Lake Union', 5, 18, 1.3, .04);
var sta = new CoffeeKiosk('Sea-Tac Airport', 28, 44, 1.1, .41);
var kioskTable = document.getElementById('kioskTable');
var employeesTable = document.getElementById('employeesTable');
var newTable = document.getElementById('newTable');
var newLocationForm = document.getElementById('rowForm');
var headings = [' '] + hours;
var allKiosks = [pikePlace, capHill, spl, slu, sta];
var baristaHoursTotals = [];
var beansNeededHourTotals = [];

function CoffeeKiosk (locationName, minCustomersHour, maxCustomersHour, avgCupsPerCustomer, avgPoundsPerCustomer){
  this.locationName = locationName;
  this.minCustomersHour = minCustomersHour;
  this.maxCustomersHour = maxCustomersHour;
  this.avgCupsPerCustomer = avgCupsPerCustomer;
  this.avgPoundsPerCustomer = avgPoundsPerCustomer;
  this.customersPerHour = [];
  this.beansPerHour = [];
  this.poundPackagesPerHour = [];
  this.dailyCustomersTotal = 0;
  this.dailyCupsTotal = 0;
  this.dailyPoundPackagesTotal = 0;
  this.dailyBeansNeeded = 0;
  this.customersPerHour = function(){
    var custPerHour = [];
    for (var i = 0; i < hours.length; i++ ) {
      var customers = Math.floor(Math.random() * (this.maxCustomersHour - this.minCustomersHour + 1)) + this.minCustomersHour;
      custPerHour.push(customers);
    }
    return custPerHour;
  };
  this.cupsPerHour = function(){
    var cupsHrArray = [];
    for (var i = 0; i < hours.length; i++){
      var cupsSold = Math.ceil(this.customersPerHour()[i] * this.avgCupsPerCustomer);
      cupsHrArray.push(cupsSold);
    }
    return cupsHrArray;
  };
  this.beansNeededForCupsPerHour = function(){
    // beans needed for cups = (num cups per hour) / 16
    var beansForCups = [];
    for (var i = 0; i < hours.length; i++){
      var beansCup = Math.round((this.cupsPerHour()[i] / 16) * 10) / 10;
      beansForCups.push(beansCup);
    }
    return beansForCups;
  };
  this.poundPackagesPerHour = function(){
    //lbs needed per hour =  average pounds per customer * num of customers per hour
    var dailyPoundsSold = [];
    for (var i = 0; i < hours.length; i++){
      var lbsHour = Math.round((this.customersPerHour()[i] * this.avgPoundsPerCustomer) * 10) / 10;
      dailyPoundsSold.push(lbsHour);
    }
    return dailyPoundsSold;
  };
  this.beansPerHour = function (){
    // lbs of beans sold per hour = number of customers per hour * average pounds per customer + the beans needed for cups.
    var beansPerHour = [];
    for (var i = 0; i < hours.length; i++){
      var allBeans = Math.round((this.beansNeededForCupsPerHour()[i] + this.poundPackagesPerHour()[i]) * 10) / 10;
      beansPerHour.push(allBeans);
    }
    return beansPerHour;
  };
  this.employeesNeeded = function(){
    var numEmployees = [];
    for (var i = 0; i < hours.length; i++){
      var employees = Math.ceil((customersPerHour[i] * 2) / 60);
      numEmployees.push(employees);
    }
    return numEmployees;
  };
  this.dailyHourlyBeans = function(){
    var total = 0;
    for (var i = 0; i < this.beansPerHour().length; i++){
      var total = total + this.beansPerHour()[i];
    }
    return parseFloat((total).toFixed(1));
  };
};

function calcLocTotDaily(arrayInput){
  var total = 0;
  for (var i = 0; i < arrayInput.length; i++){
    var total = total + arrayInput[i];
  }
  beansNeededHourTotals.push(total);
  return parseFloat((total).toFixed(1));
}
function calcLocTotDailyBaristas(arrayInput){
  var total = 0;
  for (var i = 0; i < arrayInput.length; i++){
    var total = total + arrayInput[i];
  }
  baristaHoursTotals.push(total);
  return parseFloat((total / 7.5).toFixed(1));
}
function totalsDailyPerHour (){
  // two loops:
  // loop through the rows - one to grab the line
  // one to grab the first item of the line
}

function printTable (){
  var trElement = document.createElement('tr');
  var thElement = document.createElement('th');
  trElement.appendChild(thElement);

  var thElement = document.createElement('th');
  trElement.appendChild(thElement);
  thElement.textContent = 'Totals';

  for (var i = 0; i < headings.length; i++){
    var thElement = document.createElement('th');
    thElement.textContent = hours[i];
    trElement.appendChild(thElement);
  }
  newTable.appendChild(trElement);

  for ( var j = 0; j < allKiosks.length; j++){
    var trElement = document.createElement('tr');
    var thElement = document.createElement('th');
    thElement.textContent = allKiosks[j].locationName;
    trElement.appendChild(thElement);

    var thElement = document.createElement('th');
    trElement.appendChild(thElement);
    thElement.textContent = allKiosks[j].dailyHourlyBeans();

    for (var i = 0; i < hours.length; i++){
      var thElement = document.createElement ('th');
      thElement.textContent = allKiosks[j].beansPerHour()[i];
      trElement.appendChild(thElement);
    }
    newTable.appendChild(trElement);
  }
}

function submitRowToTable(event) {
  console.log(event);
  event.preventDefault();

  var locationName = event.target.locName.value;
  var minHr = event.target.minHr.value;
  var maxHr = event.target.maxHr.value;
  var cupsCust = event.target.cupsCust.value;
  var pounds = event.target.pounds.value;

  if (locationName === null){ locationName = 0; }
  if (minHr === null){ minHr = 0; }
  if (maxHr === null){ maxHr = 0; }
  if (cupsCust === null){ cupsCust = 0;}
  if (pounds === null){ pounds = 0; }

  var formKiosk = new CoffeeKiosk(locationName, minHr, maxHr, cupsCust, pounds);
  console.log(formKiosk);

  allKiosks.push(formKiosk);
  printTable();
  //create function to print all kiosks from an array of kiosks
}

printTable();

rowForm.addEventListener('submit', submitRowToTable);
<|endoftext|>


<commit_before>// Assign DOM elements
const spooky = document.querySelector("#spooky");
const jumbotron = document.querySelector(".jumbotron");

// Random facts
const factElement = document.querySelector('#fact');

// Array of Halloween facts
// Source: https://www.womansday.com/life/g485/15-fascinating-halloween-facts-124464/
// Source: https://www.huffingtonpost.in/entry/halloween-weird-facts_n_5948456
// Source: https://www.factretriever.com/halloween-facts

const facts = [
    'California, Illinois, Michigan, New York, Ohio, and Pennsylvania produce the majority of pumpkins for Halloween – over 1 billion pounds a year!',
    'The name Jack-O-Lantern first originated from an Irish folktale about a man named Stingy Jack who tricked the Devil over and over again. When Jack died, he was forced to walk the Earth with only a carved-out turnip and burning coal to help light his way.',
    'The Plymouth Colony Pilgrims started the superstition about black cats.',
    'Tootsie Rolls, Smarties, and candy corn were among the most hated candies in 2017.',
    "Reese's Peanut Butter Cups were 2017’s most popular Halloween candy.",
    'At one time, it was customary to perform dances, songs, prayers, and plays in order to receive treats.',
    'Silly String is banned in Hollywood on Halloween.',
    'In 2014, the total estimated cost of all Halloween costumes was $2.8 billion.',
    'Candy Corn was created in 1898 and 35 million pounds of it are made every year.',
    'Halloween in the second largest consumer holiday in the United States. Consumers spent about $7 billion in 2015.',
    "Guinness World Records has named the Haunted Cave in Lewisburg, Ohio as the world's longest haunted house. It measures 3,564 feet long and is located 80 feet below ground in an abandoned mine.",
    'Harry Houdini died on Halloween in 1926.',
    'Trunk-or-Treating was created as a safer alternative to Trick-or-Treating in 2000.',
    'Halloween ranks as the sixth most popular card-giving holiday, with 20 million cards sent each year.',
    'In 2017, the most popular pet costumes were pumpkins, hot dogs, and a tie between a dog, lion, and pirate.',
    'Candy Corn was originally known as "chicken feed"',
    'Samhainophobia is the fear of Halloween.',
    'Halloween is thought to have originated around 4000 B.C., which means Halloween has been around for over 6,000 years.',
    'The first Jack O’Lanterns were actually made from turnips.',
    "Some animal shelters won't allow the adoption of black cats around Halloween for fear they'll be sacrificed.",
    'In a few American towns, Halloween was originally referred to as \"Cabbage Night.\"',
    'The first Jack O\’Lanterns were actually made from turnips.',
    'Samhainophobia is the fear of Halloween.',
    'The largest pumpkin ever measured was grown by Norm Craven, who broke the world record in 1993 with a 836 lb. pumpkin.',
    'Trick-or-treating evolved from the ancient Celtic tradition of putting out treats and food to placate spirits who roamed the streets at Samhain, a sacred festival that marked the end of the Celtic calendar year.',
    'The first known mention of trick-or-treating in print in North America occurred in 1927 in Blackie, Alberta, Canada.',
    'Ireland is typically believed to be the birthplace of Halloween.',
    'Scarecrows, a popular Halloween fixture, symbolize the ancient agricultural roots of the holiday.',
    'Halloween has variously been called All Hallows’ Eve, Witches Night, Lamswool, Snap-Apple Night, Samhaim, and Summer’s End.',
    'In 2010, 72.2% of those surveyed by the National Retail Federation will hand out candy, 46.3% will carve a pumpkin, 20.8% will visit a haunted house, and 11.5% will dress up their pets.',
    'The Village Halloween parade in New York City is the largest Halloween parade in the United States. The parade includes 50,000 participants and draws over 2 million spectators.',
    'Comedian John Evans once quipped: “What do you get if you divide the circumference of a jack-o’-lantern by its diameter? Pumpkin π.”',
    'Boston, Massachusetts, holds the record for the most Jack O’Lanterns lit at once (30,128).',
    'Both Salem, Massachusetts, and Anoka, Minnesota, are the self-proclaimed Halloween capitals of the world.',
    'Halloween is thought to have originated around 4000 B.C., which means Halloween has been around for over 6,000 years.',
    'According to tradition, if a person wears his or her clothes inside out and then walks backwards on Halloween, he or she will see a witch at midnight.',
    'Because the movie Halloween (1978) was on such a tight budget, they had to use the cheapest mask they could find for the character Michael Meyers, which turned out to be a William Shatner Star Trek mask. Shatner initially didn’t know the mask was in his likeness, but when he found out years later, he said he was honored.',
];

// Display message and fact
factElement.innerHTML = facts[Math.floor(Math.random() * facts.length)];

// Assign colors
const colors = {
    spooky: "#ada48f"
};

const getMessage = days => {
    if (days < 0) {
        return `Halloween was ${-days} days ago.`;
    }

    if (days === 0) {
        return "It's Halloween! Stay spooky!";
    }

    if (days === 1) {
        return "Halloween is tomorrow! Be afraid, be very afraid!";
    }

    return `There are ${days} days until Halloween.`;
};

const today = moment().startOf('day'); // Today
const halloween = moment("31-10", "DD-MM"); // Next Halloween
const message = getMessage(halloween.diff(today, "days")); // Calculate difference

// Display message
spooky.innerHTML = `
${message} 👻🎃

                    <button id="costumeButton">🦇</button>

Got a costume yet?

Click on the bat for a random idea!

`;

// Map of allowed keys for Konami Code
const allowedKeys = {
    37: "left",
    38: "up",
    39: "right",
    40: "down",
    65: "a",
    66: "b"
};

// 'Official' Konami Code sequence
const konamiCode = ["up", "up", "down", "down", "left", "right", "left", "right", "b", "a"];

// Variable to remember the 'position' the user has reached so far.
let konamiCodePosition = 0;

// Add keydown event listener
document.addEventListener("keydown", e => {
    // Get the value of the key code from the key map
    const key = allowedKeys[e.keyCode];

    // Get the value of the required key from the konami code
    const requiredKey = konamiCode[konamiCodePosition];

    // Compare the key with the required key
    if (key === requiredKey) {

        // Move to the next key in the konami code sequence
        konamiCodePosition++;

        // If the last key is reached, activate cheats
        if (konamiCodePosition === konamiCode.length) {
            doKonami();
            konamiCodePosition = 0;
        }
    } else {
        konamiCodePosition = 0;
    }
});

// Konami function that activates
const doKonami = () => {
    // Changes the CSS of elements into spooky theme
    jumbotron.style.backgroundColor = "transparent";
    spooky.style.color = colors["spooky"];

    document.body.classList.add(["konami"]);

    // Changes the color of all hyperlinks
    document.querySelectorAll("a").forEach(link => {
        if (link.href !== "") {
            link.style.color = colors["spooky"];
        }
    });
};

// Script for Random Costume Picker

const costumes = [
    ["Napolen Dynamite", "https://i.pinimg.com/originals/26/2a/f4/262af40e4592db053fd8613773e3f5b0.jpg"],
    ["Castaway","https://www.pinterest.ca/pin/16958936081976494/"],
    ["a 404error", "https://www.instagram.com/p/7QsQ9Vhj9_/?utm_source=ig_embed"],
    ["50 Shades of Grey", "https://i.pinimg.com/474x/9a/45/42/9a454265d6a6e59ba609831a1b7c7028--so-funny-funny-stuff.jpg"],
    ["Octocat", "https://twitter.com/Bint_alBeatz/status/793178052494815233"],
    ["The Shining", "https://i.pinimg.com/originals/21/e3/a9/21e3a9859795366b7cc1b7aa3c8ed598.jpg"]
    ["Tamagotchi", "https://www.pinterest.ca/pin/192810427770341992/"],
    ["Clippy","https://www.google.com/imgres?imgurl=https%3A%2F%2Fi.pinimg.com%2Foriginals%2F83%2F37%2F31%2F8337315668b57bcbf4fcb82a4fde2a99.jpg&imgrefurl=https%3A%2F%2Fwww.pinterest.com%2Fpin%2F518758450798995072%2F&docid=zgMyyDogGc7eJM&tbnid=Ex7IH-SdFvQoaM%3A&vet=10ahUKEwjXjKbr0_ndAhWL1FkKHZg5DfYQMwg7KAEwAQ..i&w=650&h=975&safe=off&client=firefox-b-ab&bih=781&biw=1440&q=halloween%20clippy&ved=0ahUKEwjXjKbr0_ndAhWL1FkKHZg5DfYQMwg7KAEwAQ&iact=mrc&uact=8"],
    ["Mark Zuckerberg", "https://costumewall.com/dress-like-mark-zuckerberg/"],
    ["a stick figure", "https://twitter.com/CarlForrest/status/1050448521353207808"]
  ];

  //Assign DOM elements
  let costumeButton = document.getElementById("costumeButton");
  let costumeContent = document.getElementById("costumeContent");

  //Pick a random costume
  const costumeIs = () => {
    let numCostumes = costumes.length;
    let randomNumber = Math.floor( ( Math.random() * numCostumes ) );
    return costumes[randomNumber];
  }

  //Display costume on page with link.
  const newCostume = () => {
    costume = costumeIs();
    costumeContent.innerHTML = `Got a costume yet?

                                You could be: ${costume[0]}`;
  };

  //Add event listener on 'click'
  costumeButton.addEventListener('click', newCostume, false);
<commit_msg>Add more halloween facts<commit_after>// Assign DOM elements
const spooky = document.querySelector("#spooky");
const jumbotron = document.querySelector(".jumbotron");

// Random facts
const factElement = document.querySelector('#fact');

// Array of Halloween facts
// Source: https://www.womansday.com/life/g485/15-fascinating-halloween-facts-124464/
// Source: https://www.huffingtonpost.in/entry/halloween-weird-facts_n_5948456
// Source: https://www.factretriever.com/halloween-facts

const facts = [
    'California, Illinois, Michigan, New York, Ohio, and Pennsylvania produce the majority of pumpkins for Halloween – over 1 billion pounds a year!',
    'The name Jack-O-Lantern first originated from an Irish folktale about a man named Stingy Jack who tricked the Devil over and over again. When Jack died, he was forced to walk the Earth with only a carved-out turnip and burning coal to help light his way.',
    'The Plymouth Colony Pilgrims started the superstition about black cats.',
    'Tootsie Rolls, Smarties, and candy corn were among the most hated candies in 2017.',
    "Reese's Peanut Butter Cups were 2017’s most popular Halloween candy.",
    'At one time, it was customary to perform dances, songs, prayers, and plays in order to receive treats.',
    'Silly String is banned in Hollywood on Halloween.',
    'In 2014, the total estimated cost of all Halloween costumes was $2.8 billion.',
    'Candy Corn was created in 1898 and 35 million pounds of it are made every year.',
    'Halloween in the second largest consumer holiday in the United States. Consumers spent about $7 billion in 2015.',
    "Guinness World Records has named the Haunted Cave in Lewisburg, Ohio as the world's longest haunted house. It measures 3,564 feet long and is located 80 feet below ground in an abandoned mine.",
    'Harry Houdini died on Halloween in 1926.',
    'Trunk-or-Treating was created as a safer alternative to Trick-or-Treating in 2000.',
    'Halloween ranks as the sixth most popular card-giving holiday, with 20 million cards sent each year.',
    'In 2017, the most popular pet costumes were pumpkins, hot dogs, and a tie between a dog, lion, and pirate.',
    'Candy Corn was originally known as "chicken feed"',
    'Samhainophobia is the fear of Halloween.',
    'Halloween is thought to have originated around 4000 B.C., which means Halloween has been around for over 6,000 years.',
    'The first Jack O’Lanterns were actually made from turnips.',
    "Some animal shelters won't allow the adoption of black cats around Halloween for fear they'll be sacrificed.",
    'In a few American towns, Halloween was originally referred to as \"Cabbage Night.\"',
    'The first Jack O\’Lanterns were actually made from turnips.',
    'Samhainophobia is the fear of Halloween.',
    'The largest pumpkin ever measured was grown by Norm Craven, who broke the world record in 1993 with a 836 lb. pumpkin.',
    'Trick-or-treating evolved from the ancient Celtic tradition of putting out treats and food to placate spirits who roamed the streets at Samhain, a sacred festival that marked the end of the Celtic calendar year.',
    'The first known mention of trick-or-treating in print in North America occurred in 1927 in Blackie, Alberta, Canada.',
    'Ireland is typically believed to be the birthplace of Halloween.',
    'Scarecrows, a popular Halloween fixture, symbolize the ancient agricultural roots of the holiday.',
    'Halloween has variously been called All Hallows’ Eve, Witches Night, Lamswool, Snap-Apple Night, Samhaim, and Summer’s End.',
    'In 2010, 72.2% of those surveyed by the National Retail Federation will hand out candy, 46.3% will carve a pumpkin, 20.8% will visit a haunted house, and 11.5% will dress up their pets.',
    'The Village Halloween parade in New York City is the largest Halloween parade in the United States. The parade includes 50,000 participants and draws over 2 million spectators.',
    'Comedian John Evans once quipped: “What do you get if you divide the circumference of a jack-o’-lantern by its diameter? Pumpkin π.”',
    'Boston, Massachusetts, holds the record for the most Jack O’Lanterns lit at once (30,128).',
    'Both Salem, Massachusetts, and Anoka, Minnesota, are the self-proclaimed Halloween capitals of the world.',
    'Halloween is thought to have originated around 4000 B.C., which means Halloween has been around for over 6,000 years.',
    'According to tradition, if a person wears his or her clothes inside out and then walks backwards on Halloween, he or she will see a witch at midnight.',
    'Because the movie Halloween (1978) was on such a tight budget, they had to use the cheapest mask they could find for the character Michael Meyers, which turned out to be a William Shatner Star Trek mask. Shatner initially didn’t know the mask was in his likeness, but when he found out years later, he said he was honored.',
    'Fifty percent of kids prefer to receive chocolate candy for Halloween, compared with 24% who prefer non-chocolate candy and 10% who preferred gum.',
    'Most experts trace trick-or-treating to the European practice of "mumming," or "guysing," in which costume-wearing participants would go door-to-door performing choreographed dances, songs and plays in exchange for treats.',
    'Candy makers supposedly lobbied to extend daylight savings time into the beginning of November to get an extra hour of daylight so children could collect even more candy!',
];

// Display message and fact
factElement.innerHTML = facts[Math.floor(Math.random() * facts.length)];

// Assign colors
const colors = {
    spooky: "#ada48f"
};

const getMessage = days => {
    if (days < 0) {
        return `Halloween was ${-days} days ago.`;
    }

    if (days === 0) {
        return "It's Halloween! Stay spooky!";
    }

    if (days === 1) {
        return "Halloween is tomorrow! Be afraid, be very afraid!";
    }

    return `There are ${days} days until Halloween.`;
};

const today = moment().startOf('day'); // Today
const halloween = moment("31-10", "DD-MM"); // Next Halloween
const message = getMessage(halloween.diff(today, "days")); // Calculate difference

// Display message
spooky.innerHTML = `
${message} 👻🎃

                    <button id="costumeButton">🦇</button>

Got a costume yet?

Click on the bat for a random idea!

`;

// Map of allowed keys for Konami Code
const allowedKeys = {
    37: "left",
    38: "up",
    39: "right",
    40: "down",
    65: "a",
    66: "b"
};

// 'Official' Konami Code sequence
const konamiCode = ["up", "up", "down", "down", "left", "right", "left", "right", "b", "a"];

// Variable to remember the 'position' the user has reached so far.
let konamiCodePosition = 0;

// Add keydown event listener
document.addEventListener("keydown", e => {
    // Get the value of the key code from the key map
    const key = allowedKeys[e.keyCode];

    // Get the value of the required key from the konami code
    const requiredKey = konamiCode[konamiCodePosition];

    // Compare the key with the required key
    if (key === requiredKey) {

        // Move to the next key in the konami code sequence
        konamiCodePosition++;

        // If the last key is reached, activate cheats
        if (konamiCodePosition === konamiCode.length) {
            doKonami();
            konamiCodePosition = 0;
        }
    } else {
        konamiCodePosition = 0;
    }
});

// Konami function that activates
const doKonami = () => {
    // Changes the CSS of elements into spooky theme
    jumbotron.style.backgroundColor = "transparent";
    spooky.style.color = colors["spooky"];

    document.body.classList.add(["konami"]);

    // Changes the color of all hyperlinks
    document.querySelectorAll("a").forEach(link => {
        if (link.href !== "") {
            link.style.color = colors["spooky"];
        }
    });
};

// Script for Random Costume Picker

const costumes = [
    ["Napolen Dynamite", "https://i.pinimg.com/originals/26/2a/f4/262af40e4592db053fd8613773e3f5b0.jpg"],
    ["Castaway","https://www.pinterest.ca/pin/16958936081976494/"],
    ["a 404error", "https://www.instagram.com/p/7QsQ9Vhj9_/?utm_source=ig_embed"],
    ["50 Shades of Grey", "https://i.pinimg.com/474x/9a/45/42/9a454265d6a6e59ba609831a1b7c7028--so-funny-funny-stuff.jpg"],
    ["Octocat", "https://twitter.com/Bint_alBeatz/status/793178052494815233"],
    ["The Shining", "https://i.pinimg.com/originals/21/e3/a9/21e3a9859795366b7cc1b7aa3c8ed598.jpg"]
    ["Tamagotchi", "https://www.pinterest.ca/pin/192810427770341992/"],
    ["Clippy","https://www.google.com/imgres?imgurl=https%3A%2F%2Fi.pinimg.com%2Foriginals%2F83%2F37%2F31%2F8337315668b57bcbf4fcb82a4fde2a99.jpg&imgrefurl=https%3A%2F%2Fwww.pinterest.com%2Fpin%2F518758450798995072%2F&docid=zgMyyDogGc7eJM&tbnid=Ex7IH-SdFvQoaM%3A&vet=10ahUKEwjXjKbr0_ndAhWL1FkKHZg5DfYQMwg7KAEwAQ..i&w=650&h=975&safe=off&client=firefox-b-ab&bih=781&biw=1440&q=halloween%20clippy&ved=0ahUKEwjXjKbr0_ndAhWL1FkKHZg5DfYQMwg7KAEwAQ&iact=mrc&uact=8"],
    ["Mark Zuckerberg", "https://costumewall.com/dress-like-mark-zuckerberg/"],
    ["a stick figure", "https://twitter.com/CarlForrest/status/1050448521353207808"]
  ];

  //Assign DOM elements
  let costumeButton = document.getElementById("costumeButton");
  let costumeContent = document.getElementById("costumeContent");

  //Pick a random costume
  const costumeIs = () => {
    let numCostumes = costumes.length;
    let randomNumber = Math.floor( ( Math.random() * numCostumes ) );
    return costumes[randomNumber];
  }

  //Display costume on page with link.
  const newCostume = () => {
    costume = costumeIs();
    costumeContent.innerHTML = `Got a costume yet?

                                You could be: ${costume[0]}`;
  };

  //Add event listener on 'click'
  costumeButton.addEventListener('click', newCostume, false);
<|endoftext|>


<commit_before>$(function(){
  var parser = new Parser()
    , visuals = new Visuals('graph')
    , $repositoryInput = $('#repository-input')
    , $repositoryButton = $('#repository-button')
    , $repoTitle = $('#repo-title')
    , $repoDescription = $('#repo-description')
    , loadingText = 'Loading...'
    , errorText = 'Error'
    , $repositoryAlert = $('#repository-alert')
    , parsingLocked = false
    , $graphs = $('#graphs')
    , $progress = $('#progress')
    , $progressBar = $progress.children('.progress-bar')
    , $tokenForm = $('#token-form')
    , $tokenInput = $('#token-input')
    , $tokenButton = $('#token-button')

  /*
    Alert
  */

  /**
   * Display alert message
   * @param  {String} message Message may contain html elements
   * @param  {String} type    success, info, warning or danger. info by default
   */
  function showAlert(message, type) {
    type = type !== void 0 ? type : 'info'

    $repositoryAlert
      .html(message)
      .removeClass('alert-success alert-info alert-warning alert-danger')
      .addClass('alert-' + type)
      .show()
  }

  function hideAlert() {
    $repositoryAlert.hide()
  }

  function setProgress(progress) {
    $progressBar
      .attr('aria-valuenow', progress)
      .width(progress + '%')
      .text(progress + '%')
  }

  /*
    Parser callbacks
  */
  parser.beforeParse = function(){
    $repoTitle.text(loadingText)
    $repoDescription.text(loadingText)
    lockInput()

    $graphs.hide()
    visuals.emptyGraphs()
    $progress.show()
  }

  parser.afterParse = function(data){
    $repoTitle.text(data.name || '')
    $repoDescription.text(data.description || '')
    unlockInput()

    $progress.hide()
    setProgress(0)
    $graphs.show()

    visuals.showData(data)
  }

  parser.onError = function(message){
    $repoTitle.text(errorText)
    $repoDescription.text(errorText)
    unlockInput()
    lastInputValue = null

    $progress.hide()
    setProgress(0)

    showAlert('Error occured! ' + message, 'danger')
  }

  parser.onProgress = function(progress){
    setProgress(progress)
  }

  /*
    Lock input while loading
  */
  function lockInput() {
    parsingLocked = true
    $repositoryInput.attr('disabled', 'disabled')
    $repositoryButton.button('loading')
  }

  function unlockInput() {
    parsingLocked = false
    $repositoryInput.removeAttr('disabled')
    $repositoryButton.button('reset')
  }

  /*
    On page processing
  */
  var lastInputValue = null

  function parseInput(str) {
    var fullRegexp = /^https?\:\/\/github.com\/([a-z0-9\-\_\.]+\/[a-z0-9\-\_\.]+)\/?/i
      , simpleRegexp = /([a-z0-9\-\_\.]+\/[a-z0-9\-\_\.]+)\/?/i
      , match

    // Check if full repo url was passed (http://github.com/user/name)
    if ((match = fullRegexp.exec(str)) != null) {
      return match[1]
    } else if ((match = simpleRegexp.exec(str)) != null) {
      return match[1]
    } else {
      return null
    }
  }

  function checkAndParse() {
    // Do not check if script is still working
    if (parsingLocked) {
      return
    }

    var val = parseInput($repositoryInput.val())

    // Update input value with parsed value
    if (val !== null && $repositoryInput.val() !== val) {
      $repositoryInput.val(val)
    }

    if (val !== null && val !== lastInputValue) {
      // Update browser history
      window.history.pushState({}, "", document.location.href.replace(/\?.*/i, '').replace(/\/$/i, '') + '/?repo=' + val)

      hideAlert()

      // Cache last value
      lastInputValue = val

      // Run parser
      parser.parse(val)

      // Change button state
      checkButtonState()
    } else if (val === null) {
      // Display warning
      showAlert('Wrong format! Please insert repository slug as user/name or https://github.com/user/name', 'warning')
    }
  }

  // On form submit
  $('#repository-form').submit(function(ev){
    ev.preventDefault()
    checkAndParse()
  })

  // On clicking examples links
  $('.examples').on('click', 'a', function(ev){
    $repositoryInput.val($(this).data('github'))
    checkAndParse()
  })

  function getQueryParams(qs) {
    qs = qs.split("+").join(" ");

    var params = {}
      , tokens
      , re = /[?&]?([^=]+)=([^&]*)/g
      ;

    while (tokens = re.exec(qs)) {
      params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
  }

  // If repo is passed trough URI then assign it to input
  if (document.location.search && getQueryParams(document.location.search).hasOwnProperty('repo')) {
    $repositoryInput.val(getQueryParams(document.location.search).repo)
  }

  window.onpopstate = function() {
    if (getQueryParams(document.location.search).hasOwnProperty('repo')) {
      $repositoryInput.val(getQueryParams(document.location.search).repo)
      checkAndParse()
    }
  }

  // If initial form has a value
  if ($repositoryInput.val()) {
    checkAndParse()
  }

  function checkButtonState(){
    var val = parseInput($repositoryInput.val())

    if (val !== null && val !== lastInputValue) {
      $repositoryButton.addClass('btn-primary')
    } else {
      $repositoryButton.removeClass('btn-primary')
    }
  }

  // On input content changes (but is not submitted)
  $repositoryInput.on('change paste keyup', function(ev){
    // Do not process when Enter is pressed
    if (ev.type === 'keyup' && ev.keyCode === 13) {
      return;
    }

    checkButtonState()
  })

  /*
    Authentication
  */
  // Init authentication
  hello.init({github : "baf32f7bbb8d975e64f3"})

  // Show the message with auth request
  parser.onAuthRequired = function(repositoryUri) {
    unlockInput()
    showAlert('API rate limit exceeded You have exceeded your API requests rate limit or you have no permissions to view this repository issues. In order to increase limit please authorize this application. Alternatively you can generate a token and set it manually.', 'warning')
  }

  // Auth request
  $('#repository-alert').on('click', '#authorization-request', function(ev){
    ev.preventDefault()

    hello('github').login({redirect_uri:'redirect.html'}, function(ev) {
      if (!ev.hasOwnProperty("error")) {
        var github = hello("github").getAuthResponse()

        parser.token = github.access_token
        // Save into cookies
        document.cookie = "token=" + github.access_token

        // Continue with parsing
        lastInputValue = null
        checkAndParse()
      }
    })
  })

  /*
  Token input
   */

  $('body').on('click', '.toggle-token-input', function(ev){
    ev.preventDefault()

    $tokenForm.toggle(function(){
      if ($(this).css('display') !== 'none') {
        // Update token input
        $tokenInput.val(parser.token)
      }
    })
  })

  $tokenForm.submit(function(ev){
    ev.preventDefault()

    var token = $tokenInput.val()

    // Update token
    parser.token = token
    // Save into cookies
    document.cookie = "token=" + token

    $tokenForm.hide()
  })

  // display-token-input
})
<commit_msg>:candy: Make authorization request button bigger<commit_after>$(function(){
  var parser = new Parser()
    , visuals = new Visuals('graph')
    , $repositoryInput = $('#repository-input')
    , $repositoryButton = $('#repository-button')
    , $repoTitle = $('#repo-title')
    , $repoDescription = $('#repo-description')
    , loadingText = 'Loading...'
    , errorText = 'Error'
    , $repositoryAlert = $('#repository-alert')
    , parsingLocked = false
    , $graphs = $('#graphs')
    , $progress = $('#progress')
    , $progressBar = $progress.children('.progress-bar')
    , $tokenForm = $('#token-form')
    , $tokenInput = $('#token-input')
    , $tokenButton = $('#token-button')

  /*
    Alert
  */

  /**
   * Display alert message
   * @param  {String} message Message may contain html elements
   * @param  {String} type    success, info, warning or danger. info by default
   */
  function showAlert(message, type) {
    type = type !== void 0 ? type : 'info'

    $repositoryAlert
      .html(message)
      .removeClass('alert-success alert-info alert-warning alert-danger')
      .addClass('alert-' + type)
      .show()
  }

  function hideAlert() {
    $repositoryAlert.hide()
  }

  function setProgress(progress) {
    $progressBar
      .attr('aria-valuenow', progress)
      .width(progress + '%')
      .text(progress + '%')
  }

  /*
    Parser callbacks
  */
  parser.beforeParse = function(){
    $repoTitle.text(loadingText)
    $repoDescription.text(loadingText)
    lockInput()

    $graphs.hide()
    visuals.emptyGraphs()
    $progress.show()
  }

  parser.afterParse = function(data){
    $repoTitle.text(data.name || '')
    $repoDescription.text(data.description || '')
    unlockInput()

    $progress.hide()
    setProgress(0)
    $graphs.show()

    visuals.showData(data)
  }

  parser.onError = function(message){
    $repoTitle.text(errorText)
    $repoDescription.text(errorText)
    unlockInput()
    lastInputValue = null

    $progress.hide()
    setProgress(0)

    showAlert('Error occured! ' + message, 'danger')
  }

  parser.onProgress = function(progress){
    setProgress(progress)
  }

  /*
    Lock input while loading
  */
  function lockInput() {
    parsingLocked = true
    $repositoryInput.attr('disabled', 'disabled')
    $repositoryButton.button('loading')
  }

  function unlockInput() {
    parsingLocked = false
    $repositoryInput.removeAttr('disabled')
    $repositoryButton.button('reset')
  }

  /*
    On page processing
  */
  var lastInputValue = null

  function parseInput(str) {
    var fullRegexp = /^https?\:\/\/github.com\/([a-z0-9\-\_\.]+\/[a-z0-9\-\_\.]+)\/?/i
      , simpleRegexp = /([a-z0-9\-\_\.]+\/[a-z0-9\-\_\.]+)\/?/i
      , match

    // Check if full repo url was passed (http://github.com/user/name)
    if ((match = fullRegexp.exec(str)) != null) {
      return match[1]
    } else if ((match = simpleRegexp.exec(str)) != null) {
      return match[1]
    } else {
      return null
    }
  }

  function checkAndParse() {
    // Do not check if script is still working
    if (parsingLocked) {
      return
    }

    var val = parseInput($repositoryInput.val())

    // Update input value with parsed value
    if (val !== null && $repositoryInput.val() !== val) {
      $repositoryInput.val(val)
    }

    if (val !== null && val !== lastInputValue) {
      // Update browser history
      window.history.pushState({}, "", document.location.href.replace(/\?.*/i, '').replace(/\/$/i, '') + '/?repo=' + val)

      hideAlert()

      // Cache last value
      lastInputValue = val

      // Run parser
      parser.parse(val)

      // Change button state
      checkButtonState()
    } else if (val === null) {
      // Display warning
      showAlert('Wrong format! Please insert repository slug as user/name or https://github.com/user/name', 'warning')
    }
  }

  // On form submit
  $('#repository-form').submit(function(ev){
    ev.preventDefault()
    checkAndParse()
  })

  // On clicking examples links
  $('.examples').on('click', 'a', function(ev){
    $repositoryInput.val($(this).data('github'))
    checkAndParse()
  })

  function getQueryParams(qs) {
    qs = qs.split("+").join(" ");

    var params = {}
      , tokens
      , re = /[?&]?([^=]+)=([^&]*)/g
      ;

    while (tokens = re.exec(qs)) {
      params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }

    return params;
  }

  // If repo is passed trough URI then assign it to input
  if (document.location.search && getQueryParams(document.location.search).hasOwnProperty('repo')) {
    $repositoryInput.val(getQueryParams(document.location.search).repo)
  }

  window.onpopstate = function() {
    if (getQueryParams(document.location.search).hasOwnProperty('repo')) {
      $repositoryInput.val(getQueryParams(document.location.search).repo)
      checkAndParse()
    }
  }

  // If initial form has a value
  if ($repositoryInput.val()) {
    checkAndParse()
  }

  function checkButtonState(){
    var val = parseInput($repositoryInput.val())

    if (val !== null && val !== lastInputValue) {
      $repositoryButton.addClass('btn-primary')
    } else {
      $repositoryButton.removeClass('btn-primary')
    }
  }

  // On input content changes (but is not submitted)
  $repositoryInput.on('change paste keyup', function(ev){
    // Do not process when Enter is pressed
    if (ev.type === 'keyup' && ev.keyCode === 13) {
      return;
    }

    checkButtonState()
  })

  /*
    Authentication
  */
  // Init authentication
  hello.init({github : "baf32f7bbb8d975e64f3"})

  // Show the message with auth request
  parser.onAuthRequired = function(repositoryUri) {
    unlockInput()
    showAlert('API rate limit exceeded You have exceeded your API requests rate limit or you have no permissions to view this repository issues. In order to increase limit please authorize this application. Alternatively you can generate a token and set it manually.

Click here to authorize application', 'warning')
  }

  // Auth request
  $('#repository-alert').on('click', '.authorization-request', function(ev){
    ev.preventDefault()

    hello('github').login({redirect_uri:'redirect.html'}, function(ev) {
      if (!ev.hasOwnProperty("error")) {
        var github = hello("github").getAuthResponse()

        parser.token = github.access_token
        // Save into cookies
        document.cookie = "token=" + github.access_token

        // Continue with parsing
        lastInputValue = null
        checkAndParse()
      }
    })
  })

  /*
  Token input
   */

  $('body').on('click', '.toggle-token-input', function(ev){
    ev.preventDefault()

    $tokenForm.toggle(function(){
      if ($(this).css('display') !== 'none') {
        // Update token input
        $tokenInput.val(parser.token)
      }
    })
  })

  $tokenForm.submit(function(ev){
    ev.preventDefault()

    var token = $tokenInput.val()

    // Update token
    parser.token = token
    // Save into cookies
    document.cookie = "token=" + token

    $tokenForm.hide()
  })

  // display-token-input
})
<|endoftext|>


<commit_before>var map;
function initMap() {
// Constructor creates a new map - only center and zoom are required.
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 39.4689262, lng: -0.3846146},
        zoom: 13
    });
}
<commit_msg>Added marker for 'Ciudad de las Artes y las Ciencias'<commit_after>var map;
function initMap() {
// Constructor creates a new map - only center and zoom are required.
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: 39.4689262, lng: -0.3846146},
        zoom: 13
    });
    ciudadArtes = {lat: 39.4548751, lng:-0.3526791};
    var marker = new google.maps.Marker({
        position: ciudadArtes,
        map: map,
        title: 'Ciudad de las Artes y las Ciencias'
    });
}
<|endoftext|>