<commit_before>// LICENSE : MIT
"use strict";
import {RuleHelper} from "textlint-rule-helper";
import kuromojin from "kuromojin";

function isTargetVerb(token) {
    return token.pos == '動詞' &&
        token.pos_detail_1 == '自立' &&
        token.conjugated_type == '一段' &&
        token.conjugated_form == '未然形';
}

function isRaWord(token) {
    return token.pos == '動詞' &&
        token.pos_detail_1 == '接尾' &&
        token.basic_form == 'れる'
}

module.exports = function(context) {
    const helper = new RuleHelper(context);
    let {Syntax, report, getSource, RuleError} = context;
    return {
        [Syntax.Str](node){
            if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis])) {
                return;
            }
            let text = getSource(node);
            return kuromojin(text).then(tokens => {
                tokens.reduce((prev, current) => {
                    if (isTargetVerb(prev) && isRaWord(current)) {
                        report(node, new RuleError("ら抜き言葉を使用しています。", {
                            index: (current.word_position - 1)
                        }));
                    }
                    return current;
                });
            })
        }
    }
};<commit_msg>chore(rule): add ;<commit_after>// LICENSE : MIT
"use strict";
import {RuleHelper} from "textlint-rule-helper";
import kuromojin from "kuromojin";

function isTargetVerb(token) {
    return token.pos == '動詞' &&
        token.pos_detail_1 == '自立' &&
        token.conjugated_type == '一段' &&
        token.conjugated_form == '未然形';
}

function isRaWord(token) {
    return token.pos == '動詞' &&
        token.pos_detail_1 == '接尾' &&
        token.basic_form == 'れる'
}

module.exports = function(context) {
    const helper = new RuleHelper(context);
    let {Syntax, report, getSource, RuleError} = context;
    return {
        [Syntax.Str](node){
            if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis])) {
                return;
            }
            let text = getSource(node);
            return kuromojin(text).then(tokens => {
                tokens.reduce((prev, current) => {
                    if (isTargetVerb(prev) && isRaWord(current)) {
                        report(node, new RuleError("ら抜き言葉を使用しています。", {
                            index: (current.word_position - 1)
                        }));
                    }
                    return current;
                });
            });
        }
    }
};<|endoftext|>


<commit_before><commit_msg>Canvas manipulation<commit_after><|endoftext|>


<commit_before>/**
 * @module DOM
 * @submodule DOM
 * @for p5.Element
 */
define(function(require) {

  var p5 = require('core');

  /**
   * Base class for all elements added to a sketch, including canvas,
   * graphics buffers, and other HTML elements. Methods in blue are
   * included in the core functionality, methods in brown are added
   * with the p5.dom library.
   * It is not called directly, but p5.Element
   * objects are created by calling createCanvas, createGraphics,
   * or in the p5.dom library, createDiv, createImg, createInput, etc.
   *
   * @class p5.Element
   * @constructor
   * @param {String} elt DOM node that is wrapped
   * @param {Object} [pInst] pointer to p5 instance
   */
  p5.Element = function(elt, pInst) {
    /**
     * Underlying HTML element. All normal HTML methods can be called on this.
     *
     * @property elt
     */
    this.elt = elt;
    this._pInst = pInst;
    this._events = {};
    this.width = this.elt.offsetWidth;
    this.height = this.elt.offsetHeight;
  };

  /**
   *
   * Attaches the element to the parent specified. A way of setting
   * the container for the element. Accepts either a string ID, DOM
   * node, or p5.Element.
   *
   * @method parent
   * @param  {String|Object} parent the ID, DOM node, or p5.Element
   *                         of desired parent element
   * @return {p5.Element}
   * @example
   *

   * // in the html file:
   * <div id="myContainer"></div>
   * // in the js file:
   * var cnv = createCanvas(100, 100);
   * cnv.parent("myContainer");
   *

   *

   * var div0 = createDiv('this is the parent');
   * var div1 = createDiv('this is the child');
   * div1.parent(div0); // use p5.Element
   *

   *

   * var div0 = createDiv('this is the parent');
   * div0.id('apples');
   * var div1 = createDiv('this is the child');
   * div1.parent('apples'); // use id
   *

   *

   * var elt = document.getElementById('myParentDiv');
   * var div1 = createDiv('this is the child');
   * div1.parent(elt); // use element from page
   *

   */
  p5.Element.prototype.parent = function(p) {
    if (typeof p === 'string') {
      p = document.getElementById(p);
    } else if (p instanceof p5.Element) {
      p = p.elt;
    }
    p.appendChild(this.elt);
    return this;
  };

  /**
   *
   * Sets the ID of the element
   *
   * @method id
   * @param  {String} id ID of the element
   * @return {p5.Element}
   */
  p5.Element.prototype.id = function(id) {
    this.elt.id = id;
    return this;
  };

  /**
   *
   * Adds given class to the element
   *
   * @method class
   * @param  {String} class class to add
   * @return {p5.Element}
   */
  p5.Element.prototype.class = function(c) {
    this.elt.className += ' '+c;
    return this;
  };

  /**
   * The .mousePressed() function is called once after every time a
   * mouse button is pressed over the element. This can be used to
   * attach element specific event listeners.
   *
   * @method mousePressed
   * @param  {Function} fxn function to be fired when mouse is
   *                    pressed over the element.
   * @return {p5.Element}
   * @example
   *

   * var cnv;
   * var d;
   * var g;
   * function setup() {
   *   cnv = createCanvas(100, 100);
   *   cnv.mousePressed(changeGray); // attach listener for
   *                                 // canvas click only
   *   d = 10;
   *   g = 100;
   * }
   *
   * function draw() {
   *   background(g);
   *   ellipse(width/2, height/2, d, d);
   * }
   *
   * // this function fires with any click anywhere
   * function mousePressed() {
   *   d = d + 10;
   * }
   *
   * // this function fires only when cnv is clicked
   * function changeGray() {
   *   g = random(0, 255);
   * }
   *

   *
   */
  p5.Element.prototype.mousePressed = function (fxn) {
    attachListener('mousedown', fxn, this);
    attachListener('touchstart', fxn, this);
    return this;
  };

  /**
   * The .mouseWheel() function is called once after every time a
   * mouse wheel is scrolled over the element. This can be used to
   * attach element specific event listeners.

   * The event.wheelDelta or event.detail property returns negative values if
   * the mouse wheel if rotated up or away from the user and positive in the
   * other direction. On OS X with "natural" scrolling enabled, the values are
   * opposite.
   *
   * @method mouseWheel
   * @param  {Function} fxn function to be fired when mouse wheel is
   *                    scrolled over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseWheel = function (fxn) {
    attachListener('mousewheel', fxn, this);
    return this;
  };

  /**
   * The .mouseReleased() function is called once after every time a
   * mouse button is released over the element. This can be used to
   * attach element specific event listeners.
   *
   * @method mouseReleased
   * @param  {Function} fxn function to be fired when mouse is
   *                    released over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseReleased = function (fxn) {
    attachListener('mouseup', fxn, this);
    attachListener('touchend', fxn, this);
    return this;
  };

  /**
   * The .mouseClicked() function is called once after a mouse button is
   * pressed and released over the element. This can be used to
   * attach element specific event listeners.
   *
   * @method mouseClicked
   * @param  {Function} fxn function to be fired when mouse is
   *                    clicked over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseClicked = function (fxn) {
    attachListener('click', fxn, this);
    return this;
  };

  /**
   * The .mouseMoved() function is called once every time a
   * mouse moves over the element. This can be used to attach an
   * element specific event listener.
   *
   * @method mouseMoved
   * @param  {Function} fxn function to be fired when mouse is
   *                    moved over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseMoved = function (fxn) {
    attachListener('mousemove', fxn, this);
    attachListener('touchmove', fxn, this);
    return this;
  };

  /**
   * The .mouseOver() function is called once after every time a
   * mouse moves onto the element. This can be used to attach an
   * element specific event listener.
   *
   * @method mouseOver
   * @param  {Function} fxn function to be fired when mouse is
   *                    moved over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseOver = function (fxn) {
    attachListener('mouseover', fxn, this);
    return this;
  };

  /**
   * The .mouseOut() function is called once after every time a
   * mouse moves off the element. This can be used to attach an
   * element specific event listener.
   *
   * @method mouseOut
   * @param  {Function} fxn function to be fired when mouse is
   *                    moved off the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseOut = function (fxn) {
    attachListener('mouseout', fxn, this);
    return this;
  };

  /**
   * The .touchStarted() function is called once after every time a touch is
   * registered. This can be used to attach element specific event listeners.
   *
   * @method touchStarted
   * @param  {Function} fxn function to be fired when touch is
   *                    started over the element.
   * @return {p5.Element}
   * @example
   *

   * var cnv;
   * var d;
   * var g;
   * function setup() {
   *   cnv = createCanvas(100, 100);
   *   cnv.touchStarted(changeGray); // attach listener for
   *                                 // canvas click only
   *   d = 10;
   *   g = 100;
   * }
   *
   * function draw() {
   *   background(g);
   *   ellipse(width/2, height/2, d, d);
   * }
   *
   * // this function fires with any touch anywhere
   * function touchStarted() {
   *   d = d + 10;
   * }
   *
   * // this function fires only when cnv is clicked
   * function changeGray() {
   *   g = random(0, 255);
   * }
   *

   *
   */
  p5.Element.prototype.touchStarted = function (fxn) {
    attachListener('touchstart', fxn, this);
    attachListener('mousedown', fxn, this);
    return this;
  };

  /**
   * The .touchMoved() function is called once after every time a touch move is
   * registered. This can be used to attach element specific event listeners.
   *
   * @method touchMoved
   * @param  {Function} fxn function to be fired when touch is moved
   *                    over the element.
   * @return {p5.Element}
   * @example
   *

   * var cnv;
   * var g;
   * function setup() {
   *   cnv = createCanvas(100, 100);
   *   cnv.touchMoved(changeGray); // attach listener for
   *                               // canvas click only
   *   g = 100;
   * }
   *
   * function draw() {
   *   background(g);
   * }
   *
   * // this function fires only when cnv is clicked
   * function changeGray() {
   *   g = random(0, 255);
   * }
   *

   *
   */
  p5.Element.prototype.touchMoved = function (fxn) {
    attachListener('touchmove', fxn, this);
    attachListener('mousemove', fxn, this);
    return this;
  };

  /**
   * The .touchEnded() function is called once after every time a touch is
   * registered. This can be used to attach element specific event listeners.
   *
   * @method touchEnded
   * @param  {Function} fxn function to be fired when touch is
   *                    ended over the element.
   * @return {p5.Element}
   * @example
   *

   * var cnv;
   * var d;
   * var g;
   * function setup() {
   *   cnv = createCanvas(100, 100);
   *   cnv.touchEnded(changeGray);   // attach listener for
   *                                 // canvas click only
   *   d = 10;
   *   g = 100;
   * }
   *
   * function draw() {
   *   background(g);
   *   ellipse(width/2, height/2, d, d);
   * }
   *
   * // this function fires with any touch anywhere
   * function touchEnded() {
   *   d = d + 10;
   * }
   *
   * // this function fires only when cnv is clicked
   * function changeGray() {
   *   g = random(0, 255);
   * }
   *

   *
   */
  p5.Element.prototype.touchEnded = function (fxn) {
    attachListener('touchend', fxn, this);
    attachListener('mouseup', fxn, this);
    return this;
  };

  function attachListener(ev, fxn, ctx) {
    // LM removing, not sure why we had this?
    // var _this = ctx;
    // var f = function (e) { fxn(e, _this); };
    var f = fxn.bind(ctx);
    ctx.elt.addEventListener(ev, f, false);
    ctx._events[ev] = f;
  }

  /**
   * Helper fxn for sharing pixel methods
   *
   */
  p5.Element.prototype._setProperty = function (prop, value) {
    this[prop] = value;
  };

  return p5.Element;
});
<commit_msg>adding dragLeave, dragOver, and drop events for p5.Element #370<commit_after>/**
 * @module DOM
 * @submodule DOM
 * @for p5.Element
 */
define(function(require) {

  var p5 = require('core');

  /**
   * Base class for all elements added to a sketch, including canvas,
   * graphics buffers, and other HTML elements. Methods in blue are
   * included in the core functionality, methods in brown are added
   * with the p5.dom library.
   * It is not called directly, but p5.Element
   * objects are created by calling createCanvas, createGraphics,
   * or in the p5.dom library, createDiv, createImg, createInput, etc.
   *
   * @class p5.Element
   * @constructor
   * @param {String} elt DOM node that is wrapped
   * @param {Object} [pInst] pointer to p5 instance
   */
  p5.Element = function(elt, pInst) {
    /**
     * Underlying HTML element. All normal HTML methods can be called on this.
     *
     * @property elt
     */
    this.elt = elt;
    this._pInst = pInst;
    this._events = {};
    this.width = this.elt.offsetWidth;
    this.height = this.elt.offsetHeight;
  };

  /**
   *
   * Attaches the element to the parent specified. A way of setting
   * the container for the element. Accepts either a string ID, DOM
   * node, or p5.Element.
   *
   * @method parent
   * @param  {String|Object} parent the ID, DOM node, or p5.Element
   *                         of desired parent element
   * @return {p5.Element}
   * @example
   *

   * // in the html file:
   * <div id="myContainer"></div>
   * // in the js file:
   * var cnv = createCanvas(100, 100);
   * cnv.parent("myContainer");
   *

   *

   * var div0 = createDiv('this is the parent');
   * var div1 = createDiv('this is the child');
   * div1.parent(div0); // use p5.Element
   *

   *

   * var div0 = createDiv('this is the parent');
   * div0.id('apples');
   * var div1 = createDiv('this is the child');
   * div1.parent('apples'); // use id
   *

   *

   * var elt = document.getElementById('myParentDiv');
   * var div1 = createDiv('this is the child');
   * div1.parent(elt); // use element from page
   *

   */
  p5.Element.prototype.parent = function(p) {
    if (typeof p === 'string') {
      p = document.getElementById(p);
    } else if (p instanceof p5.Element) {
      p = p.elt;
    }
    p.appendChild(this.elt);
    return this;
  };

  /**
   *
   * Sets the ID of the element
   *
   * @method id
   * @param  {String} id ID of the element
   * @return {p5.Element}
   */
  p5.Element.prototype.id = function(id) {
    this.elt.id = id;
    return this;
  };

  /**
   *
   * Adds given class to the element
   *
   * @method class
   * @param  {String} class class to add
   * @return {p5.Element}
   */
  p5.Element.prototype.class = function(c) {
    this.elt.className += ' '+c;
    return this;
  };

  /**
   * The .mousePressed() function is called once after every time a
   * mouse button is pressed over the element. This can be used to
   * attach element specific event listeners.
   *
   * @method mousePressed
   * @param  {Function} fxn function to be fired when mouse is
   *                    pressed over the element.
   * @return {p5.Element}
   * @example
   *

   * var cnv;
   * var d;
   * var g;
   * function setup() {
   *   cnv = createCanvas(100, 100);
   *   cnv.mousePressed(changeGray); // attach listener for
   *                                 // canvas click only
   *   d = 10;
   *   g = 100;
   * }
   *
   * function draw() {
   *   background(g);
   *   ellipse(width/2, height/2, d, d);
   * }
   *
   * // this function fires with any click anywhere
   * function mousePressed() {
   *   d = d + 10;
   * }
   *
   * // this function fires only when cnv is clicked
   * function changeGray() {
   *   g = random(0, 255);
   * }
   *

   *
   */
  p5.Element.prototype.mousePressed = function (fxn) {
    attachListener('mousedown', fxn, this);
    attachListener('touchstart', fxn, this);
    return this;
  };

  /**
   * The .mouseWheel() function is called once after every time a
   * mouse wheel is scrolled over the element. This can be used to
   * attach element specific event listeners.

   * The event.wheelDelta or event.detail property returns negative values if
   * the mouse wheel if rotated up or away from the user and positive in the
   * other direction. On OS X with "natural" scrolling enabled, the values are
   * opposite.
   *
   * @method mouseWheel
   * @param  {Function} fxn function to be fired when mouse wheel is
   *                    scrolled over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseWheel = function (fxn) {
    attachListener('mousewheel', fxn, this);
    return this;
  };

  /**
   * The .mouseReleased() function is called once after every time a
   * mouse button is released over the element. This can be used to
   * attach element specific event listeners.
   *
   * @method mouseReleased
   * @param  {Function} fxn function to be fired when mouse is
   *                    released over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseReleased = function (fxn) {
    attachListener('mouseup', fxn, this);
    attachListener('touchend', fxn, this);
    return this;
  };

  /**
   * The .mouseClicked() function is called once after a mouse button is
   * pressed and released over the element. This can be used to
   * attach element specific event listeners.
   *
   * @method mouseClicked
   * @param  {Function} fxn function to be fired when mouse is
   *                    clicked over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseClicked = function (fxn) {
    attachListener('click', fxn, this);
    return this;
  };

  /**
   * The .mouseMoved() function is called once every time a
   * mouse moves over the element. This can be used to attach an
   * element specific event listener.
   *
   * @method mouseMoved
   * @param  {Function} fxn function to be fired when mouse is
   *                    moved over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseMoved = function (fxn) {
    attachListener('mousemove', fxn, this);
    attachListener('touchmove', fxn, this);
    return this;
  };

  /**
   * The .mouseOver() function is called once after every time a
   * mouse moves onto the element. This can be used to attach an
   * element specific event listener.
   *
   * @method mouseOver
   * @param  {Function} fxn function to be fired when mouse is
   *                    moved over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseOver = function (fxn) {
    attachListener('mouseover', fxn, this);
    return this;
  };

  /**
   * The .mouseOut() function is called once after every time a
   * mouse moves off the element. This can be used to attach an
   * element specific event listener.
   *
   * @method mouseOut
   * @param  {Function} fxn function to be fired when mouse is
   *                    moved off the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.mouseOut = function (fxn) {
    attachListener('mouseout', fxn, this);
    return this;
  };

  /**
   * The .touchStarted() function is called once after every time a touch is
   * registered. This can be used to attach element specific event listeners.
   *
   * @method touchStarted
   * @param  {Function} fxn function to be fired when touch is
   *                    started over the element.
   * @return {p5.Element}
   * @example
   *

   * var cnv;
   * var d;
   * var g;
   * function setup() {
   *   cnv = createCanvas(100, 100);
   *   cnv.touchStarted(changeGray); // attach listener for
   *                                 // canvas click only
   *   d = 10;
   *   g = 100;
   * }
   *
   * function draw() {
   *   background(g);
   *   ellipse(width/2, height/2, d, d);
   * }
   *
   * // this function fires with any touch anywhere
   * function touchStarted() {
   *   d = d + 10;
   * }
   *
   * // this function fires only when cnv is clicked
   * function changeGray() {
   *   g = random(0, 255);
   * }
   *

   *
   */
  p5.Element.prototype.touchStarted = function (fxn) {
    attachListener('touchstart', fxn, this);
    attachListener('mousedown', fxn, this);
    return this;
  };

  /**
   * The .touchMoved() function is called once after every time a touch move is
   * registered. This can be used to attach element specific event listeners.
   *
   * @method touchMoved
   * @param  {Function} fxn function to be fired when touch is moved
   *                    over the element.
   * @return {p5.Element}
   * @example
   *

   * var cnv;
   * var g;
   * function setup() {
   *   cnv = createCanvas(100, 100);
   *   cnv.touchMoved(changeGray); // attach listener for
   *                               // canvas click only
   *   g = 100;
   * }
   *
   * function draw() {
   *   background(g);
   * }
   *
   * // this function fires only when cnv is clicked
   * function changeGray() {
   *   g = random(0, 255);
   * }
   *

   *
   */
  p5.Element.prototype.touchMoved = function (fxn) {
    attachListener('touchmove', fxn, this);
    attachListener('mousemove', fxn, this);
    return this;
  };

  /**
   * The .touchEnded() function is called once after every time a touch is
   * registered. This can be used to attach element specific event listeners.
   *
   * @method touchEnded
   * @param  {Function} fxn function to be fired when touch is
   *                    ended over the element.
   * @return {p5.Element}
   * @example
   *

   * var cnv;
   * var d;
   * var g;
   * function setup() {
   *   cnv = createCanvas(100, 100);
   *   cnv.touchEnded(changeGray);   // attach listener for
   *                                 // canvas click only
   *   d = 10;
   *   g = 100;
   * }
   *
   * function draw() {
   *   background(g);
   *   ellipse(width/2, height/2, d, d);
   * }
   *
   * // this function fires with any touch anywhere
   * function touchEnded() {
   *   d = d + 10;
   * }
   *
   * // this function fires only when cnv is clicked
   * function changeGray() {
   *   g = random(0, 255);
   * }
   *

   *
   */
  p5.Element.prototype.touchEnded = function (fxn) {
    attachListener('touchend', fxn, this);
    attachListener('mouseup', fxn, this);
    return this;
  };

  /**
   * The .dragOver() function is called once after every time a
   * file is dragged over the element. This can be used to attach an
   * element specific event listener.
   *
   * @method dragOver
   * @param  {Function} fxn function to be fired when mouse is
   *                    dragged over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.dragOver = function (fxn) {
    attachListener('dragover', fxn, this);
    return this;
  };

  /**
   * The .dragLeave() function is called once after every time a
   * dragged file leaves the element area. This can be used to attach an
   * element specific event listener.
   *
   * @method dragLeave
   * @param  {Function} fxn function to be fired when mouse is
   *                    dragged over the element.
   * @return {p5.Element}
   */
  p5.Element.prototype.dragLeave = function (fxn) {
    attachListener('dragleave', fxn, this);
    return this;
  };

  /**
   * The .drop() function is called for each file dropped on the element.
   * It requires a callback that is passed a p5.File object
   *
   * @method drop
   * @param  {Function} callback to receive loaded file.
   * @return {p5.Element}
   */
  p5.Element.prototype.drop = function (fxn, callback) {

    // If you want to be able to drop you've got to turn off
    // a lot of default behavior
    attachListener('dragover',function(evt) {
      evt.stopPropagation();
      evt.preventDefault();
    },this);

    // If this is a drag area we need to turn off the default behavior
    attachListener('dragleave',function(evt) {
      evt.stopPropagation();
      evt.preventDefault();
    },this);

    // Make a file loader callback and trigger user's callback
    function makeLoader(theFile) {
      // Making a p5.File object
      var p5file = new p5.File(theFile);
      return function(e) {
        p5file.data = e.target.result;
        callback(p5file);
      };
    }

    // If just one argument it's the callback for the files
    if (arguments.length < 2) {
      callback = fxn;
    // If two we have a separate callback for the drop moment
    } else {
      attachListener('drop', fxn, this);
    }

    // Deal with the files
    attachListener('drop', function(evt) {

      evt.stopPropagation();
      evt.preventDefault();

      // A FileList
      var files = evt.dataTransfer.files;

      // Load each one and trigger the callback
      for (var i = 0; i < files.length; i++) {
        var f = files[i];
        var reader = new FileReader();
        reader.onload = makeLoader(f);

        // Text of data?
        // This should likely be improved
        if (f.type === 'text') {
          reader.readAsText(f);
        } else {
          reader.readAsDataURL(f);
        }
      }
    }, this);

    return this;
  };

  function attachListener(ev, fxn, ctx) {
    // LM removing, not sure why we had this?
    // var _this = ctx;
    // var f = function (e) { fxn(e, _this); };
    var f = fxn.bind(ctx);
    ctx.elt.addEventListener(ev, f, false);
    ctx._events[ev] = f;
  }

  /**
   * Helper fxn for sharing pixel methods
   *
   */
  p5.Element.prototype._setProperty = function (prop, value) {
    this[prop] = value;
  };

  return p5.Element;
});
<|endoftext|>


<commit_before>/**
 * jQuery.contextMenu - Show a custom context when right clicking something
 * Jonas Arnklint, http://starksignal.com
 * Released into the public domain
 * Date: Oct 7, 2010
 * @author Jonas Arnklint
 * @version 1.0
 *
 *
 * Basic calling syntax:

$("selector").contextMenu({
    'Context Menu Item 1': {
        click: function(element){  // element is the jquery obj clicked on when contextMenu launched
            alert('Menu item 1 clicked');
            element.css({backgroundColor: 'pink'}); // just as example the clicked items backgorund is changed
        },
        class: "menu-item-1" // a custom css class for this menu item (usable for styling)
    },
    'Second menu item': {
        click: function(element){ alert('second clicked'); },
        class: "second-menu-item"
    }
});

 * These are the options you can pass into the plugin. No fancy schmancy, but KISS.
 *
 */
jQuery.fn.contextMenu = function ( name, actions ) {
    $(document).bind("contextmenu",function(e){ return false; }); // yuk :)

    var menu = $('

').hide().appendTo('body'),
        active_element = null; // last clicked element that responds with contextMenu

    var hide_menu = function(){
        $('.context-menu').hide()
    }

    $.each(actions, function(me, item_options){
        $('
'+me+'
')
            .appendTo(menu)
            .bind('click', function(e){
                item_options.click(active_element);
            });
    });

    $('body').click(function() {
         hide_menu(); //Hide the menus if visible
    });

    return $(this).live('mousedown', function(e){
        if( e.which == 3 ){
            hide_menu();
            menu.show()
                .css({
                    position: 'absolute',
                    top: e.pageY,
                    left: e.pageX,
                    zIndex: 1000
                });
            e.preventDefault();
        }
    });
}
<commit_msg>Context menu items are now links for easier css hover styling<commit_after>/**
 * jQuery.contextMenu - Show a custom context when right clicking something
 * Jonas Arnklint, http://starksignal.com
 * Released into the public domain
 * Date: Oct 7, 2010
 * @author Jonas Arnklint
 * @version 1.0
 *
 *
 * Basic calling syntax:

$("selector").contextMenu({
    'Context Menu Item 1': {
        click: function(element){  // element is the jquery obj clicked on when contextMenu launched
            alert('Menu item 1 clicked');
            element.css({backgroundColor: 'pink'}); // just as example the clicked items backgorund is changed
        },
        class: "menu-item-1" // a custom css class for this menu item (usable for styling)
    },
    'Second menu item': {
        click: function(element){ alert('second clicked'); },
        class: "second-menu-item"
    }
});

 * These are the options you can pass into the plugin. No fancy schmancy, but KISS.
 *
 */
jQuery.fn.contextMenu = function ( name, actions ) {
    $(document).bind("contextmenu",function(e){ return false; }); // yuk :)

    var menu = $('

').hide().appendTo('body'),
        active_element = null, // last clicked element that responds with contextMenu
        hide_menu = function(){
            $('.context-menu').hide()
        };

    $(".context-menu").delegate("a", "click", function(e){
        e.preventDefault();
    });

    $.each(actions, function(me, item_options){
        $('
'+me+'
')
            .appendTo(menu)
            .bind('click', function(e){
                item_options.click(active_element);
            });
    });

    $('body').click(function() {
         hide_menu(); //Hide the menus if visible
    });

    return $(this).live('mousedown', function(e){
        if( e.which == 3 ){
            hide_menu();
            menu.show()
                .css({
                    position: 'absolute',
                    top: e.pageY,
                    left: e.pageX,
                    zIndex: 1000
                });
            e.preventDefault();
        }
    });
}
<|endoftext|>


<commit_before><commit_msg>Convert BPM dynamically based on number of differences (up to 10) Added some comments<commit_after><|endoftext|>


<commit_before><commit_msg>trying to add in statefull convo to mix<commit_after><|endoftext|>


<commit_before>(function($) {

"use strict";

/**
 * jQuery.imageloader
 * (C) 2012, Takashi Mizohata
 * http://beatak.github.com/jquery-imageloader/
 * MIT LICENSE
 */

var DEFAULT_OPTIONS = {
  selector: '',
  dataattr: 'src',
  background: false,
  callback: null,
  timeout: 5000
};

var init = function (_i, self, opts) {
  var q = Queue.getInstance();
  var $this = $(self);
  var defaults = $.extend({}, DEFAULT_OPTIONS, opts || {});
  var ns = '_' + ('' + (new Date()).valueOf()).slice(-7);
  var $elms;
  var len = 0;

  if (defaults.selector === '' && $this.data(defaults.dataattr) ) {
    $elms = $this;
    len = 1;
  }
  else {
    $elms = $this.find([defaults.selector, '[data-', defaults.dataattr, ']'].join(''));
    len = $elms.length;
  }

  $this.data(
    ns,
    {
      callback: defaults.callback,
      isLoading: true,
      loadedImageCounter: 0,
      length: len
    }
  );

  if (len === 0) {
    finishImageLoad(this, ns);
  }
  else {
    $elms.each(
      function (i, elm) {
        q.add(buildImageLoadFunc(elm, self, ns, defaults.background, defaults.dataattr, defaults.timeout));
      }
    );
    // console.log(['we are gonna load ', len, ' image(s) on ', ns].join(''));
    $this.on('loadImage.' + ns, onLoadImage);
    q.run();
  }
  return this;
};

// ===================================================================

var onLoadImage = function (ev, elm) {
  // console.log('onLoadImage: ', ev.namespace);
  var parent = ev.currentTarget;
  var defaults = $(parent).data(ev.namespace);
  if (!defaults.isLoading) {
    // console.log('onLoadImage: is not loading but still called?');
    return;
  }
  ++defaults.loadedImageCounter;
  if (defaults.loadedImageCounter >= defaults.length) {
    finishImageLoad(parent, ev.namespace);
  }
};

var finishImageLoad = function (parent, ns) {
  // console.log('finishImageLoad: ', ns);
  var $parent = $(parent);
  var data = $parent.data();
  var callback = data[ns].callback;
  $parent.off('loadImage.' + ns, onLoadImage);
  delete data[ns];
  if (typeof callback === 'function') {
    setTimeout(
      function () {
        callback(parent);
      },
      $.imageloader.queueInterval * 2
    );
  }
};

var buildImageLoadFunc = function (elm, parent, namespace, isBg, attr, milsec_timeout) {
  var $elm = $(elm);
  var src = $elm.data('src');
  var hasFinished = false;

  var onFinishLoagImage = function (ev) {
    if (ev && ev.type === 'error') {
      $elm.remove();
    }
    // delete attribute
    $elm.removeAttr( ['data-', attr].join('') );
    $(parent).triggerHandler('loadImage.' + namespace, elm);
  };

  return function () {
    var $img = $('<img />')
      .bind(
        'error',
        function (ev) {
          hasFinished = true;
          clearTimeout(timer_handler);
          $(this).unbind('error').unbind('load');
          onFinishLoagImage(ev);
        }
      )
      .bind(
        'load',
        function(ev) {
          hasFinished = true;
          clearTimeout(timer_handler);
          $(this).unbind('error').unbind('load');
          if (isBg) {
            $elm.css('background-image', ['url(', src, ')'].join(''));
          }
          else {
            $elm.attr('src', src);
          }
          onFinishLoagImage(ev);
        }
      )
      .attr('src', src);
    var timer_handler = setTimeout(
      function () {
        if (hasFinished === false) {
          // console.log('timeout');
          $img.trigger('error');
        }
      },
      milsec_timeout
    );
  };
};

// ===================================================================

var _queue_instance_;
var Queue = {
  getInstance: function () {
    if (_queue_instance_ instanceof QueueImpl === false) {
      _queue_instance_ = new QueueImpl();
    }
    return _queue_instance_;
  }
};

var QueueImpl = function () {
  this.index = 0;
  this.queue = [];
  this.isRunning = false;
};

QueueImpl.prototype.add = function (func) {
  if (typeof func !== 'function') {
    throw new Error('you can only pass function.');
  }
  this.queue.push(func);
};

QueueImpl.prototype.run = function (firenow) {
  var run = $.proxy(this.run, this);
  firenow = firenow || false;
  if (this.isRunning && !firenow) {
    return;
  }
  this.isRunning = true;
  this.queue[this.index++]();
  if (this.index < this.queue.length) {
    setTimeout(
      function () {
        run(true);
      },
      $.imageloader.queueInterval
    );
  }
  else {
    this.isRunning = false;
  }
};

// ===================================================================

$.imageloader = {
  queueInterval: 17
};

$.fn.imageloader = function (opts) {
  return this.each(
    function (i, elm) {
      init(i, elm, opts);
    }
  );
};

})(jQuery);<commit_msg>adding a new each functionality<commit_after>(function($) {

"use strict";

/**
 * jQuery.imageloader
 * (C) 2012, Takashi Mizohata
 * http://beatak.github.com/jquery-imageloader/
 * MIT LICENSE
 */

var DEFAULT_OPTIONS = {
  selector: '',
  dataattr: 'src',
  background: false,
  each: null,
  callback: null,
  timeout: 5000
};

var init = function (_i, self, opts) {
  var q = Queue.getInstance();
  var $this = $(self);
  var defaults = $.extend({}, DEFAULT_OPTIONS, opts || {});
  var ns = '_' + ('' + (new Date()).valueOf()).slice(-7);
  var $elms;
  var len = 0;

  if (defaults.selector === '' && $this.data(defaults.dataattr) ) {
    $elms = $this;
    len = 1;
  }
  else {
    $elms = $this.find([defaults.selector, '[data-', defaults.dataattr, ']'].join(''));
    len = $elms.length;
  }

  $this.data(
    ns,
    {
      each: defaults.each,
      callback: defaults.callback,
      isLoading: true,
      loadedImageCounter: 0,
      length: len
    }
  );

  if (len === 0) {
    finishImageLoad(this, ns);
  }
  else {
    $elms.each(
      function (i, elm) {
        q.add(buildImageLoadFunc(elm, self, ns, defaults.background, defaults.dataattr, defaults.timeout));
      }
    );
    // console.log(['we are gonna load ', len, ' image(s) on ', ns].join(''));
    $this.on('loadImage.' + ns, onLoadImage);
    q.run();
  }
  return this;
};

// ===================================================================

var onLoadImage = function (ev, elm) {
  // console.log('onLoadImage: ', ev.namespace);
  var parent = ev.currentTarget;
  var defaults = $(parent).data(ev.namespace);
  if (!defaults.isLoading) {
    // console.log('onLoadImage: is not loading but still called?');
    return;
  }
  if (typeof defaults.each === 'function') {
    defaults.each(elm);
  }
  ++defaults.loadedImageCounter;
  if (defaults.loadedImageCounter >= defaults.length) {
    finishImageLoad(parent, ev.namespace);
  }
};

var finishImageLoad = function (parent, ns) {
  // console.log('finishImageLoad: ', ns);
  var $parent = $(parent);
  var data = $parent.data();
  var callback = data[ns].callback;
  $parent.off('loadImage.' + ns, onLoadImage);
  delete data[ns];
  if (typeof callback === 'function') {
    setTimeout(
      function () {
        callback(parent);
      },
      $.imageloader.queueInterval * 2
    );
  }
};

var buildImageLoadFunc = function (elm, parent, namespace, isBg, attr, milsec_timeout) {
  var $elm = $(elm);
  var src = $elm.data('src');
  var hasFinished = false;

  var onFinishLoagImage = function (ev) {
    if (ev && ev.type === 'error') {
      $elm.remove();
    }
    // delete attribute
    $elm.removeAttr( ['data-', attr].join('') );
    $(parent).triggerHandler('loadImage.' + namespace, elm);
  };

  return function () {
    var $img = $('<img />')
      .bind(
        'error',
        function (ev) {
          hasFinished = true;
          clearTimeout(timer_handler);
          $(this).unbind('error').unbind('load');
          onFinishLoagImage(ev);
        }
      )
      .bind(
        'load',
        function(ev) {
          hasFinished = true;
          clearTimeout(timer_handler);
          $(this).unbind('error').unbind('load');
          if (isBg) {
            $elm.css('background-image', ['url(', src, ')'].join(''));
          }
          else {
            $elm.attr('src', src);
          }
          onFinishLoagImage(ev);
        }
      )
      .attr('src', src);
    var timer_handler = setTimeout(
      function () {
        if (hasFinished === false) {
          // console.log('timeout');
          $img.trigger('error');
        }
      },
      milsec_timeout
    );
  };
};

// ===================================================================

var _queue_instance_;
var Queue = {
  getInstance: function () {
    if (_queue_instance_ instanceof QueueImpl === false) {
      _queue_instance_ = new QueueImpl();
    }
    return _queue_instance_;
  }
};

var QueueImpl = function () {
  this.index = 0;
  this.queue = [];
  this.isRunning = false;
};

QueueImpl.prototype.add = function (func) {
  if (typeof func !== 'function') {
    throw new Error('you can only pass function.');
  }
  this.queue.push(func);
};

QueueImpl.prototype.run = function (firenow) {
  var run = $.proxy(this.run, this);
  firenow = firenow || false;
  if (this.isRunning && !firenow) {
    return;
  }
  this.isRunning = true;
  this.queue[this.index++]();
  if (this.index < this.queue.length) {
    setTimeout(
      function () {
        run(true);
      },
      $.imageloader.queueInterval
    );
  }
  else {
    this.isRunning = false;
  }
};

// ===================================================================

$.imageloader = {
  queueInterval: 17
};

$.fn.imageloader = function (opts) {
  return this.each(
    function (i, elm) {
      init(i, elm, opts);
    }
  );
};

})(jQuery);<|endoftext|>


<commit_before>/**
 * Display a nice easy to use multiselect list
 * @Version: 1.3
 * @Author: Patrick Springstubbe
 * @Contact: @JediNobleclem
 * @Website: springstubbe.us
 * @Source: https://github.com/nobleclem/jQuery-MultiSelect
 * @Notes: If select list is hidden on page load use the jquery.actual plugin
 *         to resolve issues with preselected items placeholder text
 *         https://github.com/dreamerslab/jquery.actual
 *
 * Usage:
 *     $('select[multiple]').multiselect();
 *     $('select[multiple]').multiselect({ placeholder: 'Select options' });
 *
 **/
(function($){
    var msCounter = 1;
    $.fn.multiselect = function( options ){
        var defaults = {
            placeholder   : '',    // text to use in dummy input
            columns       : 1,     // how many columns should be use to show options
            maxWidth      : null,  // maximum width of option overlay (or selector)
            minHeight     : 200,   // minimum height of option overlay
            maxHeight     : null,  // maximum height of option overlay
            showCheckbox  : true,  // display the checkbox to the user
            jqActualOpts  : {},    // options for jquery.actual

            // @NOTE: these are for future development
            minSelect     : false, // minimum number of items that can be selected
            maxSelect     : false, // maximum number of items that can be selected
            groupSelect   : false, // select entire optgroup
            selectAllText : false, // add select all option
            searchOptions : false, // enable option search/filtering
        }
        options = $.extend( defaults, options );

        var func = {
            addOption: function( container, option )
            {
                container.text( $(option).text() );
                container.prepend(
                    $('<input type="checkbox" value="" title="" />')
                        .val( $(option).val() )
                        .attr( 'title', $(option).text() )
                        .attr( 'id', 'ms-opt-'+ msCounter )
                );

                if( $(option).attr( 'selected' ) ) {
                    container.addClass('selected');
                    container.find( 'input[type="checkbox"]' ).attr( 'checked', 'checked' );
                }

                var label = $('').attr( 'for', 'ms-opt-'+ msCounter );
                container.wrapInner( label );

                if( !options.showCheckbox ) {
                    container.find('input[id="ms-opt-'+ msCounter +'"]').hide();
                }

                msCounter = msCounter + 1;
            },

            ieVersion: function()
            {
                var myNav = navigator.userAgent.toLowerCase();
                return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
            }
        };

        // menuize each list
        return this.each(function(){
            // make sure this is a select list and not loaded
            if( this.nodeName != 'SELECT' || $(this).hasClass('jqmsLoaded') ) {
                return false;
            }

            // sanity check so we don't double load on a select element
            $(this).addClass('jqmsLoaded');

            // add option container
            $(this).after('
<button>None Selected</button>

');
            var placeholder = $(this).next('.ms-options-wrap').find('> button:first-child');
            var optionsWrap = $(this).next('.ms-options-wrap').find('> .ms-options');
            var optionsList = optionsWrap.find('> ul');
            var hasOptGroup = $(this).find('optgroup').length ? true : false;

            var maxWidth = null;
            if( typeof options.width == 'number' ) {
                optionsWrap.parent().css( 'position', 'relative' );
                maxWidth = options.width;
            }
            else if( typeof options.width == 'string' ) {
                $( options.width ).css( 'position', 'relative' );
                maxWidth = '100%';
            }
            else {
                optionsWrap.parent().css( 'position', 'relative' );
            }

            var maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
            if( options.maxHeight ) {
                maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
                maxHeight = maxHeight < options.minHeight ? options.minHeight : maxheight;
            }

            maxHeight = maxHeight < options.minHeight ? options.minHeight : maxHeight;

            optionsWrap.css({
                maxWidth : maxWidth,
                minHeight: options.minHeight,
                maxHeight: maxHeight,
                overflow : 'auto'
            }).hide();

            // isolate options scroll
            // @source: https://github.com/nobleclem/jQuery-IsolatedScroll
            optionsWrap.bind( 'touchmove mousewheel DOMMouseScroll', function ( e ) {
                if( ($(this).outerHeight() < $(this)[0].scrollHeight) ) {
                    var e0 = e.originalEvent,
                        delta = e0.wheelDelta || -e0.detail;

                    if( ($(this).outerHeight() + $(this)[0].scrollTop) > $(this)[0].scrollHeight ) {
                        e.preventDefault();
                        this.scrollTop += ( delta < 0 ? 1 : -1 );
                    }
                }
            });

            // hide options menus if click happens off of the list placeholder button
            $(window).off('click.ms-hideopts').on('click.ms-hideopts', function( event ){
                if( !$(event.target).closest('.ms-options-wrap').length ) {
                    $('.ms-options-wrap > .ms-options:visible').hide();
                }
            });

            // disable button action
            placeholder.bind('mousedown',function(){
                // hide other menus before showing this one
                $('.ms-options-wrap > .ms-options:visible').each(function(){
                    if( $(this).parent().prev()[0] != optionsWrap.parent().prev()[0] ) {
                        $(this).hide();
                    }
                });

                // show/hide options
                optionsWrap.toggle();

                // recalculate height
                if( optionsWrap.is(':visible') ) {
                    optionsWrap.css( 'maxHeight', '' );

                    var maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
                    if( options.maxHeight ) {
                        maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
                        maxHeight = maxHeight < options.minHeight ? options.minHeight : maxheight;
                    }
                    maxHeight = maxHeight < options.minHeight ? options.minHeight : maxHeight;

                    optionsWrap.css( 'maxHeight', maxHeight );
                }
            }).click(function( event ){ event.preventDefault(); });

            // add placeholder copy
            if( options.placeholder ) {
                placeholder.text( options.placeholder );
            }

            // hide native select list
            $(this).hide();

            // add options to wrapper
            $(this).children().each(function(){
                var container = $('

');

                // add group of items
                if( this.nodeName == 'OPTGROUP' ) {
                    container.addClass('optgroup');
                    container.append(''+ $(this).attr('label') +'');
                    container.find('> .label').css({
                        clear: 'both'
                    });
                    container.append('

');

                    $(this).children('option').each(function(){
                        var gContainer = $('

');
                        func.addOption( gContainer, this );

                        container.find('> ul').append( gContainer );
                    });
                }
                else if( this.nodeName == 'OPTION' ) {
                    func.addOption( container, this );
                }
                else {
                    // bad option
                    return true;
                }

                optionsList.append( container );
            });

            // COLUMNIZE
            if( hasOptGroup ) {
                // float non grouped options
                optionsList.find('> li:not(.optgroup)').css({
                    float: 'left',
                    width: (100 / options.columns) +'%'
                });

                // add CSS3 column styles
                optionsList.find('li.optgroup').css({
                    clear: 'both'
                }).find('> ul').css({
                    'column-count'        : options.columns,
                    'column-gap'          : 0,
                    '-webkit-column-count': options.columns,
                    '-webkit-column-gap'  : 0,
                    '-moz-column-count'   : options.columns,
                    '-moz-column-gap'     : 0
                });

                // for crappy IE versions float grouped options
                if( func.ieVersion() && func.ieVersion() < 10 ) {
                    optionsList.find('li.optgroup > ul > li').css({
                        float: 'left',
                        width: (100 / options.columns) +'%'
                    });
                }
            }
            else {
                // add CSS3 column styles
                optionsList.css({
                    'column-count'        : options.columns,
                    'column-gap'          : 0,
                    '-webkit-column-count': options.columns,
                    '-webkit-column-gap'  : 0,
                    '-moz-column-count'   : options.columns,
                    '-moz-column-gap'     : 0
                });

                // for crappy IE versions float grouped options
                if( func.ieVersion() && func.ieVersion() < 10 ) {
                    optionsList.find('> li').css({
                        float: 'left',
                        width: (100 / options.columns) +'%'
                    });
                }
            }

            // BIND SELECT ACTION
            optionsWrap.find('input[type="checkbox"]').click(function(){
                $(this).closest( 'li' ).toggleClass( 'selected' );

                var select = optionsWrap.parent().prev();

                // toggle clicked option
                select.find('option[value="'+ $(this).val() +'"]').attr(
                    'selected', $(this).is(':checked')
                ).closest('select').trigger('change');

                updatePlaceholderText();
            }).each(function( idx ){
                if( $(this).css('display').match(/block$/) ) {
                    var checkboxWidth = $(this).outerWidth();
                        checkboxWidth = checkboxWidth ? checkboxWidth : 15;

                    $(this).closest('label').css(
                        'padding-left',
                        (parseInt( $(this).closest('label').css('padding-left') ) * 2) + checkboxWidth
                    );
                }
            });

            // update selected placeholder text
            var updatePlaceholderText = function(){
                var select = optionsWrap.parent().prev();

                // get selected options
                var selOpts = [];
                select.find('option[selected="selected"]').each(function(){
                    selOpts.push( $(this).text() );
                });

                // UPDATE PLACEHOLDER TEXT WITH OPTIONS SELECTED
                placeholder.text( selOpts.join( ', ' ) );
                var copy = placeholder.clone().css({
                    display   : 'inline',
                    width     : 'auto',
                    visibility: 'hidden'
                }).appendTo( optionsWrap.parent() );

                // if the jquery.actual plugin is loaded use it to get the widths
                var copyWidth  = (typeof $.fn.actual !== 'undefined') ? copy.actual('width',options.jqActualOpts) : copy.width();
                var placeWidth = (typeof $.fn.actual !== 'undefined') ? placeholder.actual('width',options.jqActualOpts) : placeholder.width();

                // if copy is larger than button width use "# selected"
                if( copyWidth > placeWidth ) {
                    placeholder.text( selOpts.length +' selected' );
                }
                // if options selected then use those
                else if( selOpts.length ) {
                    placeholder.text( selOpts.join( ', ' ) );
                }
                // replace placeholder text
                else {
                    placeholder.text( options.placeholder );
                }

                // remove dummy element
                copy.remove();
            };

            updatePlaceholderText();
        });
    };
}(jQuery));
<commit_msg>fixed iteration skip return val.<commit_after>/**
 * Display a nice easy to use multiselect list
 * @Version: 1.3
 * @Author: Patrick Springstubbe
 * @Contact: @JediNobleclem
 * @Website: springstubbe.us
 * @Source: https://github.com/nobleclem/jQuery-MultiSelect
 * @Notes: If select list is hidden on page load use the jquery.actual plugin
 *         to resolve issues with preselected items placeholder text
 *         https://github.com/dreamerslab/jquery.actual
 *
 * Usage:
 *     $('select[multiple]').multiselect();
 *     $('select[multiple]').multiselect({ placeholder: 'Select options' });
 *
 **/
(function($){
    var msCounter = 1;
    $.fn.multiselect = function( options ){
        var defaults = {
            placeholder   : '',    // text to use in dummy input
            columns       : 1,     // how many columns should be use to show options
            maxWidth      : null,  // maximum width of option overlay (or selector)
            minHeight     : 200,   // minimum height of option overlay
            maxHeight     : null,  // maximum height of option overlay
            showCheckbox  : true,  // display the checkbox to the user
            jqActualOpts  : {},    // options for jquery.actual

            // @NOTE: these are for future development
            minSelect     : false, // minimum number of items that can be selected
            maxSelect     : false, // maximum number of items that can be selected
            groupSelect   : false, // select entire optgroup
            selectAllText : false, // add select all option
            searchOptions : false, // enable option search/filtering
        }
        options = $.extend( defaults, options );

        var func = {
            addOption: function( container, option )
            {
                container.text( $(option).text() );
                container.prepend(
                    $('<input type="checkbox" value="" title="" />')
                        .val( $(option).val() )
                        .attr( 'title', $(option).text() )
                        .attr( 'id', 'ms-opt-'+ msCounter )
                );

                if( $(option).attr( 'selected' ) ) {
                    container.addClass('selected');
                    container.find( 'input[type="checkbox"]' ).attr( 'checked', 'checked' );
                }

                var label = $('').attr( 'for', 'ms-opt-'+ msCounter );
                container.wrapInner( label );

                if( !options.showCheckbox ) {
                    container.find('input[id="ms-opt-'+ msCounter +'"]').hide();
                }

                msCounter = msCounter + 1;
            },

            ieVersion: function()
            {
                var myNav = navigator.userAgent.toLowerCase();
                return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
            }
        };

        // menuize each list
        return this.each(function(){
            // make sure this is a select list and not loaded
            if( this.nodeName != 'SELECT' || $(this).hasClass('jqmsLoaded') ) {
                return true;
            }

            // sanity check so we don't double load on a select element
            $(this).addClass('jqmsLoaded');

            // add option container
            $(this).after('
<button>None Selected</button>

');
            var placeholder = $(this).next('.ms-options-wrap').find('> button:first-child');
            var optionsWrap = $(this).next('.ms-options-wrap').find('> .ms-options');
            var optionsList = optionsWrap.find('> ul');
            var hasOptGroup = $(this).find('optgroup').length ? true : false;

            var maxWidth = null;
            if( typeof options.width == 'number' ) {
                optionsWrap.parent().css( 'position', 'relative' );
                maxWidth = options.width;
            }
            else if( typeof options.width == 'string' ) {
                $( options.width ).css( 'position', 'relative' );
                maxWidth = '100%';
            }
            else {
                optionsWrap.parent().css( 'position', 'relative' );
            }

            var maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
            if( options.maxHeight ) {
                maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
                maxHeight = maxHeight < options.minHeight ? options.minHeight : maxheight;
            }

            maxHeight = maxHeight < options.minHeight ? options.minHeight : maxHeight;

            optionsWrap.css({
                maxWidth : maxWidth,
                minHeight: options.minHeight,
                maxHeight: maxHeight,
                overflow : 'auto'
            }).hide();

            // isolate options scroll
            // @source: https://github.com/nobleclem/jQuery-IsolatedScroll
            optionsWrap.bind( 'touchmove mousewheel DOMMouseScroll', function ( e ) {
                if( ($(this).outerHeight() < $(this)[0].scrollHeight) ) {
                    var e0 = e.originalEvent,
                        delta = e0.wheelDelta || -e0.detail;

                    if( ($(this).outerHeight() + $(this)[0].scrollTop) > $(this)[0].scrollHeight ) {
                        e.preventDefault();
                        this.scrollTop += ( delta < 0 ? 1 : -1 );
                    }
                }
            });

            // hide options menus if click happens off of the list placeholder button
            $(window).off('click.ms-hideopts').on('click.ms-hideopts', function( event ){
                if( !$(event.target).closest('.ms-options-wrap').length ) {
                    $('.ms-options-wrap > .ms-options:visible').hide();
                }
            });

            // disable button action
            placeholder.bind('mousedown',function(){
                // hide other menus before showing this one
                $('.ms-options-wrap > .ms-options:visible').each(function(){
                    if( $(this).parent().prev()[0] != optionsWrap.parent().prev()[0] ) {
                        $(this).hide();
                    }
                });

                // show/hide options
                optionsWrap.toggle();

                // recalculate height
                if( optionsWrap.is(':visible') ) {
                    optionsWrap.css( 'maxHeight', '' );

                    var maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
                    if( options.maxHeight ) {
                        maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
                        maxHeight = maxHeight < options.minHeight ? options.minHeight : maxheight;
                    }
                    maxHeight = maxHeight < options.minHeight ? options.minHeight : maxHeight;

                    optionsWrap.css( 'maxHeight', maxHeight );
                }
            }).click(function( event ){ event.preventDefault(); });

            // add placeholder copy
            if( options.placeholder ) {
                placeholder.text( options.placeholder );
            }

            // hide native select list
            $(this).hide();

            // add options to wrapper
            $(this).children().each(function(){
                var container = $('

');

                // add group of items
                if( this.nodeName == 'OPTGROUP' ) {
                    container.addClass('optgroup');
                    container.append(''+ $(this).attr('label') +'');
                    container.find('> .label').css({
                        clear: 'both'
                    });
                    container.append('

');

                    $(this).children('option').each(function(){
                        var gContainer = $('

');
                        func.addOption( gContainer, this );

                        container.find('> ul').append( gContainer );
                    });
                }
                else if( this.nodeName == 'OPTION' ) {
                    func.addOption( container, this );
                }
                else {
                    // bad option
                    return true;
                }

                optionsList.append( container );
            });

            // COLUMNIZE
            if( hasOptGroup ) {
                // float non grouped options
                optionsList.find('> li:not(.optgroup)').css({
                    float: 'left',
                    width: (100 / options.columns) +'%'
                });

                // add CSS3 column styles
                optionsList.find('li.optgroup').css({
                    clear: 'both'
                }).find('> ul').css({
                    'column-count'        : options.columns,
                    'column-gap'          : 0,
                    '-webkit-column-count': options.columns,
                    '-webkit-column-gap'  : 0,
                    '-moz-column-count'   : options.columns,
                    '-moz-column-gap'     : 0
                });

                // for crappy IE versions float grouped options
                if( func.ieVersion() && func.ieVersion() < 10 ) {
                    optionsList.find('li.optgroup > ul > li').css({
                        float: 'left',
                        width: (100 / options.columns) +'%'
                    });
                }
            }
            else {
                // add CSS3 column styles
                optionsList.css({
                    'column-count'        : options.columns,
                    'column-gap'          : 0,
                    '-webkit-column-count': options.columns,
                    '-webkit-column-gap'  : 0,
                    '-moz-column-count'   : options.columns,
                    '-moz-column-gap'     : 0
                });

                // for crappy IE versions float grouped options
                if( func.ieVersion() && func.ieVersion() < 10 ) {
                    optionsList.find('> li').css({
                        float: 'left',
                        width: (100 / options.columns) +'%'
                    });
                }
            }

            // BIND SELECT ACTION
            optionsWrap.find('input[type="checkbox"]').click(function(){
                $(this).closest( 'li' ).toggleClass( 'selected' );

                var select = optionsWrap.parent().prev();

                // toggle clicked option
                select.find('option[value="'+ $(this).val() +'"]').attr(
                    'selected', $(this).is(':checked')
                ).closest('select').trigger('change');

                updatePlaceholderText();
            }).each(function( idx ){
                if( $(this).css('display').match(/block$/) ) {
                    var checkboxWidth = $(this).outerWidth();
                        checkboxWidth = checkboxWidth ? checkboxWidth : 15;

                    $(this).closest('label').css(
                        'padding-left',
                        (parseInt( $(this).closest('label').css('padding-left') ) * 2) + checkboxWidth
                    );
                }
            });

            // update selected placeholder text
            var updatePlaceholderText = function(){
                var select = optionsWrap.parent().prev();

                // get selected options
                var selOpts = [];
                select.find('option[selected="selected"]').each(function(){
                    selOpts.push( $(this).text() );
                });

                // UPDATE PLACEHOLDER TEXT WITH OPTIONS SELECTED
                placeholder.text( selOpts.join( ', ' ) );
                var copy = placeholder.clone().css({
                    display   : 'inline',
                    width     : 'auto',
                    visibility: 'hidden'
                }).appendTo( optionsWrap.parent() );

                // if the jquery.actual plugin is loaded use it to get the widths
                var copyWidth  = (typeof $.fn.actual !== 'undefined') ? copy.actual('width',options.jqActualOpts) : copy.width();
                var placeWidth = (typeof $.fn.actual !== 'undefined') ? placeholder.actual('width',options.jqActualOpts) : placeholder.width();

                // if copy is larger than button width use "# selected"
                if( copyWidth > placeWidth ) {
                    placeholder.text( selOpts.length +' selected' );
                }
                // if options selected then use those
                else if( selOpts.length ) {
                    placeholder.text( selOpts.join( ', ' ) );
                }
                // replace placeholder text
                else {
                    placeholder.text( options.placeholder );
                }

                // remove dummy element
                copy.remove();
            };

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


<commit_before>/*!
 * $ Simple Modal plugin
 * Author: John Deerhake, @jdeerhake
 * Version 0.0.6
 * Licensed under the MIT license
 */

;(function ( $ ) {
  var backdrop,
    FADE_TIME = 300,
    defaults = {
      "class" : "simple-modal-box"
    };

  function createBackdrop() {
    backdrop = $("<div />", { "class" : "simple-modal-backdrop" }).appendTo("body");
  }

  function Modal ( el, settings ) {
    $.extend( this, settings );
    this.el = $( el );
    this.isShown = false;
    this.init();
  }

  Modal.prototype = {
    init : function () {
      if(!backdrop) {
        createBackdrop();
      }
      this.modal = {};
      this.modal.el = $("<div />", { "class" :  this["class"] }).appendTo("body");
      this.modal.el
        .append( this.el.remove().show() )
        .css({ left: 0, top: 0, positon: "fixed" }); /* Legacy fix */
      this.bindings();
    },
    bindings : function () {
      this.el.on( "show",   $.proxy( this, "show" ) );
      this.el.on( "hide",   $.proxy( this, "hide" ) );
      this.el.on( "change", $.proxy( this, "center" ) );

      var triggerShow = $.proxy( function() {
        this.el.trigger("show");
        return false;
      }, this ),
      triggerHide = $.proxy( function() {
        this.el.trigger("hide");
        return false;
      }, this );

      backdrop.on( "click", triggerHide );
      this.el.on( "click", ".close", triggerHide );

      $( document ).on( "keyup", function(ev) {
        if( ev.keyCode === 27 ) { triggerHide(); } /*ESC*/
      });

      if( this.trigger ) {
        this.trigger.on( "click", triggerShow );
      }

      this.el.find(".close").on( "click" );
    },
    show : function () {
      if( this.isShown ) { return false; }
      this.isShown = true;
      backdrop.show();
      this.modal.el.css({ opacity : 0 }).show();
      this.center();
      this.modal.el.animate({ opacity : 1 }, FADE_TIME);
      return false;
    },
    hide : function () {
      if( !this.isShown ) { return false; }
      this.isShown = false;
      backdrop.fadeOut(FADE_TIME);
      this.modal.el.fadeOut(FADE_TIME, $.proxy( function () {
        this.el.trigger("hidden");
      }, this ));
      return false;
    },
    center : function () {
      this.modal.el.css({
        marginLeft  : -1 * Math.floor( this.modal.el.outerWidth() / 2 ),
        marginTop   : -1 * Math.floor( this.modal.el.outerHeight() / 2 ),
        position    : "fixed",
        top         : "50%",
        left        : "50%"
      });
    }
  };

  $.fn.simpleModal = function ( options ) {
    var settings = $.extend({}, defaults, options);
    return this.each(function() {
      new Modal ( this, settings );
    });
  };
})( jQuery );
<commit_msg>Can't spell<commit_after>/*!
 * $ Simple Modal plugin
 * Author: John Deerhake, @jdeerhake
 * Version 0.0.6
 * Licensed under the MIT license
 */

;(function ( $ ) {
  var backdrop,
    FADE_TIME = 300,
    defaults = {
      "class" : "simple-modal-box"
    };

  function createBackdrop() {
    backdrop = $("<div />", { "class" : "simple-modal-backdrop" }).appendTo("body");
  }

  function Modal ( el, settings ) {
    $.extend( this, settings );
    this.el = $( el );
    this.isShown = false;
    this.init();
  }

  Modal.prototype = {
    init : function () {
      if(!backdrop) {
        createBackdrop();
      }
      this.modal = {};
      this.modal.el = $("<div />", { "class" :  this["class"] }).appendTo("body");
      this.modal.el
        .append( this.el.remove().show() )
        .css({ left: 0, top: 0, position: "fixed" }); /* Legacy fix */
      this.bindings();
    },
    bindings : function () {
      this.el.on( "show",   $.proxy( this, "show" ) );
      this.el.on( "hide",   $.proxy( this, "hide" ) );
      this.el.on( "change", $.proxy( this, "center" ) );

      var triggerShow = $.proxy( function() {
        this.el.trigger("show");
        return false;
      }, this ),
      triggerHide = $.proxy( function() {
        this.el.trigger("hide");
        return false;
      }, this );

      backdrop.on( "click", triggerHide );
      this.el.on( "click", ".close", triggerHide );

      $( document ).on( "keyup", function(ev) {
        if( ev.keyCode === 27 ) { triggerHide(); } /*ESC*/
      });

      if( this.trigger ) {
        this.trigger.on( "click", triggerShow );
      }

      this.el.find(".close").on( "click" );
    },
    show : function () {
      if( this.isShown ) { return false; }
      this.isShown = true;
      backdrop.show();
      this.modal.el.css({ opacity : 0 }).show();
      this.center();
      this.modal.el.animate({ opacity : 1 }, FADE_TIME);
      return false;
    },
    hide : function () {
      if( !this.isShown ) { return false; }
      this.isShown = false;
      backdrop.fadeOut(FADE_TIME);
      this.modal.el.fadeOut(FADE_TIME, $.proxy( function () {
        this.el.trigger("hidden");
      }, this ));
      return false;
    },
    center : function () {
      this.modal.el.css({
        marginLeft  : -1 * Math.floor( this.modal.el.outerWidth() / 2 ),
        marginTop   : -1 * Math.floor( this.modal.el.outerHeight() / 2 ),
        position    : "fixed",
        top         : "50%",
        left        : "50%"
      });
    }
  };

  $.fn.simpleModal = function ( options ) {
    var settings = $.extend({}, defaults, options);
    return this.each(function() {
      new Modal ( this, settings );
    });
  };
})( jQuery );
<|endoftext|>


<commit_before>/*
 *  jQuery Subordinate v1.0
 *  https://github.com/brainedia/jquery-subordinate
 *
 *  Copyright 2014 Robert Saß
 *  Released under the MIT license
 */

(function($) {

	$.fn.subordinate = function( element, content ) {
		var container = this;

		if( typeof element == 'string' && element.substr(0, 1) != '<' ) {

			var insertedElement = container;
			var elements = element.split( '>' );
			for( var k in elements ) {
				var element = $.trim( elements[ k ] );
				insertedElement = insertedElement.subordinate( parseShortElementDefinition( element ) );
			}

		} else {

			var insertedElement = container.append( element ).children(':last');

		}

		if( content != undefined )
			insertedElement.append( content );

		return insertedElement;

	};

	// parse short element definition
	function parseShortElementDefinition( shortDefinition ) {
		var symbols = {
			'name'	: ':',
			'value'	: '=',
			'type'	: '(',
			'id'	: '#',
			'class'	: '.'
		};
		var ignoreCharacters = [ ')' ];
		var isSelfClosing = false;
		var selfClosingContainers = [ 'img', 'input', 'br', 'link', 'meta' ];

		// removing characters that should be ignored
		for( var character in ignoreCharacters ) {
			shortDefinition = shortDefinition.replace( new RegExp( character.escapeRegExp(), 'g' ), '' );
		}
		// splitting each definition
		var defs = shortDefinition;
		for( var attr in symbols ) {
			var symbol = symbols[ attr ];
			defs = defs.replace( new RegExp( symbol.escapeRegExp(), 'g' ), '\\'+symbol );
		}
		defs = defs.split( '\\' );

		// parsing definitions & building element
		var containerAttributes = [];
		var containerName = shortDefinition;
		for( var k in defs ) {
			var def = defs[k];
			def = $.trim( def );
			var defSymbol = def.substr(0, 1);
			var defValue = def.substr(1);
			for( var attr in symbols ) {
				var symbol = symbols[ attr ];
				if( symbol == defSymbol ) {
					containerAttributes.push( attr +'="'+ defValue +'"' );
					containerName = containerName.replace( def, '' );
					break;
				}
			}
		}
		isSelfClosing = (containerName in selfClosingContainers);
		var containerAttributeDefinition = containerAttributes.join(' ');
		var containerDefinition = '<'+ $.trim( containerName +' '+ containerAttributeDefinition ) +'>'
								+ (isSelfClosing ? '' : '</'+ containerName +'>');

		return containerDefinition;
	}

}(jQuery));
<commit_msg>Missing private function included<commit_after>/*
 *  jQuery Subordinate v1.0
 *  https://github.com/brainedia/jquery-subordinate
 *
 *  Copyright 2014 Robert Saß
 *  Released under the MIT license
 */

(function($) {

	$.fn.subordinate = function( element, content ) {
		var container = this;

		if( typeof element == 'string' && element.substr(0, 1) != '<' ) {

			var insertedElement = container;
			var elements = element.split( '>' );
			for( var k in elements ) {
				var element = $.trim( elements[ k ] );
				insertedElement = insertedElement.subordinate( parseShortElementDefinition( element ) );
			}

		} else {

			var insertedElement = container.append( element ).children(':last');

		}

		if( content != undefined )
			insertedElement.append( content );

		return insertedElement;

	};

	// parse short element definition
	function parseShortElementDefinition( shortDefinition ) {
		var symbols = {
			'name'	: ':',
			'value'	: '=',
			'type'	: '(',
			'id'	: '#',
			'class'	: '.'
		};
		var ignoreCharacters = [ ')' ];
		var isSelfClosing = false;
		var selfClosingContainers = [ 'img', 'input', 'br', 'link', 'meta' ];

		// removing characters that should be ignored
		for( var character in ignoreCharacters ) {
			shortDefinition = shortDefinition.replace( new RegExp( escapeRegExp(character), 'g' ), '' );
		}
		// splitting each definition
		var defs = shortDefinition;
		for( var attr in symbols ) {
			var symbol = symbols[ attr ];
			defs = defs.replace( new RegExp( escapeRegExp(symbol), 'g' ), '\\'+symbol );
		}
		defs = defs.split( '\\' );

		// parsing definitions & building element
		var containerAttributes = [];
		var containerName = shortDefinition;
		for( var k in defs ) {
			var def = defs[k];
			def = $.trim( def );
			var defSymbol = def.substr(0, 1);
			var defValue = def.substr(1);
			for( var attr in symbols ) {
				var symbol = symbols[ attr ];
				if( symbol == defSymbol ) {
					containerAttributes.push( attr +'="'+ defValue +'"' );
					containerName = containerName.replace( def, '' );
					break;
				}
			}
		}
		isSelfClosing = (containerName in selfClosingContainers);
		var containerAttributeDefinition = containerAttributes.join(' ');
		var containerDefinition = '<'+ $.trim( containerName +' '+ containerAttributeDefinition ) +'>'
								+ (isSelfClosing ? '' : '</'+ containerName +'>');

		return containerDefinition;
	}

	// escape regular expression
	function escapeRegExp( string ) {
		string = string+"";
		return string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
	}

}(jQuery));
<|endoftext|>


<commit_before>(function ($) {

    $.fn.tabComplete = function (nicks) {

        return this.each(function () {

            // Variables used in tab completion
            var prevKeyWasTab = false,
                pattern = "", // Text fragment respective pattern to look for
                candidate = "", // Candidate
                source = [], // Array of values to be matched
                sourcePos = 0, // The search starting position
                // Varibles used in multi tab completion
                patternPos = -1,
                prePattern = "";

            // Start snippet
            this.keydown(function (event) {
                if (source.length === 0) {
                    source = nicks; // Initialization in case we press Tab with no prior input
                }
                if (event.keyCode === 9) {
                    event.preventDefault();
                    if (prevKeyWasTab === false) {
                        prevKeyWasTab = true;
                        pattern = this.val();
                        patternPos = pattern.lastIndexOf(" ");
                        if (patternPos !== -1) {
                            prePattern = pattern.substr(0, patternPos + 1);
                            pattern = pattern.substr(patternPos + 1);
                        }
                        pattern = new RegExp("^" + pattern, "i");
                        sourcePos = 0;
                        candidate = incrementalSearch(pattern, source, sourcePos);
                        if (candidate.length > 0) {
                            // Candidate found
                            this.val(prePattern + candidate);
                            return;
                        }
                    } else {
                        candidate = incrementalSearch(pattern, source, sourcePos);
                        if (candidate.length > 0) {
                            // Candidate found
                            this.val(prePattern + candidate);
                            return;
                        }
                    }
                } else {
                    prevKeyWasTab = false;
                    prePattern = "";
                    source = nicks; // We do not want the source to change during tabcompletion
                }
            });

            var incrementalSearch = function (pattern, source, sp) {
                var result = "",
                    r = 0,
                    i = sp;
                for (i; i < source.length; i++) {
                    r = source[i].search(pattern);
                    sourcePos = (i + 1 > source.length - 1) ? 0 : i + 1;
                    if (r === 0) {
                        return source[i];
                    }
                }
                for (i = 0; i < sp; i++) {
                    r = source[i].search(pattern);
                    sourcePos = i + 1;
                    if (r === 0) {
                        return source[i];
                    }
                }
                return result;
            };

        )};

    };

})( jQuery );<commit_msg>Wrap the element and use it. Also fix to typo in closure.<commit_after>(function ($) {

    $.fn.tabComplete = function (nicks) {

        return this.each(function () {

            // Variables used in tab completion
            var prevKeyWasTab = false,
                pattern = "", // Text fragment respective pattern to look for
                candidate = "", // Candidate
                source = [], // Array of values to be matched
                sourcePos = 0, // The search starting position
                // Varibles used in multi tab completion
                patternPos = -1,
                prePattern = "",
                el = $(this); // Element

            // Start snippet
            el.bind('keydown', function (event) {
                if (source.length === 0) {
                    source = nicks; // Initialization in case we press Tab with no prior input
                }
                if (event.keyCode === 9) {
                    event.preventDefault();
                    if (prevKeyWasTab === false) {
                        prevKeyWasTab = true;
                        pattern = el.val();
                        patternPos = pattern.lastIndexOf(" ");
                        if (patternPos !== -1) {
                            prePattern = pattern.substr(0, patternPos + 1);
                            pattern = pattern.substr(patternPos + 1);
                        }
                        pattern = new RegExp("^" + pattern, "i");
                        sourcePos = 0;
                        candidate = incrementalSearch(pattern, source, sourcePos);
                        if (candidate.length > 0) {
                            // Candidate found
                            el.val(prePattern + candidate);
                            return;
                        }
                    } else {
                        candidate = incrementalSearch(pattern, source, sourcePos);
                        if (candidate.length > 0) {
                            // Candidate found
                            el.val(prePattern + candidate);
                            return;
                        }
                    }
                } else {
                    prevKeyWasTab = false;
                    prePattern = "";
                    source = nicks; // We do not want the source to change during tabcompletion
                }
            });

            var incrementalSearch = function (pattern, source, sp) {
                var result = "",
                    r = 0,
                    i = sp;
                for (i; i < source.length; i++) {
                    r = source[i].search(pattern);
                    sourcePos = (i + 1 > source.length - 1) ? 0 : i + 1;
                    if (r === 0) {
                        return source[i];
                    }
                }
                for (i = 0; i < sp; i++) {
                    r = source[i].search(pattern);
                    sourcePos = i + 1;
                    if (r === 0) {
                        return source[i];
                    }
                }
                return result;
            };

        });

    };

})( jQuery );<|endoftext|>


<commit_before>$.fn.extend({imageLoaded:function(i){var n=$(this).find("img"),t=n.length;0==t&&i(),n.each(function(n,a){var a=new Image;a.onload=function(){t--,0==t&&i()},a.onerror=function(){t--,0==t&&i()},a.src=$(a).attr("src")})},gridify:function(i){var n=$(this),i=i||{},t=function(){n.css("position","relative");var t=n.find(i.srcNode),a=((i.transition||"all 0.5s ease")+", height 0, width 0",n.innerWidth()),e=parseInt(i.margin||0),o=parseInt(i.max_width||i.width||220),r=Math.max(Math.floor(a/(o+e)),1),s=1==r?e/2:a%(o+e)/2,h=[];i.max_width&&(r=Math.ceil(a/(o+e)),o=(a-r*e-e)/r,s=e/2);for(var d=0;r>d;d++)h.push(0);t.each(function(n,t){var a=$(t),r=$.inArray(Math.min.apply(Math,h),h);a.css({width:o,position:"absolute",margin:e/2,top:h[r]+e/2,left:(o+e)*r+s,transition:i.transition||"all 0.5s ease"}),h[r]+=a.innerHeight()+e})};if(t(),n.imageLoaded(function(){setTimeout(t,200)}),i.resizable){var a=$(window).on("resize",function(){t(),i.max_width&&setTimeout(t,200)});n.on("remove",a.unbind)}}});<commit_msg>Update gridify-min.js<commit_after>$.fn.extend({imageLoaded:function(i){var n=$(this).find("img"),t=n.length;0==t&&i(),n.each(function(n,a){var a=new Image;a.onload=function(){t--,0==t&&i()},a.onerror=function(){t--,0==t&&i()},a.src=$(a).attr("src")})},gridify:function(i){var n=$(this),i=i||{},t=function(){n.css("position","relative");var t=n.find(i.srcNode),a=((i.transition||"all 0.5s ease")+", height 0, width 0",n.innerWidth()),e=parseInt(i.margin||0),r=parseInt(i.max_width||i.width||220),o=Math.max(Math.floor(a/(r+e)),1),s=1==o?e/2:a%(r+e)/2,h=[];i.max_width&&(o=Math.ceil(a/(r+e)),r=(a-o*e-e)/o,s=e/2);for(var d=0;o>d;d++)h.push(0);t.each(function(n,t){var a=$(t),o=$.inArray(Math.min.apply(Math,h),h);a.css({width:r,position:"absolute",margin:e/2,top:h[o]+e/2,left:(r+e)*o+s,transition:i.transition||"all 0.3s ease"}),h[o]+=a.innerHeight()+e})};if(t(),i.resizable){var a=$(window).on("resize",t);n.on("remove",a.unbind)}}});<|endoftext|>


<commit_before>var myLab = myLab || {};

(function (ns) {

  var stage;
  var canvas;

  var sphere;
  var SPHERE_WIDTH = 15;
  var SPHERE_HEIGHT = 15;

  var moveSpeedX;
  var moveSpeedY;
  var minPosX;
  var maxPosX;
  var minPosY;
  var maxPosY;

  // Init the stage
  var initStage = function (canvasId) {
    canvas = document.getElementById(canvasId);
    if (canvas) {
      stage = new createjs.Stage(canvas);
    }
  };

  // init  the application
  ns.init = function () {
    initStage('canvas-main');

    // create bg box
    var bg = new createjs.Bitmap('assets/TheLight-raw/background.png');
    bg.width = canvas.width;
    bg.height = canvas.height;
    stage.addChild(bg);

    // create sphere
    var baseUrl = 'assets/spaceGodzilla/';
    sphere = new createjs.Bitmap(baseUrl + 'sphere.png');
    stage.addChild(sphere);

    resetGame();
    startGame();
  };

  // reset all game properties
  var resetGame = function () {
    minPosX = 0;
    maxPosX = canvas.width - SPHERE_WIDTH;
    minPosY = 0;
    maxPosY = canvas.height - SPHERE_HEIGHT;

    moveSpeedX = 150;  // pixel per second
    moveSpeedY = -150;  // pixel per second

    // put sphere in the middle
    sphere.x = canvas.width / 2;
    sphere.y = canvas.height / 2;
  };

  // start game
  var startGame = function () {

    // start the animation
    createjs.Ticker.setFPS(60);
    createjs.Ticker.addEventListener('tick', onTick);
    createjs.Ticker.useRAF = true;
  };

  // update the sphere position
  var updateSphere = function (delta) {
    // update position
    var newPosX = sphere.x + (moveSpeedX * delta);
    var newPosY = sphere.y + (moveSpeedY * delta);

    // check new position and bounce
    if ((newPosX >= maxPosX) || (newPosX <=  minPosX)) {
      // bounce
      moveSpeedX *= -1;
    }
    if ((newPosY >= maxPosY) || (newPosY <=  minPosY)) {
      // bounce
      moveSpeedY *= -1;
    }
    sphere.x = newPosX;
    sphere.y = newPosY;
  };

  // handle the animation
  var onTick = function (event) {
    var delta = event.delta * 0.001;

    updateSphere(delta);

    // draw stage
    stage.update();
  };

})(myLab);
<commit_msg>Fix the bounce problem<commit_after>var myLab = myLab || {};

(function (ns) {

  var stage;
  var canvas;

  var sphere;
  var SPHERE_WIDTH = 15;
  var SPHERE_HEIGHT = 15;

  var moveSpeedX;
  var moveSpeedY;
  var minPosX;
  var maxPosX;
  var minPosY;
  var maxPosY;

  // Init the stage
  var initStage = function (canvasId) {
    canvas = document.getElementById(canvasId);
    if (canvas) {
      stage = new createjs.Stage(canvas);
    }
  };

  // init  the application
  ns.init = function () {
    initStage('canvas-main');

    // create bg box
    var bg = new createjs.Bitmap('assets/TheLight-raw/background.png');
    bg.width = canvas.width;
    bg.height = canvas.height;
    stage.addChild(bg);

    // create sphere
    var baseUrl = 'assets/spaceGodzilla/';
    sphere = new createjs.Bitmap(baseUrl + 'sphere.png');
    stage.addChild(sphere);

    resetGame();
    startGame();
  };

  // reset all game properties
  var resetGame = function () {
    minPosX = 0;
    maxPosX = canvas.width - SPHERE_WIDTH;
    minPosY = 0;
    maxPosY = canvas.height - SPHERE_HEIGHT;

    moveSpeedX = 150;  // pixel per second
    moveSpeedY = -150;  // pixel per second

    // put sphere in the middle
    sphere.x = canvas.width / 2;
    sphere.y = canvas.height / 2;
  };

  // start game
  var startGame = function () {

    // start the animation
    createjs.Ticker.setFPS(60);
    createjs.Ticker.addEventListener('tick', onTick);
    createjs.Ticker.useRAF = true;
  };

  // update the sphere position
  var updateSphere = function (delta) {
    // update position
    var newPosX = sphere.x + (moveSpeedX * delta);
    var newPosY = sphere.y + (moveSpeedY * delta);

    // check new position and bounce
    var dist = newPosX - maxPosX;
    if (dist > 0) {
      // bounce
      moveSpeedX *= -1;
      newPosX = maxPosX - dist;
    }
    if (newPosX < 0) {
      // bounce
      moveSpeedX *= -1;
      newPosX = newPosX * -1;
    }
    dist = newPosY - maxPosY;
    if (dist > 0) {
      // bounce
      moveSpeedY *= -1;
      newPosY = maxPosY - dist;
    }
    if (newPosY < 0) {
      // bounce
      moveSpeedY *= -1;
      newPosY = newPosY * -1;
    }

    // update position
    sphere.x = newPosX;
    sphere.y = newPosY;
  };

  // handle the animation
  var onTick = function (event) {
    var delta = event.delta * 0.001;

    updateSphere(delta);

    // draw stage
    stage.update();
  };

})(myLab);
<|endoftext|>