<commit_before>// =============================================================================
// Core.js | Arrays
// (c) Mathigon
// =============================================================================

import { run } from './utilities';

function _tabulateWith(fn, vals, args) {
  if (!args.length) return run(fn, ...vals);

  let newArgs = args.slice(0);
  let x = newArgs.shift();

  let result = [];
  for (let i=0; i<x; ++i) {
    result.push(_tabulateWith(fn, vals.concat([i]), newArgs));
  }
  return result;
}

/**
 * Creates a multi-dimensional array contains fn(i1, i2, ..., in) in cell
 * [i1][i2]...[in]. If the first argument is not a function, every item in the
 * resulting array will have that static value.
 *
 * @param {Function|*} fn
 * @param {...number} dimensions
 * @returns {Array}
 */
export function tabulate(fn, ...dimensions) {
  return _tabulateWith(fn, [], dimensions);
}

/**
 * @param {number} a
 * @param {?number} b
 * @param {?number} step
 * @returns {Array}
 */
export function list(a, b, step = 1) {
  let arr = [];

  if (b == null && a >= 0) {
    for (let i=0; i<a; i += step) arr.push(i);
  } else if (b == null) {
    for (let i=0; i>a; i -= step) arr.push(i);
  } else if (a <= b) {
    for (let i=a; i<=b; i += step) arr.push(i);
  } else {
    for (let i=a; i>=b; i -= step) arr.push(i);
  }

  return arr;
}

/**
 * Returns the last item in an array, or the ith item from the end.
 * @param {Array} array
 * @param {?Number} i
 * @returns {*}
 */
export function last(array, i=0) {
  return array[array.length - 1 - i];
}

/**
 * Maps a function over multiple arrays, the entries of which are passed as
 * multiple arguments.
 * @param {Function} fn
 * @param {...Array} args
 * @returns {Array}
 */
export function map(fn, ...args) {
  let length = Math.max(...args.map(a => a.length));
  return tabulate(i => fn(...args.map(a => a[i])), length);
}

/**
 * Finds the sum of all elements in an numeric array. This operation is safe,
 * i.e. any values that can't be cast to a number are counted as 0.
 * @param {Array} array
 * @returns {number}
 */
export function total(array) {
  if (!array.length) return 0;
  return +array.reduce((t, v) => t + (+v || 0));
}

/**
 * Evaluates the average of all the elements in an array.
 * @param {Array} array
 * @returns {number}
 */
export function average(array) {
  return array.total / array.length;
}

/**
 * Checks if an array contains a specific value.
 * @param {Array} array
 * @param {*} value
 * @returns {boolean}
 */
export function contains(array, value) {
  return array.indexOf(value) >= 0;
}

/**
 *
 * @param array
 * @param id
 */
export function extract(array, id) {
  return array.map(a => a[id]);
}

/**
 *
 * @param keys
 * @param values
 * @returns {{}}
 */
export function zip(keys, values) {
  let obj = {};
  for (let i=0; i < keys.length; ++i)
    obj[keys[i]] = values[i];
  return obj;
}

/**
 *
 * @param {Array} array
 * @param {string} id
 * @param {?boolean} reverse
 * @returns {Array}
 */
export function sortBy(array, id, reverse = false) {
  return array.slice(0).sort((a, b) => {
    return a[id] < b[id] ? (reverse ? 1 : -1) :
      a[id] > b[id] ? (reverse ? -1 : 1) : 0;
  });
}

/**
 *
 * @param {Array} array
 * @param {Function} fn
 * @param {?boolean} reverse
 * @returns {Array}
 */
export function sortByFn(array, fn, reverse = false) {
  return array.slice(0).sort((a, b) => {
    let x = fn(a);
    let y = fn(b);
    return x < y ? (reverse ? 1 : -1) : x > y ? (reverse ? -1 : 1) : 0;
  });
}

/**
 * Returns a function that can be called repeatedly, and returns items of the
 * array, continuously looping
 * @param {Array} array
 * @returns {Function}
 */
export function loop(array) {
  let i = -1;
  return function() { i = (i + 1) % array.length; return array[i]; };
}

/**
 *
 * @param array
 * @returns {Function}
 */
export function unique(array) {
  return array.filter((a, i, _this) => _this.indexOf(a) == i);
  // return [...new Set([this])];
}

/**
 * Removes any null or undefined values in array a.
 * @param {Array} array
 * @return {Array}
 */
export function clean(array) {
  return array.filter(a => a != null);
}

/**
 * Removes all occurrences of x from an array.
 * @param {Array} array
 * @param {*} x
 * @return {Array}
 */
export function without(array, x) {
  return array.filter(a => a !== x);
}

/**
 *
 * @param array
 */
export function flatten(array) {
  return array.reduce((a, b) =>
    a.concat(Array.isArray(b) ? flatten(b) : b), []);
}

/**
 *
 * @param array
 */
export function cumulative(array) {
  let total = 0;
  return array.map(a => total += a);
}

/**
 * Breaks an array into chunks of size at most n.
 * @param array
 * @param n
 * @returns {Array}
 */
export function chunk(array, n) {
  let chunks = [];
  for (let i = 0; i < array.length; i += n) {
    chunks.push(array.slice(i, i + n));
  }
  return chunks;
}

/**
 * Rotates the elements of an array by offset.
 * @param array
 * @param offset
 */
export function rotate(array, offset) {
  let n = array.length;
  offset = ((offset % n) + n) % n; // offset could initially be negative...

  let start = array.slice(0, offset);
  let end = array.slice(offset);
  return end.concat(start);
}

/**
 * Returns all elements that are in both a1 and a2.
 * @param a1
 * @param a2
 * @returns {Array}
 */
export function intersect(a1, a2) {
  let result = [];
  for (let i = 0; i < a1.length; ++i) {
    if (a2.indexOf(a1[i]) === -1) result.push(a1[i]);
  }
  return result;
}

/**
 * Returns all elements that are only in one of a1 and a2.
 * @param a1
 * @param a2
 * @returns {Array}
 */
export function difference(a1, a2) {
  let notIn1 = a2.filter(a => !a1.includes(a));
  let notIn2 = a1.filter(a => !a2.includes(a));
  return [...notIn1, ...notIn2];
}

/**
 * Converts an array into a one-way linked list, with .val and .next properties.
 * @param array
 * @returns {Array}
 */
export function toLinkedList(array) {
  const result = array.map(a => ({val: a, next: null}));
  const n = result.length;

  for (let i = 0; i < n; ++i) {
    result[i].next = result[(i + 1) % n];
  }

  return result;
}
<commit_msg>Tweaked loop() function<commit_after>// =============================================================================
// Core.js | Arrays
// (c) Mathigon
// =============================================================================

import { run } from './utilities';

function _tabulateWith(fn, vals, args) {
  if (!args.length) return run(fn, ...vals);

  let newArgs = args.slice(0);
  let x = newArgs.shift();

  let result = [];
  for (let i=0; i<x; ++i) {
    result.push(_tabulateWith(fn, vals.concat([i]), newArgs));
  }
  return result;
}

/**
 * Creates a multi-dimensional array contains fn(i1, i2, ..., in) in cell
 * [i1][i2]...[in]. If the first argument is not a function, every item in the
 * resulting array will have that static value.
 *
 * @param {Function|*} fn
 * @param {...number} dimensions
 * @returns {Array}
 */
export function tabulate(fn, ...dimensions) {
  return _tabulateWith(fn, [], dimensions);
}

/**
 * @param {number} a
 * @param {?number} b
 * @param {?number} step
 * @returns {Array}
 */
export function list(a, b, step = 1) {
  let arr = [];

  if (b == null && a >= 0) {
    for (let i=0; i<a; i += step) arr.push(i);
  } else if (b == null) {
    for (let i=0; i>a; i -= step) arr.push(i);
  } else if (a <= b) {
    for (let i=a; i<=b; i += step) arr.push(i);
  } else {
    for (let i=a; i>=b; i -= step) arr.push(i);
  }

  return arr;
}

/**
 * Returns the last item in an array, or the ith item from the end.
 * @param {Array} array
 * @param {?Number} i
 * @returns {*}
 */
export function last(array, i=0) {
  return array[array.length - 1 - i];
}

/**
 * Maps a function over multiple arrays, the entries of which are passed as
 * multiple arguments.
 * @param {Function} fn
 * @param {...Array} args
 * @returns {Array}
 */
export function map(fn, ...args) {
  let length = Math.max(...args.map(a => a.length));
  return tabulate(i => fn(...args.map(a => a[i])), length);
}

/**
 * Finds the sum of all elements in an numeric array. This operation is safe,
 * i.e. any values that can't be cast to a number are counted as 0.
 * @param {Array} array
 * @returns {number}
 */
export function total(array) {
  if (!array.length) return 0;
  return +array.reduce((t, v) => t + (+v || 0));
}

/**
 * Evaluates the average of all the elements in an array.
 * @param {Array} array
 * @returns {number}
 */
export function average(array) {
  return array.total / array.length;
}

/**
 * Checks if an array contains a specific value.
 * @param {Array} array
 * @param {*} value
 * @returns {boolean}
 */
export function contains(array, value) {
  return array.indexOf(value) >= 0;
}

/**
 *
 * @param array
 * @param id
 */
export function extract(array, id) {
  return array.map(a => a[id]);
}

/**
 *
 * @param keys
 * @param values
 * @returns {{}}
 */
export function zip(keys, values) {
  let obj = {};
  for (let i=0; i < keys.length; ++i)
    obj[keys[i]] = values[i];
  return obj;
}

/**
 *
 * @param {Array} array
 * @param {string} id
 * @param {?boolean} reverse
 * @returns {Array}
 */
export function sortBy(array, id, reverse = false) {
  return array.slice(0).sort((a, b) => {
    return a[id] < b[id] ? (reverse ? 1 : -1) :
      a[id] > b[id] ? (reverse ? -1 : 1) : 0;
  });
}

/**
 *
 * @param {Array} array
 * @param {Function} fn
 * @param {?boolean} reverse
 * @returns {Array}
 */
export function sortByFn(array, fn, reverse = false) {
  return array.slice(0).sort((a, b) => {
    let x = fn(a);
    let y = fn(b);
    return x < y ? (reverse ? 1 : -1) : x > y ? (reverse ? -1 : 1) : 0;
  });
}

/**
 * Returns a function that can be called repeatedly, and returns items of the
 * array, continuously looping
 * @param {Array} array
 * @returns {Function}
 */
export function loop(array) {
  let i = 0;
  return () => array[(i++) % array.length];
}

/**
 *
 * @param array
 * @returns {Function}
 */
export function unique(array) {
  return array.filter((a, i, _this) => _this.indexOf(a) == i);
  // return [...new Set([this])];
}

/**
 * Removes any null or undefined values in array a.
 * @param {Array} array
 * @return {Array}
 */
export function clean(array) {
  return array.filter(a => a != null);
}

/**
 * Removes all occurrences of x from an array.
 * @param {Array} array
 * @param {*} x
 * @return {Array}
 */
export function without(array, x) {
  return array.filter(a => a !== x);
}

/**
 *
 * @param array
 */
export function flatten(array) {
  return array.reduce((a, b) =>
    a.concat(Array.isArray(b) ? flatten(b) : b), []);
}

/**
 *
 * @param array
 */
export function cumulative(array) {
  let total = 0;
  return array.map(a => total += a);
}

/**
 * Breaks an array into chunks of size at most n.
 * @param array
 * @param n
 * @returns {Array}
 */
export function chunk(array, n) {
  let chunks = [];
  for (let i = 0; i < array.length; i += n) {
    chunks.push(array.slice(i, i + n));
  }
  return chunks;
}

/**
 * Rotates the elements of an array by offset.
 * @param array
 * @param offset
 */
export function rotate(array, offset) {
  let n = array.length;
  offset = ((offset % n) + n) % n; // offset could initially be negative...

  let start = array.slice(0, offset);
  let end = array.slice(offset);
  return end.concat(start);
}

/**
 * Returns all elements that are in both a1 and a2.
 * @param a1
 * @param a2
 * @returns {Array}
 */
export function intersect(a1, a2) {
  let result = [];
  for (let i = 0; i < a1.length; ++i) {
    if (a2.indexOf(a1[i]) === -1) result.push(a1[i]);
  }
  return result;
}

/**
 * Returns all elements that are only in one of a1 and a2.
 * @param a1
 * @param a2
 * @returns {Array}
 */
export function difference(a1, a2) {
  let notIn1 = a2.filter(a => !a1.includes(a));
  let notIn2 = a1.filter(a => !a2.includes(a));
  return [...notIn1, ...notIn2];
}

/**
 * Converts an array into a one-way linked list, with .val and .next properties.
 * @param array
 * @returns {Array}
 */
export function toLinkedList(array) {
  const result = array.map(a => ({val: a, next: null}));
  const n = result.length;

  for (let i = 0; i < n; ++i) {
    result[i].next = result[(i + 1) % n];
  }

  return result;
}
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require turbolinks
//= require jquery.validate
//= require jquery.validate.additional-methods
//= require bootstrap-datepicker
//= require_tree .
<commit_msg>Update application.js<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require turbolinks
//= require jquery.validate
//= require jquery.validate.additional-methods
//= require bootstrap-datepicker
//= require alertify
//= require_tree .
<|endoftext|>


<commit_before>"use strict";

/*
 * arrive.js
 * v2.0.0
 * https://github.com/uzairfarooq/arrive
 * MIT licensed
 *
 * Copyright (c) 2014 Uzair Farooq
 */

(function(window, $, undefined) {

  var utils = (function() {
    var matches = HTMLElement.prototype.matches || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector
                  || HTMLElement.prototype.msMatchesSelector;

    return {
      matchesSelector: function(elem, selector) {
        return elem instanceof HTMLElement && matches.call(elem, selector);
      },
      // to enable function overriding - By John Resig (MIT Licensed)
      addMethod: function (object, name, fn) {
        var old = object[ name ];
        object[ name ] = function(){
          if ( fn.length == arguments.length )
            return fn.apply( this, arguments );
          else if ( typeof old == 'function' )
            return old.apply( this, arguments );
        };
      }
    };
  })();

  // Class to mantain state of all registered events of a single type
  var EventsBucket = (function() {
    var EventsBucket = function() {
      // holds all the events

      this._eventsBucket    = [],
      // function to be called while adding an event, the function should do the event initialization/registration
      this._beforeAdding    = null,
      // function to be called while removing an event, the function should do the event destruction
      this._beforeRemoving  = null;
    };

    EventsBucket.prototype.addEvent = function(target, selector, options, callback) {
      var newEvent = {
        target:             target,
        selector:           selector,
        options:            options,
        callback:           callback,
        firedElems:         []
      };

      if (this._beforeAdding) {
        this._beforeAdding(newEvent);
      }

      this._eventsBucket.push(newEvent);
      return newEvent;
    };

    EventsBucket.prototype.removeEvent = function(compareFunction) {
      for (var i=this._eventsBucket.length - 1, registeredEvent; registeredEvent = this._eventsBucket[i]; i--) {
        if (compareFunction(registeredEvent)) {
          if (this._beforeRemoving) {
              this._beforeRemoving(registeredEvent);
          }
          this._eventsBucket.splice(i, 1);
        }
      }
    };

    EventsBucket.prototype.beforeAdding = function(beforeAdding) {
      this._beforeAdding = beforeAdding;
    };

    EventsBucket.prototype.beforeRemoving = function(beforeRemoving) {
      this._beforeRemoving = beforeRemoving;
    };

    return EventsBucket;
  })();

  // General class for binding/unbinding arrive and leave events
  var MutationEvents = function(getObserverConfig, defaultOptions, onMutation) {
    var eventsBucket  = new EventsBucket(),
        me            = this;

    // actual event registration before adding it to bucket
    eventsBucket.beforeAdding(function(registrationData) {
      var
        target    = registrationData.target,
        selector  = registrationData.selector,
        callback  = registrationData.callback,
        observer;

      // mutation observer does not work on window or document
      if (target === window.document || target === window)
        target = document.getElementsByTagName("html")[0];

      // Create an observer instance
      observer = new MutationObserver(function(e) {
        onMutation.call(this, e, registrationData);
      });

      var config = getObserverConfig(registrationData.options);

      observer.observe(target, config);

      registrationData.observer = observer;
    });

    // cleanup/unregister before removing an event
    eventsBucket.beforeRemoving(function (eventData) {
      eventData.observer.disconnect();
    });

    function toArray(elements) {
      if (typeof elements.length !== "number") {
        elements = [elements];
      }
      return elements;
    }

    this.bindEvent = function(selector, options, callback) {
      if (typeof callback === "undefined") {
        callback = options;
        options = defaultOptions;
      }

      var elements = toArray(this);
      for (var i = 0; i < elements.length; i++) {
        eventsBucket.addEvent(elements[i], selector, options, callback);
      }
    };

    this.unbindEvent = function() {
      var elements = toArray(this);
      eventsBucket.removeEvent(function(eventObj) {
        for (var i = 0; i < elements.length; i++) {
          if (eventObj.target === elements[i]) {
            return true;
          }
        }
        return false;
      });
    };

    this.unbindEventWithSelectorOrCallback = function(selector) {
      var elements = toArray(this),
          callback = selector,
          compareFunction;

      if (typeof selector === "function") {
        compareFunction = function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if (eventObj.target === elements[i] && eventObj.callback === callback) {
              return true;
            }
          }
          return false;
        };
      }
      else {
        compareFunction = function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if (eventObj.target === elements[i] && eventObj.selector === selector) {
              return true;
            }
          }
          return false;
        };
      }
      eventsBucket.removeEvent(compareFunction);
    };

    this.unbindEventWithSelectorAndCallback = function(selector, callback) {
      var elements = toArray(this);
      eventsBucket.removeEvent(function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if (eventObj.target === elements[i] && eventObj.selector === selector && eventObj.callback === callback) {
              return true;
            }
          }
          return false;
      });
    };

    return this;
  };

  // traverse through all descendants of a node to check if event should be fired for any descendant
  function checkChildNodesRecursively(nodes, registrationData, callbacksToBeCalled) {
    // check each new node if it matches the selector
    for (var i=0, node; node = nodes[i]; i++) {
        if (utils.matchesSelector(node, registrationData.selector)) {
            // make sure the arrive event is not already fired for the element
            if (registrationData.firedElems.indexOf(node) == -1) {
              registrationData.firedElems.push(node);
              callbacksToBeCalled.push({ callback: registrationData.callback, elem: node });
            }
        }
        if (node.childNodes.length > 0) {
            checkChildNodesRecursively(node.childNodes, registrationData, callbacksToBeCalled);
        }
    }
  }

  function callCallbacks(callbacksToBeCalled) {
    for (var i = 0, cb; cb = callbacksToBeCalled[i]; i++) {
      cb.callback.call(cb.elem);
    }
  }

  function onArriveMutation(mutations, registrationData) {
    mutations.forEach(function( mutation ) {
      var newNodes    = mutation.addedNodes,
          targetNode = mutation.target,
          callbacksToBeCalled = [];

      // If new nodes are added
      if( newNodes !== null && newNodes.length > 0 ) {
        checkChildNodesRecursively(newNodes, registrationData, callbacksToBeCalled);
      }
      else if (mutation.type === "attributes") {
          if(utils.matchesSelector(targetNode, registrationData.selector)) {
            // make sure the arrive event is not already fired for the element
            if (registrationData.firedElems.indexOf(targetNode) == -1) {
              registrationData.firedElems.push(targetNode);
              callbacksToBeCalled.push({ callback: registrationData.callback, elem: targetNode });
            }
          }
      }

      callCallbacks(callbacksToBeCalled);
    });
  }

  function onLeaveMutation(mutations, registrationData) {
    mutations.forEach(function( mutation ) {
      var removedNodes  = mutation.removedNodes,
          targetNode   = mutation.target,
          callbacksToBeCalled = [];

      if( removedNodes !== null && removedNodes.length > 0 ) {
        checkChildNodesRecursively(removedNodes, registrationData, callbacksToBeCalled);
      }

      callCallbacks(callbacksToBeCalled);
    });
  }

  function getArriveObserverConfig(options) {
    var config = {
          attributes: false,
          childList: true,
          subtree: true
        };

    if (options.fireOnAttributesModification) {
      config.attributes = true;
    }

    return config;
  }
  function getLeaveObserverConfig(options) {
    var config = {
          childList: true,
          subtree: true
        };

    return config;
  }

  // Default options
  var arriveDefaultOptions = {
        fireOnAttributesModification: false
      },
      leaveDefaultOptions = {};

  var arriveEvents = new MutationEvents(getArriveObserverConfig, arriveDefaultOptions, onArriveMutation),
      leaveEvents  = new MutationEvents(getLeaveObserverConfig, leaveDefaultOptions, onLeaveMutation);

  /*** expose APIs ***/
  function exposeApi(exposeTo) {
    exposeTo.arrive = arriveEvents.bindEvent;
    // expose unbindArrive function with overriding
    utils.addMethod(exposeTo, "unbindArrive", arriveEvents.unbindEvent);
    utils.addMethod(exposeTo, "unbindArrive", arriveEvents.unbindEventWithSelectorOrCallback);
    utils.addMethod(exposeTo, "unbindArrive", arriveEvents.unbindEventWithSelectorAndCallback);

    exposeTo.leave = leaveEvents.bindEvent;
    // expose unbindLeave function with overriding
    utils.addMethod(exposeTo, "unbindLeave", leaveEvents.unbindEvent);
    utils.addMethod(exposeTo, "unbindLeave", leaveEvents.unbindEventWithSelectorOrCallback);
    utils.addMethod(exposeTo, "unbindLeave", leaveEvents.unbindEventWithSelectorAndCallback);
  }

  if ($) {
    exposeApi($.fn);
  }
  exposeApi(HTMLElement.prototype);
  exposeApi(NodeList.prototype);
  exposeApi(HTMLCollection.prototype);
  exposeApi(HTMLDocument.prototype);
  exposeApi(Window.prototype);

})(this, typeof jQuery === 'undefined' ? null : jQuery);
<commit_msg>- Fix issue where including script triggers errors in unsupported browsers. Now it can be used with progressive enhancement or graceful degradation, via feature detection.<commit_after>"use strict";

/*
 * arrive.js
 * v2.0.0
 * https://github.com/uzairfarooq/arrive
 * MIT licensed
 *
 * Copyright (c) 2014 Uzair Farooq
 */

(function(window, $, undefined) {

  if(!window.MutationObserver || typeof HTMLElement === 'undefined'){
    return; //for unsupported browsers
  }

  var utils = (function() {
    var matches = HTMLElement.prototype.matches || HTMLElement.prototype.webkitMatchesSelector || HTMLElement.prototype.mozMatchesSelector
                  || HTMLElement.prototype.msMatchesSelector;

    return {
      matchesSelector: function(elem, selector) {
        return elem instanceof HTMLElement && matches.call(elem, selector);
      },
      // to enable function overriding - By John Resig (MIT Licensed)
      addMethod: function (object, name, fn) {
        var old = object[ name ];
        object[ name ] = function(){
          if ( fn.length == arguments.length )
            return fn.apply( this, arguments );
          else if ( typeof old == 'function' )
            return old.apply( this, arguments );
        };
      }
    };
  })();

  // Class to mantain state of all registered events of a single type
  var EventsBucket = (function() {
    var EventsBucket = function() {
      // holds all the events

      this._eventsBucket    = [],
      // function to be called while adding an event, the function should do the event initialization/registration
      this._beforeAdding    = null,
      // function to be called while removing an event, the function should do the event destruction
      this._beforeRemoving  = null;
    };

    EventsBucket.prototype.addEvent = function(target, selector, options, callback) {
      var newEvent = {
        target:             target,
        selector:           selector,
        options:            options,
        callback:           callback,
        firedElems:         []
      };

      if (this._beforeAdding) {
        this._beforeAdding(newEvent);
      }

      this._eventsBucket.push(newEvent);
      return newEvent;
    };

    EventsBucket.prototype.removeEvent = function(compareFunction) {
      for (var i=this._eventsBucket.length - 1, registeredEvent; registeredEvent = this._eventsBucket[i]; i--) {
        if (compareFunction(registeredEvent)) {
          if (this._beforeRemoving) {
              this._beforeRemoving(registeredEvent);
          }
          this._eventsBucket.splice(i, 1);
        }
      }
    };

    EventsBucket.prototype.beforeAdding = function(beforeAdding) {
      this._beforeAdding = beforeAdding;
    };

    EventsBucket.prototype.beforeRemoving = function(beforeRemoving) {
      this._beforeRemoving = beforeRemoving;
    };

    return EventsBucket;
  })();

  // General class for binding/unbinding arrive and leave events
  var MutationEvents = function(getObserverConfig, defaultOptions, onMutation) {
    var eventsBucket  = new EventsBucket(),
        me            = this;

    // actual event registration before adding it to bucket
    eventsBucket.beforeAdding(function(registrationData) {
      var
        target    = registrationData.target,
        selector  = registrationData.selector,
        callback  = registrationData.callback,
        observer;

      // mutation observer does not work on window or document
      if (target === window.document || target === window)
        target = document.getElementsByTagName("html")[0];

      // Create an observer instance
      observer = new MutationObserver(function(e) {
        onMutation.call(this, e, registrationData);
      });

      var config = getObserverConfig(registrationData.options);

      observer.observe(target, config);

      registrationData.observer = observer;
    });

    // cleanup/unregister before removing an event
    eventsBucket.beforeRemoving(function (eventData) {
      eventData.observer.disconnect();
    });

    function toArray(elements) {
      if (typeof elements.length !== "number") {
        elements = [elements];
      }
      return elements;
    }

    this.bindEvent = function(selector, options, callback) {
      if (typeof callback === "undefined") {
        callback = options;
        options = defaultOptions;
      }

      var elements = toArray(this);
      for (var i = 0; i < elements.length; i++) {
        eventsBucket.addEvent(elements[i], selector, options, callback);
      }
    };

    this.unbindEvent = function() {
      var elements = toArray(this);
      eventsBucket.removeEvent(function(eventObj) {
        for (var i = 0; i < elements.length; i++) {
          if (eventObj.target === elements[i]) {
            return true;
          }
        }
        return false;
      });
    };

    this.unbindEventWithSelectorOrCallback = function(selector) {
      var elements = toArray(this),
          callback = selector,
          compareFunction;

      if (typeof selector === "function") {
        compareFunction = function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if (eventObj.target === elements[i] && eventObj.callback === callback) {
              return true;
            }
          }
          return false;
        };
      }
      else {
        compareFunction = function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if (eventObj.target === elements[i] && eventObj.selector === selector) {
              return true;
            }
          }
          return false;
        };
      }
      eventsBucket.removeEvent(compareFunction);
    };

    this.unbindEventWithSelectorAndCallback = function(selector, callback) {
      var elements = toArray(this);
      eventsBucket.removeEvent(function(eventObj) {
          for (var i = 0; i < elements.length; i++) {
            if (eventObj.target === elements[i] && eventObj.selector === selector && eventObj.callback === callback) {
              return true;
            }
          }
          return false;
      });
    };

    return this;
  };

  // traverse through all descendants of a node to check if event should be fired for any descendant
  function checkChildNodesRecursively(nodes, registrationData, callbacksToBeCalled) {
    // check each new node if it matches the selector
    for (var i=0, node; node = nodes[i]; i++) {
        if (utils.matchesSelector(node, registrationData.selector)) {
            // make sure the arrive event is not already fired for the element
            if (registrationData.firedElems.indexOf(node) == -1) {
              registrationData.firedElems.push(node);
              callbacksToBeCalled.push({ callback: registrationData.callback, elem: node });
            }
        }
        if (node.childNodes.length > 0) {
            checkChildNodesRecursively(node.childNodes, registrationData, callbacksToBeCalled);
        }
    }
  }

  function callCallbacks(callbacksToBeCalled) {
    for (var i = 0, cb; cb = callbacksToBeCalled[i]; i++) {
      cb.callback.call(cb.elem);
    }
  }

  function onArriveMutation(mutations, registrationData) {
    mutations.forEach(function( mutation ) {
      var newNodes    = mutation.addedNodes,
          targetNode = mutation.target,
          callbacksToBeCalled = [];

      // If new nodes are added
      if( newNodes !== null && newNodes.length > 0 ) {
        checkChildNodesRecursively(newNodes, registrationData, callbacksToBeCalled);
      }
      else if (mutation.type === "attributes") {
          if(utils.matchesSelector(targetNode, registrationData.selector)) {
            // make sure the arrive event is not already fired for the element
            if (registrationData.firedElems.indexOf(targetNode) == -1) {
              registrationData.firedElems.push(targetNode);
              callbacksToBeCalled.push({ callback: registrationData.callback, elem: targetNode });
            }
          }
      }

      callCallbacks(callbacksToBeCalled);
    });
  }

  function onLeaveMutation(mutations, registrationData) {
    mutations.forEach(function( mutation ) {
      var removedNodes  = mutation.removedNodes,
          targetNode   = mutation.target,
          callbacksToBeCalled = [];

      if( removedNodes !== null && removedNodes.length > 0 ) {
        checkChildNodesRecursively(removedNodes, registrationData, callbacksToBeCalled);
      }

      callCallbacks(callbacksToBeCalled);
    });
  }

  function getArriveObserverConfig(options) {
    var config = {
          attributes: false,
          childList: true,
          subtree: true
        };

    if (options.fireOnAttributesModification) {
      config.attributes = true;
    }

    return config;
  }
  function getLeaveObserverConfig(options) {
    var config = {
          childList: true,
          subtree: true
        };

    return config;
  }

  // Default options
  var arriveDefaultOptions = {
        fireOnAttributesModification: false
      },
      leaveDefaultOptions = {};

  var arriveEvents = new MutationEvents(getArriveObserverConfig, arriveDefaultOptions, onArriveMutation),
      leaveEvents  = new MutationEvents(getLeaveObserverConfig, leaveDefaultOptions, onLeaveMutation);

  /*** expose APIs ***/
  function exposeApi(exposeTo) {
    exposeTo.arrive = arriveEvents.bindEvent;
    // expose unbindArrive function with overriding
    utils.addMethod(exposeTo, "unbindArrive", arriveEvents.unbindEvent);
    utils.addMethod(exposeTo, "unbindArrive", arriveEvents.unbindEventWithSelectorOrCallback);
    utils.addMethod(exposeTo, "unbindArrive", arriveEvents.unbindEventWithSelectorAndCallback);

    exposeTo.leave = leaveEvents.bindEvent;
    // expose unbindLeave function with overriding
    utils.addMethod(exposeTo, "unbindLeave", leaveEvents.unbindEvent);
    utils.addMethod(exposeTo, "unbindLeave", leaveEvents.unbindEventWithSelectorOrCallback);
    utils.addMethod(exposeTo, "unbindLeave", leaveEvents.unbindEventWithSelectorAndCallback);
  }

  if ($) {
    exposeApi($.fn);
  }
  exposeApi(HTMLElement.prototype);
  exposeApi(NodeList.prototype);
  exposeApi(HTMLCollection.prototype);
  exposeApi(HTMLDocument.prototype);
  exposeApi(Window.prototype);

})(this, typeof jQuery === 'undefined' ? null : jQuery);
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require kindeditor
if (window.console) {
  var cons = console;
  if (cons) {
    cons.log("喜欢看星哥的代码，星哥欢迎和您一起讨论学习! 请邮件至Edward_mjz@hotmail.com");
    cons.log("请在邮件中注明%c来自:console,星哥愿意请您吃饭！","color:red;font-weight:bold;");
  }
}

$(function(){
  $("#sub_submit").click(function(){
    email = $("#subscribe_email").val();
    $.ajax({
      url: "/subscribes/",
      type: 'POST',
      data: {
        email: email
      },
      success: function(data, status){
        if(data.status == -1) {
          swal('sorry', data.message, "error");
        } else {
          swal('sorry', data.message, "success")
        }
        $("#sub_message").html(data.message);
        $("#sub_message").show();
      }
    })
  })
})
<commit_msg>fix an issue when subscribe success should show success not sorry<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require kindeditor
if (window.console) {
  var cons = console;
  if (cons) {
    cons.log("喜欢看星哥的代码，星哥欢迎和您一起讨论学习! 请邮件至Edward_mjz@hotmail.com");
    cons.log("请在邮件中注明%c来自:console,星哥愿意请您吃饭！","color:red;font-weight:bold;");
  }
}

$(function(){
  $("#sub_submit").click(function(){
    email = $("#subscribe_email").val();
    $.ajax({
      url: "/subscribes/",
      type: 'POST',
      data: {
        email: email
      },
      success: function(data, status){
        if(data.status == -1) {
          swal('sorry', data.message, "error");
        } else {
          swal('success!', data.message, "success")
        }
        $("#sub_message").html(data.message);
        $("#sub_message").show();
      }
    })
  })
})
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
// loaclhost:3000/?debug_assets=1 > View Page Source -- to view all assets client side loads
//
//= require jquery
//= require jquery_ujs
//# = require jquery.ui.autocomplete
//= jquery-jvert-tabs-1.1.4
//= require mustache
//= require_tree .
//<commit_msg>[#3] Fix guide styling - explicitly require jvert-tabs (no require_tree)<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
// loaclhost:3000/?debug_assets=1 > View Page Source -- to view all assets client side loads
//
//= require jquery
//= require jquery_ujs
//= require mustache
//= require jquery-jvert-tabs-1.1.4
<|endoftext|>


<commit_before>"use strict";

/**
 * Yields the items of the iterator mapped through a given transformer.
 *
 * @type iT The item type of the input iterator.
 * @type rT The item type of the returned iterator.
 * @this {Iterable<iT>}
 * @ntime O(n)
 * @dspace O(1)
 * @example Basic Usage
 *
 * ```javascript
 * [1,2,3]::map(function () {
 *   return this * 2;
 * }) // yields 2, 4, 6
 * ```
*/
export function * map <iT, rT> (
    transformer : () => rT,
) : Iterable<rT> {
};
<commit_msg>Implemented iterable/map.<commit_after>"use strict";

/**
 * Yields the items of the iterator mapped through a given transformer.
 *
 * @type iT The item type of the input iterator.
 * @type rT The item type of the returned iterator.
 * @this {Iterable<iT>}
 * @ntime O(n)
 * @dspace O(1)
 * @example Basic Usage
 *
 * ```javascript
 * [1,2,3]::map(function () {
 *   return this * 2;
 * }) // yields 2, 4, 6
 * ```
*/
export function * map <iT, rT> (
    transformer : (_this : iT) => rT,
) : Iterable<rT> {
    for ( const item of this ) {
        yield item::transformer();
    }
};
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//
//= require raphael
//= require colorwheel
//= require_tree .
<commit_msg>Require jquery.pjax in application.js<commit_after>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//
//= require jquery.pjax
//= require raphael
//= require colorwheel
//= require_tree .
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require turbolinks
//= require_tree .
<commit_msg>JS: Use jQuery 3<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery3
//= require bootstrap-sprockets
//= require jquery_ujs
//= require turbolinks
//= require_tree .
<|endoftext|>


<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require jquery.sticky
//= require jquery.dotdotdot-1.5.1
//= require cocoon
//= require autocomplete-rails
//= require dataTables/jquery.dataTables
//= require dataTables_numhtml_sort.js
//= require dataTables_numhtml_detect.js
//= require dataTables/jquery.dataTables.bootstrap
//= require bootstrap
//= require variables.js
//= require select2
//= require_self

  function truncate() {
    $(".caption_cat").dotdotdot({
      height: 126,
      after: ".more_info",
      watch: 'window'
      });

    $(".equipment_title").dotdotdot({
      height: 54, // must match .equipment_title height
      watch: 'window'
      });

    $(".equipment_title").each(function(){
      $(this).trigger("isTruncated", function( isTruncated ) {
        if ( isTruncated ) {
          $(this).children(".equipment_title_link").tooltip();
        }
      });
    });
  };

$(document).ready(function() {
// For DataTables and Bootstrap
  $('.datatable').dataTable({
    "sDom": "<'row'<'span4'l><'span5'f>r>t<'row'<'span3'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "sScrollX": "100%",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  $('.datatable-wide').dataTable({
    "sDom": "<'row'<'span5'l><'span7'f>r>t<'row'<'span5'i><'span7'p>>",
    "sPaginationType": "bootstrap",
    "sScrollX": "100%",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  $('.history_table').dataTable({
    "sDom": "<'row'<l><f>r>t<'row'<'span3'i><p>>",
    "bLengthChange": false,
    "sPaginationType": "bootstrap",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  $('.report_table').dataTable({
    "sDom": "<'row'<'span3'l>fr>t<'row'<'span3'i><p>>",
    "sPaginationType": "bootstrap",
    "iDisplayLength" : 25,
    "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
    "aoColumnDefs": [{ "bSortable": false, "aTargets": [ "no_sort" ] }]
  });
// For fading out flash notices
  $(".alert .close").click( function() {
       $(this).parent().addClass("fade");
  });

// make the sidebar follow you down the page
  $("#sidebarbottom").sticky({topSpacing: 50, bottomSpacing: 200});

// perform truncate, which is also defined outside of document ready
// it needs to be both places due to a webkit bug not loading named
// JS functions in (document).ready() until AFTER displaying all the things
  $(".caption_cat").dotdotdot({
    height: 126,
    after: ".more_info",
    watch: 'window'
    });

  $(".equipment_title").dotdotdot({
    height: 54, // must match .equipment_title height
    watch: 'window'
  });

  $(".equipment_title").each(function(){
    $(this).trigger("isTruncated", function( isTruncated ) {
      if ( isTruncated ) {
        $(this).children(".equipment_title_link").tooltip();
      }
    });
  });

  $(".btn#modal").tooltip();
  $(".not-qualified-icon").tooltip();
  $(".not-qualified-icon-em").tooltip();

  // Equipment Model - show - progress bar

  $('.progress .bar').each(function() {
      var me = $(this);
      var perc = me.attr("data-percentage");
      var current_perc = 0;

      var progress = setInterval(function() {
          if (current_perc>=perc) {
              clearInterval(progress);
          } else {
              current_perc = perc;
              me.css('width', (current_perc)+'%');
          }
      }, 100);
  });

  $('.associated_em_box img').popover({ placement: 'bottom' });
  $("#my_reservations .dropdown-menu a").popover({ placement: 'bottom' });
  $("#my_equipment .dropdown-menu a").popover({ placement: 'bottom' });

  // fix sub nav on scroll
  var $win = $(window)
    , $nav = $('.subnav')
    , navTop = $('.subnav').length && $('.subnav').offset().top - 40
    , isFixed = 0
    , $hiddenName = $('.subnav .hide')

  processScroll()

  // hack sad times - holdover until rewrite for 2.1
  $nav.on('click', function () {
    if (!isFixed) setTimeout(function () {  $win.scrollTop($win.scrollTop() - 47) }, 10)
  })

  $win.on('scroll', processScroll)

  function processScroll() {
    var i, scrollTop = $win.scrollTop()
    if (scrollTop >= navTop && !isFixed) {
      isFixed = 1
      $nav.addClass('subnav-fixed')
      $hiddenName.removeClass('hide')
      if (!$('.subnav li').hasClass('active')) {
        $('.subnav li:eq(1)').addClass('active')
      }
    } else if (scrollTop <= navTop && isFixed) {
      isFixed = 0
      $nav.removeClass('subnav-fixed')
      $hiddenName.addClass('hide')
      $('.subnav li').removeClass('active')
    }
  }

  $('#modal').click(function() {
    $('#userModal div.modal-body').load(new_user, {from_cart : true }); // new_user defined in variables.js.erb
  });

  $('.date_start').datepicker({
    onClose: function(dateText, inst) {
      var start_date = $('.date_start').datepicker("getDate");
      var end_date = $('.date_end').datepicker("getDate");
      if (start_date > end_date){
        $('.date_end').datepicker("setDate", start_date)
      }
      $('.date_end').datepicker( "option" , "minDate" , start_date);
    }
  });

  // Select2 - fancy select lists
  $('#equipment_model_category_id').select2();
  $('#equipment_model_associated_equipment_model_ids').select2();
  $('#equipment_object_equipment_model_id').select2();
  $('#requirement_equipment_model_id').select2();

});
// to disable selection of dates in the past with datepicker
$.datepicker.setDefaults({
   minDate: new Date()
});

// general submit on change class
$(document).on('change', '.autosubmitme', function() {
  $(this).parents('form:first').submit();
});

//$(document).on('change', '.autosubmitme2', function() {
//  $.ajax("update_dates");
//});

$(document).on('railsAutocomplete.select', '#fake_reserver_id', function(event, data){
    $("#reserver_id").val(data.item.id); // updating reserver_id here to make sure that it is done before it submits
    $(this).parents('form').submit();
});
<commit_msg>#164 modified jquery selectors to be more particular and efficient<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require jquery.sticky
//= require jquery.dotdotdot-1.5.1
//= require cocoon
//= require autocomplete-rails
//= require dataTables/jquery.dataTables
//= require dataTables_numhtml_sort.js
//= require dataTables_numhtml_detect.js
//= require dataTables/jquery.dataTables.bootstrap
//= require bootstrap
//= require variables.js
//= require select2
//= require_self

  function truncate() {
    $(".caption_cat").dotdotdot({
      height: 126,
      after: ".more_info",
      watch: 'window'
      });

    $(".equipment_title").dotdotdot({
      height: 54, // must match .equipment_title height
      watch: 'window'
      });

    $(".equipment_title").each(function(){
      $(this).trigger("isTruncated", function( isTruncated ) {
        if ( isTruncated ) {
          $(this).children(".equipment_title_link").tooltip();
        }
      });
    });
  };

$(document).ready(function() {
// For DataTables and Bootstrap
  $('.datatable').dataTable({
    "sDom": "<'row'<'span4'l><'span5'f>r>t<'row'<'span3'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "sScrollX": "100%",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  $('.datatable-wide').dataTable({
    "sDom": "<'row'<'span5'l><'span7'f>r>t<'row'<'span5'i><'span7'p>>",
    "sPaginationType": "bootstrap",
    "sScrollX": "100%",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  $('.history_table').dataTable({
    "sDom": "<'row'<l><f>r>t<'row'<'span3'i><p>>",
    "bLengthChange": false,
    "sPaginationType": "bootstrap",
    "aoColumnDefs": [
          { "bSortable": false, "aTargets": [ "no_sort" ] }
        ]
  });

  $('.report_table').dataTable({
    "sDom": "<'row'<'span3'l>fr>t<'row'<'span3'i><p>>",
    "sPaginationType": "bootstrap",
    "iDisplayLength" : 25,
    "aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
    "aoColumnDefs": [{ "bSortable": false, "aTargets": [ "no_sort" ] }]
  });
// For fading out flash notices
  $(".alert .close").click( function() {
       $(this).parent().addClass("fade");
  });

// make the sidebar follow you down the page
  $("#sidebarbottom").sticky({topSpacing: 50, bottomSpacing: 200});

// perform truncate, which is also defined outside of document ready
// it needs to be both places due to a webkit bug not loading named
// JS functions in (document).ready() until AFTER displaying all the things
  $(".caption_cat").dotdotdot({
    height: 126,
    after: ".more_info",
    watch: 'window'
    });

  $(".equipment_title").dotdotdot({
    height: 54, // must match .equipment_title height
    watch: 'window'
  });

  $(".equipment_title").each(function(){
    $(this).trigger("isTruncated", function( isTruncated ) {
      if ( isTruncated ) {
        $(this).children(".equipment_title_link").tooltip();
      }
    });
  });

  $(".btn#modal").tooltip();
  $(".not-qualified-icon").tooltip();
  $(".not-qualified-icon-em").tooltip();

  // Equipment Model - show - progress bar

  $('.progress .bar').each(function() {
      var me = $(this);
      var perc = me.attr("data-percentage");
      var current_perc = 0;

      var progress = setInterval(function() {
          if (current_perc>=perc) {
              clearInterval(progress);
          } else {
              current_perc = perc;
              me.css('width', (current_perc)+'%');
          }
      }, 100);
  });

  $('.associated_em_box img').popover({ placement: 'bottom' });
  $("#my_reservations .dropdown-menu a").popover({ placement: 'bottom' });
  $("#my_equipment .dropdown-menu a").popover({ placement: 'bottom' });

  // fix sub nav on scroll
  var $win = $(window)
    , $nav = $('.subnav')
    , navTop = $('.subnav').length && $('.subnav').offset().top - 40
    , isFixed = 0
    , $hiddenName = $('.subnav .hide')

  processScroll()

  // hack sad times - holdover until rewrite for 2.1
  $nav.on('click', function () {
    if (!isFixed) setTimeout(function () {  $win.scrollTop($win.scrollTop() - 47) }, 10)
  })

  $win.on('scroll', processScroll)

  function processScroll() {
    var i, scrollTop = $win.scrollTop()
    if (scrollTop >= navTop && !isFixed) {
      isFixed = 1
      $nav.addClass('subnav-fixed')
      $hiddenName.removeClass('hide')
      if (!$('.subnav li').hasClass('active')) {
        $('.subnav li:eq(1)').addClass('active')
      }
    } else if (scrollTop <= navTop && isFixed) {
      isFixed = 0
      $nav.removeClass('subnav-fixed')
      $hiddenName.addClass('hide')
      $('.subnav li').removeClass('active')
    }
  }

  $('#modal').click(function() {
    $('#userModal div.modal-body').load(new_user, {from_cart : true }); // new_user defined in variables.js.erb
  });

  $('.date_start').datepicker({
    onClose: function(dateText, inst) {
      var start_date = $('.date_start').datepicker("getDate");
      var end_date = $('.date_end').datepicker("getDate");
      if (start_date > end_date){
        $('.date_end').datepicker("setDate", start_date)
      }
      $('.date_end').datepicker( "option" , "minDate" , start_date);
    }
  });

  // Select2 - fancy select lists
  $('select#equipment_model_category_id').select2();
  $('select#equipment_model_associated_equipment_model_ids').select2();
  $('select#equipment_object_equipment_model_id').select2();
  $('select#requirement_equipment_model_id').select2();

});
// to disable selection of dates in the past with datepicker
$.datepicker.setDefaults({
   minDate: new Date()
});

// general submit on change class
$(document).on('change', '.autosubmitme', function() {
  $(this).parents('form:first').submit();
});

//$(document).on('change', '.autosubmitme2', function() {
//  $.ajax("update_dates");
//});

$(document).on('railsAutocomplete.select', '#fake_reserver_id', function(event, data){
    $("#reserver_id").val(data.item.id); // updating reserver_id here to make sure that it is done before it submits
    $(this).parents('form').submit();
});
<|endoftext|>


<commit_before>import Sprite from './sprite';

var druidRun = new Image();
druidRun.src = '/assets/run-cycle-test.png';

var bg_mountain = new Image();
bg_mountain.src = '/assets/bg-mountain.png';

var bg_hill = new Image();
bg_hill.src = '/assets/bg-hill.png';

//===== Clouds=====
var bg_cloud = new Image();
bg_cloud.src = '/assets/bg-clouds-transparent.png';

var bg_sky = new Image();
bg_sky.src = '/assets/bg-sky.png';

export default {

	DRUID_RUN: new Sprite(druidRun, 0, 0, 48, 48, 8),
    BG_MOUNTAIN: new Sprite(bg_mountain, 0, 0, 1536, 767, 1),
    BG_HILL: new Sprite(bg_hill, 0, 0, 1024, 306, 1),
    BG_CLOUD_00: new Sprite(bg_cloud, 0, 0, 216, 48, 1),
    BG_CLOUD_01: new Sprite(bg_cloud, 0, 48, 216, 64, 1),
    BG_CLOUD_02: new Sprite(bg_cloud, 216, 0, 286, 48, 1),
    BG_CLOUD_03: new Sprite(bg_cloud, 216, 48, 286, 64, 1),
    BG_CLOUD_04: new Sprite(bg_cloud, 0, 112, 502, 72, 1),
    BG_CLOUD_05: new Sprite(bg_cloud, 0, 184, 502, 72, 1),
    BG_SKY: new Sprite(bg_sky, 0, 0, 1, 1, 1)

};<commit_msg>Asset Update - Trees<commit_after>import Sprite from './sprite';

var druidRun = new Image();
druidRun.src = '/assets/run-cycle-test.png';

var bg_mountain = new Image();
bg_mountain.src = '/assets/bg-mountain.png';

var bg_hill = new Image();
bg_hill.src = '/assets/bg-hill.png';

//===== Clouds=====
var bg_cloud = new Image();
bg_cloud.src = '/assets/bg-clouds-transparent.png';

var bg_sky = new Image();
bg_sky.src = '/assets/bg-sky.png';

var bg_tree_01 = new Image();
bg_tree_01.src = '/assets/trees-01a.png';

export default {

	DRUID_RUN: new Sprite(druidRun, 0, 0, 48, 48, 8),
    BG_MOUNTAIN: new Sprite(bg_mountain, 0, 0, 1536, 767, 1),
    BG_HILL: new Sprite(bg_hill, 0, 0, 1024, 306, 1),
    BG_CLOUD_00: new Sprite(bg_cloud, 0, 0, 216, 48, 1),
    BG_CLOUD_01: new Sprite(bg_cloud, 0, 48, 216, 64, 1),
    BG_CLOUD_02: new Sprite(bg_cloud, 216, 0, 286, 48, 1),
    BG_CLOUD_03: new Sprite(bg_cloud, 216, 48, 286, 64, 1),
    BG_CLOUD_04: new Sprite(bg_cloud, 0, 112, 502, 72, 1),
    BG_CLOUD_05: new Sprite(bg_cloud, 0, 184, 502, 72, 1),
    BG_SKY: new Sprite(bg_sky, 0, 0, 1, 1, 1)

    //Trees
    BG_TREE_01A: new Sprite(bg_tree_01, 0, 0, 256, 384, 1),
    BG_TREE_01B: new Sprite(bg_tree_01, 256, 0, 256, 384, 1),
    BG_TREE_01C: new Sprite(bg_tree_01, 512, 0, 256, 384, 1),
    BG_TREE_01D: new Sprite(bg_tree_01, 768, 0, 256, 384, 1),
    BG_TREE_01E: new Sprite(bg_tree_01, 0, 384, 256, 384, 1),
    BG_TREE_01F: new Sprite(bg_tree_01, 256, 384, 256, 384, 1),
    BG_TREE_01G: new Sprite(bg_tree_01, 512, 384, 256, 384, 1),
    BG_TREE_01H: new Sprite(bg_tree_01, 768, 384, 256, 384, 1),

};<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require underscore/underscore
//= require angular/angular
//= require angular-route/angular-route
//= require angular-utils-disqus/dirDisqus
//= require angular-bootstrap/ui-bootstrap
//= require angucomplete/angucomplete
//= require_tree .
<commit_msg>Adding angucomplete dependency for heroku<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require underscore/underscore
//= require angular/angular
//= require angular-route/angular-route
//= require angular-utils-disqus/dirDisqus
//= require angular-bootstrap/ui-bootstrap
//= require angucomplete
//= require_tree .
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
<commit_msg>removing gd turbolinks<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.

//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require jqplot.1.0.0b2_r792
//= require lib/jqplot.pieRenderer.min
//= require lib/jquery.tokeninput
//= require lib/jquery.mousewheel
//= require lib/jquery.placeholder
//= require scrollTo
//= require rails.validations
//= require rails.validations.simple_form
//= require underscore
//= require backbone
//= require backbone_rails_sync
//= require backbone_datalink
//= require backbone/loomio
//= require modernizr
//= require bootstrap
//= require bootstrap-custom
//= require main
//= require groups
//= require discussions
//= require motions
//= require users
//= require notifications
//= require dashboard
//= require votes
//= require jquery.atwho
//= require pop-over
<commit_msg>Add excanvas to application.js<commit_after>// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.

//= require lib/excanvas
//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require jqplot.1.0.0b2_r792
//= require lib/jqplot.pieRenderer.min
//= require lib/jquery.tokeninput
//= require lib/jquery.mousewheel
//= require lib/jquery.placeholder
//= require scrollTo
//= require rails.validations
//= require rails.validations.simple_form
//= require underscore
//= require backbone
//= require backbone_rails_sync
//= require backbone_datalink
//= require backbone/loomio
//= require modernizr
//= require bootstrap
//= require bootstrap-custom
//= require main
//= require groups
//= require discussions
//= require motions
//= require users
//= require notifications
//= require dashboard
//= require votes
//= require jquery.atwho
//= require pop-over
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery2
//= require jquery_ujs
//= require jquery-ui/autocomplete
//= require markdown/bootstrap-markdown.js
//= require markdown/bootstrap-markdown.de.js
//= require init.js
//= require_tree .

/* global cforum, MathJax */

function hasLocalstorage() {
  try {
    return 'localStorage' in window && window['localStorage'] !== null;
  }
  catch (e) {
    return false;
  }
}

function t(key, deflt) {
  var pieces = key.split('.');
  var loc = cforum.l10n;

  for(var i = 0; i < pieces.length; ++i) {
    if(loc[pieces[i]]) {
      loc = loc[pieces[i]];
    }
    else {
      if(deflt) {
        return deflt;
      }

      return "translation missing: " + key;
    }
  }

  return loc;
}

function setDismissHandlers() {
  $("[data-dismiss]").click(function() {
    var $this = $(this);
    var clss = $this.attr('data-dismiss');

    var elem = $this.closest("." + clss);
    elem.fadeOut('fast', function() { $(this).remove(); });
  });

  $("[data-dismiss]").each(function() {
    var $this = $(this);
    var clss = $this.attr('data-dismiss');

    $this.closest("." + clss).on('click', function() {
      $(this).fadeOut('fast', function() { $(this).remove(); });
    });
  });
}

function autohideAlerts() {
  window.setTimeout(function() {
    $(".cf-success").fadeOut('fast', function() { $(this).remove(); });
  }, 3000);
}

$(function() {
  setDismissHandlers();
  $(".select2").select2({minimumResultsForSearch: -1});
  $("form").dependentQuestions();

  $("#forum-list select").on('change', function() {
    if($(this).val() != "") {
      $("#forum-list").submit();
    }
  });

  autohideAlerts();
  $("textarea").tabEnable();
});

cforum.alert = {
  alert: function(text, type) {
    var alrt = $("
<button type=\"button\" class=\"close\" data-dismiss=\"cf-alert\" aria-label=\"Close\">×</button>
");
    alrt.text(text);
    $("#alerts-container").append(alrt);
    setDismissHandlers();

    window.setTimeout(function () { alrt.fadeOut('fast', function() { $(this).remove(); }); }, 3000);
  },

  error: function(text) {
    cforum.alert.alert(text, 'cf-error');
  },

  success: function(text) {
    cforum.alert.alert(text, 'cf-success');
  }
};

MathJax.Hub.Config({
  displayAlign: "left",
  menuSettings: { CHTMLpreview: false },
  tex2jax: {
    inlineMath: [],
    displayMath: []
  }
});

// eof
<commit_msg>fix: remove legacy code<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery2
//= require jquery_ujs
//= require jquery-ui/autocomplete
//= require markdown/bootstrap-markdown.js
//= require markdown/bootstrap-markdown.de.js
//= require init.js
//= require_tree .

/* global cforum, MathJax */

function hasLocalstorage() {
  try {
    return 'localStorage' in window && window['localStorage'] !== null;
  }
  catch (e) {
    return false;
  }
}

function t(key, deflt) {
  var pieces = key.split('.');
  var loc = cforum.l10n;

  for(var i = 0; i < pieces.length; ++i) {
    if(loc[pieces[i]]) {
      loc = loc[pieces[i]];
    }
    else {
      if(deflt) {
        return deflt;
      }

      return "translation missing: " + key;
    }
  }

  return loc;
}

function setDismissHandlers() {
  $("[data-dismiss]").click(function() {
    var $this = $(this);
    var clss = $this.attr('data-dismiss');

    var elem = $this.closest("." + clss);
    elem.fadeOut('fast', function() { $(this).remove(); });
  });

  $("[data-dismiss]").each(function() {
    var $this = $(this);
    var clss = $this.attr('data-dismiss');

    $this.closest("." + clss).on('click', function() {
      $(this).fadeOut('fast', function() { $(this).remove(); });
    });
  });
}

function autohideAlerts() {
  window.setTimeout(function() {
    $(".cf-success").fadeOut('fast', function() { $(this).remove(); });
  }, 3000);
}

$(function() {
  setDismissHandlers();
  $(".select2").select2({minimumResultsForSearch: -1});
  $("form").dependentQuestions();

  $("#forum-list select").on('change', function() {
    if($(this).val() != "") {
      $("#forum-list").submit();
    }
  });

  autohideAlerts();
  $("textarea").tabEnable();
});

cforum.alert = {
  alert: function(text, type) {
    var alrt = $("
<button type=\"button\" class=\"close\" data-dismiss=\"cf-alert\" aria-label=\"Close\">×</button>
");
    alrt.text(text);
    $("#alerts-container").append(alrt);
    setDismissHandlers();

    window.setTimeout(function () { alrt.fadeOut('fast', function() { $(this).remove(); }); }, 3000);
  },

  error: function(text) {
    cforum.alert.alert(text, 'cf-error');
  },

  success: function(text) {
    cforum.alert.alert(text, 'cf-success');
  }
};

// eof
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require cocoon
//= require underscore
//= require_tree .
$("input[data-role='invitation_name']").autocomplete({
  minLength: 3,
  appendTo: '.invitation-autocomplete-suggestions',
  select: function(event, ui) {
    var target = event.target;
    var yammerUserId = ui.item.yammerUserId;
    var $yammerUserIdField = $(target).closest('fieldset.inputs').find('[data-role="yammer_user_id"]');
    $yammerUserIdField.prop('value', yammerUserId);
  },
  source: function(request, response) {
    var term = request.term;
    YammerApi.setAccessToken(access_token);
    YammerApi.autocomplete.get(term, response);
  }
});
<commit_msg>removed the code duplication from application.js and yammer_autocomplete.js<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require cocoon
//= require underscore
//= require_tree .
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require lz-string

<commit_msg>Removing lz-string from application.js<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets

<|endoftext|>


<commit_before>/**
*
* jFuzz - DOM based particle system ( fuzzy phenomena )
* Date: 6/28/2011
* Author: Grant Wiant wiant@likegiant.com (grantwiant.com)
* Inspired by: @seb_ly #creativejs
* Requires: jQuery
*
*/
(function( $ ){
	$.fn.jFuzz = function( options ) {

		// default settings
		var settings = {
			'background': 'url(assets/images/spark32x32.png)',
			'border': false,
			'radius': false,
			'posX': 0,
			'posY': 0,
			'emitionRate': 1,
			'mouseX': 0,
			'mouseY': 0,
			'frameRate': 30,
			'maxParticles': 300,
			'particleWidth': 94,
			'particleHeight': 94,
			'prevMouseX': 0,
			'prevMouseY': 0,
			'gravity':-.3,
			'drag': 0.80,
			'shrink': 1.03,
			'randPos': false,
			'velocity': 10,
			'fadeOut': false,
			'rotate': false,
			'skew': false,
			'decay': .97,
			'velocityRange':false,
			'randomSkewRange': false,
			'randomSizeRange': false,
			'startOpacity': 1,
			'startScale': 1
		};

		// If options exist, lets merge them with our default settings
		if ( options ) {
			$.extend( settings, options );
		}

		// internal settings
		settings.emitters = [];

		// methods
		var methods = {
			loop: function(i) {

				// make Particles
				methods.makeParticles(i);

			  	// iteratate through each particle
				for (e=0; e<settings.emitters[i].particles.length; e++) {

					var particle = settings.emitters[i].particles[e];

					// render particles
					methods.render(i,particle);

					// update particles
					methods.update(i,particle);

					// Keep taking the oldest particles away until we have fewer than the maximum allowed.
					while(settings.emitters[i].particles.length>settings.maxParticles) {
						// remove particle
						particle = settings.emitters[i].particles.shift();
						// hide particle
						$("#"+particle.DOMid).hide();
						// make spare
						settings.emitters[i].spareParticles.push(particle);
					}
				}
			},
			update: function(i,particle) {
				// add gravity force to the y velocity
				particle.velY += particle.gravity;

				// shrink the particle
				if(particle.shrink!==0) {
					particle.scale *= particle.shrink;
					particle.scale = ( 0 | 100 * particle.scale ) / 100;
				}

				// add the velocity to the position
				particle.posX += particle.velX;
				if(settings.gravity<0) {
					particle.posY += ( particle.velY * particle.gravity );
				} else {
					particle.posY += particle.velY;
				}

				// opacity
				if(settings.fadeOut===true) {
					particle.opacity *= settings.decay;
					particle.opacity = ( 0 | 100 * particle.opacity ) / 100;
				} else {
					particle.opacity = 1;
				}

				// binary shift faster than Math.round()
				particle.posX = ( 0.5 + particle.posX >> 0 );
				particle.posY = ( 0.5 + particle.posY >> 0 );
			},
			render: function(i,particle) {
				var transStr;
				if( $.browser.chrome || $.browser.safari ) {
                    // set CSS3 transform string
    			 	transStr = "translate3d("+particle.posX+"px, "+particle.posY+"px, 0) scale3d("+particle.scale+", "+particle.scale+", 0)";
                } else if( $.browser.opera ) {
                    // set CSS3 transform string
    			 	transStr = "translate("+particle.posX+"px, "+particle.posY+"px) scale("+particle.scale+")";
                } else if( $.browser.msie ) {
                    // set CSS3 transform string
    			 	transStr = "translate("+particle.posX+"px, "+particle.posY+"px) scale("+particle.scale+")";
                } else if( $.browser.mozilla ) {
                    // set CSS3 transform string
    			 	transStr = "translate("+particle.posX+"px, "+particle.posY+"px) scale("+particle.scale+")";
                }

			 	// update DOM element with cross-browser CSS3 transform
				particle.$particle.css({'-webkit-transform': transStr, '-moz-transform': transStr, '-ms-transform': transStr, '-o-transform': transStr, transform: transStr, opacity: particle.opacity, display:'block'});
			},
			makeParticles: function(i) {
				// generate particles for this(i) emitter
				for(e=0;e<settings.emitionRate;e++) {

					// create a new particle in the stage
					if(settings.emitters[i].spareParticles.length>0) {
						// if one is already in the spare array, recycle it
						particle = settings.emitters[i].spareParticles.pop();

						// reset particle values
						particle.recycled = true;

					} else {
						// otherwise make a new particle
						// set particle DOM id
						var id = 'emitter'+i+'particle'+e, cssStr;

						// set default particle settings
						var particle = {
							id: e,
							DOMid: id,
							scale: 1,
							radius: settings.radius,
							border: settings.border,
							background: settings.background,
							recycled: false,
							width: settings.particleWidth,
							height: settings.particleHeight,
							halfWidth: ( 0.5 + ( settings.particleWidth / 2 ) >> 0 ),
							halfHeight: ( 0.5 + ( settings.particleHeight / 2 ) >> 0 ),
							rotate: 0,
						};

						cssStr = 'position:absolute; width:'+particle.width+'; height: '+particle.height+';';

						// if radius
						if(particle.radius) {
							cssStr += ' -webkit-border-radius:'+particle.radius+';';
						}

						// if border
						if(particle.border) {
							cssStr += ' border:'+particle.border+';';
						}

						// if background
						if(particle.background) {
							cssStr += ' background:'+particle.background+';';
						}

						// build particle DOM element
						particle.$particle = $('
');

						// inject this emitters particles
						$("#emitter"+i+"particles").append(particle.$particle);
					}

					// update emitter data
					var emitterOffset = settings.emitters[i].$emitter.offset();
					settings.emitters[i].left = ( emitterOffset.left - settings.emitters[i].parentLeft );
					settings.emitters[i].top = ( emitterOffset.top - settings.emitters[i].parentTop );
					//settings.emitters[i].height = height;
					//settings.emitters[i].width = width;
					//settings.emitters[i].halfHeight = (height / 2);
					//settings.emitters[i].halfWidth = (width / 2);

					// update particle
					particle.opacity = settings.startOpacity;
					particle.shrink = settings.shrink;
					particle.drag = settings.drag;
					particle.gravity = settings.gravity;
					particle.scale = settings.startScale;
					if(settings.randPos) {
						particle.randPosRange = [
							methods.randomRange(
								( settings.emitters[i].left ),
								( settings.emitters[i].left + ( settings.emitters[i].width - particle.width ) )
							),
							methods.randomRange(
								( settings.emitters[i].top ),
								( settings.emitters[i].top + ( settings.emitters[i].height - particle.height ) )
							)
						];
					} else {
						particle.randPosRange = [settings.emitters[i].left,settings.emitters[i].top];
					}
					if(settings.velocityRange) {
						particle.randVelRange = methods.randomRange(settings.velocityRange[0],settings.velocityRange[1]);
					}
					particle.posX = particle.randPosRange[0];
					particle.posY = particle.randPosRange[1];

					// ensure circular distribution of particles, for a more natural appearance
					particle.angle = ( Math.random() * Math.PI * 2 );
					particle.speed = Math.random() * particle.randVelRange;
					particle.velX = Math.sin(particle.angle) * particle.speed;
					particle.velY = Math.cos(particle.angle) * particle.speed;

					// add particle to this emitters particle collection
					settings.emitters[i].particles.push(particle);

				}
			},
			randomRange: function(min, max) {
				// return random range
				return ((Math.random()*(max-min)) + min);
			},
			init : function(i) {

				settings.userAgent = navigator.userAgent.toLowerCase();
                // Which browser?
                $.browser = {
                	version: (settings.userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
                	chrome: /chrome/.test( settings.userAgent ),
                	safari: /webkit/.test( settings.userAgent ) && !/chrome/.test( settings.userAgent ),
                	opera: /opera/.test( settings.userAgent ),
                	msie: /msie/.test( settings.userAgent ) && !/opera/.test( settings.userAgent ),
                	mozilla: /mozilla/.test( settings.userAgent ) && !/(compatible|webkit)/.test( settings.userAgent )
                };

				// inject current(i) emitters particle container
				settings.emitters[i].$emitter.after('

');

				settings.emitters[i].loop = setInterval(function(){ methods.loop(i) }, 1000 / settings.frameRate);
			}
		};

		return this.each(function( i, item ) {
			// get emitter object
			var emitterOffset = $(item).offset(), width = $(item).width(), height = $(item).height();
			var parentOffset = $(item).parent().offset();
			var emitter = { $emitter: $("#"+$(item).attr('id')), particles: [], width: width, height: height, halfHeight: (height / 2), halfWidth: (width / 2), top: emitterOffset.top, left: emitterOffset.left, parentLeft: parentOffset.left, parentTop: parentOffset.top, spareParticles: [] };
			// add emitter to emitters container
			settings.emitters.push(emitter);
			// initialize this emitter
			methods.init(i);
		});
	};
})( jQuery );<commit_msg>simplifying and optimizing -- using typed arrays, removing dom queries, using arrays instead of strings concats<commit_after>/**
*
* jFuzz - DOM based particle system ( fuzzy phenomena )
* Date: 6/28/2011
* Author: Grant Wiant wiant@likegiant.com (grantwiant.com)
* Inspired by: @seb_ly #creativejs
* Requires: jQuery
*
*/
(function ( $ ){
	$.fn.jFuzz = function ( options ) {

		String.prototype.format = function () {
		  var args = arguments;
		  return this.replace(/{(\d+)}/g, function (match, number) {
			  return typeof args[number] != 'undefined' ? (args[number] == null ? "": args[number]): match;
		  });
		};

		// default settings
		var settings = {
			'background': 'url(assets/images/spark32x32.png)',
			'posX': 0,
			'posY': 0,
			'emitionRate': 1,
			'mouseX': 0,
			'mouseY': 0,
			'frameRate': 30,
			'maxParticles': 300,
			'particleWidth': 94,
			'particleHeight': 94,
			'prevMouseX': 0,
			'prevMouseY': 0,
			'gravity':-.3,
			'drag': 0.80,
			'shrink': 1.03,
			'randPos': false,
			'velocity': 10,
			'fadeOut': true,
			'rotate': false,
			'skew': false,
			'decay': .97,
			'velocityRange':false,
			'randomSkewRange': false,
			'randomSizeRange': false,
			'startOpacity': 1,
			'startScale': 1,
			'isLittleEndian': true
		};

		var templates = {
			cssHeight: 'height: {0}px;',
			cssWidth: 'width: {0}px;',
			cssBackground: 'background: url({0});',
			cssTranslate3d: "translate3d({0}px, {1}px, 0)",
			cssTranslate: "translate({0}px, {1}px)",
			cssScale3d: "scale3d({0}, {1}, {2})",
			cssScale: "scale3d({0}, {1})",
			htmlParticle: '
'
		};

		// If options exist, lets merge them with our default settings
		if ( options ) {
			$.extend( settings, options );
		}

		// internal settings
		settings.emitters = [];

		// define array buffer by max particle count
		settings.arrayBuffer = new ArrayBuffer(settings.maxParticles);

		// test for Endianness
		/*
		if (settings.arrayBuffer[4] === 0x0a && settings.arrayBuffer[5] === 0x0b && settings.arrayBuffer[6] === 0x0c && settings.arrayBuffer[7] === 0x0d) {
	        settings.isLittleEndian = false;
	    }
	    */

		// methods
		var methods = {
			loop: function (thisEmitter) {

				// make Particles if needed
				if (thisEmitter.particles.length<settings.maxParticles) {
					methods.makeParticles(thisEmitter);
				}

			  	// iteratate through each particle
				for (p=0; p<thisEmitter.particles.length; p++) {

					var particle = thisEmitter.particles[p];

					if (thisEmitter.scaleArray[p]>0) {

						// render particles
						methods.render(thisEmitter, particle, p);

						// update particles
						methods.update(thisEmitter, particle, p);

					} else {
						methods.recycle(thisEmitter, particle);
					}

				}
			},
			update: function (thisEmitter, particle, p) {

				// add gravity force to the y velocity
				thisEmitter.velYArray[p] += particle.gravity;

				// shrink the particle
				if(particle.shrink!==0) {
					thisEmitter.scaleArray[p] = ( 0 | 100 * (thisEmitter.scaleArray[p] *= particle.shrink) ) / 100;
				}

				// add the velocity to the position
				thisEmitter.posXArray[p] += thisEmitter.velXArray[p];

				if(settings.gravity<0) {
					thisEmitter.posYArray[p] += ( thisEmitter.velYArray[p] * particle.gravity );
				} else {
					thisEmitter.posYArray[p] += thisEmitter.velYArray[p];
				}

				// update opacity if true with decay
				if(settings.fadeOut===true) {
					thisEmitter.opacityArray[p] = ( 0 | 100 * ( thisEmitter.opacityArray[p] *= settings.decay ) ) / 100;
				} else {
					thisEmitter.opacityArray[p] = 1;
				}

			},
			recycle: function (thisEmitter, particle) {
				//console.log('recycling', particle);
				thisEmitter.scaleArray[particle.id] = settings.startScale;
				thisEmitter.angleArray[particle.id] = ( Math.random() * Math.PI * 2 );
				thisEmitter.speedArray[particle.id] = Math.random() * particle.randVelRange;
				thisEmitter.velXArray[particle.id] = Math.sin(thisEmitter.angleArray[particle.id]) * thisEmitter.speedArray[particle.id];
				thisEmitter.velYArray[particle.id] = Math.cos(thisEmitter.angleArray[particle.id]) * thisEmitter.speedArray[particle.id];
				thisEmitter.posXArray[particle.id] = particle.randPosRange[0];
				thisEmitter.posYArray[particle.id] = particle.randPosRange[1];
				thisEmitter.opacityArray[p] = 1;
			},
			render: function (thisEmitter, particle, p) {

				var transformArray = [], transStr = "";

				if( $.browser.chrome || $.browser.safari ) {

                    // set position/scale
    			 	transformArray.push(templates.cssTranslate3d.format(thisEmitter.posXArray[p], thisEmitter.posYArray[p], 0));
    			 	transformArray.push(templates.cssScale3d.format(thisEmitter.scaleArray[p], thisEmitter.scaleArray[p], 0));

                } else if( $.browser.opera ) {

                    // set position/scale
    			 	transformArray.push(templates.cssTranslate.format(thisEmitter.posXArray[p], thisEmitter.posYArray[p]));
    			 	transformArray.push(templates.cssScale.format(thisEmitter.scaleArray[p], thisEmitter.scaleArray[p]));

                } else if( $.browser.msie ) {

                    // set position/scale
    			 	transformArray.push(templates.cssTranslate.format(thisEmitter.posXArray[p], thisEmitter.posYArray[p]));
    			 	transformArray.push(templates.cssScale.format(thisEmitter.scaleArray[p], thisEmitter.scaleArray[p]));

                } else if( $.browser.mozilla ) {

                    // set position/scale
    			 	transformArray.push(templates.cssTranslate.format(thisEmitter.posXArray[p], thisEmitter.posYArray[p]));
    			 	transformArray.push(templates.cssScale.format(thisEmitter.scaleArray[p], thisEmitter.scaleArray[p]));

                }

                transStr += transformArray.join('');

			 	// update DOM element with cross-browser CSS3 transform
				particle.$particle.css({'-webkit-transform': transStr, '-moz-transform': transStr, '-ms-transform': transStr, '-o-transform': transStr, transform: transStr, opacity: particle.opacity, display:'block'});
			},
			makeParticles: function (thisEmitter) {

				// generate particles for this(i) emitter
				for(e=0; e<settings.emitionRate; e++) {

					// create a new particle in the stage
					var cssArray = [];

					// set default particle settings
					var particle = {
						id: thisEmitter.particles.length,
						DOMid: 'p'+thisEmitter.particles.length,
						scale: 1,
						background: settings.background,
						recycled: false,
						rotate: 0
					};

					thisEmitter.widthArray[thisEmitter.particles.length] = settings.particleWidth;
					thisEmitter.heightArray[thisEmitter.particles.length] = settings.particleHeight;

					cssArray.push('position:absolute;');
					cssArray.push(templates.cssWidth.format(thisEmitter.widthArray[thisEmitter.particles.length]));
					cssArray.push(templates.cssHeight.format(thisEmitter.heightArray[thisEmitter.particles.length]));

					// if background
					if(particle.background) {
						cssArray.push(templates.cssBackground.format(particle.background));
					}

					// build particle DOM element
					particle.$particle = $(templates.htmlParticle.format(particle.DOMid, cssArray.join('')));

					// inject this particle
					thisEmitter.$emitter.append(particle.$particle);

					// update emitter data
					var emitterOffset = thisEmitter.$emitter.offset();
					thisEmitter.left = thisEmitter.parentLeft;
					thisEmitter.top = thisEmitter.parentTop;

					// update particle
					particle.opacity = settings.startOpacity;
					particle.shrink = settings.shrink;
					particle.drag = settings.drag;
					particle.gravity = settings.gravity;
					particle.scale = settings.startScale;

					// if random position is set
					if(settings.randPos) {
						particle.randPosRange = [
							methods.randomRange(
								thisEmitter.left,
								( thisEmitter.left + ( thisEmitter.width - thisEmitter.widthArray[thisEmitter.particles.length] ) )
							),
							methods.randomRange(
								thisEmitter.top,
								( thisEmitter.top + ( thisEmitter.height - thisEmitter.heightArray[thisEmitter.particles.length] ) )
							)
						];
					} else {
						particle.randPosRange = [thisEmitter.left,thisEmitter.top];
					}

					if(settings.velocityRange) {
						particle.randVelRange = methods.randomRange(settings.velocityRange[0],settings.velocityRange[1]);
					}

					// ensure circular distribution of particles, for a more natural appearance
					thisEmitter.angleArray[thisEmitter.particles.length] = ( Math.random() * Math.PI * 2 );
					thisEmitter.speedArray[thisEmitter.particles.length] = Math.random() * particle.randVelRange;
					thisEmitter.velXArray[thisEmitter.particles.length] = Math.sin(thisEmitter.angleArray[thisEmitter.particles.length]) * thisEmitter.speedArray[thisEmitter.particles.length];
					thisEmitter.velYArray[thisEmitter.particles.length] = Math.cos(thisEmitter.angleArray[thisEmitter.particles.length]) * thisEmitter.speedArray[thisEmitter.particles.length];
					thisEmitter.posXArray[thisEmitter.particles.length] = particle.randPosRange[0];
					thisEmitter.posYArray[thisEmitter.particles.length] = particle.randPosRange[1];
					thisEmitter.scaleArray[thisEmitter.particles.length] = particle.scale;

					// add particle to this emitters particle collection
					thisEmitter.particles.push(particle);

				}
			},
			randomRange: function (min, max) {

				// return random range
				return ((Math.random()*(max-min)) + min);

			},
			init : function (i) {

				var thisEmitter = settings.emitters[i];

				settings.userAgent = navigator.userAgent.toLowerCase();

                // Which browser?
                $.browser = {
                	version: (settings.userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
                	chrome: /chrome/.test( settings.userAgent ),
                	safari: /webkit/.test( settings.userAgent ) && !/chrome/.test( settings.userAgent ),
                	opera: /opera/.test( settings.userAgent ),
                	msie: /msie/.test( settings.userAgent ) && !/opera/.test( settings.userAgent ),
                	mozilla: /mozilla/.test( settings.userAgent ) && !/(compatible|webkit)/.test( settings.userAgent )
                };

				// inject current(i) emitters particle container
				thisEmitter.$emitter.after('

');

				thisEmitter.loop = setInterval(function (){ methods.loop(thisEmitter) }, 1000 / settings.frameRate);

			}
		};

		return this.each(function ( i, item ) {

			// get emitter object
			var emitterOffset = $(item).offset(), width = $(item).width(), height = $(item).height();
			var parentOffset = $(item).parent().offset();
			var emitter = {
				$emitter: $("#"+$(item).attr('id')),
				particles: [],
				posXArray: new Float32Array(settings.arrayBuffer.byteLength),
				posYArray: new Float32Array(settings.arrayBuffer.byteLength),
				scaleArray: new Float32Array(settings.arrayBuffer.byteLength),
				opacityArray: new Float32Array(settings.arrayBuffer.byteLength),
				heightArray: new Float32Array(settings.arrayBuffer.byteLength),
				widthArray: new Float32Array(settings.arrayBuffer.byteLength),
				angleArray: new Float32Array(settings.arrayBuffer.byteLength),
				speedArray: new Float32Array(settings.arrayBuffer.byteLength),
				velXArray: new Float32Array(settings.arrayBuffer.byteLength),
				velYArray: new Float32Array(settings.arrayBuffer.byteLength),
				width: width,
				height: height,
				top: emitterOffset.top,
				left: emitterOffset.left,
				parentLeft: parentOffset.left,
				parentTop: parentOffset.top
			};

			// add emitter to emitters container
			settings.emitters.push(emitter);

			// initialize this emitter
			methods.init(i);

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


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree .

$(window).load(function() {

	var windowHeight = $(window).height();
	var windowHeightHalf = $(window).height()/2;
	var windowWidth = $(window).width();
	var windowWidthHalf = $(window).width() /2;
	var windowWidthDouble = $(window).width() *2;

	// Set  viewport
	$('.sign').css({height:windowHeight -50});
	$('.sign .title').css({paddingTop:windowHeightHalf -200});

	$('.search_button').click( function() {
    	$(' input#plate_search').focus();
	    $("#search").fadeIn(0, function(){
		    $("body").addClass("active");
		    $("#make").slideDown(220);
	    });
		if ( $( "body" ).is( ".active" ) ) {
	    	$(' input#plate_search').focus();
		}

	});
	$('.search_make').click( function() {
	    $(".search_make ul").slideToggle();
		$('html, body').animate({scrollTop: $(".search_make ul").offset().top}, 650);
	});

	$('.search_make').click( function() {
	    $("body").addClass("make-active");

	});

	$(' input#plate_search').focus(function() {
	    $(this).addClass("active");
	    $("body").addClass("active");
		$('html, body').animate({scrollTop: $('html, body').offset().top}, 650);
	});

	// $('input#plate_search').blur(function() {
	//     $(this).removeClass("active");
	//     $("body").removeClass("active");
	// });

	$('.make_button').click( function() {
	    $("#search").fadeIn(0, function(){

	    $(".search_make ul").slideDown(0, function(){
			$('html, body').animate({scrollTop: $(".search_make ul").offset().top}, 150);

		    $("#make").slideDown(220);
	    });
    });
	    $("body").addClass("active");
	    $("body").addClass("make-active");
	});
	$('.cancel').click( function() {
	    $("body").removeClass("active");
	    $("body.make-active").removeClass("make-active");
	    $("#make").delay(50).slideUp(220);
	});

});

$(window).resize(function() {
	var windowHeight = $(window).height();
	var windowHeightHalf = $(window).height()/2;
	var windowWidth = $(window).width();
	var windowWidthHalf = $(window).width() /2;
	var windowWidthDouble = $(window).width() *2;

	$('.sign').css({height:windowHeight -50});
	$('.sign .title').css({paddingTop:windowHeightHalf -200});
	$('.interior.clicked').animate({marginLeft:-windowWidth /2 -120}, 200);

})

<commit_msg>revised search UI<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree .

$(window).load(function() {

	var windowHeight = $(window).height();
	var windowHeightHalf = $(window).height()/2;
	var windowWidth = $(window).width();
	var windowWidthHalf = $(window).width() /2;
	var windowWidthDouble = $(window).width() *2;

	// Set  viewport
	$('.sign').css({height:windowHeight -50});
	$('.sign .title').css({paddingTop:windowHeightHalf -200});

	$('.search_button').click( function() {
    	$(' input#plate_search').focus();
	    $("#search").fadeIn(0, function(){
		    $("body").addClass("active");
		    $("#make").slideDown(220);
	    });
		if ( $( "body" ).is( ".active" ) ) {
	    	$(' input#plate_search').focus();
		}

	});
	$('.search_make').click( function() {
	    $(".search_make ul").slideToggle();
		$('html, body').animate({scrollTop: $(".search_make ul").offset().top}, 650);
	});

	$('.search_make').click( function() {
	    $("body").addClass("make-active");

	});

	$(' input#plate_search').focus(function() {
	    $(this).addClass("active");
	    $("body").addClass("active");
		$('html, body').animate({scrollTop: $('html, body').offset().top}, 650);
	});

	// $('input#plate_search').blur(function() {
	//     $(this).removeClass("active");
	//     $("body").removeClass("active");
	// });

	$('.make_button').click( function() {
		$('.interior').addClass("clicked");
		$('.interior').animate({marginLeft:-windowWidth /2 -120}, 200);
	});
	$('.cancel').click( function() {
	    $("body").removeClass("active");
	    $("body.make-active").removeClass("make-active");
	    $("#make").delay(50).slideUp(220);
	});

});

$(window).resize(function() {
	var windowHeight = $(window).height();
	var windowHeightHalf = $(window).height()/2;
	var windowWidth = $(window).width();
	var windowWidthHalf = $(window).width() /2;
	var windowWidthDouble = $(window).width() *2;

	$('.sign').css({height:windowHeight -50});
	$('.sign .title').css({paddingTop:windowHeightHalf -200});
	$('.interior.clicked').animate({marginLeft:-windowWidth /2 -120}, 200);

})

<|endoftext|>