<commit_before>define(function() {

return {

  // The following palette description
  // is copied from compiled CoffeeScript.
  COFFEESCRIPT_PALETTE: [
    {
      name: 'Move',
      color: 'red',
      blocks: [
        {
          block: 'fd 100',
          title: 'Move forward'
        }, {
          block: 'rt 90',
          title: 'Turn right'
        }, {
          block: 'lt 90',
          title: 'Turn left'
        }, {
          block: 'bk 100',
          title: 'Move backward'
        }, {
          block: 'rt 180, 100',
          title: 'Make a wide right arc'
        }, {
          block: 'lt 180, 100',
          title: 'Make a wide left arc'
        }, {
          block: 'speed 10',
          title: 'Set the speed of the turtle'
        }, {
          block: 'speed Infinity',
          title: 'Use infinite speed'
        }, {
          block: 'home()',
          title: 'Jump to the origin, turned up'
        }, {
          block: 'turnto 270',
          title: 'Turn to an absolute direction'
        }, {
          block: 'turnto lastclick',
          title: 'Turn toward a located object'
        }, {
          block: 'moveto 100, 50',
          title: 'Move to coordinates'
        }, {
          block: 'movexy 30, 20',
          title: 'Move by changing x and y'
        }, {
          block: 'move 10, 5',
          title: "Move sideways or diagonal from turtle's angle"
        }, {
          block: 'jumpto 100, 50',
          title: 'Jump to coordinates without drawing'
        }, {
          block: 'jumpxy 30, 20',
          title: 'Jump changing x and y without drawing'
        }, {
          block: 'jump 10, 5',
          title: "Move sideways or diagonal without drawing"
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for [1..3]\n  ``',
          title: 'Do something multiple times'
        }, {
          block: 'for x in [1..3]\n  ``',
          title: 'Do something multiple times...?'
        }, {
          block: 'if `` is ``\n  ``',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if `` is ``\n  ``\nelse\n  ``',
          title: 'Do something if a condition is true, otherwise something else'
        }, {
          block: "tick 1, ->\n  write 'ticked'",
          title: 'Repeat something forever at qually-spaced times'
        }, {
          block: "button \'Click\', ->\n  write 'clicked'",
          title: 'Make a button and do something when clicked'
        }, {
          block: "keydown \'X\', ->\n  write 'x pressed'",
          title: 'Do something when a keyboard key is pressed'
        }, {
          block: "click (e) ->\n  moveto e",
          title: 'Move to a location when document is clicked'
        }
      ]
    }, {
      name: 'Draw',
      color: 'blue',
      blocks: [
        {
          block: 'pen purple, 10',
          title: 'Set pen color and size'
        }, {
          block: 'dot green, 50',
          title: 'Make a dot'
        }, {
          block: 'box yellow, 50',
          title: 'Make a square'
        }, {
          block: 'fill blue',
          title: 'Fill traced shape'
        }, {
          block: 'cs()',
          title: 'Clear screen'
        }, {
          block: 'cg()',
          title: 'Clear graphics'
        }, {
          block: 'pu()',
          title: 'Lift the pen up'
        }, {
          block: 'pd()',
          title: 'Put the pen down'
        }, {
          block: 'scale 3',
          title: 'Scale turtle drawing'
        }
      ]
    }, {
      name: 'Math',
      color: 'green',
      blocks: [
        {
          block: 'x = ``',
          title: 'Set a variable'
        }, {
          block: '`` + ``',
          title: 'Add two numbers'
        }, {
          block: '`` - ``',
          title: 'Subtract two numbers'
        }, {
          block: '`` * ``',
          title: 'Multiply two numbers'
        }, {
          block: '`` / ``',
          title: 'Divide two numbers'
        }, {
          block: '`` is ``',
          title: 'Compare two values'
        }, {
          block: '`` < ``',
          title: 'Compare two values'
        }, {
          block: '`` > ``',
          title: 'Compare two values'
        }, {
          block: 'random [1..100]',
          title: 'Get a random number in a range'
        }, {
          block: 'round ``',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs ``',
          title: 'Absolute value'
        }, {
          block: 'max ``, ``',
          title: 'Get the larger of two numbers'
        }, {
          block: 'min ``, ``',
          title: 'Get the smaller on two numbers'
        }, {
          block: 'text.match /pattern/',
          title: 'Test if pattern is found in text'
        }, {
          block: 'f = (param) ->\n  ``',
          title: 'Define a new function'
        }, {
          block: 'myfunc(arg)',
          title: 'Use a custom function'
        }
      ]
    }, {
      name: 'Text',
      color: 'yellow',
      blocks: [
        {
          block: 'write \'Hello.\'',
          title: 'Write text in the document'
        }, {
          block: 'type \'zz*(-.-)*zz\'',
          title: 'Typewrite text in the document'
        }, {
          block: 'label \'spot\'',
          title: 'Write text at the turtle'
        }, {
          block: 'read \'?\', (x) ->\n  write x',
          title: 'Read input from the user'
        }, {
          block: 'readnum \'?\', (x) ->\n  write x',
          title: 'Read a number from the user'
        }, {
          block: 'log [1..10]',
          title: 'Log an object to debug'
        }
      ]
    }, {
      name: 'Sprites',
      color: 'violet',
      blocks: [
        {
          block: 'wear \'/img/apple\'',
          title: 'Use an image for the turtle'
        }, {
          block: 't = new Turtle red',
          title: 'Make a new turtle'
        }, {
          block: 't.fd 100',
          title: 'Move turtle t forward'
        }, {
          block: 't.rt 90',
          title: 'Turn turtle t right'
        }, {
          block: 't.lt 90',
          title: 'Turn turtle t left'
        }, {
          block: 't.bk 100',
          title: 'Move turtle t backward'
        }, {
          block: 'ht()',
          title: 'Hide the main turtle'
        }, {
          block: 'st()',
          title: 'Show the main turtle'
        }, {
          block: 's = new Sprite',
          title: 'Make a blank sprite'
        }, {
          block: 's.wear \'/img/dragon\'',
          title: 'Load an image in sprite s'
        }, {
          block: 'drawon s',
          title: 'Draw on sprite s'
        }, {
          block: 'drawon document',
          title: 'Draw on the document'
        }, {
          block: 'p = new Piano',
          title: 'Make a visible insturment'
        }, {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }, {
          block: 'q = new Pencil',
          title: 'Make an invisible and fast drawing sprite'
        }, {
          block: 'q.pen black, 1',
          title: 'Use a thin black pen'
        }, {
          block: 'q.drawon s',
          title: 'Use q to draw on sprite s'
        }, {
          block: 'q.rt 360, 100',
          title: 'Trace a circle on the right'
        }, {
          block: 'q.lt 360, 100',
          title: 'Trace a circle on the left'
        }, {
          block: 'q.fill pink',
          title: 'Fill the traced path'
        }
      ]
    }
  ],

  JAVASCRIPT_PALETTE: [
    {
      name: 'Draw',
      color: 'blue',
      blocks: [
        {
          block: 'pen(red);',
          title: 'Set the pen color'
        }, {
          block: 'fd(100);',
          title: 'Move forward'
        }, {
          block: 'rt(90);',
          title: 'Turn right'
        }, {
          block: 'lt(90);',
          title: 'Turn left'
        }, {
          block: 'bk(100);',
          title: 'Move backward'
        }, {
          block: 'speed(10);',
          title: 'Set the speed of the turtle'
        }, {
          block: 'dot(blue, 50);',
          title: 'Make a dot'
        }, {
          block: 'box(green, 50);',
          title: 'Make a square'
        }, {
          block: 'write(\'hello\');',
          title: 'Write text on the screen'
        }, {
          block: 'label(\'hello\');',
          title: 'Write text at the turtle'
        }, {
          block: 'ht();',
          title: 'Hide the turtle'
        }, {
          block: 'st();',
          title: 'Show the turtle'
        }, {
          block: 'pu();',
          title: 'Pick the pen up'
        }, {
          block: 'pd();',
          title: 'Put the pen down'
        }, {
          block: 'pen(purple, 10);',
          title: 'Set the pen color and thickness'
        }, {
          block: 'rt(180, 100);',
          title: 'Make a wide right turn'
        }, {
          block: 'lt(180, 100);',
          title: 'Make a wide left turn'
        }, {
          block: 'slide(100, 20);',
          title: 'Slide sideways or diagonally'
        }, {
          block: 'jump(100, 20);',
          title: 'Jump without drawing'
        }, {
          block: 'play(\'GEC\');',
          title: 'Play music notes'
        }, {
          block: 'wear(\'/img/cat-icon\');',
          title: 'Change the turtle image'
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for (var i = 0; i < 4; i++) {\n  __;\n}',
          title: 'Do something multiple times'
        }, {
          block: 'if (__) {\n  __;\n}',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if (__) {\n  __;\n} else {\n  __;\n}',
          title: 'Do something if a condition is true, otherwise do something else'
        }, {
          block: 'while (__) {\n  __;\n}',
          title: 'Repeat something while a condition is true'
        }
      ]
    }, {
      name: 'Math',
      color: 'green',
      blocks: [
        {
          block: 'var x = __;',
          title: 'Create a variable for the first time'
        }, {
          block: 'x = __;',
          title: 'Reassign a variable'
        }, {
          block: '__ + __',
          title: 'Add two numbers'
        }, {
          block: '__ - __',
          title: 'Subtract two numbers'
        }, {
          block: '__ * __',
          title: 'Multiply two numbers'
        }, {
          block: '__ / __',
          title: 'Divide two numbers'
        }, {
          block: '__ === __',
          title: 'Compare two numbers'
        }, {
          block: '__ > __',
          title: 'Compare two numbers'
        }, {
          block: '__ < __',
          title: 'Compare two numbers'
        }, {
          block: 'random(1, 100)',
          title: 'Get a random number in a range'
        }, {
          block: 'round(__)',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs(__)',
          title: 'Absolute value'
        }, {
          block: 'max(__, __)',
          title: 'Absolute value'
        }, {
          block: 'min(__, __)',
          title: 'Absolute value'
        }
      ]
    }, {
      name: 'Functions',
      color: 'violet',
      blocks: [
        {
          block: 'function myFunction() {\n  __;\n}',
          title: 'Create a function without an argument'
        }, {
          block: 'function myFunction(n) {\n  __;\n}',
          title: 'Create a function with an argument'
        }, {
          block: 'myFunction()',
          title: 'Use a function without an argument'
        }, {
          block: 'myFunction(n)',
          title: 'Use a function with argument'
        }
      ]
    }
  ]
};

});
<commit_msg>Change Math to Operators<commit_after>define(function() {

return {

  // The following palette description
  // is copied from compiled CoffeeScript.
  COFFEESCRIPT_PALETTE: [
    {
      name: 'Move',
      color: 'red',
      blocks: [
        {
          block: 'fd 100',
          title: 'Move forward'
        }, {
          block: 'rt 90',
          title: 'Turn right'
        }, {
          block: 'lt 90',
          title: 'Turn left'
        }, {
          block: 'bk 100',
          title: 'Move backward'
        }, {
          block: 'rt 180, 100',
          title: 'Make a wide right arc'
        }, {
          block: 'lt 180, 100',
          title: 'Make a wide left arc'
        }, {
          block: 'speed 10',
          title: 'Set the speed of the turtle'
        }, {
          block: 'speed Infinity',
          title: 'Use infinite speed'
        }, {
          block: 'home()',
          title: 'Jump to the origin, turned up'
        }, {
          block: 'turnto 270',
          title: 'Turn to an absolute direction'
        }, {
          block: 'turnto lastclick',
          title: 'Turn toward a located object'
        }, {
          block: 'moveto 100, 50',
          title: 'Move to coordinates'
        }, {
          block: 'movexy 30, 20',
          title: 'Move by changing x and y'
        }, {
          block: 'move 10, 5',
          title: "Move sideways or diagonal from turtle's angle"
        }, {
          block: 'jumpto 100, 50',
          title: 'Jump to coordinates without drawing'
        }, {
          block: 'jumpxy 30, 20',
          title: 'Jump changing x and y without drawing'
        }, {
          block: 'jump 10, 5',
          title: "Move sideways or diagonal without drawing"
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for [1..3]\n  ``',
          title: 'Do something multiple times'
        }, {
          block: 'for x in [1..3]\n  ``',
          title: 'Do something multiple times...?'
        }, {
          block: 'if `` is ``\n  ``',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if `` is ``\n  ``\nelse\n  ``',
          title: 'Do something if a condition is true, otherwise something else'
        }, {
          block: "tick 1, ->\n  write 'ticked'",
          title: 'Repeat something forever at qually-spaced times'
        }, {
          block: "button \'Click\', ->\n  write 'clicked'",
          title: 'Make a button and do something when clicked'
        }, {
          block: "keydown \'X\', ->\n  write 'x pressed'",
          title: 'Do something when a keyboard key is pressed'
        }, {
          block: "click (e) ->\n  moveto e",
          title: 'Move to a location when document is clicked'
        }
      ]
    }, {
      name: 'Draw',
      color: 'blue',
      blocks: [
        {
          block: 'pen purple, 10',
          title: 'Set pen color and size'
        }, {
          block: 'dot green, 50',
          title: 'Make a dot'
        }, {
          block: 'box yellow, 50',
          title: 'Make a square'
        }, {
          block: 'fill blue',
          title: 'Fill traced shape'
        }, {
          block: 'cs()',
          title: 'Clear screen'
        }, {
          block: 'cg()',
          title: 'Clear graphics'
        }, {
          block: 'pu()',
          title: 'Lift the pen up'
        }, {
          block: 'pd()',
          title: 'Put the pen down'
        }, {
          block: 'scale 3',
          title: 'Scale turtle drawing'
        }
      ]
    }, {
      name: 'Operators',
      color: 'green',
      blocks: [
        {
          block: 'x = ``',
          title: 'Set a variable'
        }, {
          block: '`` + ``',
          title: 'Add two numbers'
        }, {
          block: '`` - ``',
          title: 'Subtract two numbers'
        }, {
          block: '`` * ``',
          title: 'Multiply two numbers'
        }, {
          block: '`` / ``',
          title: 'Divide two numbers'
        }, {
          block: '`` is ``',
          title: 'Compare two values'
        }, {
          block: '`` < ``',
          title: 'Compare two values'
        }, {
          block: '`` > ``',
          title: 'Compare two values'
        }, {
          block: 'random [1..100]',
          title: 'Get a random number in a range'
        }, {
          block: 'round ``',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs ``',
          title: 'Absolute value'
        }, {
          block: 'max ``, ``',
          title: 'Get the larger of two numbers'
        }, {
          block: 'min ``, ``',
          title: 'Get the smaller on two numbers'
        }, {
          block: 'text.match /pattern/',
          title: 'Test if pattern is found in text'
        }, {
          block: 'f = (param) ->\n  ``',
          title: 'Define a new function'
        }, {
          block: 'myfunc(arg)',
          title: 'Use a custom function'
        }
      ]
    }, {
      name: 'Text',
      color: 'yellow',
      blocks: [
        {
          block: 'write \'Hello.\'',
          title: 'Write text in the document'
        }, {
          block: 'type \'zz*(-.-)*zz\'',
          title: 'Typewrite text in the document'
        }, {
          block: 'label \'spot\'',
          title: 'Write text at the turtle'
        }, {
          block: 'read \'?\', (x) ->\n  write x',
          title: 'Read input from the user'
        }, {
          block: 'readnum \'?\', (x) ->\n  write x',
          title: 'Read a number from the user'
        }, {
          block: 'log [1..10]',
          title: 'Log an object to debug'
        }
      ]
    }, {
      name: 'Sprites',
      color: 'violet',
      blocks: [
        {
          block: 'wear \'/img/apple\'',
          title: 'Use an image for the turtle'
        }, {
          block: 't = new Turtle red',
          title: 'Make a new turtle'
        }, {
          block: 't.fd 100',
          title: 'Move turtle t forward'
        }, {
          block: 't.rt 90',
          title: 'Turn turtle t right'
        }, {
          block: 't.lt 90',
          title: 'Turn turtle t left'
        }, {
          block: 't.bk 100',
          title: 'Move turtle t backward'
        }, {
          block: 'ht()',
          title: 'Hide the main turtle'
        }, {
          block: 'st()',
          title: 'Show the main turtle'
        }, {
          block: 's = new Sprite',
          title: 'Make a blank sprite'
        }, {
          block: 's.wear \'/img/dragon\'',
          title: 'Load an image in sprite s'
        }, {
          block: 'drawon s',
          title: 'Draw on sprite s'
        }, {
          block: 'drawon document',
          title: 'Draw on the document'
        }, {
          block: 'p = new Piano',
          title: 'Make a visible insturment'
        }, {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }, {
          block: 'q = new Pencil',
          title: 'Make an invisible and fast drawing sprite'
        }, {
          block: 'q.pen black, 1',
          title: 'Use a thin black pen'
        }, {
          block: 'q.drawon s',
          title: 'Use q to draw on sprite s'
        }, {
          block: 'q.rt 360, 100',
          title: 'Trace a circle on the right'
        }, {
          block: 'q.lt 360, 100',
          title: 'Trace a circle on the left'
        }, {
          block: 'q.fill pink',
          title: 'Fill the traced path'
        }
      ]
    }
  ],

  JAVASCRIPT_PALETTE: [
    {
      name: 'Draw',
      color: 'blue',
      blocks: [
        {
          block: 'pen(red);',
          title: 'Set the pen color'
        }, {
          block: 'fd(100);',
          title: 'Move forward'
        }, {
          block: 'rt(90);',
          title: 'Turn right'
        }, {
          block: 'lt(90);',
          title: 'Turn left'
        }, {
          block: 'bk(100);',
          title: 'Move backward'
        }, {
          block: 'speed(10);',
          title: 'Set the speed of the turtle'
        }, {
          block: 'dot(blue, 50);',
          title: 'Make a dot'
        }, {
          block: 'box(green, 50);',
          title: 'Make a square'
        }, {
          block: 'write(\'hello\');',
          title: 'Write text on the screen'
        }, {
          block: 'label(\'hello\');',
          title: 'Write text at the turtle'
        }, {
          block: 'ht();',
          title: 'Hide the turtle'
        }, {
          block: 'st();',
          title: 'Show the turtle'
        }, {
          block: 'pu();',
          title: 'Pick the pen up'
        }, {
          block: 'pd();',
          title: 'Put the pen down'
        }, {
          block: 'pen(purple, 10);',
          title: 'Set the pen color and thickness'
        }, {
          block: 'rt(180, 100);',
          title: 'Make a wide right turn'
        }, {
          block: 'lt(180, 100);',
          title: 'Make a wide left turn'
        }, {
          block: 'slide(100, 20);',
          title: 'Slide sideways or diagonally'
        }, {
          block: 'jump(100, 20);',
          title: 'Jump without drawing'
        }, {
          block: 'play(\'GEC\');',
          title: 'Play music notes'
        }, {
          block: 'wear(\'/img/cat-icon\');',
          title: 'Change the turtle image'
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for (var i = 0; i < 4; i++) {\n  __;\n}',
          title: 'Do something multiple times'
        }, {
          block: 'if (__) {\n  __;\n}',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if (__) {\n  __;\n} else {\n  __;\n}',
          title: 'Do something if a condition is true, otherwise do something else'
        }, {
          block: 'while (__) {\n  __;\n}',
          title: 'Repeat something while a condition is true'
        }
      ]
    }, {
      name: 'Math',
      color: 'green',
      blocks: [
        {
          block: 'var x = __;',
          title: 'Create a variable for the first time'
        }, {
          block: 'x = __;',
          title: 'Reassign a variable'
        }, {
          block: '__ + __',
          title: 'Add two numbers'
        }, {
          block: '__ - __',
          title: 'Subtract two numbers'
        }, {
          block: '__ * __',
          title: 'Multiply two numbers'
        }, {
          block: '__ / __',
          title: 'Divide two numbers'
        }, {
          block: '__ === __',
          title: 'Compare two numbers'
        }, {
          block: '__ > __',
          title: 'Compare two numbers'
        }, {
          block: '__ < __',
          title: 'Compare two numbers'
        }, {
          block: 'random(1, 100)',
          title: 'Get a random number in a range'
        }, {
          block: 'round(__)',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs(__)',
          title: 'Absolute value'
        }, {
          block: 'max(__, __)',
          title: 'Absolute value'
        }, {
          block: 'min(__, __)',
          title: 'Absolute value'
        }
      ]
    }, {
      name: 'Functions',
      color: 'violet',
      blocks: [
        {
          block: 'function myFunction() {\n  __;\n}',
          title: 'Create a function without an argument'
        }, {
          block: 'function myFunction(n) {\n  __;\n}',
          title: 'Create a function with an argument'
        }, {
          block: 'myFunction()',
          title: 'Use a function without an argument'
        }, {
          block: 'myFunction(n)',
          title: 'Use a function with argument'
        }
      ]
    }
  ]
};

});
<|endoftext|>


<commit_before>define(function() {

return {

  // The following palette description
  // is copied from compiled CoffeeScript.
  COFFEESCRIPT_PALETTE: [
    {
      name: 'Move',
      color: 'red',
      blocks: [
        {
          block: 'fd 100',
          title: 'Move forward'
        }, {
          block: 'rt 90',
          title: 'Turn right'
        }, {
          block: 'lt 90',
          title: 'Turn left'
        }, {
          block: 'bk 100',
          title: 'Move backward'
        }, {
          block: 'rt 180, 100',
          title: 'Make a wide right arc'
        }, {
          block: 'lt 180, 100',
          title: 'Make a wide left arc'
        }, {
          block: 'speed 10',
          title: 'Set the speed of the turtle'
        }, {
          block: 'speed Infinity',
          title: 'Use infinite speed'
        }, {
          block: 'home()',
          title: 'Jump to the origin, turned up'
        }, {
          block: 'turnto 270',
          title: 'Turn to an absolute direction'
        }, {
          block: 'turnto lastclick',
          title: 'Turn toward a located object'
        }, {
          block: 'moveto 100, 50',
          title: 'Move to coordinates'
        }, {
          block: 'movexy 30, 20',
          title: 'Move by changing x and y'
        }, {
          block: 'move 10, 5',
          title: "Move sideways or diagonal from turtle's angle"
        }, {
          block: 'jumpto 100, 50',
          title: 'Jump to coordinates without drawing'
        }, {
          block: 'jumpxy 30, 20',
          title: 'Jump changing x and y without drawing'
        }, {
          block: 'jump 10, 5',
          title: "Move sideways or diagonal without drawing"
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for [1..3]\n  ``',
          title: 'Do something multiple times'
        }, {
          block: 'if `` is ``\n  ``',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if `` is ``\n  ``\nelse\n  ``',
          title: 'Do something if a condition is true, otherwise something else'
        }, {
          block: "tick 1, ->\n  write 'ticked'",
          title: 'Repeat something forever at qually-spaced times'
        }, {
          block: "button \'Click\', ->\n  write 'clicked'",
          title: 'Make a button and do something when clicked'
        }, {
          block: "keydown \'X\', ->\n  write 'x pressed'",
          title: 'Do something when a keyboard key is pressed'
        }, {
          block: "click (e) ->\n  moveto e",
          title: 'Move to a location when document is clicked'
        }
      ]
    }, {
      name: 'Looks',
      color: 'blue',
      blocks: [
         {
          block: 'pen purple, 10',
          title: 'Set pen color and size'
        }, {
          block: 'dot green, 50',
          title: 'Make a dot'
        }, {
          block: 'box yellow, 50',
          title: 'Make a square'
        }, {
          block: 'fill blue',
          title: 'Fill traced shape'
        }, {
          block: 'wear \'/img/apple\'',
          title: 'Use an image for the turtle'
        }, {
          block: 'scale 3',
          title: 'Scale turtle drawing'
        }, {
          block: 'ht()',
          title: 'Hide the main turtle'
        }, {
          block: 'st()',
          title: 'Show the main turtle'
        }, {
          block: 'cs()',
          title: 'Clear screen'
        }, {
          block: 'cg()',
          title: 'Clear graphics'
        }, {
          block: 'pu()',
          title: 'Lift the pen up'
        }, {
          block: 'pd()',
          title: 'Put the pen down'
        }, {
          block: 'drawon s',
          title: 'Draw on sprite s'
        }, {
          block: 'drawon document',
          title: 'Draw on the document'
        }
      ]
    }, {
      name: 'Operators',
      color: 'green',
      blocks: [
        {
          block: 'x = ``',
          title: 'Set a variable'
        }, {
          block: '`` is ``',
          title: 'Compare two values'
        }, {
          block: '`` < ``',
          title: 'Compare two values'
        }, {
          block: '`` > ``',
          title: 'Compare two values'
        }, {
          block: '`` + ``',
          title: 'Add two numbers'
        }, {
          block: '`` - ``',
          title: 'Subtract two numbers'
        }, {
          block: '`` * ``',
          title: 'Multiply two numbers'
        }, {
          block: '`` / ``',
          title: 'Divide two numbers'
        }, {
          block: 'random [1..100]',
          title: 'Get a random number in a range'
        }, {
          block: 'round ``',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs ``',
          title: 'Absolute value'
        }, {
          block: 'max ``, ``',
          title: 'Get the larger of two numbers'
        }, {
          block: 'min ``, ``',
          title: 'Get the smaller on two numbers'
        }, {
          block: 'x.match /pattern/',
          title: 'Test if a text pattern is found in x'
        }, {
          block: 'f = (x) ->\n  ``',
          title: 'Define a new function'
        }, {
          block: 'f(x)',
          title: 'Use a custom function'
        }
      ]
    }, {
      name: 'Text',
      color: 'yellow',
      blocks: [
        {
          block: 'write \'Hello.\'',
          title: 'Write text in the document'
        }, {
          block: 'type \'zz*(-.-)*zz\'',
          title: 'Typewrite text in the document'
        }, {
          block: 'label \'spot\'',
          title: 'Write text at the turtle'
        }, {
          block: 'read \'?\', (x) ->\n  write x',
          title: 'Read input from the user'
        }, {
          block: 'readnum \'?\', (x) ->\n  write x',
          title: 'Read a number from the user'
        }, {
          block: 'log [1..10]',
          title: 'Log an object to debug'
        }
      ]
    }, {
      name: 'Sprites',
      color: 'violet',
      blocks: [
        {
          block: 't = new Turtle red',
          title: 'Make a new turtle'
        }, {
          block: 's = new Sprite',
          title: 'Make a blank sprite'
        }, {
          block: 'p = new Piano',
          title: 'Make a visible insturment'
        }, {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }, {
          block: 'q = new Pencil',
          title: 'Make an invisible and fast drawing sprite'
        }
      ]
    }, {
      name: 'Sound',
      color: 'violet',
      blocks: [
        {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }
      ]
    }
  ],

  JAVASCRIPT_PALETTE: [
    {
      name: 'Draw',
      color: 'blue',
      blocks: [
        {
          block: 'pen(red);',
          title: 'Set the pen color'
        }, {
          block: 'fd(100);',
          title: 'Move forward'
        }, {
          block: 'rt(90);',
          title: 'Turn right'
        }, {
          block: 'lt(90);',
          title: 'Turn left'
        }, {
          block: 'bk(100);',
          title: 'Move backward'
        }, {
          block: 'speed(10);',
          title: 'Set the speed of the turtle'
        }, {
          block: 'dot(blue, 50);',
          title: 'Make a dot'
        }, {
          block: 'box(green, 50);',
          title: 'Make a square'
        }, {
          block: 'write(\'hello\');',
          title: 'Write text on the screen'
        }, {
          block: 'label(\'hello\');',
          title: 'Write text at the turtle'
        }, {
          block: 'ht();',
          title: 'Hide the turtle'
        }, {
          block: 'st();',
          title: 'Show the turtle'
        }, {
          block: 'pu();',
          title: 'Pick the pen up'
        }, {
          block: 'pd();',
          title: 'Put the pen down'
        }, {
          block: 'pen(purple, 10);',
          title: 'Set the pen color and thickness'
        }, {
          block: 'rt(180, 100);',
          title: 'Make a wide right turn'
        }, {
          block: 'lt(180, 100);',
          title: 'Make a wide left turn'
        }, {
          block: 'slide(100, 20);',
          title: 'Slide sideways or diagonally'
        }, {
          block: 'jump(100, 20);',
          title: 'Jump without drawing'
        }, {
          block: 'play(\'GEC\');',
          title: 'Play music notes'
        }, {
          block: 'wear(\'/img/cat-icon\');',
          title: 'Change the turtle image'
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for (var i = 0; i < 4; i++) {\n  __;\n}',
          title: 'Do something multiple times'
        }, {
          block: 'if (__) {\n  __;\n}',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if (__) {\n  __;\n} else {\n  __;\n}',
          title: 'Do something if a condition is true, otherwise do something else'
        }, {
          block: 'while (__) {\n  __;\n}',
          title: 'Repeat something while a condition is true'
        }
      ]
    }, {
      name: 'Math',
      color: 'green',
      blocks: [
        {
          block: 'var x = __;',
          title: 'Create a variable for the first time'
        }, {
          block: 'x = __;',
          title: 'Reassign a variable'
        }, {
          block: '__ + __',
          title: 'Add two numbers'
        }, {
          block: '__ - __',
          title: 'Subtract two numbers'
        }, {
          block: '__ * __',
          title: 'Multiply two numbers'
        }, {
          block: '__ / __',
          title: 'Divide two numbers'
        }, {
          block: '__ === __',
          title: 'Compare two numbers'
        }, {
          block: '__ > __',
          title: 'Compare two numbers'
        }, {
          block: '__ < __',
          title: 'Compare two numbers'
        }, {
          block: 'random(1, 100)',
          title: 'Get a random number in a range'
        }, {
          block: 'round(__)',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs(__)',
          title: 'Absolute value'
        }, {
          block: 'max(__, __)',
          title: 'Absolute value'
        }, {
          block: 'min(__, __)',
          title: 'Absolute value'
        }
      ]
    }, {
      name: 'Functions',
      color: 'violet',
      blocks: [
        {
          block: 'function myFunction() {\n  __;\n}',
          title: 'Create a function without an argument'
        }, {
          block: 'function myFunction(n) {\n  __;\n}',
          title: 'Create a function with an argument'
        }, {
          block: 'myFunction()',
          title: 'Use a function without an argument'
        }, {
          block: 'myFunction(n)',
          title: 'Use a function with argument'
        }
      ]
    }
  ]
};

});
<commit_msg>Add a snippet menu<commit_after>define(function() {

return {

  // The following palette description
  // is copied from compiled CoffeeScript.
  COFFEESCRIPT_PALETTE: [
    {
      name: 'Move',
      color: 'red',
      blocks: [
        {
          block: 'fd 100',
          title: 'Move forward'
        }, {
          block: 'rt 90',
          title: 'Turn right'
        }, {
          block: 'lt 90',
          title: 'Turn left'
        }, {
          block: 'bk 100',
          title: 'Move backward'
        }, {
          block: 'rt 180, 100',
          title: 'Make a wide right arc'
        }, {
          block: 'lt 180, 100',
          title: 'Make a wide left arc'
        }, {
          block: 'speed 10',
          title: 'Set the speed of the turtle'
        }, {
          block: 'speed Infinity',
          title: 'Use infinite speed'
        }, {
          block: 'home()',
          title: 'Jump to the origin, turned up'
        }, {
          block: 'turnto 270',
          title: 'Turn to an absolute direction'
        }, {
          block: 'turnto lastclick',
          title: 'Turn toward a located object'
        }, {
          block: 'moveto 100, 50',
          title: 'Move to coordinates'
        }, {
          block: 'movexy 30, 20',
          title: 'Move by changing x and y'
        }, {
          block: 'move 10, 5',
          title: "Move sideways or diagonal from turtle's angle"
        }, {
          block: 'jumpto 100, 50',
          title: 'Jump to coordinates without drawing'
        }, {
          block: 'jumpxy 30, 20',
          title: 'Jump changing x and y without drawing'
        }, {
          block: 'jump 10, 5',
          title: "Move sideways or diagonal without drawing"
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for [1..3]\n  ``',
          title: 'Do something multiple times'
        }, {
          block: 'if `` is ``\n  ``',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if `` is ``\n  ``\nelse\n  ``',
          title: 'Do something if a condition is true, otherwise something else'
        }, {
          block: "tick 1, ->\n  write 'ticked'",
          title: 'Repeat something forever at qually-spaced times'
        }, {
          block: "button \'Click\', ->\n  write 'clicked'",
          title: 'Make a button and do something when clicked'
        }, {
          block: "keydown \'X\', ->\n  write 'x pressed'",
          title: 'Do something when a keyboard key is pressed'
        }, {
          block: "click (e) ->\n  moveto e",
          title: 'Move to a location when document is clicked'
        }
      ]
    }, {
      name: 'Looks',
      color: 'blue',
      blocks: [
         {
          block: 'pen purple, 10',
          title: 'Set pen color and size'
        }, {
          block: 'dot green, 50',
          title: 'Make a dot'
        }, {
          block: 'box yellow, 50',
          title: 'Make a square'
        }, {
          block: 'fill blue',
          title: 'Fill traced shape'
        }, {
          block: 'wear \'/img/apple\'',
          title: 'Use an image for the turtle'
        }, {
          block: 'scale 3',
          title: 'Scale turtle drawing'
        }, {
          block: 'ht()',
          title: 'Hide the main turtle'
        }, {
          block: 'st()',
          title: 'Show the main turtle'
        }, {
          block: 'cs()',
          title: 'Clear screen'
        }, {
          block: 'cg()',
          title: 'Clear graphics'
        }, {
          block: 'pu()',
          title: 'Lift the pen up'
        }, {
          block: 'pd()',
          title: 'Put the pen down'
        }, {
          block: 'drawon s',
          title: 'Draw on sprite s'
        }, {
          block: 'drawon document',
          title: 'Draw on the document'
        }
      ]
    }, {
      name: 'Operators',
      color: 'green',
      blocks: [
        {
          block: 'x = ``',
          title: 'Set a variable'
        }, {
          block: '`` is ``',
          title: 'Compare two values'
        }, {
          block: '`` < ``',
          title: 'Compare two values'
        }, {
          block: '`` > ``',
          title: 'Compare two values'
        }, {
          block: '`` + ``',
          title: 'Add two numbers'
        }, {
          block: '`` - ``',
          title: 'Subtract two numbers'
        }, {
          block: '`` * ``',
          title: 'Multiply two numbers'
        }, {
          block: '`` / ``',
          title: 'Divide two numbers'
        }, {
          block: 'random [1..100]',
          title: 'Get a random number in a range'
        }, {
          block: 'round ``',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs ``',
          title: 'Absolute value'
        }, {
          block: 'max ``, ``',
          title: 'Get the larger of two numbers'
        }, {
          block: 'min ``, ``',
          title: 'Get the smaller on two numbers'
        }, {
          block: 'x.match /pattern/',
          title: 'Test if a text pattern is found in x'
        }, {
          block: 'f = (x) ->\n  ``',
          title: 'Define a new function'
        }, {
          block: 'f(x)',
          title: 'Use a custom function'
        }
      ]
    }, {
      name: 'Text',
      color: 'yellow',
      blocks: [
        {
          block: 'write \'Hello.\'',
          title: 'Write text in the document'
        }, {
          block: 'type \'zz*(-.-)*zz\'',
          title: 'Typewrite text in the document'
        }, {
          block: 'label \'spot\'',
          title: 'Write text at the turtle'
        }, {
          block: 'read \'?\', (x) ->\n  write x',
          title: 'Read input from the user'
        }, {
          block: 'readnum \'?\', (x) ->\n  write x',
          title: 'Read a number from the user'
        }, {
          block: 'log [1..10]',
          title: 'Log an object to debug'
        }
      ]
    }, {
      name: 'Sprites',
      color: 'violet',
      blocks: [
        {
          block: 't = new Turtle red',
          title: 'Make a new turtle'
        }, {
          block: 's = new Sprite',
          title: 'Make a blank sprite'
        }, {
          block: 'p = new Piano',
          title: 'Make a visible insturment'
        }, {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }, {
          block: 'q = new Pencil',
          title: 'Make an invisible and fast drawing sprite'
        }
      ]
    }, {
      name: 'Sound',
      color: 'violet',
      blocks: [
        {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }
      ]
    }, {
      name: 'Snippets',
      color: 'yellow',
      blocks: [
        {
          block: 'p.play \'CDEDC\'',
          title: 'Play and show music notes'
        }
      ]
    }
  ],

  JAVASCRIPT_PALETTE: [
    {
      name: 'Draw',
      color: 'blue',
      blocks: [
        {
          block: 'pen(red);',
          title: 'Set the pen color'
        }, {
          block: 'fd(100);',
          title: 'Move forward'
        }, {
          block: 'rt(90);',
          title: 'Turn right'
        }, {
          block: 'lt(90);',
          title: 'Turn left'
        }, {
          block: 'bk(100);',
          title: 'Move backward'
        }, {
          block: 'speed(10);',
          title: 'Set the speed of the turtle'
        }, {
          block: 'dot(blue, 50);',
          title: 'Make a dot'
        }, {
          block: 'box(green, 50);',
          title: 'Make a square'
        }, {
          block: 'write(\'hello\');',
          title: 'Write text on the screen'
        }, {
          block: 'label(\'hello\');',
          title: 'Write text at the turtle'
        }, {
          block: 'ht();',
          title: 'Hide the turtle'
        }, {
          block: 'st();',
          title: 'Show the turtle'
        }, {
          block: 'pu();',
          title: 'Pick the pen up'
        }, {
          block: 'pd();',
          title: 'Put the pen down'
        }, {
          block: 'pen(purple, 10);',
          title: 'Set the pen color and thickness'
        }, {
          block: 'rt(180, 100);',
          title: 'Make a wide right turn'
        }, {
          block: 'lt(180, 100);',
          title: 'Make a wide left turn'
        }, {
          block: 'slide(100, 20);',
          title: 'Slide sideways or diagonally'
        }, {
          block: 'jump(100, 20);',
          title: 'Jump without drawing'
        }, {
          block: 'play(\'GEC\');',
          title: 'Play music notes'
        }, {
          block: 'wear(\'/img/cat-icon\');',
          title: 'Change the turtle image'
        }
      ]
    }, {
      name: 'Control',
      color: 'orange',
      blocks: [
        {
          block: 'for (var i = 0; i < 4; i++) {\n  __;\n}',
          title: 'Do something multiple times'
        }, {
          block: 'if (__) {\n  __;\n}',
          title: 'Do something only if a condition is true'
        }, {
          block: 'if (__) {\n  __;\n} else {\n  __;\n}',
          title: 'Do something if a condition is true, otherwise do something else'
        }, {
          block: 'while (__) {\n  __;\n}',
          title: 'Repeat something while a condition is true'
        }
      ]
    }, {
      name: 'Math',
      color: 'green',
      blocks: [
        {
          block: 'var x = __;',
          title: 'Create a variable for the first time'
        }, {
          block: 'x = __;',
          title: 'Reassign a variable'
        }, {
          block: '__ + __',
          title: 'Add two numbers'
        }, {
          block: '__ - __',
          title: 'Subtract two numbers'
        }, {
          block: '__ * __',
          title: 'Multiply two numbers'
        }, {
          block: '__ / __',
          title: 'Divide two numbers'
        }, {
          block: '__ === __',
          title: 'Compare two numbers'
        }, {
          block: '__ > __',
          title: 'Compare two numbers'
        }, {
          block: '__ < __',
          title: 'Compare two numbers'
        }, {
          block: 'random(1, 100)',
          title: 'Get a random number in a range'
        }, {
          block: 'round(__)',
          title: 'Round to the nearest integer'
        }, {
          block: 'abs(__)',
          title: 'Absolute value'
        }, {
          block: 'max(__, __)',
          title: 'Absolute value'
        }, {
          block: 'min(__, __)',
          title: 'Absolute value'
        }
      ]
    }, {
      name: 'Functions',
      color: 'violet',
      blocks: [
        {
          block: 'function myFunction() {\n  __;\n}',
          title: 'Create a function without an argument'
        }, {
          block: 'function myFunction(n) {\n  __;\n}',
          title: 'Create a function with an argument'
        }, {
          block: 'myFunction()',
          title: 'Use a function without an argument'
        }, {
          block: 'myFunction(n)',
          title: 'Use a function with argument'
        }
      ]
    }
  ]
};

});
<|endoftext|>


<commit_before>/**
 * BPM for Discord
 * (c) 2015-2016 ByzantineFailure
 *
 * Settings panel.  Sets up the tab in Discord settings, as well as
 * handling switching between subpanels.  Manages teardown.
 *
 * Subpanels are inserted into `subpanelMap` and are objects of the form:
 * {
 *   init: FUNCTION(subpanel_node),
 *   teardown: FUNCTION(subpanel_node),
 *   html: RAW_HTML_STRING
 * }
 *
 * The subpanel's key in the map should be the value of `data-bpmSubpanelMessage`
 * for its tab in `base-panel.html`
 *
 * When the subpanel is selected, `html` is set as the subpanel div's innerHTML
 * and `init` is called with the subpanel div's node passed to it.
 *
 * When the settings panel is closed or another subpanel is selected, `teardown`
 * is called with the subpanel div's node passed to it.
 **/

require('!style!css!./settings.css');

var BPM_utils = require('../utils.js'),
    basePanelHtml = require('raw!./html/base-panel.html'),
    emotes = require('./emotes.js'),
    general = require('./general.js'),
    subreddits = require('./subreddits.js'),
    search = require('./search.js'),
    updates = require('./updates.js'),
    about = require('./about.js');

//Maps subpanel requests to their corresponding init/teardown objects
var subpanelMap = {
    insert_general_settings: general,
    insert_emote_settings: emotes,
    insert_subreddit_settings: subreddits,
    insert_search_settings: search,
    insert_updates: updates,
    insert_about: about
};

var settingsObserver = new MutationObserver(function(mutations) {
    function addTabElement(tabBar) {
        var tabElement = document.createElement('div');
        tabElement.className = 'tab-bar-item';
        tabElement.innerHTML = 'BPM';
        tabElement.id = 'bpm-settings-tab-item';
        tabBar.appendChild(tabElement);
    }

    function addTabAndListeners(tabBar) {
        addTabElement(tabBar);
        var items = document.getElementsByClassName('tab-bar-item');
        Array.prototype.forEach.call(items, function(item) {
            item.addEventListener('click', function() {
                focusTabElement(item);
                showSettings(item.id == 'bpm-settings-tab-item');
            }, false);
        });
    }

    mutations.forEach(function(mutation) {
        if(mutation.type != 'childList' || mutation.addedNodes.length === 0) return;
        var addedNode = mutation.addedNodes[0];
        if(!addedNode.querySelector('div .user-settings-modal')) return;
        BPM_utils.waitForElementByClass('tab-bar SIDE', addTabAndListeners);
        BPM_utils.waitForElementByClass('settings-inner', injectSettingsPage);
    });
});

function injectSettingsPage(injectInto) {
    if(document.getElementById('bpm-settings-panel')) return;

    var toInject = document.createElement('div');
    toInject.className = 'scroller-wrap';
    toInject.id = 'bpm-settings-panel';
    toInject.style.display = 'none';
    toInject.innerHTML = basePanelHtml;

    injectInto.appendChild(toInject);

    addSubpanelSelectListeners();
}

//When we click done we should release all our listeners to avoid a memory leak
function addDoneClickListener(doneButton) {
    doneButton.addEventListener('click', function(e) {
        var settingElement = document.getElementById('bpm-settings-panel');
        if(settingElement) {
            settingElement.parent.removeChild(settingElement);
            //TODO: Also very ew
            var bpmTabs = BPM_utils.htmlCollectionToArray(document.getElementById('bpm-options-tab-list')
                                                .getElementsByClassName('tab-bar-item'));
            bpmTabs.forEach(function(tab) { tab.removeEventListener('click'); });
            var sidebarTabs = BPM_utils.htmlCollectionToArray(document.getElementsByClassName('tab-bar SIDE')[0]
                                                            .getElementsByClassName('tab-bar-item'));
            sidebarTabs.forEach(function(tab) { tab.removeEventListener('click'); });
            cleanSubpanel();
        }
        doneButton.removeEventListener('click', onDoneClick);
    });
}

//Initial setup for subpanels and their listeners
function addSubpanelSelectListeners() {
    var topTabs = document.getElementById('bpm-options-tab-list'),
        subpanelSelectors = BPM_utils.htmlCollectionToArray(topTabs.getElementsByTagName('div'));

    //TODO: WTF, ew
    var selected = subpanelSelectors.filter(function(selector) {
        return selector.className.indexOf('selected') > -1;
    })[0] || subpanelSelectors[0];

    selectSubpanel(selected, false);

    subpanelSelectors.forEach(function(selector) {
        selector.addEventListener('click', function() { selectSubpanel(selector, true); });
    });
}

//Clean listeners off of a subpanel
function cleanSubpanel() {
    var topTabs = document.getElementById('bpm-options-tab-list');
    var subpanelSelectors = BPM_utils.htmlCollectionToArray(topTabs.getElementsByTagName('div'));
    var selected = subpanelSelectors.filter(function(element) { return element.className.indexOf('selected') > -1; })[0];
    if(!selected) {
        console.log('BPM: called cleanSubpanel but could not find selected subpanel');
        return;
    }

    var content = document.getElementById('bpm-settings-subpanel');
    if(!content) {
        console.log('BPM: called cleanSubpanel without a subpanel present!');
            return;
    }

    var subpanel = getSubpanelFunctions(selected);
    subpanel.teardown(content);
}

function getSubpanelFunctions(selector) {
    return subpanelMap[selector.getAttribute('data-bpmSubpanelMessage')];
}

function selectSubpanel(selector, performTeardown) {
    var subpanelSelectors = BPM_utils.htmlCollectionToArray(selector.parentElement.getElementsByTagName('div')),
        injectTarget = document.getElementById('bpm-options-inject-target'),
        subpanel = getSubpanelFunctions(selector);

    if(performTeardown) {
        cleanSubpanel();
    }
    while(injectTarget.lastChild) {
        injectTarget.removeChild(injectTarget.lastChild);
    }

    var content = document.createElement('div');
    content.id = 'bpm-settings-subpanel';
    content.innerHTML = subpanel.html;
    injectTarget.appendChild(content);

    focusTabElement(selector);

    subpanel.init(content);
}

function focusTabElement(element) {
    var settingsItems = element.parentElement.getElementsByClassName('tab-bar-item');
    Array.prototype.forEach.call(settingsItems, function(item) {
        item.className = 'tab-bar-item';
    });
    element.className += ' selected';
}

function showSettings(display) {
    var settingsInner = document.getElementsByClassName('settings-inner')[0];
    if(!settingsInner) {
        console.log('BPM: Called showSettings when settingsInner does not exist!');
        return;
    }
    BPM_utils.waitForElementById('bpm-settings-panel', toggleSettingsDisplay);
    function toggleSettingsDisplay(settings) {
        if(display) {
            settingsInner.firstChild.style.display = 'none';
            settings.style.display = 'flex';
        } else {
            settingsInner.firstChild.style.display = 'flex';
            settings.style.display = 'none';
        }
    }
}

/*
 Old Implementation -- I'm keeping this around because I'd like to be able to
 quickly revert to it in the event the new MutationObserver version is subtly broken.

function injectBpmSettingsPanel(settingsButton) {
    function addTabElement(tabBar) {
        var tabElement = document.createElement('div');
        tabElement.className = 'tab-bar-item';
        tabElement.innerHTML = 'BPM';
        tabElement.id = 'bpm-settings-tab-item';
        tabBar.appendChild(tabElement);
    }

    function addTabAndListeners(tabBar) {
        addTabElement(tabBar);
        var items = document.getElementsByClassName('tab-bar-item');
        Array.prototype.forEach.call(items, function(item) {
            item.addEventListener('click', function() {
                focusTabElement(item);
                showSettings(item.id == 'bpm-settings-tab-item');
            }, false);
        });
    }

    settingsButton.addEventListener('click', function() {
        BPM_utils.waitForElementByClass('tab-bar SIDE', addTabAndListeners);
        BPM_utils.waitForElementByClass('settings-inner', injectSettingsPage);
    });
}

BPM_utils.waitForElementByClass('btn btn-settings', injectBpmSettingsPanel);
*/

//Not exactly the greatest way to do this, need to figure out some non-timeout based
//way to ensure we have the modal spans
BPM_utils.waitForElementByClass('tooltips', function(tooltips) {
    window.setTimeout(function(){
        var modalSpans = document.querySelectorAll('div[data-reactroot] > span');
        var observerConfig = {
            childList: true,
            attributes: false,
            characterData: false
        };
        Array.prototype.forEach.call(modalSpans, function(span) {
            settingsObserver.observe(span, observerConfig);
        });
    }, 100);
});

<commit_msg>Fix BD settings not appearing<commit_after>/**
 * BPM for Discord
 * (c) 2015-2016 ByzantineFailure
 *
 * Settings panel.  Sets up the tab in Discord settings, as well as
 * handling switching between subpanels.  Manages teardown.
 *
 * Subpanels are inserted into `subpanelMap` and are objects of the form:
 * {
 *   init: FUNCTION(subpanel_node),
 *   teardown: FUNCTION(subpanel_node),
 *   html: RAW_HTML_STRING
 * }
 *
 * The subpanel's key in the map should be the value of `data-bpmSubpanelMessage`
 * for its tab in `base-panel.html`
 *
 * When the subpanel is selected, `html` is set as the subpanel div's innerHTML
 * and `init` is called with the subpanel div's node passed to it.
 *
 * When the settings panel is closed or another subpanel is selected, `teardown`
 * is called with the subpanel div's node passed to it.
 **/

require('!style!css!./settings.css');

var BPM_utils = require('../utils.js'),
    basePanelHtml = require('raw!./html/base-panel.html'),
    emotes = require('./emotes.js'),
    general = require('./general.js'),
    subreddits = require('./subreddits.js'),
    search = require('./search.js'),
    updates = require('./updates.js'),
    about = require('./about.js');

//Maps subpanel requests to their corresponding init/teardown objects
var subpanelMap = {
    insert_general_settings: general,
    insert_emote_settings: emotes,
    insert_subreddit_settings: subreddits,
    insert_search_settings: search,
    insert_updates: updates,
    insert_about: about
};

var settingsObserver = new MutationObserver(function(mutations) {
    function addTabElement(tabBar) {
        var tabElement = document.createElement('div');
        tabElement.className = 'tab-bar-item';
        tabElement.innerHTML = 'BPM';
        tabElement.id = 'bpm-settings-tab-item';
        tabBar.appendChild(tabElement);
    }

    function addTabAndListeners(tabBar) {
        addTabElement(tabBar);
        var items = document.getElementsByClassName('tab-bar-item');
        Array.prototype.forEach.call(items, function(item) {
            item.addEventListener('click', function() {
                focusTabElement(item);
                showSettings(item.id == 'bpm-settings-tab-item');
            }, false);
        });
    }

    mutations.forEach(function(mutation) {
        if(mutation.type != 'childList' || mutation.addedNodes.length === 0) {
            return;
        }
        var addedNode = mutation.addedNodes[0];
        if(!addedNode.querySelector || !addedNode.querySelector('.user-settings-modal')) {
            return;
        }
        BPM_utils.waitForElementByClass('tab-bar SIDE', addTabAndListeners);
        BPM_utils.waitForElementByClass('settings-inner', injectSettingsPage);
    });
});

function injectSettingsPage(injectInto) {
    if(document.getElementById('bpm-settings-panel')) return;

    var toInject = document.createElement('div');
    toInject.className = 'scroller-wrap';
    toInject.id = 'bpm-settings-panel';
    toInject.style.display = 'none';
    toInject.innerHTML = basePanelHtml;

    injectInto.appendChild(toInject);

    addSubpanelSelectListeners();
}

//When we click done we should release all our listeners to avoid a memory leak
function addDoneClickListener(doneButton) {
    doneButton.addEventListener('click', function(e) {
        var settingElement = document.getElementById('bpm-settings-panel');
        if(settingElement) {
            settingElement.parent.removeChild(settingElement);
            //TODO: Also very ew
            var bpmTabs = BPM_utils.htmlCollectionToArray(document.getElementById('bpm-options-tab-list')
                                                .getElementsByClassName('tab-bar-item'));
            bpmTabs.forEach(function(tab) { tab.removeEventListener('click'); });
            var sidebarTabs = BPM_utils.htmlCollectionToArray(document.getElementsByClassName('tab-bar SIDE')[0]
                                                            .getElementsByClassName('tab-bar-item'));
            sidebarTabs.forEach(function(tab) { tab.removeEventListener('click'); });
            cleanSubpanel();
        }
        doneButton.removeEventListener('click', onDoneClick);
    });
}

//Initial setup for subpanels and their listeners
function addSubpanelSelectListeners() {
    var topTabs = document.getElementById('bpm-options-tab-list'),
        subpanelSelectors = BPM_utils.htmlCollectionToArray(topTabs.getElementsByTagName('div'));

    //TODO: WTF, ew
    var selected = subpanelSelectors.filter(function(selector) {
        return selector.className.indexOf('selected') > -1;
    })[0] || subpanelSelectors[0];

    selectSubpanel(selected, false);

    subpanelSelectors.forEach(function(selector) {
        selector.addEventListener('click', function() { selectSubpanel(selector, true); });
    });
}

//Clean listeners off of a subpanel
function cleanSubpanel() {
    var topTabs = document.getElementById('bpm-options-tab-list');
    var subpanelSelectors = BPM_utils.htmlCollectionToArray(topTabs.getElementsByTagName('div'));
    var selected = subpanelSelectors.filter(function(element) { return element.className.indexOf('selected') > -1; })[0];
    if(!selected) {
        console.log('BPM: called cleanSubpanel but could not find selected subpanel');
        return;
    }

    var content = document.getElementById('bpm-settings-subpanel');
    if(!content) {
        console.log('BPM: called cleanSubpanel without a subpanel present!');
            return;
    }

    var subpanel = getSubpanelFunctions(selected);
    subpanel.teardown(content);
}

function getSubpanelFunctions(selector) {
    return subpanelMap[selector.getAttribute('data-bpmSubpanelMessage')];
}

function selectSubpanel(selector, performTeardown) {
    var subpanelSelectors = BPM_utils.htmlCollectionToArray(selector.parentElement.getElementsByTagName('div')),
        injectTarget = document.getElementById('bpm-options-inject-target'),
        subpanel = getSubpanelFunctions(selector);

    if(performTeardown) {
        cleanSubpanel();
    }
    while(injectTarget.lastChild) {
        injectTarget.removeChild(injectTarget.lastChild);
    }

    var content = document.createElement('div');
    content.id = 'bpm-settings-subpanel';
    content.innerHTML = subpanel.html;
    injectTarget.appendChild(content);

    focusTabElement(selector);

    subpanel.init(content);
}

function focusTabElement(element) {
    var settingsItems = element.parentElement.getElementsByClassName('tab-bar-item');
    Array.prototype.forEach.call(settingsItems, function(item) {
        item.className = 'tab-bar-item';
    });
    element.className += ' selected';
}

function showSettings(display) {
    var settingsInner = document.getElementsByClassName('settings-inner')[0];
    if(!settingsInner) {
        console.log('BPM: Called showSettings when settingsInner does not exist!');
        return;
    }
    BPM_utils.waitForElementById('bpm-settings-panel', toggleSettingsDisplay);
    function toggleSettingsDisplay(settings) {
        if(display) {
            settingsInner.firstChild.style.display = 'none';
            settings.style.display = 'flex';
        } else {
            settingsInner.firstChild.style.display = 'flex';
            settings.style.display = 'none';
        }
    }
}

/*
 Old Implementation -- I'm keeping this around because I'd like to be able to
 quickly revert to it in the event the new MutationObserver version is subtly broken.

function injectBpmSettingsPanel(settingsButton) {
    function addTabElement(tabBar) {
        var tabElement = document.createElement('div');
        tabElement.className = 'tab-bar-item';
        tabElement.innerHTML = 'BPM';
        tabElement.id = 'bpm-settings-tab-item';
        tabBar.appendChild(tabElement);
    }

    function addTabAndListeners(tabBar) {
        addTabElement(tabBar);
        var items = document.getElementsByClassName('tab-bar-item');
        Array.prototype.forEach.call(items, function(item) {
            item.addEventListener('click', function() {
                focusTabElement(item);
                showSettings(item.id == 'bpm-settings-tab-item');
            }, false);
        });
    }

    settingsButton.addEventListener('click', function() {
        BPM_utils.waitForElementByClass('tab-bar SIDE', addTabAndListeners);
        BPM_utils.waitForElementByClass('settings-inner', injectSettingsPage);
    });
}

BPM_utils.waitForElementByClass('btn btn-settings', injectBpmSettingsPanel);
*/

//Not exactly the greatest way to do this, need to figure out some non-timeout based
//way to ensure we have the modal spans.
//I don't like the shotgun approach here (all subtree changes to the approot) but
//after BD broke I can't find a better way
BPM_utils.waitForElementById('app-mount', function(mount) {
    window.setTimeout(function(){
        var observerConfig = {
                childList: true,
                subtree: true,
                attributes: false,
                characterData: false
            },
            reactRoot = document.querySelector('div[data-reactroot]');

        settingsObserver.observe(reactRoot, observerConfig);
    }, 100);
});

<|endoftext|>


<commit_before>// entry point
(function() {

    var root = this;

    var cdb = root.cdb = {};

    cdb.VERSION = '2.0.0';

    cdb.CARTOCSS_VERSIONS = {
      '2.0.0': '',
      '2.1.0': ''
    };

    cdb.CARTOCSS_DEFAULT_VERSION = '2.0.0';

    cdb.CDB_HOST = {
      'http': 'tiles.cartocdn.com',
      'https': 'd3pu9mtm6f0hk5.cloudfront.net'
    };

    root.cdb.config = {};
    root.cdb.core = {};
    root.cdb.geo = {};
    root.cdb.geo.ui = {};
    root.cdb.geo.geocoder = {};
    root.cdb.ui = {};
    root.cdb.ui.common = {};
    root.cdb.vis = {};
    root.cdb.decorators = {};
    /**
     * global variables
     */
    root.JST = root.JST || {};
    root.cartodb = cdb;

    cdb.files = [
        "../vendor/jquery.min.js",
        "../vendor/underscore-min.js",
        "../vendor/backbone.js",

        "../vendor/leaflet.js",
        "../vendor/wax.leaf.js",
        "../vendor/wax.g.js",
        "../vendor/GeoJSON.js", //geojson gmaps lib

        "../vendor/jscrollpane.js",
        "../vendor/mousewheel.js",
        "../vendor/mwheelIntent.js",

        'core/decorator.js',
        'core/config.js',
        'core/log.js',
        'core/profiler.js',
        'core/template.js',
        'core/model.js',
        'core/view.js',
        'core/sql.js',

        'geo/geocoder.js',
        'geo/geometry.js',
        'geo/map.js',
        'geo/ui/zoom.js',
        'geo/ui/legend.js',
        'geo/ui/switcher.js',
        'geo/ui/infowindow.js',
        'geo/ui/header.js',
        'geo/ui/search.js',

        'geo/common.js',

        'geo/leaflet/leaflet.geometry.js',
        'geo/leaflet/leaflet_base.js',
        'geo/leaflet/leaflet_plainlayer.js',
        'geo/leaflet/leaflet_tiledlayer.js',
        'geo/leaflet/leaflet_cartodb_layer.js',
        'geo/leaflet/leaflet.js',

        'geo/gmaps/gmaps_base.js',
        'geo/gmaps/gmaps_baselayer.js',
        'geo/gmaps/gmaps_plainlayer.js',
        'geo/gmaps/gmaps_tiledlayer.js',
        'geo/gmaps/gmaps_cartodb_layer.js',
        'geo/gmaps/gmaps.js',

        'ui/common/dialog.js',
        'ui/common/notification.js',
        'ui/common/table.js',

        'vis/vis.js',
        'vis/overlays.js',
        'vis/layers.js',

        // PUBLIC API
        'api/layers.js'
    ];

    cdb.init = function(ready) {
      // define a simple class
      var Class = cdb.Class = function() {};
      _.extend(Class.prototype, Backbone.Events);

      cdb._loadJST();
      root.cdb.god = new Backbone.Model();

      ready && ready();
    };

    /**
     * load all the javascript files. For testing, do not use in production
     */
    cdb.load = function(prefix, ready) {
        var c = 0;

        var next = function() {
            var script = document.createElement('script');
            script.src = prefix + cdb.files[c];
            document.body.appendChild(script);
            ++c;
            if(c == cdb.files.length) {
                if(ready) {
                    script.onload = ready;
                }
            } else {
                script.onload = next;
            }
        };

        next();

    };
})();
<commit_msg>added sql.js to files<commit_after>// entry point
(function() {

    var root = this;

    var cdb = root.cdb = {};

    cdb.VERSION = '2.0.0';

    cdb.CARTOCSS_VERSIONS = {
      '2.0.0': '',
      '2.1.0': ''
    };

    cdb.CARTOCSS_DEFAULT_VERSION = '2.0.0';

    cdb.CDB_HOST = {
      'http': 'tiles.cartocdn.com',
      'https': 'd3pu9mtm6f0hk5.cloudfront.net'
    };

    root.cdb.config = {};
    root.cdb.core = {};
    root.cdb.geo = {};
    root.cdb.geo.ui = {};
    root.cdb.geo.geocoder = {};
    root.cdb.ui = {};
    root.cdb.ui.common = {};
    root.cdb.vis = {};
    root.cdb.decorators = {};
    /**
     * global variables
     */
    root.JST = root.JST || {};
    root.cartodb = cdb;

    cdb.files = [
        "../vendor/jquery.min.js",
        "../vendor/underscore-min.js",
        "../vendor/backbone.js",

        "../vendor/leaflet.js",
        "../vendor/wax.leaf.js",
        "../vendor/wax.g.js",
        "../vendor/GeoJSON.js", //geojson gmaps lib

        "../vendor/jscrollpane.js",
        "../vendor/mousewheel.js",
        "../vendor/mwheelIntent.js",

        'core/decorator.js',
        'core/config.js',
        'core/log.js',
        'core/profiler.js',
        'core/template.js',
        'core/model.js',
        'core/view.js',
        'core/sql.js',

        'geo/geocoder.js',
        'geo/geometry.js',
        'geo/map.js',
        'geo/ui/zoom.js',
        'geo/ui/legend.js',
        'geo/ui/switcher.js',
        'geo/ui/infowindow.js',
        'geo/ui/header.js',
        'geo/ui/search.js',

        'geo/common.js',

        'geo/leaflet/leaflet.geometry.js',
        'geo/leaflet/leaflet_base.js',
        'geo/leaflet/leaflet_plainlayer.js',
        'geo/leaflet/leaflet_tiledlayer.js',
        'geo/leaflet/leaflet_cartodb_layer.js',
        'geo/leaflet/leaflet.js',

        'geo/gmaps/gmaps_base.js',
        'geo/gmaps/gmaps_baselayer.js',
        'geo/gmaps/gmaps_plainlayer.js',
        'geo/gmaps/gmaps_tiledlayer.js',
        'geo/gmaps/gmaps_cartodb_layer.js',
        'geo/gmaps/gmaps.js',

        'ui/common/dialog.js',
        'ui/common/notification.js',
        'ui/common/table.js',

        'vis/vis.js',
        'vis/overlays.js',
        'vis/layers.js',

        // PUBLIC API
        'api/layers.js',
        'api/sql.js'
    ];

    cdb.init = function(ready) {
      // define a simple class
      var Class = cdb.Class = function() {};
      _.extend(Class.prototype, Backbone.Events);

      cdb._loadJST();
      root.cdb.god = new Backbone.Model();

      ready && ready();
    };

    /**
     * load all the javascript files. For testing, do not use in production
     */
    cdb.load = function(prefix, ready) {
        var c = 0;

        var next = function() {
            var script = document.createElement('script');
            script.src = prefix + cdb.files[c];
            document.body.appendChild(script);
            ++c;
            if(c == cdb.files.length) {
                if(ready) {
                    script.onload = ready;
                }
            } else {
                script.onload = next;
            }
        };

        next();

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


<commit_before>import Audio from './audio';
import Battle from './battle';
import Input from './input';
import Screen from './screen';
import Title from './title';

export default class Game {
    constructor() {
        this.screen = new Screen();
        this.input = new Input();
        Audio.play();

        this.tutorial = true;
        this.currentState = new Title();
    }

    start() {
        setInterval(this.update.bind(this), 1000 / 30);
    }

    update() {
        this.currentState.update(this);
        this.draw();
        if (this.input.hasKey(84)) {
            this.input.handleKey(84);
            Audio.isPlaying ? Audio.stop() : Audio.play();
        }
    }

    draw() {
        this.screen.reset();
        this.currentState.draw(this.screen);
    }

    startBattle() {
        this.currentState = new Battle(this, this.tutorial);
    }
}
<commit_msg>use requestAnimationFrame<commit_after>import Audio from './audio';
import Battle from './battle';
import Input from './input';
import Screen from './screen';
import Title from './title';

export default class Game {
    constructor() {
        this.screen = new Screen();
        this.input = new Input();
        Audio.play();

        this.tutorial = true;
        this.currentState = new Title();
    }

    start() {
        setInterval(this.update.bind(this), 1000 / 30);
    }

    update() {
        this.currentState.update(this);
        requestAnimationFrame(() => this.draw());
        if (this.input.hasKey(84)) {
            this.input.handleKey(84);
            Audio.isPlaying ? Audio.stop() : Audio.play();
        }
    }

    draw() {
        this.screen.reset();
        this.currentState.draw(this.screen);
    }

    startBattle() {
        this.currentState = new Battle(this, this.tutorial);
    }
}
<|endoftext|>


<commit_before>$(function(){
  if(Mutiny.options.initOnReady) {
    Mutiny.init();
  }
});

var Mutiny = window.Mutiny = {
  options: {
    initOnReady: true
  },

  widgets: {},

  init: function($es, namespace) {
    namespace = namespace || 'mutiny';

    var filter = function($es, arg) {
      return $es ? $es.filter(arg) : $(arg);
    };

    var mutiny_call = function($instigator, widget_name, instance_options) {
      /* Deprecated: Mutiny.<widget_name> should be Mutiny.widgets.<widget_name> */
      var widget = Mutiny.widgets[widget_name] || Mutiny[widget_name];
      if(widget === undefined) {
        throw '"' + widget_name + '" not found';
      }

      var options = $.extend({}, widget.defaults);
      if(isString(instance_options)) {
        /* Deprecated: <widget>.string_arg should be <widget>.stringArg */
        if(widget.string_arg) {
          options[widget.string_arg] = instance_options;
        } else if(widget.stringArg) {
          options[widget.stringArg] = instance_options;
        } else {
          throw '"' + widget_name + '" cannot parse "' + instance_options + '"';
        }
      } else {
        $.extend(options, instance_options);
      }
      widget.init($instigator, options);
    };

    filter($es, '[data-' + namespace + ']').each(function(i, e) {
      var $e = $(e);
      var data = $e.data();
      /* Deprecated.  data-mutiny="widget" should be data-mutiny-widget="" */
      if(namespace in data) {
        var directives = data[namespace];
        if(isString(directives)) {
          /* data-mutiny='slider' */
          mutiny_call($e, directives, {});
        } else if(typeof data === 'object') {
          /* data-mutiny='{"slider": {"some": "options"}}' */
          for(var directive in directives) {
            mutiny_call($e, directive, directives[directive]);
          }
        } else {
          throw 'Unsupported data';
        }
      }
    });

    var capitalize = function(string) {
      return string.charAt(0).toUpperCase() + string.slice(1);
    };

    var queries = [];
    for(var name in Mutiny.widgets) {
      queries.push('[data-' + namespace + '-' + name + ']');
    }
    var $widgetable = filter($es, queries.join(','));
    for(var i=0; i < $widgetable.length; i++) {
      var $e = $($widgetable[i]);
      var data = $e.data();
      for(var key in data) {
        if(key.indexOf(namespace) === 0) {
          var widget = key.replace(namespace, '').toLowerCase();
          var options = data[key];
          mutiny_call($e, widget, options || {});
        }
      }
    }
  }
};
<commit_msg>Refactored inner functions outwards<commit_after>$(function(){
  if(Mutiny.options.initOnReady) {
    Mutiny.init();
  }
});

var Mutiny = window.Mutiny = {
  options: {
    initOnReady: true
  },

  widgets: {},

  init: function($es, namespace) {
    namespace = namespace || 'mutiny';

    /* Deprecated.  data-mutiny="widget" should be data-mutiny-widget="" */
    filter($es, '[data-' + namespace + ']').each(function(i, e) {
      var $e = $(e);
      var data = $e.data();
      if(namespace in data) {
        var directives = data[namespace];
        if(isString(directives)) {
          /* data-mutiny='slider' */
          mutinyCall($e, directives, {});
        } else if(typeof data === 'object') {
          /* data-mutiny='{"slider": {"some": "options"}}' */
          for(var directive in directives) {
            mutinyCall($e, directive, directives[directive]);
          }
        } else {
          throw 'Unsupported data';
        }
      }
    });

    var queries = [];
    for(var name in Mutiny.widgets) {
      queries.push('[data-' + namespace + '-' + name + ']');
    }
    var $needWidgets = filter($es, queries.join(','));
    for(var i=0; i < $needWidgets.length; i++) {
      var $e = $($needWidgets[i]);
      var data = $e.data();
      for(var key in data) {
        if(key.indexOf(namespace) === 0) {
          var widget = lowerCaseFirst(key.replace(namespace, ''));
          mutinyCall($e, widget, data[key]);
        }
      }
    }
  }
};

var filter = function($es, arg) {
  return $es ? $es.filter(arg) : $(arg);
};

var mutinyCall = function($instigator, widget_name, options) {
  /* Deprecated: Mutiny.<widget_name> should be Mutiny.widgets.<widget_name> */
  var widget = Mutiny.widgets[widget_name] || Mutiny[widget_name];
  if(widget === undefined) {
    throw '"' + widget_name + '" not found';
  }

  var instanceOptions = {};
  if(!options) {
  } else if(isString(options)) {
    /* Deprecated: <widget>.string_arg should be <widget>.stringArg */
    if(widget.string_arg) {
      instanceOptions[widget.string_arg] = options;
    } else if(widget.stringArg) {
      instanceOptions[widget.stringArg] = options;
    } else {
      throw '"' + widget_name + '" cannot parse "' + options + '"';
    }
  } else {
    instanceOptions = options;
  }

  widget.init($instigator, $.extend({}, widget.defaults, instanceOptions));
};

var lowerCaseFirst = function(string) {
  return string.charAt(0).toLowerCase() + string.slice(1);
};
<|endoftext|>


<commit_before>// ebay active request for synchronization
// ebay webhook handler
"use strict";

var builder = require('xmlbuilder');
var parser = require('xml2js');
var router = require('express').Router();
const {eBayClient, ShopifyClient} = require('./client.js');

/**
 * webhook handler for item deletion from shopify
 * 1. should check if the item has been deleted from ebay already
 * 2. if not, delete it from ebay
 **/
router.get('/deleteItemCallback/shopify', (req, res, next) => {
    var ebayClient = new ebayClient('dsadasdasd');
    ebayClient.delete('dasjkdgasjhdgjhasgdhja')
    .then((result) => {
        console.log("yeah, deleted!");
    })
})

function ebay_changeQuantity(itemid,quantity,res){
	//var res;
	var xmlbdy = {
		'ReviseItemRequest':{
			'@xmlns':  "urn:ebay:apis:eBLBaseComponents",
			'ErrorLanguage' : 'en_US',
			'WarningLevel' : 'High',
			'item' :{
				'ItemID': itemid,
				'Quantity': quantity
			}
		}
	};

	var xml = builder.create(xmlbdy,{encoding: 'utf-8'});
	var str = xml.end({pretty:true});
	console.log(str);
	var ebayclient = new eBayClient('testuser_shuangzhang','SOAP');

	return ebayclient.post('ReviseItem',str)
	.then((result) => {
        //console.log(result);
		parser.parseString(result,function(err,resdata){
			console.dir(resdata);
			if(resdata.ReviseItemResponse.Ack[0]=="Success"||resdata.ReviseItemResponse.Ack[0]=="Warning"){console.log("Item revision succeeded");
				res.status(200).send("Item with id " +itemid + " revision succeeded. New quantity is now " + quantity);
			}
			else{res.status(200).send("Item with id " +itemid + " revision failed.");}
			//res=resdata.ReviseItemResponse.Ack[0];

		});

    }).catch((err) => {
        console.log(err);
    });
	//return res;

}

function ebay_getItem(itemid,res){
	var xmlbdy = {
		'GetItemRequest' : {
			'@xmlns':  "urn:ebay:apis:eBLBaseComponents",
			'ErrorLanguage' : 'en_US',
			'WarningLevel' : 'High',
			'ItemID' : itemid
		}
	};
	var xml = builder.create(xmlbdy,{encoding: 'utf-8'});
	var str = xml.end({pretty:true});
	console.log(str);
	var ebayclient = new eBayClient('testuser_shuangzhang','SOAP');
	return ebayclient.post('GetItem',str)
	.then((result) => {

		parser.parseString(result,function(err,resdata){
			console.dir(resdata);
			if(resdata.GetItemResponse.Ack[0]=="Success"||resdata.GetItemResponse.Ack[0]=="Warning"){console.log("Item retrieve succeeded");
				res.status(200).send("Item with id " +itemid + " retrieve succeeded. Quantity is now " + resdata.GetItemResponse.Item[0].Quantity[0] );
				//console.dir(resdata.GetItemResponse.Item[0].Quantity[0]);
				//can do something with the quantity here call to revise the quantity on shopify for example
			}
			else{res.status(200).send("Item with id " +itemid + " retrieve failed.");}

		});

    }).catch((err) => {
        console.log(err);
    });
}

function ebay_endItem(itemid,res){
	var xmlbdy = {
		'EndItemRequest' : {
			'@xmlns':  "urn:ebay:apis:eBLBaseComponents",
			'ErrorLanguage' : 'en_US',
			'WarningLevel' : 'High',
			'ItemID' : itemid,
			'EndingReason' : 'NotAvailable'
		}
	};
	var xml = builder.create(xmlbdy,{encoding: 'utf-8'});
	var str = xml.end({pretty:true});
	console.log(str);
	var ebayclient = new eBayClient('testuser_shuangzhang','SOAP');
	return ebayclient.post('EndItem',str)
	.then((result) => {

		parser.parseString(result,function(err,resdata){
			console.dir(resdata);
			if(resdata.EndItemResponse.Ack[0]=="Success"||resdata.EndItemResponse.Ack[0]=="Warning"){console.log("Item retrieve succeeded");
				res.status(200).send("Item with id " + itemid + " ended successfully." );
				//console.dir(resdata.GetItemResponse.Item[0].Quantity[0]);
				//can do something with the quantity here call to revise the quantity on shopify for example
			}
			else{res.status(200).send("Item with id " +itemid + " failed to end.");}

		});

    }).catch((err) => {
        console.log(err);
    });

}

router.get('/testEndItemQuantity/ebay/:itemid',(req,res,err) =>{
	var itemid = req.params.itemid;
	ebay_endItem(itemid,res);
});

router.get('/testGetItemQuantity/ebay/:itemid',(req,res,err) =>{
	var itemid = req.params.itemid;
	ebay_getItem(itemid,res);
});

router.get('/testReviseItemQuantity/ebay/:itemid/:newquantity',(req,res,err) =>{
	var itemid = req.params.itemid;
	var newquantity = req.params.newquantity;

	ebay_changeQuantity(itemid,newquantity,res);
/* 	.then((result)=>{
		console.log(result);
		if(result=="Success"||result=="Warning"){
				res.status(200).send("Item revision succeeded.");
		}
		else{
				res.status(200).send("Item revision failed.");
		}

	}); */

});

router.get('/testInventoryItem/ebay',(req,res,err) => {
	var ebayclient = new eBayClient('testuser_shuangzhang','SOAP');

var test = {
	'GetSellerListRequest':{
		'@xmlns':  'urn:ebay:apis:eBLBaseComponents',
		'ErrorLanguage' : 'en_US',
		'WarningLevel' : 'High',
		'GranularityLevel' : 'Coarse',
		'StartTimeFrom' : '2017-05-01T21:59:59.005Z',
		'StartTimeTo' : '2017-05-10T21:59:59.005Z',
		'IncludeWatchCount' : true,
		'Pagination' :{
			'EntriesPerPage' : 2
		}
	}
};
	var xml = builder.create(test,{encoding: 'utf-8'});
	//console.log(JSON.stringify(xml.end({pretty:true,indent: ' ',newline : '\n'})));
	var str = xml.end({pretty:true,indent: ' ',newline : '\n'});
	//str = str.substring(1,str.length-1);
	//str.replace(/\\"/g, '\"');
	console.log(str);
	//ebayclient.get('sell/inventory/v1/inventory_item')
    ebayclient.post('GetSellerList',str)
	.then((result) => {
        //console.log(result);
		parser.parseString(result,function(err,resdata){
			console.dir(resdata);
			res.status(200).send(resdata);

		});

    }).catch((err) => {
        console.log(err);
    });

});

/**
 * webhook handler for item deletion from ebay
 * 1. should check if the item has been deleted from shopify already
 * 2. if not, delete it from ebay
 **/
router.get('/deleteItemCallback/ebay', (req, res, next) => {

})

module.exports = router;
<commit_msg>Update with get only active items api<commit_after>// ebay active request for synchronization
// ebay webhook handler
"use strict";

var builder = require('xmlbuilder');
var parser = require('xml2js');
var router = require('express').Router();
const {eBayClient, ShopifyClient} = require('./client.js');

/**
 * webhook handler for item deletion from shopify
 * 1. should check if the item has been deleted from ebay already
 * 2. if not, delete it from ebay
 **/
router.get('/deleteItemCallback/shopify', (req, res, next) => {
    var ebayClient = new ebayClient('dsadasdasd');
    ebayClient.delete('dasjkdgasjhdgjhasgdhja')
    .then((result) => {
        console.log("yeah, deleted!");
    })
})

function ebay_changeQuantity(itemid,quantity,res){
	//var res;
	var xmlbdy = {
		'ReviseItemRequest':{
			'@xmlns':  "urn:ebay:apis:eBLBaseComponents",
			'ErrorLanguage' : 'en_US',
			'WarningLevel' : 'High',
			'item' :{
				'ItemID': itemid,
				'Quantity': quantity
			}
		}
	};

	var xml = builder.create(xmlbdy,{encoding: 'utf-8'});
	var str = xml.end({pretty:true});
	console.log(str);
	var ebayclient = new eBayClient('testuser_shuangzhang','SOAP');

	return ebayclient.post('ReviseItem',str)
	.then((result) => {
        //console.log(result);
		parser.parseString(result,function(err,resdata){
			console.dir(resdata);
			if(resdata.ReviseItemResponse.Ack[0]=="Success"||resdata.ReviseItemResponse.Ack[0]=="Warning"){console.log("Item revision succeeded");
				res.status(200).send("Item with id " +itemid + " revision succeeded. New quantity is now " + quantity);
			}
			else{res.status(200).send("Item with id " +itemid + " revision failed.");}
			//res=resdata.ReviseItemResponse.Ack[0];

		});

    }).catch((err) => {
        console.log(err);
    });
	//return res;

}

function ebay_getItem(itemid,res){
	var xmlbdy = {
		'GetItemRequest' : {
			'@xmlns':  "urn:ebay:apis:eBLBaseComponents",
			'ErrorLanguage' : 'en_US',
			'WarningLevel' : 'High',
			'ItemID' : itemid
		}
	};
	var xml = builder.create(xmlbdy,{encoding: 'utf-8'});
	var str = xml.end({pretty:true});
	console.log(str);
	var ebayclient = new eBayClient('testuser_shuangzhang','SOAP');
	return ebayclient.post('GetItem',str)
	.then((result) => {

		parser.parseString(result,function(err,resdata){
			console.dir(resdata);
			if(resdata.GetItemResponse.Ack[0]=="Success"||resdata.GetItemResponse.Ack[0]=="Warning"){console.log("Item retrieve succeeded");
				res.status(200).send("Item with id " +itemid + " retrieve succeeded. Quantity is now " + resdata.GetItemResponse.Item[0].Quantity[0] );
				//console.dir(resdata.GetItemResponse.Item[0].Quantity[0]);
				//can do something with the quantity here call to revise the quantity on shopify for example
			}
			else{res.status(200).send("Item with id " +itemid + " retrieve failed.");}

		});

    }).catch((err) => {
        console.log(err);
    });
}

function ebay_endItem(itemid,res){
	var xmlbdy = {
		'EndItemRequest' : {
			'@xmlns':  "urn:ebay:apis:eBLBaseComponents",
			'ErrorLanguage' : 'en_US',
			'WarningLevel' : 'High',
			'ItemID' : itemid,
			'EndingReason' : 'NotAvailable'
		}
	};
	var xml = builder.create(xmlbdy,{encoding: 'utf-8'});
	var str = xml.end({pretty:true});
	console.log(str);
	var ebayclient = new eBayClient('testuser_shuangzhang','SOAP');
	return ebayclient.post('EndItem',str)
	.then((result) => {

		parser.parseString(result,function(err,resdata){
			console.dir(resdata);
			if(resdata.EndItemResponse.Ack[0]=="Success"||resdata.EndItemResponse.Ack[0]=="Warning"){console.log("Item retrieve succeeded");
				res.status(200).send("Item with id " + itemid + " ended successfully." );
				//console.dir(resdata.GetItemResponse.Item[0].Quantity[0]);
				//can do something with the quantity here call to revise the quantity on shopify for example
			}
			else{res.status(200).send("Item with id " +itemid + " failed to end.");}

		});

    }).catch((err) => {
        console.log(err);
    });

}

router.get('/testEndItemQuantity/ebay/:itemid',(req,res,err) =>{
	var itemid = req.params.itemid;
	ebay_endItem(itemid,res);
});

router.get('/testGetItemQuantity/ebay/:itemid',(req,res,err) =>{
	var itemid = req.params.itemid;
	ebay_getItem(itemid,res);
});

router.get('/testReviseItemQuantity/ebay/:itemid/:newquantity',(req,res,err) =>{
	var itemid = req.params.itemid;
	var newquantity = req.params.newquantity;

	ebay_changeQuantity(itemid,newquantity,res);
/* 	.then((result)=>{
		console.log(result);
		if(result=="Success"||result=="Warning"){
				res.status(200).send("Item revision succeeded.");
		}
		else{
				res.status(200).send("Item revision failed.");
		}

	}); */

});

//get active selling item only
router.get('/testActiveItem/ebay',(req,res,err) => {
	var ebayclient = new eBayClient('testuser_shuangzhang','SOAP');

	var xmlbdy = {
		'GetMyeBaySellingRequest':{
			'@xmlns':  'urn:ebay:apis:eBLBaseComponents',
			'ErrorLanguage' : 'en_US',
			'WarningLevel' : 'High',
			'ActiveList' :{
				'Pagination' :{
					'EntriesPerPage' : 200,
					'PageNumber' : 1
				}
			}
		}
	};
	var xml = builder.create(xmlbdy,{encoding: 'utf-8'});

	var str = xml.end({pretty:true,indent: ' ',newline : '\n'});

	console.log(str);

    ebayclient.post('GetMyeBaySelling',str)
	.then((result) => {

		parser.parseString(result,function(err,resdata){
			console.dir(resdata);
			res.status(200).send(JSON.stringify(resdata,null,2));

		});

    }).catch((err) => {
        console.log(err);
    });

});

router.get('/testInventoryItem/ebay',(req,res,err) => {
	var ebayclient = new eBayClient('testuser_shuangzhang','SOAP');

var test = {
	'GetSellerListRequest':{
		'@xmlns':  'urn:ebay:apis:eBLBaseComponents',
		'ErrorLanguage' : 'en_US',
		'WarningLevel' : 'High',
		'GranularityLevel' : 'Coarse',
		'StartTimeFrom' : '2017-05-01T21:59:59.005Z',
		'StartTimeTo' : '2017-05-15T21:59:59.005Z',
		'IncludeWatchCount' : true,
		'Pagination' :{
			'EntriesPerPage' : 200
		}
	}
};
	var xml = builder.create(test,{encoding: 'utf-8'});
	//console.log(JSON.stringify(xml.end({pretty:true,indent: ' ',newline : '\n'})));
	var str = xml.end({pretty:true,indent: ' ',newline : '\n'});
	//str = str.substring(1,str.length-1);
	//str.replace(/\\"/g, '\"');
	console.log(str);
	//ebayclient.get('sell/inventory/v1/inventory_item')
    ebayclient.post('GetSellerList',str)
	.then((result) => {
        //console.log(result);
		parser.parseString(result,function(err,resdata){
			console.dir(resdata);
			res.status(200).send(JSON.stringify(resdata,null,2));

		});

    }).catch((err) => {
        console.log(err);
    });

});

/**
 * webhook handler for item deletion from ebay
 * 1. should check if the item has been deleted from shopify already
 * 2. if not, delete it from ebay
 **/
router.get('/deleteItemCallback/ebay', (req, res, next) => {

})

module.exports = router;
<|endoftext|>