<commit_before>'use strict';

goog.provide('Blockly.Arduino.loops');

goog.require('Blockly.Arduino');

Blockly.Arduino.base_setup = function() {
  var branch = Blockly.Arduino.statementToCode(this, 'DO');
  branch=branch.replace(/(^\s*)|(\s*$)/g, "");//去除两端空格
  if(branch){
	Blockly.Arduino.setups_['setup_setup'] = branch;
  }
  return '';
};

Blockly.Arduino.controls_if = function() {
  // If/elseif/else condition.
  var n = 0;
  var argument = Blockly.Arduino.valueToCode(this, 'IF' + n,
      Blockly.Arduino.ORDER_NONE) || 'false';
  var branch = Blockly.Arduino.statementToCode(this, 'DO' + n);
  var code = 'if (' + argument + ') {\n' + branch + '\n}';
  for (n = 1; n <= this.elseifCount_; n++) {
    argument = Blockly.Arduino.valueToCode(this, 'IF' + n,
      Blockly.Arduino.ORDER_NONE) || 'false';
    branch = Blockly.Arduino.statementToCode(this, 'DO' + n);
    code += ' else if (' + argument + ') {\n' + branch + '}';
  }
  if (this.elseCount_) {
    branch = Blockly.Arduino.statementToCode(this, 'ELSE');
    code += ' else {\n' + branch + '\n}';
  }
  return code + '\n';
};

Blockly.Arduino.controls_switch_case = function() {
  var n = 0;
  var argument = Blockly.Arduino.valueToCode(this, 'IF' + n,
      Blockly.Arduino.ORDER_NONE) || 'NULL';
  var branch ='';
  var code = 'switch (' + argument + ') {\n';
  for (n = 1; n <= this.elseifCount_; n++) {
    argument = Blockly.Arduino.valueToCode(this, 'IF' + n,
      Blockly.Arduino.ORDER_NONE) || 'NULL';
    branch = Blockly.Arduino.statementToCode(this, 'DO' + n);
    code += ' case ' + argument + ': \n' + branch+'  break;\n';
  }
  if (this.elseCount_) {
    branch = Blockly.Arduino.statementToCode(this, 'ELSE');
    code += ' default:\n' + branch+'  break;\n';
  }
  code +='}';
  return code + '\n';
};

Blockly.Arduino.controls_for = function() {
  // For loop.
  var variable0 = Blockly.Arduino.variableDB_.getName(
      this.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
  var argument0 = Blockly.Arduino.valueToCode(this, 'FROM',
      Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
  var argument1 = Blockly.Arduino.valueToCode(this, 'TO',
      Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
  var step = Blockly.Arduino.valueToCode(this, 'STEP',
      Blockly.Arduino.ORDER_ASSIGNMENT) || '1';;
  var branch = Blockly.Arduino.statementToCode(this, 'DO');
  if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
    branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
        '\'' + this.id + '\'') + branch;
  }
  var code;
  var down = step<0;
  if (argument0.match(/^-?\d+(\.\d+)?$/) &&
      argument1.match(/^-?\d+(\.\d+)?$/)) {
    code = 'for (int ' + variable0 + ' = ' + argument0 + '; ' +
        variable0 + (down ? ' >= ' : ' <= ') + argument1 + '; ' +
        variable0 + ' = '  + variable0 + ' + (' +step+')) {\n' +
        branch + '}\n';
  }else {
      //涉及到变量
      code = 'for (int ' + variable0 + ' = (' + argument0 + '); ' +
      variable0 + (down ? ' >= ' : ' <= ')+'(' + argument1 + '); ' +
      variable0 + ' = '  + variable0 + ' + (' +step+')) {\n' +
      branch + '}\n';
  }
  return code;
};

Blockly.Arduino.controls_whileUntil = function() {
  // Do while/until loop.
  var argument0 = Blockly.Arduino.valueToCode(this, 'BOOL',
      Blockly.Arduino.ORDER_NONE) || 'false';
  var branch = Blockly.Arduino.statementToCode(this, 'DO');
  if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
    branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
        '\'' + this.id + '\'') + branch;
  }
  if (this.getFieldValue('MODE') == 'UNTIL') {
    if (!argument0.match(/^\w+$/)) {
      argument0 = '(' + argument0 + ')';
    }
    argument0 = '!' + argument0;
  }
  return 'while (' + argument0 + ') {\n' + branch + '}\n';
};

Blockly.Arduino.controls_flow_statements = function() {
  // Flow statements: continue, break.
  switch (this.getFieldValue('FLOW')) {
    case 'BREAK':
      return 'break;\n';
    case 'CONTINUE':
      return 'continue;\n';
  }
  throw 'Unknown flow statement.';
};

Blockly.Arduino.base_delay = function() {
  var delay_time = Blockly.Arduino.valueToCode(this, 'DELAY_TIME', Blockly.Arduino.ORDER_ATOMIC) || '1000'
  var unit = this.getFieldValue('UNIT');
  var code = unit+'(' + delay_time + ');\n';
  return code;
};

Blockly.Arduino.controls_millis = function(){
  var unit = this.getFieldValue('UNIT');
  var code=unit+"()";
  return [code,Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.controls_mstimer2 = function(){
  Blockly.Arduino.definitions_['define_MsTimer2'] = '#include <MsTimer2.h>';
  var time = Blockly.Arduino.valueToCode(this, 'TIME', Blockly.Arduino.ORDER_ATOMIC);
  var funcName = 'msTimer2_func';
  var branch = Blockly.Arduino.statementToCode(this, 'DO' );
  var code='void'+ ' ' + funcName + '() {\n' + branch + '}\n';
  Blockly.Arduino.definitions_[funcName] = code;
  return 'MsTimer2::set('+time+', '+funcName+');\n';
};

Blockly.Arduino.controls_mstimer2_start = function(){
  Blockly.Arduino.definitions_['define_MsTimer2'] = '#include <MsTimer2.h>';
  return 'MsTimer2::start();\n';
};

Blockly.Arduino.controls_mstimer2_stop = function(){
  Blockly.Arduino.definitions_['define_MsTimer2'] = '#include <MsTimer2.h>';
  return 'MsTimer2::stop();\n';
};

Blockly.Arduino.controls_end_program = function(){
  return 'while(true);\n';
};
Blockly.Arduino.controls_interrupts = function () {
    return 'interrupts();\n';
};

Blockly.Arduino.controls_nointerrupts = function () {
    return 'nointerrupts();\n';
};
<commit_msg>fix nointerrupt bug<commit_after>'use strict';

goog.provide('Blockly.Arduino.loops');

goog.require('Blockly.Arduino');

Blockly.Arduino.base_setup = function() {
  var branch = Blockly.Arduino.statementToCode(this, 'DO');
  branch=branch.replace(/(^\s*)|(\s*$)/g, "");//去除两端空格
  if(branch){
	Blockly.Arduino.setups_['setup_setup'] = branch;
  }
  return '';
};

Blockly.Arduino.controls_if = function() {
  // If/elseif/else condition.
  var n = 0;
  var argument = Blockly.Arduino.valueToCode(this, 'IF' + n,
      Blockly.Arduino.ORDER_NONE) || 'false';
  var branch = Blockly.Arduino.statementToCode(this, 'DO' + n);
  var code = 'if (' + argument + ') {\n' + branch + '\n}';
  for (n = 1; n <= this.elseifCount_; n++) {
    argument = Blockly.Arduino.valueToCode(this, 'IF' + n,
      Blockly.Arduino.ORDER_NONE) || 'false';
    branch = Blockly.Arduino.statementToCode(this, 'DO' + n);
    code += ' else if (' + argument + ') {\n' + branch + '}';
  }
  if (this.elseCount_) {
    branch = Blockly.Arduino.statementToCode(this, 'ELSE');
    code += ' else {\n' + branch + '\n}';
  }
  return code + '\n';
};

Blockly.Arduino.controls_switch_case = function() {
  var n = 0;
  var argument = Blockly.Arduino.valueToCode(this, 'IF' + n,
      Blockly.Arduino.ORDER_NONE) || 'NULL';
  var branch ='';
  var code = 'switch (' + argument + ') {\n';
  for (n = 1; n <= this.elseifCount_; n++) {
    argument = Blockly.Arduino.valueToCode(this, 'IF' + n,
      Blockly.Arduino.ORDER_NONE) || 'NULL';
    branch = Blockly.Arduino.statementToCode(this, 'DO' + n);
    code += ' case ' + argument + ': \n' + branch+'  break;\n';
  }
  if (this.elseCount_) {
    branch = Blockly.Arduino.statementToCode(this, 'ELSE');
    code += ' default:\n' + branch+'  break;\n';
  }
  code +='}';
  return code + '\n';
};

Blockly.Arduino.controls_for = function() {
  // For loop.
  var variable0 = Blockly.Arduino.variableDB_.getName(
      this.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
  var argument0 = Blockly.Arduino.valueToCode(this, 'FROM',
      Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
  var argument1 = Blockly.Arduino.valueToCode(this, 'TO',
      Blockly.Arduino.ORDER_ASSIGNMENT) || '0';
  var step = Blockly.Arduino.valueToCode(this, 'STEP',
      Blockly.Arduino.ORDER_ASSIGNMENT) || '1';;
  var branch = Blockly.Arduino.statementToCode(this, 'DO');
  if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
    branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
        '\'' + this.id + '\'') + branch;
  }
  var code;
  var down = step<0;
  if (argument0.match(/^-?\d+(\.\d+)?$/) &&
      argument1.match(/^-?\d+(\.\d+)?$/)) {
    code = 'for (int ' + variable0 + ' = ' + argument0 + '; ' +
        variable0 + (down ? ' >= ' : ' <= ') + argument1 + '; ' +
        variable0 + ' = '  + variable0 + ' + (' +step+')) {\n' +
        branch + '}\n';
  }else {
      //涉及到变量
      code = 'for (int ' + variable0 + ' = (' + argument0 + '); ' +
      variable0 + (down ? ' >= ' : ' <= ')+'(' + argument1 + '); ' +
      variable0 + ' = '  + variable0 + ' + (' +step+')) {\n' +
      branch + '}\n';
  }
  return code;
};

Blockly.Arduino.controls_whileUntil = function() {
  // Do while/until loop.
  var argument0 = Blockly.Arduino.valueToCode(this, 'BOOL',
      Blockly.Arduino.ORDER_NONE) || 'false';
  var branch = Blockly.Arduino.statementToCode(this, 'DO');
  if (Blockly.Arduino.INFINITE_LOOP_TRAP) {
    branch = Blockly.Arduino.INFINITE_LOOP_TRAP.replace(/%1/g,
        '\'' + this.id + '\'') + branch;
  }
  if (this.getFieldValue('MODE') == 'UNTIL') {
    if (!argument0.match(/^\w+$/)) {
      argument0 = '(' + argument0 + ')';
    }
    argument0 = '!' + argument0;
  }
  return 'while (' + argument0 + ') {\n' + branch + '}\n';
};

Blockly.Arduino.controls_flow_statements = function() {
  // Flow statements: continue, break.
  switch (this.getFieldValue('FLOW')) {
    case 'BREAK':
      return 'break;\n';
    case 'CONTINUE':
      return 'continue;\n';
  }
  throw 'Unknown flow statement.';
};

Blockly.Arduino.base_delay = function() {
  var delay_time = Blockly.Arduino.valueToCode(this, 'DELAY_TIME', Blockly.Arduino.ORDER_ATOMIC) || '1000'
  var unit = this.getFieldValue('UNIT');
  var code = unit+'(' + delay_time + ');\n';
  return code;
};

Blockly.Arduino.controls_millis = function(){
  var unit = this.getFieldValue('UNIT');
  var code=unit+"()";
  return [code,Blockly.Arduino.ORDER_ATOMIC];
};

Blockly.Arduino.controls_mstimer2 = function(){
  Blockly.Arduino.definitions_['define_MsTimer2'] = '#include <MsTimer2.h>';
  var time = Blockly.Arduino.valueToCode(this, 'TIME', Blockly.Arduino.ORDER_ATOMIC);
  var funcName = 'msTimer2_func';
  var branch = Blockly.Arduino.statementToCode(this, 'DO' );
  var code='void'+ ' ' + funcName + '() {\n' + branch + '}\n';
  Blockly.Arduino.definitions_[funcName] = code;
  return 'MsTimer2::set('+time+', '+funcName+');\n';
};

Blockly.Arduino.controls_mstimer2_start = function(){
  Blockly.Arduino.definitions_['define_MsTimer2'] = '#include <MsTimer2.h>';
  return 'MsTimer2::start();\n';
};

Blockly.Arduino.controls_mstimer2_stop = function(){
  Blockly.Arduino.definitions_['define_MsTimer2'] = '#include <MsTimer2.h>';
  return 'MsTimer2::stop();\n';
};

Blockly.Arduino.controls_end_program = function(){
  return 'while(true);\n';
};
Blockly.Arduino.controls_interrupts = function () {
    return 'interrupts();\n';
};

Blockly.Arduino.controls_nointerrupts = function () {
    return 'noInterrupts();\n';
};
<|endoftext|>


<commit_before>"use strict";

const MAX_SIZE = 4096;

// can be swapped to symbols to make more 'private'
// makes it more difficult to debug, though.
let ARR = '_arr';
let SIZE = '_size';

// internal to be inherited
class Data {
    constructor() {
        this[ARR] = [];
    }

    static construct() {
        return Object.create(this.constructor);
    }

    get [Symbol.toStringTag]() {
        return 'Data';
    }

    [Symbol.iterator]() {
        return this[ARR][Symbol.iterator](); // should be overridden for stacks, so we iterate from back to front
    }

    flush() {
        this[ARR].length = 0;
    }

    empty() {
        return this[ARR].length === 0;
    }

    get length() {
        return this[ARR].length;
    }

    toString() {
        return this[ARR].join(', ');
    }

    values() {
        return [...this[ARR]];
    }
}
// Data[Symbol.toStringTag] = 'Data';

export class Stack extends Data {
    constructor() {
        super();
    }

    get [Symbol.toStringTag]() {
        return 'Stack';
    }

    push(val) {
        this[ARR].push(val);
    }

    pop() {
        return this[ARR].pop();
    }

    peek() {
        return this[ARR][this.length - 1];
    }
}

export class FixedStack extends Stack {
    constructor(size = MAX_SIZE) {
        super();
        this[SIZE] = size;
    }

    get [Symbol.toStringTag]() {
        return 'FixedStack';
    }

    get size() {
        return this[SIZE];
    }

    push(val) {
        if (!this.full())
            return super.push(val);
    }

    full() {
        return this.length >= this[SIZE];
    }
}

export class Queue extends Data {
    constructor() {
        super();
    }

    get [Symbol.toStringTag]() {
        return 'Queue';
    }

    push(val) {
        this[ARR].push(val);
    }

    shift() {
        return this[ARR].shift();
    }

    peek() {
        return this[ARR][0];
    }
}

export class List extends Queue {
    constructor() {
        super();
    }

    get [Symbol.toStringTag]() {
        return 'List';
    }

    unshift(...vals) {
        return this[ARR].unshift(...vals);
    }
}

export class FixedQueue extends Queue {
    constructor(size = MAX_SIZE) {
        super();
        this[SIZE] = size;
    }

    get [Symbol.toStringTag]() {
        return 'FixedQueue';
    }

    get size() {
        return this[SIZE];
    }

    push(val) {
        if (!this.full()) // throw overflow? drop overflow? allow overflow?
            return super.push(val);
    }

    full() {
        return this.length >= this[SIZE];
    }

    unshift(...vals) { // this isn't really a queue anymore. maybe FixedList instead?
        return this[ARR].unshift(...vals);
    }
}
<commit_msg>style: lint updates to data-structures<commit_after>"use strict";

const MAX_SIZE = 4096;

// can be swapped to symbols to make more 'private'
// makes it more difficult to debug, though.
let ARR = '_arr';
let SIZE = '_size';

// internal to be inherited
class Data {
    constructor() {
        this[ARR] = [];
    }

    static construct() {
        return Object.create(this.constructor);
    }

    get [Symbol.toStringTag]() {
        return 'Data';
    }

    [Symbol.iterator]() {
        return this[ARR][Symbol.iterator](); // should be overridden for stacks, so we iterate from back to front
    }

    flush() {
        this[ARR].length = 0;
    }

    empty() {
        return this[ARR].length === 0;
    }

    get length() {
        return this[ARR].length;
    }

    toString() {
        return this[ARR].join(', ');
    }

    values() {
        return [ ...this[ARR] ];
    }
}
// Data[Symbol.toStringTag] = 'Data';

export class Stack extends Data {
    constructor() {
        super();
    }

    get [Symbol.toStringTag]() {
        return 'Stack';
    }

    push(val) {
        this[ARR].push(val);
    }

    pop() {
        return this[ARR].pop();
    }

    peek() {
        return this[ARR][this.length - 1];
    }
}

export class FixedStack extends Stack {
    constructor(size = MAX_SIZE) {
        super();
        this[SIZE] = size;
    }

    get [Symbol.toStringTag]() {
        return 'FixedStack';
    }

    get size() {
        return this[SIZE];
    }

    push(val) {
        if (!this.full())
            return super.push(val);
    }

    full() {
        return this.length >= this[SIZE];
    }
}

export class Queue extends Data {
    constructor() {
        super();
    }

    get [Symbol.toStringTag]() {
        return 'Queue';
    }

    push(val) {
        this[ARR].push(val);
    }

    shift() {
        return this[ARR].shift();
    }

    peek() {
        return this[ARR][0];
    }
}

export class List extends Queue {
    constructor() {
        super();
    }

    get [Symbol.toStringTag]() {
        return 'List';
    }

    unshift(...vals) {
        return this[ARR].unshift(...vals);
    }
}

export class FixedQueue extends Queue {
    constructor(size = MAX_SIZE) {
        super();
        this[SIZE] = size;
    }

    get [Symbol.toStringTag]() {
        return 'FixedQueue';
    }

    get size() {
        return this[SIZE];
    }

    push(val) {
        if (!this.full()) // throw overflow? drop overflow? allow overflow?
            return super.push(val);
    }

    full() {
        return this.length >= this[SIZE];
    }

    unshift(...vals) { // this isn't really a queue anymore. maybe FixedList instead?
        return this[ARR].unshift(...vals);
    }
}
<|endoftext|>


<commit_before>/* eslint camelcase: 0 */

module.exports = {
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  parallel: 5,
  launch_in_ci: [
    'Chrome'
  ],
  launch_in_dev: [
    'Chrome'
  ],
  browser_args: {
    Chrome: {
      ci: [
        // --no-sandbox is needed when running Chrome inside a container
        process.env.CI ? '--no-sandbox' : null,
        '--headless',
        '--disable-gpu',
        '--disable-dev-shm-usage',
        '--disable-software-rasterizer',
        '--mute-audio',
        '--remote-debugging-port=0',
        '--window-size=1440,900'
      ].filter(Boolean)
    }
  }
};
<commit_msg>Wait longer to timeout<commit_after>/* eslint camelcase: 0 */

module.exports = {
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  launch_in_ci: [
    'Chrome'
  ],
  launch_in_dev: [
    'Chrome'
  ],
  browser_disconnect_timeout: 300,
  browser_start_timeout: 60,
  browser_args: {
    Chrome: {
      ci: [
        // --no-sandbox is needed when running Chrome inside a container
        process.env.CI ? '--no-sandbox' : null,
        '--headless',
        '--disable-gpu',
        '--disable-dev-shm-usage',
        '--disable-software-rasterizer',
        '--mute-audio',
        '--remote-debugging-port=0',
        '--window-size=1440,900'
      ].filter(Boolean)
    }
  }
};
<|endoftext|>


<commit_before>/* eslint-env node */
module.exports = {
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  launch_in_ci: [
    'Chrome'
  ],
  launch_in_dev: [
    'Chrome'
  ],
  browser_args: {
    Chrome: {
      mode: 'ci',
      args: [
        '--touch-events',
        '--disable-gpu',
        '--headless',
        '--remote-debugging-port=0',
        '--window-size=1440,900'
      ]
    }
  }
};
<commit_msg>Prevent chrome sandboxing in travis<commit_after>/* eslint-env node */
module.exports = {
  test_page: 'tests/index.html?hidepassed',
  disable_watching: true,
  launch_in_ci: [
    'Chrome'
  ],
  launch_in_dev: [
    'Chrome'
  ],
  browser_args: {
    Chrome: {
      mode: 'ci',
      args: [
        process.env.TRAVIS ? '--no-sandbox' : null,
        '--touch-events',
        '--disable-gpu',
        '--headless',
        '--remote-debugging-port=0',
        '--window-size=1440,900'
      ]
    }
  }
};
<|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  "framework": "qunit",
  "test_page": "tests/index.html?hidepassed",
  "disable_watching": true,
  "launch_in_ci": [
    "PhantomJS",
    "Firefox"
  ],
  "launch_in_dev": [
    "PhantomJS",
    "Firefox",
    "Chromium"
  ]
};
<commit_msg>Do not start browsers automatically for testing<commit_after>/*jshint node:true*/

module.exports = {
  'framework': 'qunit',
  'test_page': 'tests/index.html?hidepassed',
  'disable_watching': true,
  'launch_in_ci': [
    'PhantomJS',
    'Firefox'
  ],
  'launch_in_dev': []
}
<|endoftext|>


<commit_before>function degToRad(a) { return a*pi/180 }
var pi = Math.PI
var cos = function(a) { return Math.cos(degToRad(a)) }
var sin = function(a) { return Math.sin(degToRad(a)) }

var side = 100
var svg = d3.select("svg").node()

SVGMatrix.prototype.m = function() { return [this.a,this.b,this.c,this.d,this.e,this.f] }
I = svg.createSVGMatrix()

var drawnObj = function() {
    this.matrix = svg.createSVGMatrix()
}
drawnObj.prototype = {
    bbox : function () {
        obj = this.node
        bbox = $(obj)[0].getBBox()
        return bbox
    },
    draw : function() { this.update() },
    update : function() { // won't call this directly, but once draw() does its thing, it'll map here
        d3.select(this.node.parentNode).attr("transform",
                "matrix("+ this.matrix.m().join(' ') +")"
                )
    },
    show: function() {
        for ( var i=0, len=sibs.length; i < len; i++ ) {
            $(sibs[i]).show()
        }
    },
    hide: function() {
        sibs = this.node.parentNode.children
        for ( var i=0, len=sibs.length; i < len; i++ ) {
            $(sibs[i]).hide()
        }
    },
    translate: function(x,y) {
        this.x += x
        this.y += y
        this.matrix = this.matrix.translate( x, y )
        this.draw()
    },
    setPosition: function(x,y) {
        this.matrix = this.matrix.translate( -this.x, -this.y )
        this.x = x
        this.y = y
        this.matrix = this.matrix.translate( this.x, this.y )
        this.draw()
    },
    setRotation: function(ang) {
        this.matrix = I.translate(this.x,this.y).rotate(ang)
        this.draw()
    },
    rotate : function(ang) {
        this.matrix = this.matrix.rotate(ang)
        this.draw()
    },
    rotateAroundPoint(pt,ang) {
        shift = [ pt[0] - this.x, pt[1] - this.y ]
        // shift, rotate, shift back; pretty sure this is correct
        this.matrix = this.matrix.translate( shift[0], shift[1] )
            .rotate(ang)
            .translate( -shift[0], -shift[1] )
        this.draw()
    },
    rotateAroundLocalPoint(pt,ang) {
        this.rotateAroundPoint( [ this.x + pt[0], this.y + pt[1] ], ang )
    },
    x: 0,
    y: 0,
}

var drawGroup = function() {
    drawnObj.apply(this)
    this.node = document.createElementNS("http://www.w3.org/2000/svg","g")
    svg.appendChild( this.node )
}
drawGroup.prototype = $.extend({},drawnObj.prototype,{
    appendChild: function(n) {
        this.node.appendChild(n)
    },
    removeChild: function(n) {
        this.node.removeChild(n)
    }
})

var poly = function() {
    drawnObj.apply(this)
}
poly.prototype = $.extend({},drawnObj.prototype,{
    points : function() { return [] },
    color : "#00FF00",
    draw : function() {
        pointsStr = ""
        for(var i=0; i<this.points.length; i++){
            pointsStr += this.points[i].toString() + " "
        }
        canvas = d3.select("svg")
        this.drawable = canvas.append("g").append("polygon")
            .attr("points", pointsStr)
            .attr({ fill: this.color })
        this.node = this.drawable.node()
        this.update() // we wanna be in the right place/orientation
        this.draw = this.update // done with first-time creation, drawing means updating, now
        return this.drawable
    }
})

function drawTriSides(tr) {
    sides = [
    {pt1: tr.points[0], pt2: tr.points[1], color:"FF0000"},
    {pt1: tr.points[1], pt2: tr.points[2], color:"00FF00"},
    {pt1: tr.points[2], pt2: tr.points[0], color:"0000FF"},
    ]
    console.log(sides)
    for(s in sides) {
        s=sides[s]
        d3.select(tr.node.parentNode).append("line").attr({x1: s.pt1[0], y1: s.pt1[1]}).attr({x2: s.pt2[0], y2: s.pt2[1]}).style({"stroke":s.color, "stroke-width":"5px"}).attr("transform", d3.select(tr.node).attr("transform"))
    }
}
// classes to contain the isosceles tris described in "Updown generation of Penrose patterns"
// http://www.sciencedirect.com/science/article/pii/0019357790900058
//
// local origin is the center of the defining cut
tri = function() {
    poly.apply(this)
    this.points = [
        [0,side*cos(this.beta)],
        [side * sin(this.beta),0],
        [0,-side * cos(this.beta)]
    ]
}
tri.prototype = $.extend({},poly.prototype, {
    alpha : 45, // the angle NOT on the cut
    beta : 45, // the two angles on the cut (bisected from the rhomb)
    color: "#000000"
})

// 'primed' triangle
trip = function() {
    tri.apply(this)
    // primed tris are mirror copies of unprimed tris
    this.points[1][0] *= -1
}
$.extend(trip.prototype,tri.prototype)

triA = function() {
    tri.apply(this)
    this.sides = {
        one: {pt1: this.points[0], pt2: this.points[1]},
        two: {pt1: this.points[2], pt2: this.points[1]},
        three: {pt1: this.points[2], pt2: this.points[0]},
        four: null
    }
}
triA.prototype = $.extend({},tri.prototype,{
    alpha : 36,
    beta : 144/2,
    color: "#FF0000",
})

triAp = function() {
    trip.apply(this)
    this.sides = {
        one: {pt1: this.points[0], pt2: this.points[1]},
        two: {pt1: this.points[2], pt2: this.points[1]},
        three: {pt1: this.points[2], pt2: this.points[0]},
        four: null
    }
}
triAp.prototype = $.extend({},trip.prototype,{
    alpha : 36,
    beta : 144/2,
    color: "#FF00FF"
})

triB = function() { tri.apply(this) }
triB.prototype = $.extend({},tri.prototype,{
    alpha : 108,
    beta : 72/2,
    color: "#0000FF"
})

triBp = function() { trip.apply(this) }
triBp.prototype = $.extend({},trip.prototype,{
    alpha : 108,
    beta : 72/2,
    color: "#00FFFF"
})

// universal prototype for rhombs
var rhomb = function() {
    this.points = this.points()
}
rhomb.prototype = $.extend({},poly.prototype,{
    points : function() {
        return [
            [0,0],
            [ side*cos(this.theta/2), side*sin(this.theta/2) ],
            [ 2*side*cos(this.theta/2), 0],
            [ side*cos(this.theta/2), -side*sin(this.theta/2) ]
        ]
    }
})

var thickrhomb = function() {
    rhomb.apply(this)
}
thickrhomb.prototype = $.extend({},rhomb.prototype,{
    theta : 72,
    alpha : 108,
    position : [0,50],

    color : "#FF0000"
})

var thinrhomb = function() {
    rhomb.apply(this)
}
thinrhomb.prototype = $.extend({},rhomb.prototype,{
    theta : 36,
    alpha : 144,
    position : [0,50],

    color : "#0000FF"
})

//thin = new thinrhomb()
//thin.rotate(90)
//thin.draw()
//
//thick = new thickrhomb()
//thick.draw()
//thick.setRotation(thin.theta*3/2)
//thick.setPosition([-40,120])

mytri = new triA();
mytri.draw()
mytri.setRotation(0)
mytri.setPosition(100,100)
drawTriSides(mytri)

mytri2 = new triAp();
mytri2.draw()
mytri2.setPosition(100,100)
drawTriSides(mytri2)

d3.selectAll("polygon").attr("fill","black")
<commit_msg>example of a by-hand assembly of an inflated thin rhomb<commit_after>function degToRad(a) { return a*pi/180 }
var pi = Math.PI
var cos = function(a) { return Math.cos(degToRad(a)) }
var sin = function(a) { return Math.sin(degToRad(a)) }

var side = 100
var svg = d3.select("svg").node()

SVGMatrix.prototype.m = function() { return [this.a,this.b,this.c,this.d,this.e,this.f] }
I = svg.createSVGMatrix()

var drawnObj = function() {
    this.matrix = svg.createSVGMatrix()
}
drawnObj.prototype = {
    bbox : function () {
        obj = this.node
        bbox = $(obj)[0].getBBox()
        return bbox
    },
    draw : function() { this.update() },
    update : function() { // won't call this directly, but once draw() does its thing, it'll map here
        d3.select(this.node.parentNode).attr("transform",
                "matrix("+ this.matrix.m().join(' ') +")"
                )
    },
    show: function() {
        for ( var i=0, len=sibs.length; i < len; i++ ) {
            $(sibs[i]).show()
        }
    },
    hide: function() {
        sibs = this.node.parentNode.children
        for ( var i=0, len=sibs.length; i < len; i++ ) {
            $(sibs[i]).hide()
        }
    },
    translate: function(x,y) {
        this.x += x
        this.y += y
        this.matrix = I.translate( x, y ).multiply(this.matrix)
        this.draw()
    },
    setPosition: function(x,y) {
        this.matrix = I.translate( -this.x, -this.y ).multiply(this.matrix)
        this.x = x
        this.y = y
        this.matrix = I.translate( this.x, this.y ).multiply(this.matrix)
        this.draw()
    },
    setRotation: function(ang) {
        this.matrix = I.translate(this.x,this.y).rotate(ang)
        this.draw()
    },
    rotate : function(ang) {
        this.matrix = this.matrix.rotate(ang)
        this.draw()
    },
    rotateAroundPoint(pt,ang) {
        shift = [ pt[0] - this.x, pt[1] - this.y ]
        // shift, rotate, shift back; pretty sure this is correct
        this.matrix = this.matrix.translate( shift[0], shift[1] )
            .rotate(ang)
            .translate( -shift[0], -shift[1] )
        this.draw()
    },
    rotateAroundLocalPoint(pt,ang) {
        this.rotateAroundPoint( [ this.x + pt[0], this.y + pt[1] ], ang )
    },
    x: 0,
    y: 0,
}

var drawGroup = function() {
    drawnObj.apply(this)
    this.node = document.createElementNS("http://www.w3.org/2000/svg","g")
    svg.appendChild( this.node )
}
drawGroup.prototype = $.extend({},drawnObj.prototype,{
    appendChild: function(n) {
        this.node.appendChild(n)
    },
    removeChild: function(n) {
        this.node.removeChild(n)
    }
})

var poly = function() {
    drawnObj.apply(this)
}
poly.prototype = $.extend({},drawnObj.prototype,{
    points : function() { return [] },
    color : "#00FF00",
    draw : function() {
        pointsStr = ""
        for(var i=0; i<this.points.length; i++){
            pointsStr += this.points[i].toString() + " "
        }
        canvas = d3.select("svg")
        this.drawable = canvas.append("g").append("polygon")
            .attr("points", pointsStr)
            .attr({ fill: this.color })
        this.node = this.drawable.node()
        this.update() // we wanna be in the right place/orientation
        this.draw = this.update // done with first-time creation, drawing means updating, now
        return this.drawable
    }
})

function drawTriSides(tr) {
    sides = [
    {pt1: tr.points[0], pt2: tr.points[1], color:"FF0000"},
    {pt1: tr.points[1], pt2: tr.points[2], color:"00FF00"},
    {pt1: tr.points[2], pt2: tr.points[0], color:"0000FF"},
    ]
    console.log(sides)
    for(s in sides) {
        s=sides[s]
        d3.select(tr.node.parentNode).append("line").attr({x1: s.pt1[0], y1: s.pt1[1]}).attr({x2: s.pt2[0], y2: s.pt2[1]}).style({"stroke":s.color, "stroke-width":"5px"}).attr("transform", d3.select(tr.node).attr("transform"))
    }
}
// classes to contain the isosceles tris described in "Updown generation of Penrose patterns"
// http://www.sciencedirect.com/science/article/pii/0019357790900058
//
// BEFORE any transformation, the center of the cut is at the local origin
tri = function() {
    poly.apply(this)
    this.points = [
        [0,side*cos(this.beta)],
        [side * sin(this.beta),0],
        [0,-side * cos(this.beta)]
    ]
}
tri.prototype = $.extend({},poly.prototype, {
    alpha : 45, // the angle NOT on the cut
    beta : 45, // the two angles on the cut (bisected from the rhomb)
    color: "#000000"
})

// 'primed' triangle
trip = function() {
    tri.apply(this)
    // primed tris are mirror copies of unprimed tris
    this.points[1][0] *= -1
}
$.extend(trip.prototype,tri.prototype)

triA = function() {
    tri.apply(this)
    this.sides = {
        one: {pt1: this.points[0], pt2: this.points[1]},
        two: {pt1: this.points[2], pt2: this.points[1]},
        three: {pt1: this.points[2], pt2: this.points[0]},
        four: null
    }
    this.draw()
    d3.select(this.node.parentNode).append("text").text("A").attr("fill","white").attr("transform","translate("+side/4+",0)")
}
triA.prototype = $.extend({},tri.prototype,{
    alpha : 36,
    beta : 144/2,
    color: "#FF0000",
})

triAp = function() {
    trip.apply(this)
    this.sides = {
        one: {pt1: this.points[0], pt2: this.points[1]},
        two: {pt1: this.points[2], pt2: this.points[1]},
        three: {pt1: this.points[2], pt2: this.points[0]},
        four: null
    }
    this.draw()
    d3.select(this.node.parentNode).append("text").text("A'").attr("fill","white").attr("transform","translate(-"+side/3+",0)")
}
triAp.prototype = $.extend({},trip.prototype,{
    alpha : 36,
    beta : 144/2,
    color: "#FF00FF"
})

triB = function() {
    tri.apply(this)
    this.draw()
    d3.select(this.node.parentNode).append("text").text("B").attr("fill","white").attr("transform","translate("+side/4+",0)")
}
triB.prototype = $.extend({},tri.prototype,{
    alpha : 108,
    beta : 72/2,
    color: "#0000FF"
})

triBp = function() {
    trip.apply(this)
    this.draw()
    d3.select(this.node.parentNode).append("text").text("B'").attr("fill","white").attr("transform","translate(-"+side/3+",0)")
}
triBp.prototype = $.extend({},trip.prototype,{
    alpha : 108,
    beta : 72/2,
    color: "#00FFFF"
})

// universal prototype for rhombs
var rhomb = function() {
    this.points = this.points()
}
rhomb.prototype = $.extend({},poly.prototype,{
    points : function() {
        return [
            [0,0],
            [ side*cos(this.theta/2), side*sin(this.theta/2) ],
            [ 2*side*cos(this.theta/2), 0],
            [ side*cos(this.theta/2), -side*sin(this.theta/2) ]
        ]
    }
})

var thickrhomb = function() {
    rhomb.apply(this)
}
thickrhomb.prototype = $.extend({},rhomb.prototype,{
    theta : 72,
    alpha : 108,
    position : [0,50],

    color : "#FF0000"
})

var thinrhomb = function() {
    rhomb.apply(this)
}
thinrhomb.prototype = $.extend({},rhomb.prototype,{
    theta : 36,
    alpha : 144,
    position : [0,50],

    color : "#0000FF"
})

//thin = new thinrhomb()
//thin.rotate(90)
//thin.draw()
//
//thick = new thickrhomb()
//thick.draw()
//thick.setRotation(thin.theta*3/2)
//thick.setPosition([-40,120])

mytri = new triA()
mytri.setRotation(0)
mytri.setPosition(100,100)
drawTriSides(mytri)

mytri2 = new triAp()
mytri2.setPosition( 100 - 2*mytri2.points[1][0], 100 )
mytri2.rotateAroundLocalPoint( mytri2.points[1], 180+mytri2.alpha ) // match up edges
drawTriSides(mytri2)

mytri3 = new triBp()
mytri3.setPosition( 100 - mytri3.points[1][0], 100 + mytri3.points[1][1] + mytri.points[0][1])
mytri3.rotateAroundLocalPoint( mytri3.points[1], mytri3.beta*1 ) // match up edges
drawTriSides(mytri3)

mytri4 = new triB()
mytri4.setPosition(100 + mytri.points[1][0],100 - mytri4.points[2][1])
mytri4.rotateAroundLocalPoint( mytri4.points[2], 180 ) // match up edges
drawTriSides(mytri4)

masterg = d3.select("svg").append("g").attr("transform","translate(200,00) rotate(45) ").attr("id","masterg").node()
masterg.appendChild(mytri.node.parentNode)
masterg.appendChild(mytri2.node.parentNode)
masterg.appendChild(mytri3.node.parentNode)
masterg.appendChild(mytri4.node.parentNode)

d3.selectAll("polygon").attr("fill","black")
<|endoftext|>


<commit_before>/*Copyright (c) 2015 Jason Zissman
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/*
	Notice!  This project requires ifvisible.js to run.  You can get a copy from
	the ifinvisible.js github (https://github.com/serkanyersen/ifvisible.js) or
	by running "bower install timeme.js", which will install both TimeMe.js and ifvisible.js.
*/

(function(ifvisible) {

	TimeMe = {
		startStopTimes: {},

		idleTimeout: 60,

		currentPageName: "default-page-name",

		getIfVisibleHandle: function(){
			if (typeof ifvisible === 'object') {
				return ifvisible;
			} else {
				console.log("Required dependency (ifvisible.js) not found.  Make sure it has been included.");
				throw {
					name: "MissingDependencyException",
					message: "Required dependency (ifvisible.js) not found.  Make sure it has been included."
				};
			}
		},

		startTimer: function() {
			var pageName = TimeMe.currentPageName;
			if (TimeMe.startStopTimes[pageName] === undefined){
				TimeMe.startStopTimes[pageName] = [];
			} else {
				var arrayOfTimes = TimeMe.startStopTimes[pageName];
				var latestStartStopEntry = arrayOfTimes[arrayOfTimes.length -1];
				if (latestStartStopEntry !== undefined && latestStartStopEntry.stopTime === undefined) {
					// Can't start new timer until previous finishes.
					return;
				}
			}
			TimeMe.startStopTimes[pageName].push({
				"startTime": new Date(),
				"stopTime": undefined
			});
		},

		stopTimer: function() {
			var pageName = TimeMe.currentPageName;
			var arrayOfTimes = TimeMe.startStopTimes[pageName];
			if (arrayOfTimes === undefined || arrayOfTimes.length === 0){
				// Can't stop timer before you've started it.
				return;
			}
			if (arrayOfTimes[arrayOfTimes.length -1].stopTime === undefined) {
				arrayOfTimes[arrayOfTimes.length -1].stopTime = new Date();
			}
		},

		getTimeOnCurrentPageInSeconds : function() {
			return TimeMe.getTimeOnPageInSeconds(TimeMe.currentPageName);
		},

		getTimeOnPageInSeconds: function(pageName) {

			var totalTimeOnPage = 0;

			var arrayOfTimes = TimeMe.startStopTimes[pageName];
			if (arrayOfTimes === undefined){
				// Can't get time on page before you've started the timer.
				return;
			}

			var timeSpentOnPageInSeconds = 0;
			for(var i=0; i < arrayOfTimes.length; i++) {
				var startTime = arrayOfTimes[i].startTime;
				var stopTime = arrayOfTimes[i].stopTime;
				if (stopTime === undefined){
					stopTime = new Date();
				}
				var difference = stopTime - startTime;
				timeSpentOnPageInSeconds += (difference / 1000);
			}

			totalTimeOnPage = Number(timeSpentOnPageInSeconds);
			return totalTimeOnPage;
		},

		getTimeOnAllPagesInSeconds: function() {
			var allTimes = [];
			var pageNames = Object.keys(TimeMe.startStopTimes);
			for (var i=0; i < pageNames.length; i++){
				var pageName = pageNames[i];
				var timeOnPage = TimeMe.getTimeOnPageInSeconds(pageName);
				allTimes.push({
					"pageName": pageName,
					"timeOnPage": timeOnPage
				});
			}
			return allTimes;
		},

		setIdleDurationInSeconds: function(duration) {
			var durationFloat = parseFloat(duration);
			if (isNaN(durationFloat) === false){
				TimeMe.getIfVisibleHandle().setIdleDuration(durationFloat);
				TimeMe.idleTimeout = durationFloat;
			} else {
				throw {
					name: "InvalidDurationException",
					message: "An invalid duration time (" + duration + ") was provided."
				};
			}
		},

		setCurrentPageName: function(pageName) {
			TimeMe.currentPageName = pageName;
		},

		resetRecordedPageTime: function(pageName) {
			delete TimeMe.startStopTimes[pageName];
		},

		resetAllRecordedPageTimes: function() {
			var pageNames = Object.keys(TimeMe.startStopTimes);
			for (var i=0; i < pageNames.length; i++){
				TimeMe.resetRecordedPageTime(pageNames[i]);
			}
		},

		listenForVisibilityEvents: function(){
			TimeMe.getIfVisibleHandle().on("blur", function(){
				TimeMe.stopTimer();
			});

			TimeMe.getIfVisibleHandle().on("focus", function(){
				TimeMe.startTimer();
			});

			TimeMe.getIfVisibleHandle().on("idle", function(){
				if (TimeMe.idleTimeout > 0){
					TimeMe.stopTimer();
				}
			});

			TimeMe.getIfVisibleHandle().on("wakeup", function(){
				if (TimeMe.idleTimeout > 0){
					TimeMe.startTimer();
				}
			});
		},

		initialize: function (){
			TimeMe.listenForVisibilityEvents();
			TimeMe.startTimer();
		}
	};

	if (typeof define === "function" && define.amd) {
		define(function() {
			return TimeMe;
		});
	} else {
		window.TimeMe = TimeMe;
	}
})(this.ifvisible);
<commit_msg>Only using console log if defined<commit_after>/*Copyright (c) 2015 Jason Zissman
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/*
	Notice!  This project requires ifvisible.js to run.  You can get a copy from
	the ifinvisible.js github (https://github.com/serkanyersen/ifvisible.js) or
	by running "bower install timeme.js", which will install both TimeMe.js and ifvisible.js.
*/

(function(ifvisible) {

	TimeMe = {
		startStopTimes: {},

		idleTimeout: 60,

		currentPageName: "default-page-name",

		getIfVisibleHandle: function(){
			if (typeof ifvisible === 'object') {
				return ifvisible;
			} else {
				if (typeof console !== "undefined") {
					console.log("Required dependency (ifvisible.js) not found.  Make sure it has been included.");
				}
				throw {
					name: "MissingDependencyException",
					message: "Required dependency (ifvisible.js) not found.  Make sure it has been included."
				};
			}
		},

		startTimer: function() {
			var pageName = TimeMe.currentPageName;
			if (TimeMe.startStopTimes[pageName] === undefined){
				TimeMe.startStopTimes[pageName] = [];
			} else {
				var arrayOfTimes = TimeMe.startStopTimes[pageName];
				var latestStartStopEntry = arrayOfTimes[arrayOfTimes.length -1];
				if (latestStartStopEntry !== undefined && latestStartStopEntry.stopTime === undefined) {
					// Can't start new timer until previous finishes.
					return;
				}
			}
			TimeMe.startStopTimes[pageName].push({
				"startTime": new Date(),
				"stopTime": undefined
			});
		},

		stopTimer: function() {
			var pageName = TimeMe.currentPageName;
			var arrayOfTimes = TimeMe.startStopTimes[pageName];
			if (arrayOfTimes === undefined || arrayOfTimes.length === 0){
				// Can't stop timer before you've started it.
				return;
			}
			if (arrayOfTimes[arrayOfTimes.length -1].stopTime === undefined) {
				arrayOfTimes[arrayOfTimes.length -1].stopTime = new Date();
			}
		},

		getTimeOnCurrentPageInSeconds : function() {
			return TimeMe.getTimeOnPageInSeconds(TimeMe.currentPageName);
		},

		getTimeOnPageInSeconds: function(pageName) {

			var totalTimeOnPage = 0;

			var arrayOfTimes = TimeMe.startStopTimes[pageName];
			if (arrayOfTimes === undefined){
				// Can't get time on page before you've started the timer.
				return;
			}

			var timeSpentOnPageInSeconds = 0;
			for(var i=0; i < arrayOfTimes.length; i++) {
				var startTime = arrayOfTimes[i].startTime;
				var stopTime = arrayOfTimes[i].stopTime;
				if (stopTime === undefined){
					stopTime = new Date();
				}
				var difference = stopTime - startTime;
				timeSpentOnPageInSeconds += (difference / 1000);
			}

			totalTimeOnPage = Number(timeSpentOnPageInSeconds);
			return totalTimeOnPage;
		},

		getTimeOnAllPagesInSeconds: function() {
			var allTimes = [];
			var pageNames = Object.keys(TimeMe.startStopTimes);
			for (var i=0; i < pageNames.length; i++){
				var pageName = pageNames[i];
				var timeOnPage = TimeMe.getTimeOnPageInSeconds(pageName);
				allTimes.push({
					"pageName": pageName,
					"timeOnPage": timeOnPage
				});
			}
			return allTimes;
		},

		setIdleDurationInSeconds: function(duration) {
			var durationFloat = parseFloat(duration);
			if (isNaN(durationFloat) === false){
				TimeMe.getIfVisibleHandle().setIdleDuration(durationFloat);
				TimeMe.idleTimeout = durationFloat;
			} else {
				throw {
					name: "InvalidDurationException",
					message: "An invalid duration time (" + duration + ") was provided."
				};
			}
		},

		setCurrentPageName: function(pageName) {
			TimeMe.currentPageName = pageName;
		},

		resetRecordedPageTime: function(pageName) {
			delete TimeMe.startStopTimes[pageName];
		},

		resetAllRecordedPageTimes: function() {
			var pageNames = Object.keys(TimeMe.startStopTimes);
			for (var i=0; i < pageNames.length; i++){
				TimeMe.resetRecordedPageTime(pageNames[i]);
			}
		},

		listenForVisibilityEvents: function(){
			TimeMe.getIfVisibleHandle().on("blur", function(){
				TimeMe.stopTimer();
			});

			TimeMe.getIfVisibleHandle().on("focus", function(){
				TimeMe.startTimer();
			});

			TimeMe.getIfVisibleHandle().on("idle", function(){
				if (TimeMe.idleTimeout > 0){
					TimeMe.stopTimer();
				}
			});

			TimeMe.getIfVisibleHandle().on("wakeup", function(){
				if (TimeMe.idleTimeout > 0){
					TimeMe.startTimer();
				}
			});
		},

		initialize: function (){
			TimeMe.listenForVisibilityEvents();
			TimeMe.startTimer();
		}
	};

	if (typeof define === "function" && define.amd) {
		define(function() {
			return TimeMe;
		});
	} else {
		window.TimeMe = TimeMe;
	}
})(this.ifvisible);
<|endoftext|>


<commit_before>/**
 * @author iCodingStar
 * @date 2016/6/27 10:14
 * @version 1.0
 */
var MESSAGE_RECEIVE = 0;
var MESSAGE_SEND = 1;
var MESSAGE_UNREAD = 2;
var MESSAGE_STATUS_READ = 0;
var MESSAGE_STATUS_UNREAD = 1;
var MESSAGE_STATUS_DELETE = 2;
var MESSAGE_STATUS = ['已读', '未读', '已删除'];

$(function () {
    var pageSize = 10;
    var pageNumber = 0;

    $("#send-message").attr('disabled', true);//禁用发送按钮

    //获取收件箱中的消息
    parseReceiveMessages(pageNumber, pageSize, MESSAGE_RECEIVE, null);

    //获取收件箱中的消息
    $(".message-receive").on('click', function () {
        $(".message-content").css("display", "none");
        $("#message-content").css("display", "none");
        parseReceiveMessages(pageNumber, pageSize, MESSAGE_RECEIVE, null);
    });

    //获取发件箱中的短消息
    $(".message-send").on('click', function () {
        $(".message-content").css("display", "none");
        $("#message-content").css("display", "none");
        parseSendMessages(pageNumber, pageSize, MESSAGE_SEND, null);
    });

    //获取收件箱中的未读消息
    $(".message-unread").on('click', function () {
        $(".message-content").css("display", "none");
        $("#message-content").css("display", "none");
        parseUnreadMessages(pageNumber, pageSize, MESSAGE_RECEIVE, MESSAGE_STATUS_UNREAD);
    });

    //发消息
    $("#send-message").on('click', function () {
        $(".message-content").css("display", "none");
        $("#message-content").css("display", "none");
        var username = $("#message-write #receiver").val();
        if (isNaN(username)) {
            receiver = null;
        } else {
            receiver = username;
            username = null;
        }
        var title = $("#message-write #title").val();
        var content = $('#message-write #content').val();

        postMessageDataAndParse(contextPath + "/MessageBox/Send", {
            username: username,
            receiver: receiver,
            title: title,
            content: content,
            status: 0
        }, function (result) {
            if (result.data == 1) {
                console.table(result);
                alert("发送成功");
                $(".message-send a").trigger("click");
            }
        });
    });

});

/***
 * 显示消息详情
 *
 * @param id
 */
function read_message_content(id) {
    getMessageDataAndParse(contextPath + "/MessageBox/Content", {
        id: id
    }, function (result) {
        var message = result.data.message;
        var sender = result.data.sender;
        var receiver = result.data.receiver;
        $(".message-content").css('display', 'block');
        $("#message-content").css("display", "block");
        $("#message-content .title").text(message.title);
        $("#message-content .sender").text(sender.username);
        $("#message-content .receiver").text(receiver.username);
        $("#message-content .content").text(message.content);
        $(".message-content a").trigger("click");
    });
}

/***
 * 更新短消息状态
 *
 * @param id
 * @param status
 */
function update_message_status(id, status) {
    getMessageDataAndParse(contextPath + "/MessageBox/Update", {
        id: id,
        status: status
    }, function (result) {
        console.log("更新成功");
    });
}
/***
 * 检查内容是否合法
 */
function check_content_input(event) {
    $("#send-message").attr('disabled', false);//解禁发送按钮
    var content_value = $('#content').val();
    if (content_value.length < 6){
        $('#content_tips').text("短信息内容不少于6个字!");
        $("#send-message").attr('disabled', true);//禁用发送按钮
    }else if (content_value.length > 512){
        $('#content_tips').text("短信息内容不超过512个字！");
        $("#send-message").attr('disabled', true);//禁用发送按钮
    }
}
/***
 *检查标题是否合法
 */
function check_title_input(event) {
    $("#send-message").attr('disabled', false);//解禁发送按钮
    var title_value = $('#title').val();
    if (title_value.length < 2){
        $('#title_tips').text("短信息标题不少于2个字!");
        $("#send-message").attr('disabled', true);//禁用发送按钮
    }else if (title_value.length > 32){
        $('#title_tips').text("短信息标题不超过32个字！");
        $("#send-message").attr('disabled', true);//禁用发送按钮
    }
}
/***
 * 检查收件人是否合法
 */
function check_receiver_input(event) {
    var username = $("#message-write #receiver").val();
    if (isNaN(username)) {
        receiver = null;
    } else {
        receiver = username;
        username = null;
    }
    checkUser(username, receiver);
}

/***
 * 判断收件人是否存在
 * @param username
 * @param receiver
 * @returns {boolean}
 */
function checkUser(username, receiver) {
    getMessageDataAndParse("/MessageBox/CheckUser",
        {
            username: username,
            receiver: receiver
        }, function (result) {
            if (result.data == "1") {
                $('#receiver_tips').text(" ");//提示文本置空
                $("#send-message").attr('disabled', false);//解禁发送按钮
            } else {
                $('#receiver_tips').text("用户不存在！");
                $("#send-message").attr('disabled', true);//禁用发送按钮
            }
        });
}

/***
 *  获取数据并解析
 *
 * @param url
 * @param data
 */
function getMessageDataAndParse(url, data, callback) {
    $.ajax({
        url: url,
        dataType: "json",
        data: data,
        type: "GET",
        cache: false,
        success: function (result) {
            callback(result);
        },
        error: function () {
            console.log("获取消息失败！");
        }
    });
}

/***
 * 向服务器发送数据并显示反馈信息
 *
 * @param url
 * @param data
 * @param callback
 */
function postMessageDataAndParse(url, data, callback) {
    $.ajax({
        url: url,
        dataType: "json",
        data: data,
        type: "POST",
        cache: false,
        success: function (result) {
            callback(result);
        },
        error: function () {
            console.log("获取消息失败！");
        }
    });
}

//解析收件箱短信数据
function parseReceiveMessages(currentPageNumber, pageSize, type, status) {
    //从服务器端获取数据并解析
    getMessageDataAndParse(contextPath + "/MessageBox/List", {
        currentPageNumber: currentPageNumber,
        pageSize: pageSize,
        type: type,
        status: status
    }, function (result) {
        $("#message-receive .table tr:not(:first)").remove();
        if (result == null) {
            return;
        }
        var node = "";
        /***
         * 修改短消息状态
         * 0:已读
         * 1:未读
         * 2:已删除
         *
         * @param messageBoxDto
         * @return
         */

        $.each(result.data.data, function (index, item) {
            var webUserName = item.sender.username;
            var webUserId = item.sender.id;
            node += "
" + MESSAGE_STATUS[item.message.status] + "	"
                + " " + webUserName + "	"
                + " " + item.message.title + "	"
                + "" + item.message.createTime + "	";
            var params = item.message.id + "," + MESSAGE_STATUS_DELETE;
            node += "" + "" + "删除" + "" + "";
        });
        $("#message-receive .table").append(node);

        //分页
        $("#message-receive .page-nav .pagination li").remove();
        var page = result.data;
        var message = page.data;
        var paramStr = "";
        if (page.totalPageNumber > 1) {
            if (page.currentPageNumber > 1) {
                paramStr += page.currentPageNumber - 1 + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var prevPage = "
上一页
";
                $("#message-receive .page-nav .pagination").append(prevPage);
                paramStr = "";
            }
            for (var i = 1; i <= page.totalPageNumber; i++) {
                paramStr += i + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var pageNav = "";
                if (page.currentPageNumber == i) {
                    pageNav = "
" + i + "
"
                } else {
                    pageNav = "
" + i + "
";
                }
                $("#message-receive .page-nav .pagination").append(pageNav);
                paramStr = ""
            }
            if (page.currentPageNumber < page.totalPageNumber) {
                paramStr += page.currentPageNumber + 1 + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var nextPage = "
下一页
";
                $("#message-receive .page-nav .pagination").append(nextPage);
                paramStr = "";
            }
        }
    });
}

//解析发件箱短信数据
function parseSendMessages(currentPageNumber, pageSize, type, status) {
    //从服务器端获取数据并解析
    getMessageDataAndParse(contextPath + "/MessageBox/List", {
        currentPageNumber: currentPageNumber,
        pageSize: pageSize,
        type: type,
        status: status
    }, function (result) {
        $("#message-send .table tr:not(:first)").remove();
        if (result == null) {
            return;
        }
        var node = "";
        /***
         * 修改短消息状态
         * 0:已读
         * 1:未读
         * 2:已删除
         *
         * @param messageBoxDto
         * @return
         */

        $.each(result.data.data, function (index, item) {
            var webUserName = item.receiver.username;
            var webUserId = item.receiver.id;
            node += "
" + MESSAGE_STATUS[item.message.status] + "	"
                + " " + webUserName + "	"
                + " " + item.message.title + "	"
                + "" + item.message.createTime + "	";
            var params = item.message.id + "," + MESSAGE_STATUS_DELETE;
            node += "" + "" + "删除" + "" + "";
        });

        $("#message-send .table").append(node);

        //分页
        $("#message-send  .page-nav .pagination li").remove();
        var page = result.data;
        var message = page.data;
        var paramStr = "";
        if (page.totalPageNumber > 1) {
            if (page.currentPageNumber > 1) {
                paramStr += page.currentPageNumber - 1 + "," + page.pageSize + "," + MESSAGE_SEND + "," + null;
                var prevPage = "
上一页
";
                $("#message-send .page-nav .pagination").append(prevPage);
                paramStr = "";
            }
            for (var i = 1; i <= page.totalPageNumber; i++) {
                paramStr += i + "," + page.pageSize + "," + MESSAGE_SEND + "," + null;
                var pageNav = "";
                if (page.currentPageNumber == i) {
                    pageNav = "
" + i + "
"
                } else {
                    pageNav = "
" + i + "
";
                }
                $("#message-send .page-nav .pagination").append(pageNav);
                paramStr = ""
            }
            if (page.currentPageNumber < page.totalPageNumber) {
                paramStr += page.currentPageNumber + 1 + "," + page.pageSize + "," + MESSAGE_SEND + "," + null;
                var nextPage = "
下一页
";
                $("#message-send .page-nav .pagination").append(nextPage);
                paramStr = "";
            }
        }
    });
}

//解析未读短信数据
function parseUnreadMessages(currentPageNumber, pageSize, type, status) {
    //从服务器端获取数据并解析
    getMessageDataAndParse(contextPath + "/MessageBox/List", {
        currentPageNumber: currentPageNumber,
        pageSize: pageSize,
        type: type,
        status: status
    }, function (result) {
        $("#message-unread .table tr:not(:first)").remove();
        if (result == null) {
            return;
        }
        var node = "";
        /***
         * 修改短消息状态
         * 0:已读
         * 1:未读
         * 2:已删除
         *
         * @param messageBoxDto
         * @return
         */

        $.each(result.data.data, function (index, item) {
            var webUserName = item.sender.username;
            var webUserId = item.sender.id;
            node += "
" + MESSAGE_STATUS[item.message.status] + "	"
                + " " + webUserName + "	"
                + " " + item.message.title + "	"
                + "" + item.message.createTime + "	";
            var params = item.message.id + "," + MESSAGE_STATUS_DELETE;
            node += "" + "" + "删除" + "" + "";
        });

        $("#message-unread .table").append(node);

        $("#message-unread  .page-nav .pagination li").remove();
        var page = result.data;
        var message = page.data;
        var paramStr = "";
        if (page.totalPageNumber > 1) {
            if (page.currentPageNumber > 1) {
                paramStr += page.currentPageNumber - 1 + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var prevPage = "
上一页
";
                $("#message-unread .page-nav .pagination").append(prevPage);
                paramStr = "";
            }
            for (var i = 1; i <= page.totalPageNumber; i++) {
                paramStr += i + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var pageNav = "";
                if (page.currentPageNumber == i) {
                    pageNav = "
" + i + "
"
                } else {
                    pageNav = "
" + i + "
";
                }
                $("#message-unread .page-nav .pagination").append(pageNav);
                paramStr = ""
            }
            if (page.currentPageNumber < page.totalPageNumber) {
                paramStr += page.currentPageNumber + 1 + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var nextPage = "
下一页
";
                $("#message-unread .page-nav .pagination").append(nextPage);
                paramStr = "";
            }
        }
    });
}<commit_msg>完善短信息功能<commit_after>/**
 * @author iCodingStar
 * @date 2016/6/27 10:14
 * @version 1.0
 */
var MESSAGE_RECEIVE = 0;
var MESSAGE_SEND = 1;
var MESSAGE_UNREAD = 2;
var MESSAGE_STATUS_READ = 0;
var MESSAGE_STATUS_UNREAD = 1;
var MESSAGE_STATUS_DELETE = 2;
var MESSAGE_STATUS = ['已读', '未读', '已删除'];

$(function () {
    var pageSize = 10;
    var pageNumber = 0;

    $("#send-message").attr('disabled', true);//禁用发送按钮

    //获取收件箱中的消息
    parseReceiveMessages(pageNumber, pageSize, MESSAGE_RECEIVE, null);

    //获取收件箱中的消息
    $(".message-receive").on('click', function () {
        $(".message-content").css("display", "none");
        $("#message-content").css("display", "none");
        parseReceiveMessages(pageNumber, pageSize, MESSAGE_RECEIVE, null);
    });

    //获取发件箱中的短消息
    $(".message-send").on('click', function () {
        $(".message-content").css("display", "none");
        $("#message-content").css("display", "none");
        parseSendMessages(pageNumber, pageSize, MESSAGE_SEND, null);
    });

    //获取收件箱中的未读消息
    $(".message-unread").on('click', function () {
        $(".message-content").css("display", "none");
        $("#message-content").css("display", "none");
        parseUnreadMessages(pageNumber, pageSize, MESSAGE_RECEIVE, MESSAGE_STATUS_UNREAD);
    });

    //发消息
    $("#send-message").on('click', function () {
        $(".message-content").css("display", "none");
        $("#message-content").css("display", "none");
        var username = $("#message-write #receiver").val();
        if (isNaN(username)) {
            receiver = null;
        } else {
            receiver = username;
            username = null;
        }
        var title = $("#message-write #title").val();
        var content = $('#message-write #content').val();

        postMessageDataAndParse(contextPath + "/MessageBox/Send", {
            username: username,
            receiver: receiver,
            title: title,
            content: content,
            status: 0
        }, function (result) {
            if (result.data == 1) {
                console.table(result);
                alert("发送成功");
                $(".message-send a").trigger("click");
            }
        });
    });

});

/***
 * 显示消息详情
 *
 * @param id
 */
function read_message_content(id) {
    getMessageDataAndParse(contextPath + "/MessageBox/Content", {
        id: id
    }, function (result) {
        var message = result.data.message;
        var sender = result.data.sender;
        var receiver = result.data.receiver;
        $(".message-content").css('display', 'block');
        $("#message-content").css("display", "block");
        $("#message-content .title").text(message.title);
        $("#message-content .sender").text(sender.username);
        $("#message-content .receiver").text(receiver.username);
        $("#message-content .content").text(message.content);
        $(".message-content a").trigger("click");
    });
}

/***
 * 更新短消息状态
 *
 * @param id
 * @param status
 */
function update_message_status(id, status) {
    getMessageDataAndParse(contextPath + "/MessageBox/Update", {
        id: id,
        status: status
    }, function (result) {
        console.log("更新成功");
    });
}
/***
 * 检查内容是否合法
 */
function check_content_input(event) {
    $("#send-message").attr('disabled', false);//解禁发送按钮
    var content_value = $('#content').val();
    if (content_value.length < 6){
        $('#content_tips').text("短信息内容不少于6个字符!");
        $("#send-message").attr('disabled', true);//禁用发送按钮
    }else if (content_value.length > 2000){
        $('#content_tips').text("短信息内容不超过512个字符！");
        $("#send-message").attr('disabled', true);//禁用发送按钮
    }
}
/***
 *检查标题是否合法
 */
function check_title_input(event) {
    $("#send-message").attr('disabled', false);//解禁发送按钮
    var title_value = $('#title').val();
    if (title_value.length < 2){
        $('#title_tips').text("短信息标题不少于2个字符!");
        $("#send-message").attr('disabled', true);//禁用发送按钮
    }else if (title_value.length > 128){
        $('#title_tips').text("短信息标题不超过128个字符！");
        $("#send-message").attr('disabled', true);//禁用发送按钮
    }
}
/***
 * 检查收件人是否合法
 */
function check_receiver_input(event) {
    var username = $("#message-write #receiver").val();
    if (isNaN(username)) {
        receiver = null;
    } else {
        receiver = username;
        username = null;
    }
    checkUser(username, receiver);
}

/***
 * 判断收件人是否存在
 * @param username
 * @param receiver
 * @returns {boolean}
 */
function checkUser(username, receiver) {
    getMessageDataAndParse("/MessageBox/CheckUser",
        {
            username: username,
            receiver: receiver
        }, function (result) {
            if (result.data == "1") {
                $('#receiver_tips').text(" ");//提示文本置空
                $("#send-message").attr('disabled', false);//解禁发送按钮
            } else {
                $('#receiver_tips').text("用户不存在！");
                $("#send-message").attr('disabled', true);//禁用发送按钮
            }
        });
}

/***
 *  获取数据并解析
 *
 * @param url
 * @param data
 */
function getMessageDataAndParse(url, data, callback) {
    $.ajax({
        url: url,
        dataType: "json",
        data: data,
        type: "GET",
        cache: false,
        success: function (result) {
            callback(result);
        },
        error: function () {
            console.log("获取消息失败！");
        }
    });
}

/***
 * 向服务器发送数据并显示反馈信息
 *
 * @param url
 * @param data
 * @param callback
 */
function postMessageDataAndParse(url, data, callback) {
    $.ajax({
        url: url,
        dataType: "json",
        data: data,
        type: "POST",
        cache: false,
        success: function (result) {
            callback(result);
        },
        error: function () {
            console.log("获取消息失败！");
        }
    });
}

//解析收件箱短信数据
function parseReceiveMessages(currentPageNumber, pageSize, type, status) {
    //从服务器端获取数据并解析
    getMessageDataAndParse(contextPath + "/MessageBox/List", {
        currentPageNumber: currentPageNumber,
        pageSize: pageSize,
        type: type,
        status: status
    }, function (result) {
        $("#message-receive .table tr:not(:first)").remove();
        if (result == null) {
            return;
        }
        var node = "";
        /***
         * 修改短消息状态
         * 0:已读
         * 1:未读
         * 2:已删除
         *
         * @param messageBoxDto
         * @return
         */

        $.each(result.data.data, function (index, item) {
            var webUserName = item.sender.username;
            var webUserId = item.sender.id;
            node += "
" + MESSAGE_STATUS[item.message.status] + "	"
                + " " + webUserName + "	"
                + " " + item.message.title + "	"
                + "" + item.message.createTime + "	";
            var params = item.message.id + "," + MESSAGE_STATUS_DELETE;
            node += "" + "" + "删除" + "" + "";
        });
        $("#message-receive .table").append(node);

        //分页
        $("#message-receive .page-nav .pagination li").remove();
        var page = result.data;
        var message = page.data;
        var paramStr = "";
        if (page.totalPageNumber > 1) {
            if (page.currentPageNumber > 1) {
                paramStr += page.currentPageNumber - 1 + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var prevPage = "
上一页
";
                $("#message-receive .page-nav .pagination").append(prevPage);
                paramStr = "";
            }
            for (var i = 1; i <= page.totalPageNumber; i++) {
                paramStr += i + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var pageNav = "";
                if (page.currentPageNumber == i) {
                    pageNav = "
" + i + "
"
                } else {
                    pageNav = "
" + i + "
";
                }
                $("#message-receive .page-nav .pagination").append(pageNav);
                paramStr = ""
            }
            if (page.currentPageNumber < page.totalPageNumber) {
                paramStr += page.currentPageNumber + 1 + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var nextPage = "
下一页
";
                $("#message-receive .page-nav .pagination").append(nextPage);
                paramStr = "";
            }
        }
    });
}

//解析发件箱短信数据
function parseSendMessages(currentPageNumber, pageSize, type, status) {
    //从服务器端获取数据并解析
    getMessageDataAndParse(contextPath + "/MessageBox/List", {
        currentPageNumber: currentPageNumber,
        pageSize: pageSize,
        type: type,
        status: status
    }, function (result) {
        $("#message-send .table tr:not(:first)").remove();
        if (result == null) {
            return;
        }
        var node = "";
        /***
         * 修改短消息状态
         * 0:已读
         * 1:未读
         * 2:已删除
         *
         * @param messageBoxDto
         * @return
         */

        $.each(result.data.data, function (index, item) {
            var webUserName = item.receiver.username;
            var webUserId = item.receiver.id;
            node += "
" + MESSAGE_STATUS[item.message.status] + "	"
                + " " + webUserName + "	"
                + " " + item.message.title + "	"
                + "" + item.message.createTime + "	";
            var params = item.message.id + "," + MESSAGE_STATUS_DELETE;
            node += "" + "" + "删除" + "" + "";
        });

        $("#message-send .table").append(node);

        //分页
        $("#message-send  .page-nav .pagination li").remove();
        var page = result.data;
        var message = page.data;
        var paramStr = "";
        if (page.totalPageNumber > 1) {
            if (page.currentPageNumber > 1) {
                paramStr += page.currentPageNumber - 1 + "," + page.pageSize + "," + MESSAGE_SEND + "," + null;
                var prevPage = "
上一页
";
                $("#message-send .page-nav .pagination").append(prevPage);
                paramStr = "";
            }
            for (var i = 1; i <= page.totalPageNumber; i++) {
                paramStr += i + "," + page.pageSize + "," + MESSAGE_SEND + "," + null;
                var pageNav = "";
                if (page.currentPageNumber == i) {
                    pageNav = "
" + i + "
"
                } else {
                    pageNav = "
" + i + "
";
                }
                $("#message-send .page-nav .pagination").append(pageNav);
                paramStr = ""
            }
            if (page.currentPageNumber < page.totalPageNumber) {
                paramStr += page.currentPageNumber + 1 + "," + page.pageSize + "," + MESSAGE_SEND + "," + null;
                var nextPage = "
下一页
";
                $("#message-send .page-nav .pagination").append(nextPage);
                paramStr = "";
            }
        }
    });
}

//解析未读短信数据
function parseUnreadMessages(currentPageNumber, pageSize, type, status) {
    //从服务器端获取数据并解析
    getMessageDataAndParse(contextPath + "/MessageBox/List", {
        currentPageNumber: currentPageNumber,
        pageSize: pageSize,
        type: type,
        status: status
    }, function (result) {
        $("#message-unread .table tr:not(:first)").remove();
        if (result == null) {
            return;
        }
        var node = "";
        /***
         * 修改短消息状态
         * 0:已读
         * 1:未读
         * 2:已删除
         *
         * @param messageBoxDto
         * @return
         */

        $.each(result.data.data, function (index, item) {
            var webUserName = item.sender.username;
            var webUserId = item.sender.id;
            node += "
" + MESSAGE_STATUS[item.message.status] + "	"
                + " " + webUserName + "	"
                + " " + item.message.title + "	"
                + "" + item.message.createTime + "	";
            var params = item.message.id + "," + MESSAGE_STATUS_DELETE;
            node += "" + "" + "删除" + "" + "";
        });

        $("#message-unread .table").append(node);

        $("#message-unread  .page-nav .pagination li").remove();
        var page = result.data;
        var message = page.data;
        var paramStr = "";
        if (page.totalPageNumber > 1) {
            if (page.currentPageNumber > 1) {
                paramStr += page.currentPageNumber - 1 + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var prevPage = "
上一页
";
                $("#message-unread .page-nav .pagination").append(prevPage);
                paramStr = "";
            }
            for (var i = 1; i <= page.totalPageNumber; i++) {
                paramStr += i + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var pageNav = "";
                if (page.currentPageNumber == i) {
                    pageNav = "
" + i + "
"
                } else {
                    pageNav = "
" + i + "
";
                }
                $("#message-unread .page-nav .pagination").append(pageNav);
                paramStr = ""
            }
            if (page.currentPageNumber < page.totalPageNumber) {
                paramStr += page.currentPageNumber + 1 + "," + page.pageSize + "," + MESSAGE_RECEIVE + "," + null;
                var nextPage = "
下一页
";
                $("#message-unread .page-nav .pagination").append(nextPage);
                paramStr = "";
            }
        }
    });
}<|endoftext|>


<commit_before>module.exports = {
  normalizeEntityName: function() {},

  afterInstall: function() {
    var self = this;
    return this.addBowerPackageToProject('fullcalendar', '^3.0.0').then(function() {
      return self.addBowerPackageToProject('fullcalendar-scheduler', '^1.4.0');
    });
  }
};
<commit_msg>Removes outdated blueprint<commit_after><|endoftext|>


<commit_before>SingleResourcePageController = AppController.extend({
    data: {
        'title': 'Example content',
        'author': 'Illya Nziyev',
        'date': " 29 Tammi 2015",
        'content': "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.",
        sections: [
            {
                "title": "Birds",
                "lessons": [
                    {
                        "title": "Nest building"
                    },
                    {
                        "title": "Feeding"
                    },
                    {
                        "title": "Flight"
                    }
                ]
            },
            {
                "title": "Bees",
                "lessons": [
                    {
                        "title": "Hive building"
                    },
                    {
                        "title": "Brood"
                    },
                ]
            }
        ]
    }
});
<commit_msg>de-lint.<commit_after>SingleResourcePageController = AppController.extend({
    data: {
        'title': 'Example content',
        'author': 'Illya Nziyev',
        'date': " 29 Tammi 2015",
        'content': "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.",
        sections: [
            {
                "title": "Birds",
                "lessons": [
                    {
                        "title": "Nest building"
                    },
                    {
                        "title": "Feeding"
                    },
                    {
                        "title": "Flight"
                    }
                ]
            },
            {
                "title": "Bees",
                "lessons": [
                    {
                        "title": "Hive building"
                    },
                    {
                        "title": "Brood"
                    }
                ]
            }
        ]
    }
});
<|endoftext|>


<commit_before>/*
 * Author: Dave Millman <dave@cs.montana.edu>
 * Created: 07 Sep 2015
 */

var http = require('http');
var Fs = require('fs');
var Rss = require('rss');
var request = require('request');

// global constans
var SITE_URL = 'https://muut.com/comptop';
var FEED_URL = 'https://muut.com/comptop';
var SESSION_ID = 'vkx7sqKjKuJaZ4fxk5BxWqWz.50ae54e856e5d118bb16b4b3fdaf0b28b7686000';
var MAINTAINER_EMAIL = 'dave@cs.unc.edu';

// the data to get things going
var fileName = 'data/data-2016-01-19.json';
var extracted_data = {};

function makeEntryData(author, description, postTitle, url, guid, date) {
    return {
        'title': postTitle,
        'description': description,
        'url': url,
        'guid': guid,
        'author': author,
        'date': date
    };
}

function makeEntryErrorData() {
    author = 'ERROR';
    description = 'There was an error extracting data from an entry. ' +
        'Please contact ' + MAINTAINER_EMAIL + ' to report an error.';
    postTitle = 'Error extracting data for an entry';
    guid = new Date().getTime();
    date = guid;
    return makeEntryData(author, description, postTitle, guid, date);
}

function extract(entry) {
    var entryData;
    try {
        var seed = entry.seed;
        var author = seed.user.displayname;
        var description = seed.body;
        var postTitle = seed.title;
        var guid = seed.key;
        var date = seed.time;
        entryData = makeEntryData(author, description, postTitle,
                                  SITE_URL, guid, date);
    } catch (error) {
        entryData = makeEntryErrorData();
    }
    return entryData;
}

function createFeed(entries) {
    feed = new Rss({
        'title': 'Computational Topology Message Board',
        'description': 'RSS feed of the computational topology message board',
        'feed_url': FEED_URL,
        'site_url': SITE_URL
    });

    for (var idx in entries) {
        feed.item(entries[idx]);
    }

    var xml = feed.xml({indent: true});
    return xml;
}

function parseData(response, data) {
    var extractedEntries;
    try {
        var entries = data.result.moots.entries;
        extractedEntries = entries.map(extract);
    } catch (error) {
        extractedEntries = [makeEntryErrorData()];
    }
    xml = createFeed(extractedEntries);
    response.writeHead(200);
    response.write(xml);
}

function make_mutt_response_processor(client_response) {
    mutt_response_processor = function(error, response, body) {
        console.log(response.statusCode);
        if (error || response.statusCode != 200) {
            consolse.log(makeEntryErrorData());
        } else {
            parseData(client_response, body);
        }
    };
    return mutt_response_processor;
}

function makeRequest(response) {
    options = {
        url: 'https://api.muut.com/',
        method: 'POST',
        headers: {'Accept': 'application/json'},
        json: {
            'method': 'init',
            'params':[ {
                'version': '1.14.0',
                'path': '/comptop',
                'currentForum': 'comptop',
                'pageLocation': 'https://muut.com/comptop',
                'expand_all': false,
                'reload': false
            } ],
            'id':'#1',
            'session':{'sessionId': SESSION_ID},
            'jsonrpc':'2.1.0',
            'transport':'upgrade'
        }
    };
    mutt_response_processor = make_mutt_response_processor(response);
    request(options, mutt_response_processor);
}

// function readFile(error, data) {
//     if (error) {
//         throw error;
//     } else {
//         var jsonData = JSON.parse(data);
//         parseData(jsonData);
//     }
// }
//Fs.readFile(fileName, 'utf8', readFile);

function requestHandler(request, response) {
    makeRequest(response);
}

http.createServer(requestHandler).listen(8080);
<commit_msg>Close response<commit_after>/*
 * Author: Dave Millman <dave@cs.montana.edu>
 * Created: 07 Sep 2015
 */

var http = require('http');
var Fs = require('fs');
var Rss = require('rss');
var request = require('request');

// global constans
var SITE_URL = 'https://muut.com/comptop';
var FEED_URL = 'https://muut.com/comptop';
var SESSION_ID = 'vkx7sqKjKuJaZ4fxk5BxWqWz.50ae54e856e5d118bb16b4b3fdaf0b28b7686000';
var MAINTAINER_EMAIL = 'dave@cs.unc.edu';

// the data to get things going
var fileName = 'data/data-2016-01-19.json';
var extracted_data = {};

function makeEntryData(author, description, postTitle, url, guid, date) {
    return {
        'title': postTitle,
        'description': description,
        'url': url,
        'guid': guid,
        'author': author,
        'date': date
    };
}

function makeEntryErrorData() {
    author = 'ERROR';
    description = 'There was an error extracting data from an entry. ' +
        'Please contact ' + MAINTAINER_EMAIL + ' to report an error.';
    postTitle = 'Error extracting data for an entry';
    guid = new Date().getTime();
    date = guid;
    return makeEntryData(author, description, postTitle, guid, date);
}

function extract(entry) {
    var entryData;
    try {
        var seed = entry.seed;
        var author = seed.user.displayname;
        var description = seed.body;
        var postTitle = seed.title;
        var guid = seed.key;
        var date = seed.time;
        entryData = makeEntryData(author, description, postTitle,
                                  SITE_URL, guid, date);
    } catch (error) {
        entryData = makeEntryErrorData();
    }
    return entryData;
}

function createFeed(entries) {
    feed = new Rss({
        'title': 'Computational Topology Message Board',
        'description': 'RSS feed of the computational topology message board',
        'feed_url': FEED_URL,
        'site_url': SITE_URL
    });

    for (var idx in entries) {
        feed.item(entries[idx]);
    }

    var xml = feed.xml({indent: true});
    return xml;
}

function parseData(response, data) {
    var extractedEntries;
    try {
        var entries = data.result.moots.entries;
        extractedEntries = entries.map(extract);
    } catch (error) {
        extractedEntries = [makeEntryErrorData()];
    }
    xml = createFeed(extractedEntries);
    response.writeHead(200);
    response.end(xml);
}

function make_mutt_response_processor(client_response) {
    mutt_response_processor = function(error, response, body) {
        console.log(response.statusCode);
        if (error || response.statusCode != 200) {
            consolse.log(makeEntryErrorData());
        } else {
            parseData(client_response, body);
        }
    };
    return mutt_response_processor;
}

function makeRequest(response) {
    options = {
        url: 'https://api.muut.com/',
        method: 'POST',
        headers: {'Accept': 'application/json'},
        json: {
            'method': 'init',
            'params':[ {
                'version': '1.14.0',
                'path': '/comptop',
                'currentForum': 'comptop',
                'pageLocation': 'https://muut.com/comptop',
                'expand_all': false,
                'reload': false
            } ],
            'id':'#1',
            'session':{'sessionId': SESSION_ID},
            'jsonrpc':'2.1.0',
            'transport':'upgrade'
        }
    };
    mutt_response_processor = make_mutt_response_processor(response);
    request(options, mutt_response_processor);
}

// function readFile(error, data) {
//     if (error) {
//         throw error;
//     } else {
//         var jsonData = JSON.parse(data);
//         parseData(jsonData);
//     }
// }
//Fs.readFile(fileName, 'utf8', readFile);

function requestHandler(request, response) {
    makeRequest(response);
}

http.createServer(requestHandler).listen(8080);
<|endoftext|>


<commit_before>/**
 * Modal
 */
Garnish.Modal = Garnish.Base.extend({

	$container: null,
	$shade: null,

	visible: false,

	dragger: null,

	desiredWidth: null,
	desiredHeight: null,
	resizeDragger: null,
	resizeStartWidth: null,
	resizeStartHeight: null,

	init: function(container, settings)
	{
		// Param mapping
		if (!settings && $.isPlainObject(container))
		{
			// (settings)
			settings = container;
            container = null;
		}

		this.setSettings(settings, Garnish.Modal.defaults);

        // If container already set, drop the shade below it.
        if (container)
        {
            this.$shade = $('
').insertBefore(container);
        }
        else
        {
            this.$shade = $('
').appendTo(Garnish.$bod);
        }

        if (container)
		{
			this.setContainer(container);
			this.show();
		}

		Garnish.Modal.instances.push(this);
	},

	setContainer: function(container)
	{
		this.$container = $(container);

		// Is this already a modal?
		if (this.$container.data('modal'))
		{
			Garnish.log('Double-instantiating a modal on an element');
			this.$container.data('modal').destroy();
		}

		this.$container.data('modal', this);

		if (this.settings.draggable)
		{
			this.dragger = new Garnish.DragMove(this.$container, {
				handle: (this.settings.dragHandleSelector ? this.$container.find(this.settings.dragHandleSelector) : this.$container)
			});
		}

		if (this.settings.resizable)
		{
			var $resizeDragHandle = $('
').appendTo(this.$container);

			this.resizeDragger = new Garnish.BaseDrag($resizeDragHandle, {
				onDragStart:   $.proxy(this, '_onResizeStart'),
				onDrag:        $.proxy(this, '_onResize')
			});
		}

		this.addListener(this.$container, 'click', function(ev) {
			ev.stopPropagation();
		});
	},

	show: function()
	{
        // Close other modals as needed
		if (Garnish.Modal.visibleModal && this.settings.closeOtherModals)
		{
			Garnish.Modal.visibleModal.hide();
		}

		if (this.$container)
		{
			this.$container.show();
			this.updateSizeAndPosition();
			this.$container.delay(50).fadeIn($.proxy(this, 'onFadeIn'));
		}

		this.visible = true;
		Garnish.Modal.visibleModal = this;
		this.$shade.fadeIn(50);

		this.addListener(this.$shade, 'click', 'hide');
		this.addListener(Garnish.$win, 'resize', 'updateSizeAndPosition');

		Garnish.escManager.register(this, 'hide');

		this.settings.onShow();
	},

	hide: function(ev)
	{
		if (ev)
		{
			ev.stopPropagation();
		}

		if (this.$container)
		{
			this.$container.fadeOut('fast');
			this.removeListener(Garnish.$win, 'resize');
		}

		this.visible = false;
		Garnish.Modal.visibleModal = null;
		this.$shade.fadeOut('fast', $.proxy(this, 'onFadeOut'));
		this.removeListener(this.$shade, 'click');
		this.removeListener(Garnish.$bod, 'keyup');

		Garnish.escManager.unregister(this);
		this.settings.onHide();
	},

	updateSizeAndPosition: function()
	{
		if (!this.$container)
		{
			return;
		}

		this.$container.css({
			'width':      (this.desiredWidth ? this.desiredWidth : ''),
			'height':     (this.desiredHeight ? this.desiredHeight : ''),
			'min-width':  '',
			'min-height': ''
		});

		this.updateSizeAndPosition._windowWidth = Garnish.$win.width();
		this.updateSizeAndPosition._windowHeight = Garnish.$win.height();
		this.updateSizeAndPosition._width = Math.min(this.getWidth(), this.updateSizeAndPosition._windowWidth - 20);
		this.updateSizeAndPosition._height = Math.min(this.getHeight(), this.updateSizeAndPosition._windowHeight - 20);

		this.$container.css({
			'width':      this.updateSizeAndPosition._width,
			'height':     this.updateSizeAndPosition._height,
			'min-width':  this.updateSizeAndPosition._width,
			'min-height': this.updateSizeAndPosition._height,
			'left':       Math.round((this.updateSizeAndPosition._windowWidth - this.updateSizeAndPosition._width) / 2),
			'top':        Math.round((this.updateSizeAndPosition._windowHeight - this.updateSizeAndPosition._height) / 2)
		});
	},

	onFadeIn: function()
	{
		this.settings.onFadeIn();
	},

	onFadeOut: function()
	{
		this.settings.onFadeOut();
	},

	getHeight: function()
	{
		if (!this.$container)
		{
			throw 'Attempted to get the height of a modal whose container has not been set.';
		}

		if (!this.visible)
		{
			this.$container.show();
		}

		this.getHeight._height = this.$container.outerHeight();

		if (!this.visible)
		{
			this.$container.hide();
		}

		return this.getHeight._height;
	},

	getWidth: function()
	{
		if (!this.$container)
		{
			throw 'Attempted to get the width of a modal whose container has not been set.';
		}

		if (!this.visible)
		{
			this.$container.show();
		}

		this.getWidth._width = this.$container.outerWidth();

		if (!this.visible)
		{
			this.$container.hide();
		}

		return this.getWidth._width;
	},

	_onResizeStart: function()
	{
		this.resizeStartWidth = this.getWidth();
		this.resizeStartHeight = this.getHeight();
	},

	_onResize: function()
	{
		if (Garnish.ltr)
		{
			this.desiredWidth = this.resizeStartWidth + (this.resizeDragger.mouseDistX * 2);
			this.desiredHeight = this.resizeStartHeight + (this.resizeDragger.mouseDistY * 2);
		}
		else
		{
			this.desiredWidth = this.resizeStartWidth - (this.resizeDragger.mouseDistX * 2);
			this.desiredHeight = this.resizeStartHeight - (this.resizeDragger.mouseDistY * 2);
		}

		this.updateSizeAndPosition();
	},

	destroy: function()
	{
		this.base();

		if (this.dragger)
		{
			this.dragger.destroy();
		}

		if (this.resizeDragger)
		{
			this.resizeDragger.destroy();
		}
	},

    shiftModalToEnd: function ()
    {
        this.$shade.appendTo(Garnish.$bod);
        this.$container.appendTo(Garnish.$bod);
    }
},
{
	relativeElemPadding: 8,
	defaults: {
		draggable: false,
		dragHandleSelector: null,
		resizable: false,
		onShow: $.noop,
		onHide: $.noop,
		onFadeIn: $.noop,
		onFadeOut: $.noop,
        closeOtherModals: true
	},
	instances: [],
	visibleModal: null
});
<commit_msg>Don't let them go overboard<commit_after>/**
 * Modal
 */
Garnish.Modal = Garnish.Base.extend({

	$container: null,
	$shade: null,

	visible: false,

	dragger: null,

	desiredWidth: null,
	desiredHeight: null,
	resizeDragger: null,
	resizeStartWidth: null,
	resizeStartHeight: null,

	init: function(container, settings)
	{
		// Param mapping
		if (!settings && $.isPlainObject(container))
		{
			// (settings)
			settings = container;
            container = null;
		}

		this.setSettings(settings, Garnish.Modal.defaults);

        // If container already set, drop the shade below it.
        if (container)
        {
            this.$shade = $('
').insertBefore(container);
        }
        else
        {
            this.$shade = $('
').appendTo(Garnish.$bod);
        }

        if (container)
		{
			this.setContainer(container);
			this.show();
		}

		Garnish.Modal.instances.push(this);
	},

	setContainer: function(container)
	{
		this.$container = $(container);

		// Is this already a modal?
		if (this.$container.data('modal'))
		{
			Garnish.log('Double-instantiating a modal on an element');
			this.$container.data('modal').destroy();
		}

		this.$container.data('modal', this);

		if (this.settings.draggable)
		{
			this.dragger = new Garnish.DragMove(this.$container, {
				handle: (this.settings.dragHandleSelector ? this.$container.find(this.settings.dragHandleSelector) : this.$container)
			});
		}

		if (this.settings.resizable)
		{
			var $resizeDragHandle = $('
').appendTo(this.$container);

			this.resizeDragger = new Garnish.BaseDrag($resizeDragHandle, {
				onDragStart:   $.proxy(this, '_onResizeStart'),
				onDrag:        $.proxy(this, '_onResize')
			});
		}

		this.addListener(this.$container, 'click', function(ev) {
			ev.stopPropagation();
		});
	},

	show: function()
	{
        // Close other modals as needed
		if (Garnish.Modal.visibleModal && this.settings.closeOtherModals)
		{
			Garnish.Modal.visibleModal.hide();
		}

		if (this.$container)
		{
			this.$container.show();
			this.updateSizeAndPosition();
			this.$container.delay(50).fadeIn($.proxy(this, 'onFadeIn'));
		}

		this.visible = true;
		Garnish.Modal.visibleModal = this;
		this.$shade.fadeIn(50);

		this.addListener(this.$shade, 'click', 'hide');
		this.addListener(Garnish.$win, 'resize', 'updateSizeAndPosition');

		Garnish.escManager.register(this, 'hide');

		this.settings.onShow();
	},

	hide: function(ev)
	{
		if (ev)
		{
			ev.stopPropagation();
		}

		if (this.$container)
		{
			this.$container.fadeOut('fast');
			this.removeListener(Garnish.$win, 'resize');
		}

		this.visible = false;
		Garnish.Modal.visibleModal = null;
		this.$shade.fadeOut('fast', $.proxy(this, 'onFadeOut'));
		this.removeListener(this.$shade, 'click');
		this.removeListener(Garnish.$bod, 'keyup');

		Garnish.escManager.unregister(this);
		this.settings.onHide();
	},

	updateSizeAndPosition: function()
	{
		if (!this.$container)
		{
			return;
		}

		this.$container.css({
			'width':      (this.desiredWidth ? Math.max(this.desiredWidth, 200) : ''),
			'height':     (this.desiredHeight ? Math.max(this.desiredHeight, 200) : ''),
			'min-width':  '',
			'min-height': ''
		});

		this.updateSizeAndPosition._windowWidth = Garnish.$win.width();
		this.updateSizeAndPosition._windowHeight = Garnish.$win.height();
		this.updateSizeAndPosition._width = Math.min(this.getWidth(), this.updateSizeAndPosition._windowWidth - 20);
		this.updateSizeAndPosition._height = Math.min(this.getHeight(), this.updateSizeAndPosition._windowHeight - 20);

		this.$container.css({
			'width':      this.updateSizeAndPosition._width,
			'height':     this.updateSizeAndPosition._height,
			'min-width':  this.updateSizeAndPosition._width,
			'min-height': this.updateSizeAndPosition._height,
			'left':       Math.round((this.updateSizeAndPosition._windowWidth - this.updateSizeAndPosition._width) / 2),
			'top':        Math.round((this.updateSizeAndPosition._windowHeight - this.updateSizeAndPosition._height) / 2)
		});
	},

	onFadeIn: function()
	{
		this.settings.onFadeIn();
	},

	onFadeOut: function()
	{
		this.settings.onFadeOut();
	},

	getHeight: function()
	{
		if (!this.$container)
		{
			throw 'Attempted to get the height of a modal whose container has not been set.';
		}

		if (!this.visible)
		{
			this.$container.show();
		}

		this.getHeight._height = this.$container.outerHeight();

		if (!this.visible)
		{
			this.$container.hide();
		}

		return this.getHeight._height;
	},

	getWidth: function()
	{
		if (!this.$container)
		{
			throw 'Attempted to get the width of a modal whose container has not been set.';
		}

		if (!this.visible)
		{
			this.$container.show();
		}

		this.getWidth._width = this.$container.outerWidth();

		if (!this.visible)
		{
			this.$container.hide();
		}

		return this.getWidth._width;
	},

	_onResizeStart: function()
	{
		this.resizeStartWidth = this.getWidth();
		this.resizeStartHeight = this.getHeight();
	},

	_onResize: function()
	{
		if (Garnish.ltr)
		{
			this.desiredWidth = this.resizeStartWidth + (this.resizeDragger.mouseDistX * 2);
			this.desiredHeight = this.resizeStartHeight + (this.resizeDragger.mouseDistY * 2);
		}
		else
		{
			this.desiredWidth = this.resizeStartWidth - (this.resizeDragger.mouseDistX * 2);
			this.desiredHeight = this.resizeStartHeight - (this.resizeDragger.mouseDistY * 2);
		}

		this.updateSizeAndPosition();
	},

	destroy: function()
	{
		this.base();

		if (this.dragger)
		{
			this.dragger.destroy();
		}

		if (this.resizeDragger)
		{
			this.resizeDragger.destroy();
		}
	},

    shiftModalToEnd: function ()
    {
        this.$shade.appendTo(Garnish.$bod);
        this.$container.appendTo(Garnish.$bod);
    }
},
{
	relativeElemPadding: 8,
	defaults: {
		draggable: false,
		dragHandleSelector: null,
		resizable: false,
		onShow: $.noop,
		onHide: $.noop,
		onFadeIn: $.noop,
		onFadeOut: $.noop,
        closeOtherModals: true
	},
	instances: [],
	visibleModal: null
});
<|endoftext|>