<commit_before>/*!
 * jQuery Remote Clock 0.3.0
 *
 * Author: Andrii Volin <angy.volin@gmail.com>
 * Released under the MIT license
 * https://github.com/angyvolin/jquery-remote-clock/blob/master/LICENSE
 */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
    var old;

    var RemoteClock = function (element, options) {
        this.type = null;
        this.options = null;
        this.tickTimeout = null;
        this.syncTimeout = null;
        this.diff = 0;
        this.$element = null;
        this.$clock = null;
        this.parser = null;

        this.init('remoteClock', element, options);
    };

    RemoteClock.VERSION = '1.0.0';

    RemoteClock.TICK_INTERVAL = 1000;

    RemoteClock.DEFAULTS = {
        url: '/time',
        syncInterval: 10000,
        template: '88:88:88',
        selector: '.time',
        parser: Date.parse
    };

    RemoteClock.prototype.init = function (type, element, options) {
        this.type = type;
        this.options = $.extend({}, RemoteClock.DEFAULTS, options || {});
        this.$element = $(element).append(this.options.template);
        this.$clock = this.$element.find(this.options.selector);
        this.setParser(this.options.parser);
        this.sync();
    };

    RemoteClock.prototype.setParser = function (parser) {
        if ('object' === typeof parser) {
            this.parser = parser.parse;
        } else if ('function' === typeof parser) {
            this.parser = parser;
        } else {
            throw Error('The "parser" option is expected to be of type function or object with ::parse() method.');
        }
    };

    RemoteClock.prototype.sync = function () {
        var self = this;

        clearTimeout(this.syncTimeout);

        $.ajax({
            url: this.options.url,
            suppressErrors: true
        }).done(function (serverTime) {
            self.diff = self.parser(serverTime) - Date.now();
            self.tick.apply(self);
            self.syncTimeout = setTimeout($.proxy(self.sync, self), self.options.syncInterval);
        });
    };

    RemoteClock.prototype.tick = function () {
        clearTimeout(this.tickTimeout);

        this.$clock.text(
            new Date(Date.now() + this.diff).toTimeString().split(' ')[0]
        );

        this.tickTimeout = setTimeout($.proxy(this.tick, this), RemoteClock.TICK_INTERVAL);
    };

    RemoteClock.prototype.destroy = function () {
        clearInterval(this.tickTimeout);
        clearInterval(this.syncTimeout);
        this.$element.off('click').removeData(this.type);
        if (null !== this.$clock) {
            this.$clock.detach();
            this.$clock = null;
        }
        this.$element.empty();
        this.$element = null;
    };

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this);
            var data = $this.data('remoteClock');
            var options = 'object' === typeof option && option;

            if (!data && 'destroy' === option) {
                return;
            }

            if (!data) {
                data = new RemoteClock(this, options);
                $this.data('remoteClock', data);
            }

            if ('string' === typeof option) {
                data[option]();
            }
        });
    }

    old = $.fn.remoteClock;

    $.fn.remoteClock = Plugin;
    $.fn.remoteClock.Constructor = RemoteClock;

    $.fn.remoteClock.noConflict = function () {
        $.fn.remoteClock = old;

        return this;
    };
}));
<commit_msg>fix version in README.md<commit_after>/*!
 * jQuery Remote Clock 1.0.0
 *
 * Author: Andrii Volin <angy.volin@gmail.com>
 * Released under the MIT license
 * https://github.com/angyvolin/jquery-remote-clock/blob/master/LICENSE
 */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
    var old;

    var RemoteClock = function (element, options) {
        this.type = null;
        this.options = null;
        this.tickTimeout = null;
        this.syncTimeout = null;
        this.diff = 0;
        this.$element = null;
        this.$clock = null;
        this.parser = null;

        this.init('remoteClock', element, options);
    };

    RemoteClock.VERSION = '1.0.0';

    RemoteClock.TICK_INTERVAL = 1000;

    RemoteClock.DEFAULTS = {
        url: '/time',
        syncInterval: 10000,
        template: '88:88:88',
        selector: '.time',
        parser: Date.parse
    };

    RemoteClock.prototype.init = function (type, element, options) {
        this.type = type;
        this.options = $.extend({}, RemoteClock.DEFAULTS, options || {});
        this.$element = $(element).append(this.options.template);
        this.$clock = this.$element.find(this.options.selector);
        this.setParser(this.options.parser);
        this.sync();
    };

    RemoteClock.prototype.setParser = function (parser) {
        if ('object' === typeof parser) {
            this.parser = parser.parse;
        } else if ('function' === typeof parser) {
            this.parser = parser;
        } else {
            throw Error('The "parser" option is expected to be of type function or object with ::parse() method.');
        }
    };

    RemoteClock.prototype.sync = function () {
        var self = this;

        clearTimeout(this.syncTimeout);

        $.ajax({
            url: this.options.url,
            suppressErrors: true
        }).done(function (serverTime) {
            self.diff = self.parser(serverTime) - Date.now();
            self.tick.apply(self);
            self.syncTimeout = setTimeout($.proxy(self.sync, self), self.options.syncInterval);
        });
    };

    RemoteClock.prototype.tick = function () {
        clearTimeout(this.tickTimeout);

        this.$clock.text(
            new Date(Date.now() + this.diff).toTimeString().split(' ')[0]
        );

        this.tickTimeout = setTimeout($.proxy(this.tick, this), RemoteClock.TICK_INTERVAL);
    };

    RemoteClock.prototype.destroy = function () {
        clearInterval(this.tickTimeout);
        clearInterval(this.syncTimeout);
        this.$element.off('click').removeData(this.type);
        if (null !== this.$clock) {
            this.$clock.detach();
            this.$clock = null;
        }
        this.$element.empty();
        this.$element = null;
    };

    function Plugin(option) {
        return this.each(function () {
            var $this = $(this);
            var data = $this.data('remoteClock');
            var options = 'object' === typeof option && option;

            if (!data && 'destroy' === option) {
                return;
            }

            if (!data) {
                data = new RemoteClock(this, options);
                $this.data('remoteClock', data);
            }

            if ('string' === typeof option) {
                data[option]();
            }
        });
    }

    old = $.fn.remoteClock;

    $.fn.remoteClock = Plugin;
    $.fn.remoteClock.Constructor = RemoteClock;

    $.fn.remoteClock.noConflict = function () {
        $.fn.remoteClock = old;

        return this;
    };
}));
<|endoftext|>


<commit_before>/*! NProgress (c) 2013, Rico Sta. Cruz
 *  http://ricostacruz.com/nprogress */

;(function(root, factory) {

  if (typeof define === 'function' && define.amd) {
    define(factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.NProgress = factory();
  }

})(this, function() {
  var NProgress = {};

  NProgress.version = '0.1.5';

  var Settings = NProgress.settings = {
    minimum: 0.08,
    easing: 'ease',
    positionUsing: '',
    speed: 200,
    trickle: true,
    trickleRate: 0.02,
    trickleSpeed: 800,
    showSpinner: true,
    barSelector: '[role="bar"]',
    spinnerSelector: '[role="spinner"]',
    parent: 'body',
    template: '

'
  };

  /**
   * Updates configuration.
   *
   *     NProgress.configure({
   *       minimum: 0.1
   *     });
   */
  NProgress.configure = function(options) {
    var key, value;
    for (key in options) {
      value = options[key];
      if (value !== undefined && options.hasOwnProperty(key)) Settings[key] = value;
    }

    return this;
  };

  /**
   * Last number.
   */

  NProgress.status = null;

  /**
   * Sets the progress bar status, where `n` is a number from `0.0` to `1.0`.
   *
   *     NProgress.set(0.4);
   *     NProgress.set(1.0);
   */

  NProgress.set = function(n) {
    var started = NProgress.isStarted();

    n = clamp(n, Settings.minimum, 1);
    NProgress.status = (n === 1 ? null : n);

    var progress = NProgress.render(!started),
        bar      = progress.querySelector(Settings.barSelector),
        speed    = Settings.speed,
        ease     = Settings.easing;

    progress.offsetWidth; /* Repaint */

    queue(function(next) {
      // Set positionUsing if it hasn't already been set
      if (Settings.positionUsing === '') Settings.positionUsing = NProgress.getPositioningCSS();

      // Add transition
      css(bar, barPositionCSS(n, speed, ease));

      if (n === 1) {
        // Fade out
        css(progress, {
          transition: 'none',
          opacity: 1
        });
        progress.offsetWidth; /* Repaint */

        setTimeout(function() {
          css(progress, {
            transition: 'all ' + speed + 'ms linear',
            opacity: 0
          });
          setTimeout(function() {
            NProgress.remove();
            next();
          }, speed);
        }, speed);
      } else {
        setTimeout(next, speed);
      }
    });

    return this;
  };

  NProgress.isStarted = function() {
    return typeof NProgress.status === 'number';
  };

  /**
   * Shows the progress bar.
   * This is the same as setting the status to 0%, except that it doesn't go backwards.
   *
   *     NProgress.start();
   *
   */
  NProgress.start = function() {
    if (!NProgress.status) NProgress.set(0);

    var work = function() {
      setTimeout(function() {
        if (!NProgress.status) return;
        NProgress.trickle();
        work();
      }, Settings.trickleSpeed);
    };

    if (Settings.trickle) work();

    return this;
  };

  /**
   * Hides the progress bar.
   * This is the *sort of* the same as setting the status to 100%, with the
   * difference being `done()` makes some placebo effect of some realistic motion.
   *
   *     NProgress.done();
   *
   * If `true` is passed, it will show the progress bar even if its hidden.
   *
   *     NProgress.done(true);
   */

  NProgress.done = function(force) {
    if (!force && !NProgress.status) return this;

    return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
  };

  /**
   * Increments by a random amount.
   */

  NProgress.inc = function(amount) {
    var n = NProgress.status;

    if (!n) {
      return NProgress.start();
    } else {
      if (typeof amount !== 'number') {
        amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
      }

      n = clamp(n + amount, 0, 0.994);
      return NProgress.set(n);
    }
  };

  NProgress.trickle = function() {
    return NProgress.inc(Math.random() * Settings.trickleRate);
  };

  /**
   * Waits for all supplied jQuery promises and
   * increases the progress as the promises resolve.
   *
   * @param $promise jQUery Promise
   */
  (function() {
    var initial = 0, current = 0;

    NProgress.promise = function($promise) {
      if (!$promise || $promise.state() == "resolved") {
        return this;
      }

      if (current == 0) {
        NProgress.start();
      }

      initial++;
      current++;

      $promise.always(function() {
        current--;
        if (current == 0) {
            initial = 0;
            NProgress.done();
        } else {
            NProgress.set((initial - current) / initial);
        }
      });

      return this;
    };

  })();

  /**
   * (Internal) renders the progress bar markup based on the `template`
   * setting.
   */

  NProgress.render = function(fromStart) {
    if (NProgress.isRendered()) return document.getElementById('nprogress');

    addClass(document.documentElement, 'nprogress-busy');

    var progress = document.createElement('div');
    progress.id = 'nprogress';
    progress.innerHTML = Settings.template;

    var bar      = progress.querySelector(Settings.barSelector),
        perc     = fromStart ? '-100' : toBarPerc(NProgress.status || 0),
        parent   = document.querySelector(Settings.parent),
        spinner;

    css(bar, {
      transition: 'all 0 linear',
      transform: 'translate3d(' + perc + '%,0,0)'
    });

    if (!Settings.showSpinner) {
      spinner = progress.querySelector(Settings.spinnerSelector);
      spinner && removeElement(spinner);
    }

    if (parent != document.body) {
      addClass(parent, 'nprogress-custom-parent');
    }

    parent.appendChild(progress);
    return progress;
  };

  /**
   * Removes the element. Opposite of render().
   */

  NProgress.remove = function() {
    removeClass(document.documentElement, 'nprogress-busy');
    removeClass(document.querySelector(Settings.parent), 'nprogress-custom-parent')
    var progress = document.getElementById('nprogress');
    progress && removeElement(progress);
  };

  /**
   * Checks if the progress bar is rendered.
   */

  NProgress.isRendered = function() {
    return !!document.getElementById('nprogress');
  };

  /**
   * Determine which positioning CSS rule to use.
   */

  NProgress.getPositioningCSS = function() {
    // Sniff on document.body.style
    var bodyStyle = document.body.style;

    // Sniff prefixes
    var vendorPrefix = ('WebkitTransform' in bodyStyle) ? 'Webkit' :
                       ('MozTransform' in bodyStyle) ? 'Moz' :
                       ('msTransform' in bodyStyle) ? 'ms' :
                       ('OTransform' in bodyStyle) ? 'O' : '';

    if (vendorPrefix + 'Perspective' in bodyStyle) {
      // Modern browsers with 3D support, e.g. Webkit, IE10
      return 'translate3d';
    } else if (vendorPrefix + 'Transform' in bodyStyle) {
      // Browsers without 3D support, e.g. IE9
      return 'translate';
    } else {
      // Browsers without translate() support, e.g. IE7-8
      return 'margin';
    }
  };

  /**
   * Helpers
   */

  function clamp(n, min, max) {
    if (n < min) return min;
    if (n > max) return max;
    return n;
  }

  /**
   * (Internal) converts a percentage (`0..1`) to a bar translateX
   * percentage (`-100%..0%`).
   */

  function toBarPerc(n) {
    return (-1 + n) * 100;
  }

  /**
   * (Internal) returns the correct CSS for changing the bar's
   * position given an n percentage, and speed and ease from Settings
   */

  function barPositionCSS(n, speed, ease) {
    var barCSS;

    if (Settings.positionUsing === 'translate3d') {
      barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };
    } else if (Settings.positionUsing === 'translate') {
      barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };
    } else {
      barCSS = { 'margin-left': toBarPerc(n)+'%' };
    }

    barCSS.transition = 'all '+speed+'ms '+ease;

    return barCSS;
  }

  /**
   * (Internal) Queues a function to be executed.
   */

  var queue = (function() {
    var pending = [];

    function next() {
      var fn = pending.shift();
      if (fn) {
        fn(next);
      }
    }

    return function(fn) {
      pending.push(fn);
      if (pending.length == 1) next();
    };
  })();

  /**
   * (Internal) Applies css properties to an element, similar to the jQuery
   * css method.
   *
   * While this helper does assist with vendor prefixed property names, it
   * does not perform any manipulation of values prior to setting styles.
   */

  var css = (function() {
    var cssPrefixes = [ 'Webkit', 'O', 'Moz', 'ms' ],
        cssProps    = {};

    function camelCase(string) {
      return string.replace(/^-ms-/, 'ms-').replace(/-([\da-z])/gi, function(match, letter) {
        return letter.toUpperCase();
      });
    }

    function getVendorProp(name) {
      var style = document.body.style;
      if (name in style) return name;

      var i = cssPrefixes.length,
          capName = name.charAt(0).toUpperCase() + name.slice(1),
          vendorName;
      while (i--) {
        vendorName = cssPrefixes[i] + capName;
        if (vendorName in style) return vendorName;
      }

      return name;
    }

    function getStyleProp(name) {
      name = camelCase(name);
      return cssProps[name] || (cssProps[name] = getVendorProp(name));
    }

    function applyCss(element, prop, value) {
      prop = getStyleProp(prop);
      element.style[prop] = value;
    }

    return function(element, properties) {
      var args = arguments,
          prop,
          value;

      if (args.length == 2) {
        for (prop in properties) {
          value = properties[prop];
          if (value !== undefined && properties.hasOwnProperty(prop)) applyCss(element, prop, value);
        }
      } else {
        applyCss(element, args[1], args[2]);
      }
    }
  })();

  /**
   * (Internal) Determines if an element or space separated list of class names contains a class name.
   */

  function hasClass(element, name) {
    var list = typeof element == 'string' ? element : classList(element);
    return list.indexOf(' ' + name + ' ') >= 0;
  }

  /**
   * (Internal) Adds a class to an element.
   */

  function addClass(element, name) {
    var oldList = classList(element),
        newList = oldList + name;

    if (hasClass(oldList, name)) return;

    // Trim the opening space.
    element.className = newList.substring(1);
  }

  /**
   * (Internal) Removes a class from an element.
   */

  function removeClass(element, name) {
    var oldList = classList(element),
        newList;

    if (!hasClass(element, name)) return;

    // Replace the class name.
    newList = oldList.replace(' ' + name + ' ', ' ');

    // Trim the opening and closing spaces.
    element.className = newList.substring(1, newList.length - 1);
  }

  /**
   * (Internal) Gets a space separated list of the class names on the element.
   * The list is wrapped with a single space on each end to facilitate finding
   * matches within the list.
   */

  function classList(element) {
    return (' ' + (element.className || '') + ' ').replace(/\s+/gi, ' ');
  }

  /**
   * (Internal) Removes an element from the DOM.
   */

  function removeElement(element) {
    element && element.parentNode && element.parentNode.removeChild(element);
  }

  return NProgress;
});

<commit_msg>Update copyright block.<commit_after>/* NProgress, (c) 2013, 2014 Rico Sta. Cruz - http://ricostacruz.com/nprogress
 * @license MIT */

;(function(root, factory) {

  if (typeof define === 'function' && define.amd) {
    define(factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.NProgress = factory();
  }

})(this, function() {
  var NProgress = {};

  NProgress.version = '0.1.5';

  var Settings = NProgress.settings = {
    minimum: 0.08,
    easing: 'ease',
    positionUsing: '',
    speed: 200,
    trickle: true,
    trickleRate: 0.02,
    trickleSpeed: 800,
    showSpinner: true,
    barSelector: '[role="bar"]',
    spinnerSelector: '[role="spinner"]',
    parent: 'body',
    template: '

'
  };

  /**
   * Updates configuration.
   *
   *     NProgress.configure({
   *       minimum: 0.1
   *     });
   */
  NProgress.configure = function(options) {
    var key, value;
    for (key in options) {
      value = options[key];
      if (value !== undefined && options.hasOwnProperty(key)) Settings[key] = value;
    }

    return this;
  };

  /**
   * Last number.
   */

  NProgress.status = null;

  /**
   * Sets the progress bar status, where `n` is a number from `0.0` to `1.0`.
   *
   *     NProgress.set(0.4);
   *     NProgress.set(1.0);
   */

  NProgress.set = function(n) {
    var started = NProgress.isStarted();

    n = clamp(n, Settings.minimum, 1);
    NProgress.status = (n === 1 ? null : n);

    var progress = NProgress.render(!started),
        bar      = progress.querySelector(Settings.barSelector),
        speed    = Settings.speed,
        ease     = Settings.easing;

    progress.offsetWidth; /* Repaint */

    queue(function(next) {
      // Set positionUsing if it hasn't already been set
      if (Settings.positionUsing === '') Settings.positionUsing = NProgress.getPositioningCSS();

      // Add transition
      css(bar, barPositionCSS(n, speed, ease));

      if (n === 1) {
        // Fade out
        css(progress, {
          transition: 'none',
          opacity: 1
        });
        progress.offsetWidth; /* Repaint */

        setTimeout(function() {
          css(progress, {
            transition: 'all ' + speed + 'ms linear',
            opacity: 0
          });
          setTimeout(function() {
            NProgress.remove();
            next();
          }, speed);
        }, speed);
      } else {
        setTimeout(next, speed);
      }
    });

    return this;
  };

  NProgress.isStarted = function() {
    return typeof NProgress.status === 'number';
  };

  /**
   * Shows the progress bar.
   * This is the same as setting the status to 0%, except that it doesn't go backwards.
   *
   *     NProgress.start();
   *
   */
  NProgress.start = function() {
    if (!NProgress.status) NProgress.set(0);

    var work = function() {
      setTimeout(function() {
        if (!NProgress.status) return;
        NProgress.trickle();
        work();
      }, Settings.trickleSpeed);
    };

    if (Settings.trickle) work();

    return this;
  };

  /**
   * Hides the progress bar.
   * This is the *sort of* the same as setting the status to 100%, with the
   * difference being `done()` makes some placebo effect of some realistic motion.
   *
   *     NProgress.done();
   *
   * If `true` is passed, it will show the progress bar even if its hidden.
   *
   *     NProgress.done(true);
   */

  NProgress.done = function(force) {
    if (!force && !NProgress.status) return this;

    return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
  };

  /**
   * Increments by a random amount.
   */

  NProgress.inc = function(amount) {
    var n = NProgress.status;

    if (!n) {
      return NProgress.start();
    } else {
      if (typeof amount !== 'number') {
        amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
      }

      n = clamp(n + amount, 0, 0.994);
      return NProgress.set(n);
    }
  };

  NProgress.trickle = function() {
    return NProgress.inc(Math.random() * Settings.trickleRate);
  };

  /**
   * Waits for all supplied jQuery promises and
   * increases the progress as the promises resolve.
   *
   * @param $promise jQUery Promise
   */
  (function() {
    var initial = 0, current = 0;

    NProgress.promise = function($promise) {
      if (!$promise || $promise.state() == "resolved") {
        return this;
      }

      if (current == 0) {
        NProgress.start();
      }

      initial++;
      current++;

      $promise.always(function() {
        current--;
        if (current == 0) {
            initial = 0;
            NProgress.done();
        } else {
            NProgress.set((initial - current) / initial);
        }
      });

      return this;
    };

  })();

  /**
   * (Internal) renders the progress bar markup based on the `template`
   * setting.
   */

  NProgress.render = function(fromStart) {
    if (NProgress.isRendered()) return document.getElementById('nprogress');

    addClass(document.documentElement, 'nprogress-busy');

    var progress = document.createElement('div');
    progress.id = 'nprogress';
    progress.innerHTML = Settings.template;

    var bar      = progress.querySelector(Settings.barSelector),
        perc     = fromStart ? '-100' : toBarPerc(NProgress.status || 0),
        parent   = document.querySelector(Settings.parent),
        spinner;

    css(bar, {
      transition: 'all 0 linear',
      transform: 'translate3d(' + perc + '%,0,0)'
    });

    if (!Settings.showSpinner) {
      spinner = progress.querySelector(Settings.spinnerSelector);
      spinner && removeElement(spinner);
    }

    if (parent != document.body) {
      addClass(parent, 'nprogress-custom-parent');
    }

    parent.appendChild(progress);
    return progress;
  };

  /**
   * Removes the element. Opposite of render().
   */

  NProgress.remove = function() {
    removeClass(document.documentElement, 'nprogress-busy');
    removeClass(document.querySelector(Settings.parent), 'nprogress-custom-parent')
    var progress = document.getElementById('nprogress');
    progress && removeElement(progress);
  };

  /**
   * Checks if the progress bar is rendered.
   */

  NProgress.isRendered = function() {
    return !!document.getElementById('nprogress');
  };

  /**
   * Determine which positioning CSS rule to use.
   */

  NProgress.getPositioningCSS = function() {
    // Sniff on document.body.style
    var bodyStyle = document.body.style;

    // Sniff prefixes
    var vendorPrefix = ('WebkitTransform' in bodyStyle) ? 'Webkit' :
                       ('MozTransform' in bodyStyle) ? 'Moz' :
                       ('msTransform' in bodyStyle) ? 'ms' :
                       ('OTransform' in bodyStyle) ? 'O' : '';

    if (vendorPrefix + 'Perspective' in bodyStyle) {
      // Modern browsers with 3D support, e.g. Webkit, IE10
      return 'translate3d';
    } else if (vendorPrefix + 'Transform' in bodyStyle) {
      // Browsers without 3D support, e.g. IE9
      return 'translate';
    } else {
      // Browsers without translate() support, e.g. IE7-8
      return 'margin';
    }
  };

  /**
   * Helpers
   */

  function clamp(n, min, max) {
    if (n < min) return min;
    if (n > max) return max;
    return n;
  }

  /**
   * (Internal) converts a percentage (`0..1`) to a bar translateX
   * percentage (`-100%..0%`).
   */

  function toBarPerc(n) {
    return (-1 + n) * 100;
  }

  /**
   * (Internal) returns the correct CSS for changing the bar's
   * position given an n percentage, and speed and ease from Settings
   */

  function barPositionCSS(n, speed, ease) {
    var barCSS;

    if (Settings.positionUsing === 'translate3d') {
      barCSS = { transform: 'translate3d('+toBarPerc(n)+'%,0,0)' };
    } else if (Settings.positionUsing === 'translate') {
      barCSS = { transform: 'translate('+toBarPerc(n)+'%,0)' };
    } else {
      barCSS = { 'margin-left': toBarPerc(n)+'%' };
    }

    barCSS.transition = 'all '+speed+'ms '+ease;

    return barCSS;
  }

  /**
   * (Internal) Queues a function to be executed.
   */

  var queue = (function() {
    var pending = [];

    function next() {
      var fn = pending.shift();
      if (fn) {
        fn(next);
      }
    }

    return function(fn) {
      pending.push(fn);
      if (pending.length == 1) next();
    };
  })();

  /**
   * (Internal) Applies css properties to an element, similar to the jQuery
   * css method.
   *
   * While this helper does assist with vendor prefixed property names, it
   * does not perform any manipulation of values prior to setting styles.
   */

  var css = (function() {
    var cssPrefixes = [ 'Webkit', 'O', 'Moz', 'ms' ],
        cssProps    = {};

    function camelCase(string) {
      return string.replace(/^-ms-/, 'ms-').replace(/-([\da-z])/gi, function(match, letter) {
        return letter.toUpperCase();
      });
    }

    function getVendorProp(name) {
      var style = document.body.style;
      if (name in style) return name;

      var i = cssPrefixes.length,
          capName = name.charAt(0).toUpperCase() + name.slice(1),
          vendorName;
      while (i--) {
        vendorName = cssPrefixes[i] + capName;
        if (vendorName in style) return vendorName;
      }

      return name;
    }

    function getStyleProp(name) {
      name = camelCase(name);
      return cssProps[name] || (cssProps[name] = getVendorProp(name));
    }

    function applyCss(element, prop, value) {
      prop = getStyleProp(prop);
      element.style[prop] = value;
    }

    return function(element, properties) {
      var args = arguments,
          prop,
          value;

      if (args.length == 2) {
        for (prop in properties) {
          value = properties[prop];
          if (value !== undefined && properties.hasOwnProperty(prop)) applyCss(element, prop, value);
        }
      } else {
        applyCss(element, args[1], args[2]);
      }
    }
  })();

  /**
   * (Internal) Determines if an element or space separated list of class names contains a class name.
   */

  function hasClass(element, name) {
    var list = typeof element == 'string' ? element : classList(element);
    return list.indexOf(' ' + name + ' ') >= 0;
  }

  /**
   * (Internal) Adds a class to an element.
   */

  function addClass(element, name) {
    var oldList = classList(element),
        newList = oldList + name;

    if (hasClass(oldList, name)) return;

    // Trim the opening space.
    element.className = newList.substring(1);
  }

  /**
   * (Internal) Removes a class from an element.
   */

  function removeClass(element, name) {
    var oldList = classList(element),
        newList;

    if (!hasClass(element, name)) return;

    // Replace the class name.
    newList = oldList.replace(' ' + name + ' ', ' ');

    // Trim the opening and closing spaces.
    element.className = newList.substring(1, newList.length - 1);
  }

  /**
   * (Internal) Gets a space separated list of the class names on the element.
   * The list is wrapped with a single space on each end to facilitate finding
   * matches within the list.
   */

  function classList(element) {
    return (' ' + (element.className || '') + ' ').replace(/\s+/gi, ' ');
  }

  /**
   * (Internal) Removes an element from the DOM.
   */

  function removeElement(element) {
    element && element.parentNode && element.parentNode.removeChild(element);
  }

  return NProgress;
});

<|endoftext|>


<commit_before>/*!
 * RestfulizerJs 0.1
 * http://ifnot.github.io/RestfulizerJs/
 *
 * Use jQuery
 * http://jquery.com/
 *
 * Inspired by froztbytes works :
 * https://gist.github.com/froztbytes/5385905
 *
 * Copyright 2014 Anael Favre and other contributors
 * Released under the MIT license
 * https://raw.github.com/Ifnot/RestfulizerJs/master/LICENCE
 */

(function ($) {
    $.fn.extend({
        restfulizer: function (options) {
            var defaults = {
                parse: false,
                target: null,
                method: "POST"
            };
            var options = $.extend(defaults, options);
            var last = null;

            return $(this).each(function () {
                var self = $(this);

                // Try to get data-param into options
                if (typeof(self.attr('data-method')) != "undefined") {
                    options.method = self.attr('data-method').toUpperCase();
                }

                if (typeof(self.attr('href')) != "undefined") {
                    options.target = self.attr('href');
                }

                // Parse href parameters and create an input for each parameter
                var inputs = "";

                if (options.parse) {
                    var paramsIndex = options.target.indexOf("?");
                    var hasParams = (paramsIndex > -1);

                    if (hasParams) {
                        var params = options.target.substr(paramsIndex + 1).split('&');
                        options.target = options.target.substr(0, paramsIndex);

                        for (var i = 0; i < params.length; i++) {
                            var pair = params[i].split('=');
                            inputs += "	<input type='hidden' name='" + decodeURIComponent(pair[0]) + "' value='" + decodeURIComponent(pair[1]) + "'>\n";
                        }
                    }
                }

                if (options.method == 'GET' || options.method == 'POST') {
                    var form = "\n" +
                        "<form action='" + options.target + "' method='" + options.method + "' style='display:none'>\n" +
                        inputs +
                        "</form>\n";
                }
                else {
                    var form = "\n" +
                        "<form action='" + options.target + "' method='POST' style='display:none'>\n" +
                        "	<input type='hidden' name='_method' value='" + options.method + "'>\n" +
                        inputs +
                        "</form>\n";
                }

                self.append(form)
                    .removeAttr('href')
                    .attr('style', 'cursor:pointer;')
                    .attr('onclick', '$(this).find("form").submit();');
            });
        }
    });
})(jQuery);

<commit_msg>Purge fragment in url before parsing for inputs<commit_after>/*!
 * RestfulizerJs 0.1
 * http://ifnot.github.io/RestfulizerJs/
 *
 * Use jQuery
 * http://jquery.com/
 *
 * Inspired by froztbytes works :
 * https://gist.github.com/froztbytes/5385905
 *
 * Copyright 2014 Anael Favre and other contributors
 * Released under the MIT license
 * https://raw.github.com/Ifnot/RestfulizerJs/master/LICENCE
 */

(function ($) {
    $.fn.extend({
        restfulizer: function (options) {
            var defaults = {
                parse: false,
                target: null,
                method: "POST"
            };
            var options = $.extend(defaults, options);
            var last = null;

            return $(this).each(function () {
                var self = $(this);

                // Try to get data-param into options
                if (typeof(self.attr('data-method')) != "undefined") {
                    options.method = self.attr('data-method').toUpperCase();
                }

                if (typeof(self.attr('href')) != "undefined") {
                    options.target = self.attr('href');
                }

                // Parse href parameters and create an input for each parameter
                var inputs = "";

                if (options.parse) {
                    var paramsIndex = options.target.indexOf("?");
                    var hasParams = (paramsIndex > -1);

                    if (hasParams) {
                        var params = options.target.substr(paramsIndex + 1).split('#')[0].split('&');
                        options.target = options.target.substr(0, paramsIndex);

                        for (var i = 0; i < params.length; i++) {
                            var pair = params[i].split('=');
                            inputs += "	<input type='hidden' name='" + decodeURIComponent(pair[0]) + "' value='" + decodeURIComponent(pair[1]) + "'>\n";
                        }
                    }
                }

                if (options.method == 'GET' || options.method == 'POST') {
                    var form = "\n" +
                        "<form action='" + options.target + "' method='" + options.method + "' style='display:none'>\n" +
                        inputs +
                        "</form>\n";
                }
                else {
                    var form = "\n" +
                        "<form action='" + options.target + "' method='POST' style='display:none'>\n" +
                        "	<input type='hidden' name='_method' value='" + options.method + "'>\n" +
                        inputs +
                        "</form>\n";
                }

                self.append(form)
                    .removeAttr('href')
                    .attr('style', 'cursor:pointer;')
                    .attr('onclick', '$(this).find("form").submit();');
            });
        }
    });
})(jQuery);

<|endoftext|>


<commit_before>/*global Igloo State */

/**
 * Shortest past solver that runs on the GPU using cellular automata.
 * @param {number} w width
 * @param {number} h height
 * @param {Uint8Array} maze
 * @param {HTMLCanvasElement} canvas to access WebGL and draw progress
 */
function GpuSolver(w, h, maze, canvas) {
    this.statesize = new Float32Array([w, h]);
    this.viewsize = new Float32Array([canvas.width, canvas.height]);
    var igloo = this.igloo = new Igloo(canvas);
    if (igloo == null) {
        alert('Could not initialize WebGL!');
        throw new Error('No WebGL');
    }
    var gl = igloo.gl;
    gl.disable(gl.BLEND);
    gl.disable(gl.DEPTH_TEST);
    this.programs = {
        step: igloo.program('glsl/quad.vert', 'glsl/12state.frag'),
        draw: igloo.program('glsl/quad.vert', 'glsl/12draw.frag')
    };
    this.buffers = {
        quad: igloo.array(Igloo.QUAD2)
    };
    this.textures = {
        fore: igloo.texture(null, null, null, gl.NEAREST).blank(w, h),
        back: igloo.texture(null, null, null, gl.NEAREST).blank(w, h),
        arrow: igloo.texture().set(GpuSolver.ARROW32, 32, 32)
    };
    this.framebuffers = {
        step: igloo.framebuffer()
    };
    this.reset(maze);
    this.done = false;
    this.cancelled = false;
    this.age = 0;
}

/**
 * Arrow texture.
 * @const
 * @type {Uint8Array}
 */
GpuSolver.ARROW32 = (function(size) {
    var canvas = document.createElement('canvas');
    canvas.width = canvas.height = size;
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, size, size);
    ctx.fillStyle = '#fff';
    ctx.translate(size / 2, size / 2);
    ctx.scale(size, -size);
    ctx.beginPath();
    ctx.moveTo( 0/4, -1/4);
    ctx.lineTo(-1/4,  1/4);
    ctx.lineTo( 1/4,  1/4);
    ctx.fill();
    return new Uint8Array(ctx.getImageData(0, 0, size, size).data);
}(32));

/**
 * Swap the foreground and background states.
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.swap = function() {
    var tmp = this.textures.fore;
    this.textures.fore = this.textures.back;
    this.textures.back = tmp;
    return this;
};

/**
 * Set a new maze to solve, resetting the solver.
 * @param {Uint8Array} maze
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.reset = function(maze) {
    var w = this.statesize[0], h = this.statesize[1],
        rgba = new Uint8Array(w * h * 4);
    for (var i = 0; i < maze.length; i++) {
        rgba[i * 4 + 0] = maze[i] * 255 / 11;
        rgba[i * 4 + 1] = 0;
        rgba[i * 4 + 2] = 0;
        rgba[i * 4 + 3] = 0;
    }
    rgba[0]               = State.BEGIN * 255 / 11;
    rgba[rgba.length - 4] = State.END   * 255 / 11;
    this.textures.fore.subset(rgba, 0, 0, w, h);
    this.done = false;
    this.age = 0;
    return this;
};

/**
 * Take one or more steps towards the solution.
 * @param {number} [n] the number of steps to take
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.step = function(n) {
    n = n || 1;
    var gl = this.igloo.gl;
    gl.viewport(0, 0, this.statesize[0], this.statesize[1]);
    var step = this.programs.step.use()
        .attrib('quad', this.buffers.quad, 2)
        .uniform('scale', this.statesize)
        .uniformi('maze', 0);
    var rgba = new Uint8Array(4);
    while (n-- > 0 && !this.done) {
        this.age++;
        this.framebuffers.step.attach(this.textures.back);
        this.textures.fore.bind(0);
        step.draw(gl.TRIANGLE_STRIP, Igloo.QUAD2.length / 2);
        gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba);
        /* Test if START changed into a ROUTE. */
        if (State.isRoute(Math.round(rgba[0] * 11 / 255))) {
            this.done = true;
        }
        this.swap();
    }
    return this;
};

/**
 * Draw the current solution state to the canvas.
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.draw = function() {
    var gl = this.igloo.gl;
    this.igloo.defaultFramebuffer.bind();
    this.textures.fore.bind(0);
    this.textures.arrow.bind(1);
    gl.viewport(0, 0, this.viewsize[0], this.viewsize[1]);
    this.programs.draw.use()
        .attrib('quad', this.buffers.quad, 2)
        .uniform('viewport', this.viewsize)
        .uniform('statesize', this.statesize)
        .uniform('statesize', this.statesize)
        .uniformi('arrow', 1)
        .draw(gl.TRIANGLE_STRIP, Igloo.QUAD2.length / 2);
    return this;
};

/**
 * Animate the solution using requestAnimationFrame.
 * @param {Function} [callback]
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.animate = function(callback) {
    var _this = this;
    window.requestAnimationFrame(function() {
        if (!_this.done && !_this.cancelled) {
            _this.step(1).draw();
            _this.animate(callback);
        } else {
            if (!_this.cancelled && callback != null) callback();
            _this.cancelled = false;
        }
    });
    return this;
};

/**
 * Stop animation without calling the callback.
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.cancel = function() {
    this.cancelled = true;
    return this;
};
<commit_msg>Use glReadPixels much less often.<commit_after>/*global Igloo State */

/**
 * Shortest past solver that runs on the GPU using cellular automata.
 * @param {number} w width
 * @param {number} h height
 * @param {Uint8Array} maze
 * @param {HTMLCanvasElement} canvas to access WebGL and draw progress
 */
function GpuSolver(w, h, maze, canvas) {
    this.statesize = new Float32Array([w, h]);
    this.viewsize = new Float32Array([canvas.width, canvas.height]);
    var igloo = this.igloo = new Igloo(canvas);
    if (igloo == null) {
        alert('Could not initialize WebGL!');
        throw new Error('No WebGL');
    }
    var gl = igloo.gl;
    gl.disable(gl.BLEND);
    gl.disable(gl.DEPTH_TEST);
    this.programs = {
        step: igloo.program('glsl/quad.vert', 'glsl/12state.frag'),
        draw: igloo.program('glsl/quad.vert', 'glsl/12draw.frag')
    };
    this.buffers = {
        quad: igloo.array(Igloo.QUAD2)
    };
    this.textures = {
        fore: igloo.texture(null, null, null, gl.NEAREST).blank(w, h),
        back: igloo.texture(null, null, null, gl.NEAREST).blank(w, h),
        arrow: igloo.texture().set(GpuSolver.ARROW32, 32, 32)
    };
    this.framebuffers = {
        step: igloo.framebuffer()
    };
    this.reset(maze);
    this.done = false;
    this.cancelled = false;
    this.age = 0;
}

/**
 * Arrow texture.
 * @const
 * @type {Uint8Array}
 */
GpuSolver.ARROW32 = (function(size) {
    var canvas = document.createElement('canvas');
    canvas.width = canvas.height = size;
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, size, size);
    ctx.fillStyle = '#fff';
    ctx.translate(size / 2, size / 2);
    ctx.scale(size, -size);
    ctx.beginPath();
    ctx.moveTo( 0/4, -1/4);
    ctx.lineTo(-1/4,  1/4);
    ctx.lineTo( 1/4,  1/4);
    ctx.fill();
    return new Uint8Array(ctx.getImageData(0, 0, size, size).data);
}(32));

/**
 * Swap the foreground and background states.
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.swap = function() {
    var tmp = this.textures.fore;
    this.textures.fore = this.textures.back;
    this.textures.back = tmp;
    return this;
};

/**
 * Set a new maze to solve, resetting the solver.
 * @param {Uint8Array} maze
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.reset = function(maze) {
    var w = this.statesize[0], h = this.statesize[1],
        rgba = new Uint8Array(w * h * 4);
    for (var i = 0; i < maze.length; i++) {
        rgba[i * 4 + 0] = maze[i] * 255 / 11;
        rgba[i * 4 + 1] = 0;
        rgba[i * 4 + 2] = 0;
        rgba[i * 4 + 3] = 0;
    }
    rgba[0]               = State.BEGIN * 255 / 11;
    rgba[rgba.length - 4] = State.END   * 255 / 11;
    this.textures.fore.subset(rgba, 0, 0, w, h);
    this.done = false;
    this.age = 0;
    return this;
};

/**
 * Take one or more steps towards the solution.
 * @param {number} [n] the number of steps to take
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.step = function(n) {
    n = n || 1;
    var gl = this.igloo.gl;
    gl.viewport(0, 0, this.statesize[0], this.statesize[1]);
    var step = this.programs.step.use()
        .attrib('quad', this.buffers.quad, 2)
        .uniform('scale', this.statesize)
        .uniformi('maze', 0);
    var rgba = new Uint8Array(4);
    while (n-- > 0 && !this.done) {
        this.age++;
        this.framebuffers.step.attach(this.textures.back);
        this.textures.fore.bind(0);
        step.draw(gl.TRIANGLE_STRIP, Igloo.QUAD2.length / 2);
        if ((n % 500) === 0) {
            /* Test if START changed into a ROUTE. */
            gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba);
            if (State.isRoute(Math.round(rgba[0] * 11 / 255))) {
                this.done = true;
            }
        }
        this.swap();
    }
    return this;
};

/**
 * Draw the current solution state to the canvas.
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.draw = function() {
    var gl = this.igloo.gl;
    this.igloo.defaultFramebuffer.bind();
    this.textures.fore.bind(0);
    this.textures.arrow.bind(1);
    gl.viewport(0, 0, this.viewsize[0], this.viewsize[1]);
    this.programs.draw.use()
        .attrib('quad', this.buffers.quad, 2)
        .uniform('viewport', this.viewsize)
        .uniform('statesize', this.statesize)
        .uniform('statesize', this.statesize)
        .uniformi('arrow', 1)
        .draw(gl.TRIANGLE_STRIP, Igloo.QUAD2.length / 2);
    return this;
};

/**
 * Animate the solution using requestAnimationFrame.
 * @param {Function} [callback]
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.animate = function(callback) {
    var _this = this;
    window.requestAnimationFrame(function() {
        if (!_this.done && !_this.cancelled) {
            _this.step(1).draw();
            _this.animate(callback);
        } else {
            if (!_this.cancelled && callback != null) callback();
            _this.cancelled = false;
        }
    });
    return this;
};

/**
 * Stop animation without calling the callback.
 * @returns {GpuSolver} this
 */
GpuSolver.prototype.cancel = function() {
    this.cancelled = true;
    return this;
};
<|endoftext|>


<commit_before>//Dialogue writer and selector module for combat sequence.
var Cwriter = (function()
{
    var timeCheck = 0;         //Current interval to wait to place a character. Changes based on special characters.
    var timeAsterisk = .75;    //Interval to use for asterisk.
    var timePeriod = .33;      //Interval to use for periods.
    var timeComma = .21;       //Interval to use for commas.
    var timeStandard = .033;   //Interval to use for all other characters.

    var text;                  //Text to display.
    var charCounter;           //Counter for characters in text being displayed.
    var timeCounter;           //Tracks time for character counting.

    var horizontalPositions;   //Positions for horizontal menu.
    var verticalPositions;     //Positions for vertical menu.

    //Init
    function init()
    {
        horizontalPositions =
        [
            [100, 296],
            [356, 296],
            [100, 328],
            [356, 328],
            [100, 360],
            [356, 360]
        ]

        verticalPositions =
        [
            [100, 296],
            [100, 328],
            [100, 360]
        ]
    }

    //Set the time delays of the writer.
    function setupTimes(
        _timeAsterisk,
        _timePeriod,
        _timeComma,
        _timeStandard)
    {
        timeCheck = 0;
        timeAsterisk = _timeAsterisk;
        timePeriod = _timePeriod;
        timeComma = _timeComma;
        timeStandard = _timeStandard;
    }

    //Set the text for the writer and reset counters.
    function setupText(_text)
    {
        text = _text;
        charCounter = -1;           //Counter for the index of the most recent displayed character.
        timeCounter = 0;            //Counter for the time since a character was placed.
    }

    //Update the writer.
    function update(dt)
    {
        if(myKeys.keydown[myKeys.KEYBOARD.KEY_X])
        {
            skip();
        }

        //Tick.
        timeCounter += dt;

        //If time to place a new character and if there is a new character.
        if(timeCounter > timeCheck && charCounter < text.length)
        {
            //Reset counter and increment current character for next character.
            timeCounter = timeCounter - timeCheck;
            charCounter++;

            //SFX
            if(charCounter < text.length - 2)
            {
                //Change interval for new character.
                switch(text.charAt(charCounter + 1))
                {
                    case ".":
                        Sound.pauseSound("text", 70);
                        timeCheck = timePeriod;
                        break;
                    case "?":
                        Sound.pauseSound("text", 70);
                        timeCheck = timePeriod;
                        break;
                    case ",":
                        Sound.pauseSound("text", 70);
                        timeCheck = timeComma;
                        break;
                    case "*":
                        Sound.pauseSound("text", 70);
                        timeCheck = timeAsterisk;
                        break;
                    default:
                        Sound.playSound("text", false);
                        timeCheck = timeStandard;
                        break;
                }
            }
            else
            {
                Sound.playSound("text", false);
                timeCheck = timeStandard;
            }

        }

        if(charCounter >= text.length - 1)
        {
            Sound.pauseSoundHard("text");
        }
    }

    //Draw text.
    function drawText(ctx)
    {
        ctx.save();

        //Style.
        ctx.font = "24pt undertale";
        ctx.fillStyle = "#FFF";

        //Initial position.
        var textXPos = 52;
        var textYPos = 296;

        //Draw each active character, characters up to the character after the current character.
        for(var i = 0; i < charCounter + 1; i++)
        {
            //Display character if not last character and asterisk.
            if(
                text.charAt(i) != "*" ||
                text.charAt(i) != "|" ||
                i < charCounter)
            {
                ctx.fillText(
                    text.charAt(i),
                    textXPos + 2 * Math.floor(Math.random() * 1.0004),     //Random text wobble.
                    textYPos + 2 * Math.floor(Math.random() * 1.0004));
            }

            if(text.charAt(i + 1) == "|")
            {
                textXPos += ctx.measureText(text.charAt(i)).width;
                ctx.fillStyle = text.substring(i + 2, i + 6);
                i += 5;
            }
            else if(text.charAt(i + 1) == "\n") //New line moveover.
            {
                textXPos = 70;
                textYPos += 32;
            }
            else if(text.charAt(i + 1) == "*")  //Asterisk moveover
            {
                textXPos = 52;
                textYPos += 32;
            }
            else                                //Next-char moveover.
            {
                textXPos += ctx.measureText(text.charAt(i)).width + 2;
            }
        }

        ctx.restore();
    }

    //Draw a menu.
    function drawMenu(ctx, menu, menuState, MENU_STATE)
    {
        ctx.save();

        //Style.
        ctx.font = "24pt undertale";
        ctx.fillStyle = "#FFF";

        switch(menuState)
        {
            case MENU_STATE.FIGHT:
                drawMenuTexts(ctx, menu, verticalPositions, true);
                break;
            case MENU_STATE.ACT:
                drawMenuTexts(ctx, menu, horizontalPositions, false);
                break;
            case MENU_STATE.ITEM:
                drawMenuTexts(ctx, menu, horizontalPositions, false);
                break;
            case MENU_STATE.MERCY:
                drawMenuTexts(ctx, menu, verticalPositions, false);
                break;
            default:
                drawMenuTexts(ctx, menu, verticalPositions, false);
                break;
        }

        ctx.restore();
    }

    //Draw text for all menu options.
    function drawMenuTexts(ctx, menu, positions, bars)
    {
        var barPos = 0;
        if(bars)
        {
            for(var i = 0; i < menu.length; i++)
            {
                var temp = ctx.measureText(menu[i]).width;
                if(temp > barPos)
                    barPos = temp;
            }
        }
        for(var i = 0; i < menu.length; i++)
        {
            drawMenuText(ctx, menu[i], positions[i][0], positions[i][1]);
            if(bars)
            {
                ctx.fillStyle = "#404040";
                ctx.strokeStyle = "#000";
                ctx.lineWidth = 1;
                ctx.beginPath();
                ctx.rect(
                    positions[i][0] + barPos + 50,
                    positions[i][1] - 15,
                    100,
                    15);
                ctx.fill();
                ctx.stroke();
                ctx.fillStyle = "#0F0";
                ctx.fillRect(
                    positions[i][0] + barPos + 50,
                    positions[i][1] - 15,
                    100 * Cgroup.getCurHP(i) / Cgroup.getMaxHP(i),
                    15);
            }
            ctx.fillStyle = "#FFF"; //Color reset.
        }
    }

    //Draw text for a menu option.
    function drawMenuText(ctx, option, xPos, yPos)
    {
        //Asterisk.
        ctx.fillText(
            "*",
            xPos + 2 * Math.floor(Math.random() * 1.0004),
            yPos + 2 * Math.floor(Math.random() * 1.0004));

        //Text offset.
        xPos += 32;

        //Draw characters.
        for(var i = 0; i < option.length; i++)
        {
            if(option.charAt(i) == "|")
            {
                ctx.fillStyle = option.substring(i + 1, i + 5);
                i += 4;
            }
            else
            {
                ctx.fillText(
                    option.charAt(i),
                    xPos + 2 * Math.floor(Math.random() * 1.0004),     //Random text wobble.
                    yPos + 2 * Math.floor(Math.random() * 1.0004));
                xPos += ctx.measureText(option.charAt(i)).width;
            }
        }
    }

    //Skip text growing entirely.
    function skip ()
    {
        charCounter = text.length;
    }

    //Reset text
    function reset()
    {
        charCounter = -1;
        timeCounter = timeAsterisk;
    }

    //Get the soul position for the option at a given menu index and style
    function getSoulPos (index, style)
    {
        var pos;

        switch(style)
        {
            case 0:
                pos = new Vect(
                    horizontalPositions[index][0] - 36,
                    horizontalPositions[index][1] - 18,
                    0);
                break;
            case 1:
                pos = new Vect(
                    verticalPositions[index][0] - 36,
                    verticalPositions[index][1] - 18,
                    0);
                break;
        }
        return pos;
    }

    //Return
    return{
        init : init,
        setupTimes : setupTimes,
        setupText : setupText,
        update : update,
        drawText : drawText,
        drawMenu : drawMenu,
        skip : skip,
        reset : reset,
        getSoulPos : getSoulPos}
}());<commit_msg>Fixed improper reset of cwriter<commit_after>//Dialogue writer and selector module for combat sequence.
var Cwriter = (function()
{
    var timeCheck = 0;         //Current interval to wait to place a character. Changes based on special characters.
    var timeAsterisk = .75;    //Interval to use for asterisk.
    var timePeriod = .33;      //Interval to use for periods.
    var timeComma = .21;       //Interval to use for commas.
    var timeStandard = .033;   //Interval to use for all other characters.

    var text;                  //Text to display.
    var charCounter;           //Counter for characters in text being displayed.
    var timeCounter;           //Tracks time for character counting.

    var horizontalPositions;   //Positions for horizontal menu.
    var verticalPositions;     //Positions for vertical menu.

    //Init
    function init()
    {
        horizontalPositions =
        [
            [100, 296],
            [356, 296],
            [100, 328],
            [356, 328],
            [100, 360],
            [356, 360]
        ]

        verticalPositions =
        [
            [100, 296],
            [100, 328],
            [100, 360]
        ]
    }

    //Set the time delays of the writer.
    function setupTimes(
        _timeAsterisk,
        _timePeriod,
        _timeComma,
        _timeStandard)
    {
        timeCheck = 0;
        timeAsterisk = _timeAsterisk;
        timePeriod = _timePeriod;
        timeComma = _timeComma;
        timeStandard = _timeStandard;
    }

    //Set the text for the writer and reset counters.
    function setupText(_text)
    {
        text = _text;
        charCounter = -1;           //Counter for the index of the most recent displayed character.
        timeCounter = 0;            //Counter for the time since a character was placed.
    }

    //Update the writer.
    function update(dt)
    {
        if(myKeys.keydown[myKeys.KEYBOARD.KEY_X])
        {
            skip();
        }

        //Tick.
        timeCounter += dt;

        //If time to place a new character and if there is a new character.
        if(timeCounter > timeCheck && charCounter < text.length)
        {
            //Reset counter and increment current character for next character.
            timeCounter = timeCounter - timeCheck;
            charCounter++;

            //SFX
            if(charCounter < text.length - 2)
            {
                //Change interval for new character.
                switch(text.charAt(charCounter + 1))
                {
                    case ".":
                        Sound.pauseSound("text", 70);
                        timeCheck = timePeriod;
                        break;
                    case "?":
                        Sound.pauseSound("text", 70);
                        timeCheck = timePeriod;
                        break;
                    case ",":
                        Sound.pauseSound("text", 70);
                        timeCheck = timeComma;
                        break;
                    case "*":
                        Sound.pauseSound("text", 70);
                        timeCheck = timeAsterisk;
                        break;
                    default:
                        Sound.playSound("text", false);
                        timeCheck = timeStandard;
                        break;
                }
            }
            else
            {
                Sound.playSound("text", false);
                timeCheck = timeStandard;
            }
        }

        if(charCounter >= text.length - 1)
        {
            Sound.pauseSoundHard("text");
        }
    }

    //Draw text.
    function drawText(ctx)
    {
        ctx.save();

        //Style.
        ctx.font = "24pt undertale";
        ctx.fillStyle = "#FFF";

        //Initial position.
        var textXPos = 52;
        var textYPos = 296;

        //Draw each active character, characters up to the character after the current character.
        for(var i = 0; i < charCounter + 1; i++)
        {
            //Display character if not last character and asterisk.
            if(
                text.charAt(i) != "*" ||
                text.charAt(i) != "|" ||
                i < charCounter)
            {
                ctx.fillText(
                    text.charAt(i),
                    textXPos + 2 * Math.floor(Math.random() * 1.0004),     //Random text wobble.
                    textYPos + 2 * Math.floor(Math.random() * 1.0004));
            }

            if(text.charAt(i + 1) == "|")
            {
                textXPos += ctx.measureText(text.charAt(i)).width;
                ctx.fillStyle = text.substring(i + 2, i + 6);
                i += 5;
            }
            else if(text.charAt(i + 1) == "\n") //New line moveover.
            {
                textXPos = 70;
                textYPos += 32;
            }
            else if(text.charAt(i + 1) == "*")  //Asterisk moveover
            {
                textXPos = 52;
                textYPos += 32;
            }
            else                                //Next-char moveover.
            {
                textXPos += ctx.measureText(text.charAt(i)).width + 2;
            }
        }

        ctx.restore();
    }

    //Draw a menu.
    function drawMenu(ctx, menu, menuState, MENU_STATE)
    {
        ctx.save();

        //Style.
        ctx.font = "24pt undertale";
        ctx.fillStyle = "#FFF";

        switch(menuState)
        {
            case MENU_STATE.FIGHT:
                drawMenuTexts(ctx, menu, verticalPositions, true);
                break;
            case MENU_STATE.ACT:
                drawMenuTexts(ctx, menu, horizontalPositions, false);
                break;
            case MENU_STATE.ITEM:
                drawMenuTexts(ctx, menu, horizontalPositions, false);
                break;
            case MENU_STATE.MERCY:
                drawMenuTexts(ctx, menu, verticalPositions, false);
                break;
            default:
                drawMenuTexts(ctx, menu, verticalPositions, false);
                break;
        }

        ctx.restore();
    }

    //Draw text for all menu options.
    function drawMenuTexts(ctx, menu, positions, bars)
    {
        var barPos = 0;
        if(bars)
        {
            for(var i = 0; i < menu.length; i++)
            {
                var temp = ctx.measureText(menu[i]).width;
                if(temp > barPos)
                    barPos = temp;
            }
        }
        for(var i = 0; i < menu.length; i++)
        {
            drawMenuText(ctx, menu[i], positions[i][0], positions[i][1]);
            if(bars)
            {
                ctx.fillStyle = "#404040";
                ctx.strokeStyle = "#000";
                ctx.lineWidth = 1;
                ctx.beginPath();
                ctx.rect(
                    positions[i][0] + barPos + 50,
                    positions[i][1] - 15,
                    100,
                    15);
                ctx.fill();
                ctx.stroke();
                ctx.fillStyle = "#0F0";
                ctx.fillRect(
                    positions[i][0] + barPos + 50,
                    positions[i][1] - 15,
                    100 * Cgroup.getCurHP(i) / Cgroup.getMaxHP(i),
                    15);
            }
            ctx.fillStyle = "#FFF"; //Color reset.
        }
    }

    //Draw text for a menu option.
    function drawMenuText(ctx, option, xPos, yPos)
    {
        //Asterisk.
        ctx.fillText(
            "*",
            xPos + 2 * Math.floor(Math.random() * 1.0004),
            yPos + 2 * Math.floor(Math.random() * 1.0004));

        //Text offset.
        xPos += 32;

        //Draw characters.
        for(var i = 0; i < option.length; i++)
        {
            if(option.charAt(i) == "|")
            {
                ctx.fillStyle = option.substring(i + 1, i + 5);
                i += 4;
            }
            else
            {
                ctx.fillText(
                    option.charAt(i),
                    xPos + 2 * Math.floor(Math.random() * 1.0004),     //Random text wobble.
                    yPos + 2 * Math.floor(Math.random() * 1.0004));
                xPos += ctx.measureText(option.charAt(i)).width;
            }
        }
    }

    //Skip text growing entirely.
    function skip ()
    {
        charCounter = text.length;
    }

    //Reset text
    function reset()
    {
        charCounter = -1;
        timeCounter = 0;
    }

    //Get the soul position for the option at a given menu index and style
    function getSoulPos (index, style)
    {
        var pos;

        switch(style)
        {
            case 0:
                pos = new Vect(
                    horizontalPositions[index][0] - 36,
                    horizontalPositions[index][1] - 18,
                    0);
                break;
            case 1:
                pos = new Vect(
                    verticalPositions[index][0] - 36,
                    verticalPositions[index][1] - 18,
                    0);
                break;
        }
        return pos;
    }

    //Return
    return{
        init : init,
        setupTimes : setupTimes,
        setupText : setupText,
        update : update,
        drawText : drawText,
        drawMenu : drawMenu,
        skip : skip,
        reset : reset,
        getSoulPos : getSoulPos}
}());<|endoftext|>


<commit_before>/* jshint multistr:true */
osmly.qa = (function () {
    var qa = {live: false},
        data = {};

    qa.go = function(){
        // toggle qa mode
        if (!qa.live) {
            if (osmly.import.live) osmly.import.go();
            setInterface();
            bind();
            next();
            qa.live = true;
        } else {
            reset();
            unbind();
            unsetInterface();
            qa.live = false;
            osmly.import.go();
        }
    };

    function setInterface() {
        byId('qa').innerHTML = 'Leave QA';
        byId('qa').style.backgroundColor = 'black';
        byId('qa').style.color = 'white';

        var body = byTag('body')[0],
            qablock = createId('div', 'qa-block');
        body.appendChild(qablock);

        var report = createId('div', 'report');
        qablock.appendChild(report);

        var layerz = createId('div', 'toggleLayers');
        qablock.appendChild(layerz);
        layerz.innerHTML = '[w] see original feature';

        var skip = createId('div', 'qa-skip');
        qablock.appendChild(skip);
        skip.innerHTML = '[s] skip';

        var confirmz = createId('div', 'confirm');
        qablock.appendChild(confirmz);
        confirmz.innerHTML = 'confirm';

        $('body').append('\

\

see OSM map
\

open at osm.org
\

\
        ');
    }

    function bind() {
        $('#toggleLayers').on('click', toggleLayers);
        $('#qa-skip').one('click', next);
        $('#confirm').on('click', confirm);
        $('#osmlink').on('click', function(){
            window.open(osmly.osmlink);
        });
        $('#osmtiles').on('click', osmly.map.toggleOSM);

        $('body').on('keydown', function(that){
            if (that.keyCode === 87) toggleLayers(); //w
            if (that.keyCode === 83) next(); //s
        });
    }

    function unbind() {
        $('#toggleLayers, #qa-skip, #confirm').off();
        $('body').off('keydown');
        $('#osmlink, #osmtiles').off();
    }

    function unsetInterface() {
        byTag('body')[0].removeChild(byId('qa-block'));
        byId('qa').innerHTML = 'QA';
        byId('qa').style.backgroundColor = 'white';
        byId('qa').style.color = 'black';
    }

    function request(callback) {
        $.ajax({
            url: osmly.settings.db + '&qa',
            cache: false,
            dataType: 'json',
            success: function(item){
                data = {
                    id: item[0],
                    geo: JSON.parse(item[1]),
                    problem: item[2],
                    submit: item[3],
                    user: item[4],
                    time: item[5],
                };

                if (data.geo.properties.name) data.name = data.geo.properties.name;
                if (callback) callback();
            }
        });
    }

    function fillReport() {
        var table = createE('table'),
            report = byId('report');
        if (report.getElementsByTagName('table').length) {
            report.removeChild(report.childNodes[0]);
        }
        var tbody = createE('tbody');

        // columns = 'id, geo, problem, submit, user, time'
        for (var item in data) {
            var tr = createE('tr');
            if (item == 'id') tr.innerHTML = 'id	' + data.id + '	';
            if (item == 'user') tr.innerHTML = 'who	' + data.user + '	';
            if (item == 'time') tr.innerHTML = 'when	' + format_date(data.time) + '	';
            if (item == 'problem' && data.problem !== '') tr.innerHTML = 'problem	' + data.problem + '	';
            if (item == 'submit' && data.submit != 1){
                tr.innerHTML = 'via	' + data.submit + '	';
            }
            if (item == 'name') tr.innerHTML = 'name	' + data.name + '	';
            if (tr.innerHTML !== '') tbody.appendChild(tr);
        }

        table.appendChild(tbody);
        report.appendChild(table);
    }

    function next() {
        reset();
        request(function(){
            fillReport();
            setGeometry();
            setContext();
            setTimeout(bind, 1000);
                // it can be too quick
        });
    }

    function reset() {
        unbind();
        osmly.map.removeContext();
        if (osmly.map.featureLayer) osmly.map.removeLayer(osmly.map.featureLayer);
        byId('toggleLayers').innerHTML = '[w] see original feature';
        $('#qa-block, #bottom-right').hide();
        osmly.map.removeOSM();
    }

    function setContext() {
        var bounds = data.geo.properties.bounds;

        osmly.map.fitBounds([
            [bounds[1], bounds[0]],
            [bounds[3], bounds[2]]
        ]);

        osmly.map.context(bounds, 0.002, function(){
            osmly.map.removeLayer(osmly.map.featureLayer);
            $('#qa-block, #bottom-right').fadeIn(250);
            $('#notify').fadeOut(250);
        });

    }

    function setGeometry() {
        osmly.map.setFeature(data.geo, false, true);
    }

    function confirm() {
        osmly.connect.updateItem('confirm', false, false, data.id);
        next();
    }

    function toggleLayers() {
        if (osmly.map.hasLayer(osmly.map.featureLayer)) {
            byId('toggleLayers').innerHTML = '[w] see original feature';
            osmly.map.removeLayer(osmly.map.featureLayer);
            osmly.map.showContext();
        } else {
            byId('toggleLayers').innerHTML = '[w] see OSM data';
            osmly.map.removeContext();
            osmly.map.featureLayer.addTo(osmly.map);
            osmly.map.featureLayer.bringToFront();
        }
    }

    return qa;
}());
<commit_msg>Simplified QA bindings, closes #26<commit_after>/* jshint multistr:true */
osmly.qa = (function () {
    var qa = {live: false},
        data = {};

    qa.go = function(){
        // toggle qa mode
        if (!qa.live) {
            if (osmly.import.live) osmly.import.go();
            setInterface();
            next();
            qa.live = true;
        } else {
            reset();
            unbind();
            unsetInterface();
            qa.live = false;
            osmly.import.go();
        }
    };

    function setInterface() {
        byId('qa').innerHTML = 'Leave QA';
        byId('qa').style.backgroundColor = 'black';
        byId('qa').style.color = 'white';

        var body = byTag('body')[0],
            qablock = createId('div', 'qa-block');
        body.appendChild(qablock);

        var report = createId('div', 'report');
        qablock.appendChild(report);

        var layerz = createId('div', 'toggleLayers');
        qablock.appendChild(layerz);
        layerz.innerHTML = '[w] see original feature';

        var skip = createId('div', 'qa-skip');
        qablock.appendChild(skip);
        skip.innerHTML = '[s] skip';

        var confirmz = createId('div', 'confirm');
        qablock.appendChild(confirmz);
        confirmz.innerHTML = 'confirm';

        $('body').append('\

\

see OSM map
\

open at osm.org
\

\
        ');
    }

    function bind() {
        $('#toggleLayers').on('click', toggleLayers);
        $('#qa-skip').one('click', next);
        $('#confirm').on('click', confirm);
        $('#osmlink').on('click', function(){
            window.open(osmly.osmlink);
        });
        $('#osmtiles').on('click', osmly.map.toggleOSM);

        $('body').on('keydown', function(that){
            if (that.keyCode === 87) toggleLayers(); //w
            if (that.keyCode === 83) next(); //s
        });
    }

    function unbind() {
        $('#toggleLayers, #qa-skip, #confirm').off();
        $('body').off('keydown');
        $('#osmlink, #osmtiles').off();
    }

    function unsetInterface() {
        byTag('body')[0].removeChild(byId('qa-block'));
        byId('qa').innerHTML = 'QA';
        byId('qa').style.backgroundColor = 'white';
        byId('qa').style.color = 'black';
    }

    function request(callback) {
        $.ajax({
            url: osmly.settings.db + '&qa',
            cache: false,
            dataType: 'json',
            success: function(item){
                data = {
                    id: item[0],
                    geo: JSON.parse(item[1]),
                    problem: item[2],
                    submit: item[3],
                    user: item[4],
                    time: item[5],
                };

                if (data.geo.properties.name) data.name = data.geo.properties.name;
                if (callback) callback();
            }
        });
    }

    function fillReport() {
        var table = createE('table'),
            report = byId('report');
        if (report.getElementsByTagName('table').length) {
            report.removeChild(report.childNodes[0]);
        }
        var tbody = createE('tbody');

        // columns = 'id, geo, problem, submit, user, time'
        for (var item in data) {
            var tr = createE('tr');
            if (item == 'id') tr.innerHTML = 'id	' + data.id + '	';
            if (item == 'user') tr.innerHTML = 'who	' + data.user + '	';
            if (item == 'time') tr.innerHTML = 'when	' + format_date(data.time) + '	';
            if (item == 'problem' && data.problem !== '') tr.innerHTML = 'problem	' + data.problem + '	';
            if (item == 'submit' && data.submit != 1){
                tr.innerHTML = 'via	' + data.submit + '	';
            }
            if (item == 'name') tr.innerHTML = 'name	' + data.name + '	';
            if (tr.innerHTML !== '') tbody.appendChild(tr);
        }

        table.appendChild(tbody);
        report.appendChild(table);
    }

    function next() {
        reset();
        request(function(){
            fillReport();
            setGeometry();
            setContext();
        });
    }

    function reset() {
        unbind();
        osmly.map.removeContext();
        if (osmly.map.featureLayer) osmly.map.removeLayer(osmly.map.featureLayer);
        byId('toggleLayers').innerHTML = '[w] see original feature';
        $('#qa-block, #bottom-right').hide();
        osmly.map.removeOSM();
    }

    function setContext() {
        var bounds = data.geo.properties.bounds;

        osmly.map.fitBounds([
            [bounds[1], bounds[0]],
            [bounds[3], bounds[2]]
        ]);

        osmly.map.context(bounds, 0.002, show);

    }

    function show() {
        osmly.map.removeLayer(osmly.map.featureLayer);
        $('#qa-block, #bottom-right').fadeIn(250);
        $('#notify').fadeOut(250);
        bind();
    }

    function setGeometry() {
        osmly.map.setFeature(data.geo, false, true);
    }

    function confirm() {
        osmly.connect.updateItem('confirm', false, false, data.id);
        next();
    }

    function toggleLayers() {
        if (osmly.map.hasLayer(osmly.map.featureLayer)) {
            byId('toggleLayers').innerHTML = '[w] see original feature';
            osmly.map.removeLayer(osmly.map.featureLayer);
            osmly.map.showContext();
        } else {
            byId('toggleLayers').innerHTML = '[w] see OSM data';
            osmly.map.removeContext();
            osmly.map.featureLayer.addTo(osmly.map);
            osmly.map.featureLayer.bringToFront();
        }
    }

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


<commit_before>/*!
* Still Alive v1.2
* http://github.com/sidewaysmilk/still-alive
*
* Copyright 2011, Justin Force
* Licensed under the BSD 3-Clause License
*/

/*jslint browser: true, indent: 2 */
/*global jQuery */

(function ($) {

  'use strict';

  // default values for optional arguments
  var DEFAULT_WAKEEVENTS = 'mousemove mousedown mouseup keydown keyup',
    DEFAULT_INTERVAL     = 60000,
    DEFAULT_IMMEDIATELY  = true;

  // sugar. Just get the current time in milliseconds
  function getTime() {
    return (new Date()).getTime();
  }

  $.stillAlive = function (callback, interval, immediately, wakeEvents) {

    var ptr,                // pointer to the interval so it can be cleared from outside
      args,                 // object containing optional arguments
      awake = true,         // awake status. Are we awake?
      lastSeen = getTime(); // the last time the user was seen (a wake event triggered)

    // For named arguments, copy the arguments object and assign its supported
    // properties.
    if (typeof interval === 'object') {
      args = interval;
      interval = args.interval;
      immediately = args.immediately;
      wakeEvents = args.wakeEvents;
    }

    // set default values for optional arguments
    if (interval === undefined) {
      interval = DEFAULT_INTERVAL;
    }
    if (immediately === undefined) {
      immediately = DEFAULT_IMMEDIATELY;
    }
    if (wakeEvents === undefined) {
      wakeEvents = DEFAULT_WAKEEVENTS;
    }

    // true if it's been (1.5 x interval) milliseconds
    function timeToSleep() {
      return (getTime() - lastSeen > (interval + (interval / 2)));
    }

    // set status to awake and update the lastSeen time, then execute the
    // callback.
    function wake() {
      if (!awake) {
        callback();
      }
      awake = true;
      lastSeen = getTime();
    }

    // set status to !awake (asleep)
    function sleep() {
      awake = false;
    }

    $(window).bind(wakeEvents, wake);

    // if enough time has passed without a wake event, sleep. If we happen to
    // be awake, execute the callback.
    ptr = setInterval(function () {
      if (timeToSleep()) {
        sleep();
      }
      if (awake) {
        callback();
      }
    }, interval);

    // if we're supposed to run immediately, execute the callback once
    if (immediately) {
      callback();
    }

    return ptr;
  };

}(jQuery));

<commit_msg>update URL<commit_after>/*!
* Still Alive v1.2
* http://github.com/justinforce/still-alive
*
* Copyright 2011, Justin Force
* Licensed under the BSD 3-Clause License
*/

/*jslint browser: true, indent: 2 */
/*global jQuery */

(function ($) {

  'use strict';

  // default values for optional arguments
  var DEFAULT_WAKEEVENTS = 'mousemove mousedown mouseup keydown keyup',
    DEFAULT_INTERVAL     = 60000,
    DEFAULT_IMMEDIATELY  = true;

  // sugar. Just get the current time in milliseconds
  function getTime() {
    return (new Date()).getTime();
  }

  $.stillAlive = function (callback, interval, immediately, wakeEvents) {

    var ptr,                // pointer to the interval so it can be cleared from outside
      args,                 // object containing optional arguments
      awake = true,         // awake status. Are we awake?
      lastSeen = getTime(); // the last time the user was seen (a wake event triggered)

    // For named arguments, copy the arguments object and assign its supported
    // properties.
    if (typeof interval === 'object') {
      args = interval;
      interval = args.interval;
      immediately = args.immediately;
      wakeEvents = args.wakeEvents;
    }

    // set default values for optional arguments
    if (interval === undefined) {
      interval = DEFAULT_INTERVAL;
    }
    if (immediately === undefined) {
      immediately = DEFAULT_IMMEDIATELY;
    }
    if (wakeEvents === undefined) {
      wakeEvents = DEFAULT_WAKEEVENTS;
    }

    // true if it's been (1.5 x interval) milliseconds
    function timeToSleep() {
      return (getTime() - lastSeen > (interval + (interval / 2)));
    }

    // set status to awake and update the lastSeen time, then execute the
    // callback.
    function wake() {
      if (!awake) {
        callback();
      }
      awake = true;
      lastSeen = getTime();
    }

    // set status to !awake (asleep)
    function sleep() {
      awake = false;
    }

    $(window).bind(wakeEvents, wake);

    // if enough time has passed without a wake event, sleep. If we happen to
    // be awake, execute the callback.
    ptr = setInterval(function () {
      if (timeToSleep()) {
        sleep();
      }
      if (awake) {
        callback();
      }
    }, interval);

    // if we're supposed to run immediately, execute the callback once
    if (immediately) {
      callback();
    }

    return ptr;
  };

}(jQuery));

<|endoftext|>


<commit_before>var BusinessService = require('peasy-js').BusinessService;

var CustomerService = BusinessService.extend().service;

module.exports = CustomerService;
<commit_msg>add whitelist functionality to insert/update init methods<commit_after>var BusinessService = require('peasy-js').BusinessService;

function stripValues(customer) {
  var allowableFields = ['name', 'street'];
  Object.keys(customer).forEach(function(field) {
    if (allowableFields.indexOf(field) === -1) {
      delete customer[field];
    }
  });
}

var CustomerService = BusinessService.extend({
  functions: {
    _onInsertCommandInitialization: function(customer, context, done) {
      stripValues(customer);
      done();
    },
    _onUpdateCommandInitialization: function(customer, context, done) {
      stripValues(customer);
      done();
    }
  }
}).service;

module.exports = CustomerService;
<|endoftext|>


<commit_before>const fs = require("fs");
const semver = require("semver");
const { resolve } = require("path");
const child_process = require("child_process");

const devVersion = child_process.execSync("npm show tone@next version").toString();
const masterVersion = child_process.execSync("npm show tone version").toString();

//go with whichever is the latest version
let version = masterVersion;
let isDev = false;
if (semver.gt(devVersion, masterVersion)){
	isDev = true;
	version = devVersion;
}

version = version.split(".");
//increment the patch
version[2] = parseInt(version[2]) + 1;
//put it back in semver
version = version.join(".");

//write it to the package.json
const packageFile = resolve(__dirname, "../package.json");
const packageObj = JSON.parse(fs.readFileSync(packageFile, "utf-8"));

//if the package version if the latest, go with that one
if (semver.gt(packageObj.version, version)){
	version = packageObj.version;
}

console.log(`incrementing to version ${version}`);
packageObj.version = version;
fs.writeFileSync(packageFile, JSON.stringify(packageObj, undefined, "  "));

//write a version file
var versionFile = `module.exports = ${JSON.stringify({ version, dev : isDev }, undefined, "\t")};\n`;
fs.writeFileSync(resolve(__dirname, "../Tone/version.js"), versionFile);
<commit_msg>only write the package.json if it's travis<commit_after>const fs = require("fs");
const semver = require("semver");
const { resolve } = require("path");
const child_process = require("child_process");

const devVersion = child_process.execSync("npm show tone@next version").toString();
const masterVersion = child_process.execSync("npm show tone version").toString();

//go with whichever is the latest version
let version = masterVersion;
let isDev = false;
if (semver.gt(devVersion, masterVersion)){
	isDev = true;
	version = devVersion;
}

version = version.split(".");
//increment the patch
version[2] = parseInt(version[2]) + 1;
//put it back in semver
version = version.join(".");

//write it to the package.json
const packageFile = resolve(__dirname, "../package.json");
const packageObj = JSON.parse(fs.readFileSync(packageFile, "utf-8"));

//if the package version if the latest, go with that one
if (semver.gt(packageObj.version, version)){
	version = packageObj.version;
}

console.log(`incrementing to version ${version}`);
packageObj.version = version;
//only if it's travis, update the package.json
if (process.env.TRAVIS){
	fs.writeFileSync(packageFile, JSON.stringify(packageObj, undefined, "  "));
}

//write a version file
var versionFile = `module.exports = ${JSON.stringify({ version, dev : isDev }, undefined, "\t")};\n`;
fs.writeFileSync(resolve(__dirname, "../Tone/version.js"), versionFile);
<|endoftext|>


<commit_before>'use strict'
const render = require('../../render')
const test = require('tape')
// const parse = require('parse-element')
const s = require('brisky-struct')

test('collection - recursion', (t) => {
  const elem = {
    types: {
      ul: {
        tag: 'ul',
        $: 'items.$any', // make it for '$any'
        child: {
          tag: 'li',
          text: { $: 'text' },
          // type: 'ul' // its magical but will work! -- make it so
          inject (li, stamp) {
            console.log('ONCE')
            li.set({
              ul: new li.parent.Constructor()
            }, stamp)
          }
        }
      }
    },
    ul: { type: 'ul' },
    ul2: { type: 'ul' },
    holder: {
      text: 'holder!',
      ul3: { $: 'items2.$any', type: 'ul' }
    }
  }

  const state = s({
    items: [
      { text: 'a' },
      {
        text: 'b',
        items: [
          { text: 'b.a' },
          {
            text: 'b.b',
            items: [
              { text: 'b.b.a' },
              { text: 'b.b.b' }
            ]
          }
        ]
      }
    ],

    // uses wrong tree here ofc
    items2: [
      { text: '2.a' },
      {
        text: '2.b',
        items: [
          { text: '2.b.a' },
          {
            text: '2.b.b',
            items: [
              { text: '2.b.b.a' },
              {
                text: '2.b.b.b',
                items: [
                  { text: '2.b.b.b.a' },
                  { text: '2.b.b.b.b' }
                ]
              }
            ]
          }
        ]
      }
    ]
  })

  const app = render(elem, state, (s, t, state) => {
    global.s = s
    console.log('render:', state.path())
  })

  if ('document' in global && 'body' in global.document) {
    global.document.body.appendChild(app)
  }

  // console.log(parse(app))
  t.end()
})
<commit_msg>removed recursive<commit_after><|endoftext|>


<commit_before>/**
 * @author Marcelo G.
 */
(function ($) {
    $.viaAjaxLite = {
        sendForm: function(selector, callback) {

            var jqElement = $(selector);
            var self = this;

            $(selector + ' input[type="submit"], ' +
              selector + ' button[type="submit"]' ).bind('click', function(event) {
                event.preventDefault();
                self.send({
                    url: jqElement.attr('action'),
                    type: jqElement.attr('method'),
                    data: jqElement.serialize(),
                    target: jqElement.attr('target') || jqElement.attr('rel')
                },
                callback
                );
            });

        },

        load: function(options, callback) {
            this.send(options, callback);
        },

        send: function(options, callback) {
            // enviar consulta

            options = $.extend({type: 'get', data: {}}, options);

            $.ajax({
                url: options.url,
                type: options.type,
                data: options.data,
                success: function(data, textStatus, jqXHR) {
                    // procesar respuesta
                    $(options.target).html(data);
                    return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]);
                },
                beforeSend: function() {
                    $(options.target).html('

');
                }
            });
        }

    };
}(typeof jQuery === 'function' ? jQuery : this));
<commit_msg>add error event to handle requests errors<commit_after>/**
 * @author Marcelo G.
 */
(function ($) {
    $.viaAjaxLite = {
        sendForm: function(selector, callback) {

            var jqElement = $(selector);
            var self = this;

            $(selector + ' input[type="submit"], ' +
              selector + ' button[type="submit"]' ).bind('click', function(event) {
                event.preventDefault();
                self.send({
                    url: jqElement.attr('action'),
                    type: jqElement.attr('method'),
                    data: jqElement.serialize(),
                    target: jqElement.attr('target') || jqElement.attr('rel')
                },
                callback
                );
            });

        },

        load: function(options, callback) {
            this.send(options, callback);
        },

        send: function(options, callback) {
            // enviar consulta

            options = $.extend({type: 'get', data: {}}, options);

            $.ajax({
                url: options.url,
                type: options.type,
                data: options.data,
                success: function(data, textStatus, jqXHR) {
                    // procesar respuesta
                    $(options.target).html(data);
                    return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]);
                },
                beforeSend: function() {
                    $(options.target).html('

');
                },
                error: function() {
                    return $.isFunction(callback) && callback.call(self, [data, textStatus, jqXHR]);
                }
            });
        }

    };
}(typeof jQuery === 'function' ? jQuery : this));
<|endoftext|>