<commit_before>var pendingQueries = []
var runningQueries = []
var maxQueries = 3

function runQuery(data, success, error) {
  data.run_id = uuid()
  var query = {
    data: data,
    success: success,
    error: error,
    run_id: data.run_id,
    data_source: data.data_source,
    canceled: false
  }
  pendingQueries.push(query)
  runNext()
  return query
}

function runNext() {
  if (runningQueries.length < maxQueries) {
    var query = pendingQueries.shift()
    if (query) {
      runningQueries.push(query)
      runQueryHelper(query)
      runNext()
    }
  }
}

function runQueryHelper(query) {
  var xhr = $.ajax({
    url: Routes.run_queries_path(),
    method: "POST",
    data: query.data,
    dataType: "html"
  }).done( function (d) {
    if (d[0] == "{") {
      var response = $.parseJSON(d)
      query.data.blazer = response
      setTimeout( function () {
        if (!query.canceled) {
          runQueryHelper(query)
        }
      }, 1000)
    } else {
      if (!query.canceled) {
        query.success(d)
      }
      queryComplete(query)
    }
  }).fail( function(jqXHR, textStatus, errorThrown) {
    if (!query.canceled) {
      var message = (typeof errorThrown === "string") ? errorThrown : errorThrown.message
      query.error(message)
    }
    queryComplete(query)
  })
  query.xhr = xhr
  return xhr
}

function queryComplete(query) {
  var index = runningQueries.indexOf(query)
  runningQueries.splice(index, 1)
  runNext()
}

function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8)
    return v.toString(16)
  })
}

function cancelAllQueries() {
  pendingQueries = []
  for (var i = 0; i < runningQueries.length; i++) {
    cancelQuery(runningQueries[i])
  }
}

$(window).unload(cancelAllQueries)

function cancelQuery(query) {
  query.canceled = true
  if (query.xhr) {
    query.xhr.abort()
  }

  // tell server
  var path = Routes.cancel_queries_path()
  var data = {run_id: query.run_id, data_source: query.data_source}
  if (navigator.sendBeacon) {
    navigator.sendBeacon(path, csrfProtect(data))
  } else {
    // TODO make sync
    $.post(path, data)
  }
}

function csrfProtect(payload) {
  var param = $("meta[name=csrf-param]").attr("content")
  var token = $("meta[name=csrf-token]").attr("content")
  if (param && token) payload[param] = token
  return new Blob([JSON.stringify(payload)], {type : "application/json; charset=utf-8"})
}
<commit_msg>Always show error message<commit_after>var pendingQueries = []
var runningQueries = []
var maxQueries = 3

function runQuery(data, success, error) {
  data.run_id = uuid()
  var query = {
    data: data,
    success: success,
    error: error,
    run_id: data.run_id,
    data_source: data.data_source,
    canceled: false
  }
  pendingQueries.push(query)
  runNext()
  return query
}

function runNext() {
  if (runningQueries.length < maxQueries) {
    var query = pendingQueries.shift()
    if (query) {
      runningQueries.push(query)
      runQueryHelper(query)
      runNext()
    }
  }
}

function runQueryHelper(query) {
  var xhr = $.ajax({
    url: Routes.run_queries_path(),
    method: "POST",
    data: query.data,
    dataType: "html"
  }).done( function (d) {
    if (d[0] == "{") {
      var response = $.parseJSON(d)
      query.data.blazer = response
      setTimeout( function () {
        if (!query.canceled) {
          runQueryHelper(query)
        }
      }, 1000)
    } else {
      if (!query.canceled) {
        query.success(d)
      }
      queryComplete(query)
    }
  }).fail( function(jqXHR, textStatus, errorThrown) {
    if (!query.canceled) {
      var message = (typeof errorThrown === "string") ? errorThrown : errorThrown.message
      if (!message) {
        message = "An error occurred"
      }
      query.error(message)
    }
    queryComplete(query)
  })
  query.xhr = xhr
  return xhr
}

function queryComplete(query) {
  var index = runningQueries.indexOf(query)
  runningQueries.splice(index, 1)
  runNext()
}

function uuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8)
    return v.toString(16)
  })
}

function cancelAllQueries() {
  pendingQueries = []
  for (var i = 0; i < runningQueries.length; i++) {
    cancelQuery(runningQueries[i])
  }
}

$(window).unload(cancelAllQueries)

function cancelQuery(query) {
  query.canceled = true
  if (query.xhr) {
    query.xhr.abort()
  }

  // tell server
  var path = Routes.cancel_queries_path()
  var data = {run_id: query.run_id, data_source: query.data_source}
  if (navigator.sendBeacon) {
    navigator.sendBeacon(path, csrfProtect(data))
  } else {
    // TODO make sync
    $.post(path, data)
  }
}

function csrfProtect(payload) {
  var param = $("meta[name=csrf-param]").attr("content")
  var token = $("meta[name=csrf-token]").attr("content")
  if (param && token) payload[param] = token
  return new Blob([JSON.stringify(payload)], {type : "application/json; charset=utf-8"})
}
<|endoftext|>


<commit_before>import Service, { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { isPresent } from '@ember/utils';

export default Service.extend({
  commonAjax: service(),
  serverVariables: service(),

  config: computed('apiHost', function(){
    const apiHost = this.get('apiHost');
    const url = apiHost + '/application/config';
    const commonAjax = this.get('commonAjax');
    return commonAjax.request(url);
  }),

  itemFromConfig(key){
    return this.get('config').then(config => {
      const obj = config.config;

      return key in obj?obj[key]:null;
    });
  },

  userSearchType: computed('config.userSearchType', function(){
    return this.itemFromConfig('userSearchType');
  }),

  authenticationType: computed('config.type', function(){
    return this.itemFromConfig('type');
  }),

  maxUploadSize: computed('config.maxUploadSize', function(){
    return this.itemFromConfig('maxUploadSize');
  }),

  apiVersion: computed('config.apiVersion', function(){
    return this.itemFromConfig('apiVersion');
  }),

  trackingEnabled: computed('config.trackingEnabled', function(){
    return this.itemFromConfig('trackingEnabled');
  }),

  trackingCode: computed('config.trackingCode', function(){
    return this.itemFromConfig('trackingCode');
  }),

  loginUrl: computed('config.loginUrl', function(){
    return this.itemFromConfig('loginUrl');
  }),

  casLoginUrl: computed('config.casLoginUrl', function(){
    return this.itemFromConfig('casLoginUrl');
  }),

  apiNameSpace: computed('serverVariables.apiNameSpace', function(){
    const serverVariables = this.get('serverVariables');
    const apiNameSpace = serverVariables.get('apiNameSpace');
    if (isPresent(apiNameSpace)) {
      //remove trailing slashes
      return apiNameSpace.replace(/\/+$/, "");
    }
    return '';
  }),

  apiHost: computed('serverVariables.apiHost', function(){
    const serverVariables = this.get('serverVariables');
    const apiHost = serverVariables.get('apiHost');
    if (isPresent(apiHost)) {
      //remove trailing slashes
      return apiHost.replace(/\/+$/, "");
    }
    return '';
  }),

  errorCaptureEnabled: computed('serverVariables.errorCaptureEnabled', function(){
    const serverVariables = this.get('serverVariables');
    const errorCaptureEnabled = serverVariables.get('errorCaptureEnabled');
    if (typeof errorCaptureEnabled === 'boolean') {
      return errorCaptureEnabled;
    }

    return errorCaptureEnabled === 'true';
  }),
});
<commit_msg>Add searchEnable to config service<commit_after>import Service, { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import { isPresent } from '@ember/utils';

export default Service.extend({
  commonAjax: service(),
  serverVariables: service(),

  config: computed('apiHost', function(){
    const apiHost = this.get('apiHost');
    const url = apiHost + '/application/config';
    const commonAjax = this.get('commonAjax');
    return commonAjax.request(url);
  }),

  itemFromConfig(key){
    return this.get('config').then(config => {
      const obj = config.config;

      return key in obj?obj[key]:null;
    });
  },

  userSearchType: computed('config.userSearchType', function(){
    return this.itemFromConfig('userSearchType');
  }),

  authenticationType: computed('config.type', function(){
    return this.itemFromConfig('type');
  }),

  maxUploadSize: computed('config.maxUploadSize', function(){
    return this.itemFromConfig('maxUploadSize');
  }),

  apiVersion: computed('config.apiVersion', function(){
    return this.itemFromConfig('apiVersion');
  }),

  trackingEnabled: computed('config.trackingEnabled', function(){
    return this.itemFromConfig('trackingEnabled');
  }),

  trackingCode: computed('config.trackingCode', function(){
    return this.itemFromConfig('trackingCode');
  }),

  loginUrl: computed('config.loginUrl', function(){
    return this.itemFromConfig('loginUrl');
  }),

  casLoginUrl: computed('config.casLoginUrl', function(){
    return this.itemFromConfig('casLoginUrl');
  }),

  apiNameSpace: computed('serverVariables.apiNameSpace', function(){
    const serverVariables = this.get('serverVariables');
    const apiNameSpace = serverVariables.get('apiNameSpace');
    if (isPresent(apiNameSpace)) {
      //remove trailing slashes
      return apiNameSpace.replace(/\/+$/, "");
    }
    return '';
  }),

  apiHost: computed('serverVariables.apiHost', function(){
    const serverVariables = this.get('serverVariables');
    const apiHost = serverVariables.get('apiHost');
    if (isPresent(apiHost)) {
      //remove trailing slashes
      return apiHost.replace(/\/+$/, "");
    }
    return '';
  }),

  errorCaptureEnabled: computed('serverVariables.errorCaptureEnabled', function(){
    const serverVariables = this.get('serverVariables');
    const errorCaptureEnabled = serverVariables.get('errorCaptureEnabled');
    if (typeof errorCaptureEnabled === 'boolean') {
      return errorCaptureEnabled;
    }

    return errorCaptureEnabled === 'true';
  }),

  searchEnabled: computed('config.searchEnabled', async function(){
    const searchEnabled = await this.itemFromConfig('searchEnabled');
    if (searchEnabled === null) {
      return false;
    }
    if (typeof searchEnabled === 'boolean') {
      return searchEnabled;
    }

    return searchEnabled === 'true';
  }),
});
<|endoftext|>


<commit_before>/*! Plugin options and other jQuery stuff */

// Responsive Nav
var navigation = responsiveNav("#site-nav", { // Selector: The ID of the wrapper
  animate: true, // Boolean: Use CSS3 transitions, true or false
  transition: 200, // Integer: Speed of the transition, in milliseconds
  label: " Menu", // String: Label for the navigation toggle
  insert: "before", // String: Insert the toggle before or after the navigation
  customToggle: "", // Selector: Specify the ID of a custom toggle
  openPos: "relative", // String: Position of the opened nav, relative or static
  jsClass: "js", // String: 'JS enabled' class which is added to  el
  init: function(){}, // Function: Init callback
  open: function(){}, // Function: Open callback
  close: function(){} // Function: Close callback
});

$('html').click(function() {
  //Hide the menus if visible
  if ($(navigation.wrapper).hasClass('opened')) {
  	navigation.toggle();
  }
});

$('#site-nav').click(function(event){
    event.stopPropagation();
});

// FitVids options
$(function() {
	$("article").fitVids();
});

// Add lightbox class to all image links
$("a[href$='.jpg'],a[href$='.jpeg'],a[href$='.JPG'],a[href$='.png'],a[href$='.gif']").addClass("image-popup");

// Magnific-Popup options
$(document).ready(function() {
  $('.image-popup').magnificPopup({
    type: 'image',
    tLoading: 'Loading image #%curr%...',
    gallery: {
      enabled: true,
      navigateByImgClick: true,
      preload: [0,1] // Will preload 0 - before current, and 1 after the current image
    },
    image: {
      tError: 'Image #%curr% could not be loaded.',
    },
    removalDelay: 300, // Delay in milliseconds before popup is removed
    // Class that is added to body when popup is open.
    // make it unique to apply your CSS animations just to this exact popup
    mainClass: 'mfp-fade'
  });
});

// Smooth Scrolling
$('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
        || location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
           if (target.length) {
             $('html,body').animate({
                 scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    }
});
<commit_msg>delete smooth scrolling<commit_after>/*! Plugin options and other jQuery stuff */

// Responsive Nav
var navigation = responsiveNav("#site-nav", { // Selector: The ID of the wrapper
  animate: true, // Boolean: Use CSS3 transitions, true or false
  transition: 200, // Integer: Speed of the transition, in milliseconds
  label: " Menu", // String: Label for the navigation toggle
  insert: "before", // String: Insert the toggle before or after the navigation
  customToggle: "", // Selector: Specify the ID of a custom toggle
  openPos: "relative", // String: Position of the opened nav, relative or static
  jsClass: "js", // String: 'JS enabled' class which is added to  el
  init: function(){}, // Function: Init callback
  open: function(){}, // Function: Open callback
  close: function(){} // Function: Close callback
});

$('html').click(function() {
  //Hide the menus if visible
  if ($(navigation.wrapper).hasClass('opened')) {
  	navigation.toggle();
  }
});

$('#site-nav').click(function(event){
    event.stopPropagation();
});

// FitVids options
$(function() {
	$("article").fitVids();
});

// Add lightbox class to all image links
$("a[href$='.jpg'],a[href$='.jpeg'],a[href$='.JPG'],a[href$='.png'],a[href$='.gif']").addClass("image-popup");

// Magnific-Popup options
$(document).ready(function() {
  $('.image-popup').magnificPopup({
    type: 'image',
    tLoading: 'Loading image #%curr%...',
    gallery: {
      enabled: true,
      navigateByImgClick: true,
      preload: [0,1] // Will preload 0 - before current, and 1 after the current image
    },
    image: {
      tError: 'Image #%curr% could not be loaded.',
    },
    removalDelay: 300, // Delay in milliseconds before popup is removed
    // Class that is added to body when popup is open.
    // make it unique to apply your CSS animations just to this exact popup
    mainClass: 'mfp-fade'
  });
});
<|endoftext|>


<commit_before>/* global io */
import Ember from 'ember';
import WithLoggerMixin from '../mixins/with-logger';

var computed = Ember.computed;
var run = Ember.run;
var bind = run.bind;
var next = run.next;
var later = run.later;
var EmberString = Ember.String;
var fmt = EmberString.fmt;

/**
 * Shortcut to know if an object is alive or not
 *
 * @since 0.0.4
 * @param {Ember.Object} obj The object to test
 * @returns {Boolean} Returns `true` if the object is still alive, else `false`
 * @private
 */
function isAlive(obj) {
  return !(!obj || obj.isDestroying || obj.isDestroyed);
}

/**
 * Layer on top of io.socket from Sails to play well with Ember
 *
 * @since 0.0.4
 * @class SailsSocketService
 * @extends Ember.Object
 * @uses Ember.Evented
 * @uses WithLoggerMixin
 * @constructor
 */
var SailsSocketService = Ember.Object.extend(Ember.Evented, WithLoggerMixin, {
  /**
   * Holds our sails socket
   * @since 0.0.4
   * @property _sailsSocket
   * @type SailsSocket
   * @private
   */
  _sailsSocket: null,

  /**
   * Holds the events we are listening on the socket for later re-binding
   * @since 0.0.4
   * @property _listeners
   * @type Object<Object>
   * @private
   */
  _listeners: null,

  /**
   * The URL to the sails socket
   * @since 0.0.13
   * @property socketUrl
   * @type String
   */
  socketUrl: computed(function () {
    var script = document.getElementById('eds-sails-io-script');
    return script.src.replace(/^([^:]+:\/\/[^\/]+).*$/g, '$1');
  }),

  /**
   * Whether the socket core object is initialized or not
   * @since 0.0.4
   * @property isInitialized
   * @type Boolean
   */
  isInitialized: null,

  /**
   * Whether the socket is connected or not
   * @since 0.0.4
   * @property isConnected
   * @type Boolean
   */
  isConnected: null,

  /**
   * The number of currently pending operations
   * @since 0.0.4
   * @property pendingOperationCount
   * @type Number
   */
  pendingOperationCount: null,

  /**
   * Whether the service is busy or not
   * @since 0.0.4
   * @property isBusy
   * @type Boolean
   */
  isBusy: computed('pendingOperationCount', 'isInitialized', function () {
    return !this.get('isInitialized') || this.get('pendingOperationCount') > 0;
  }),

  /**
   * @since 0.0.4
   * @method init
   * @inheritDoc
   */
  init: function () {
    this._super();
    this._listeners = {};
    this._sailsSocket = null;
    this.setProperties({
      pendingOperationCount: 0,
      isInitialized:         false,
      isConnected:           false
    });
  },

  /**
   * @since 0.0.4
   * @method destroy
   * @inheritDoc
   */
  destroy: function () {
    if (this.get('isConnected')) {
      this._sailsSocket.disconnect();
    }
    this._super();
  },

  /**
   * Enable/disable listening for a given socket event
   *
   * @since 0.0.4
   * @method listenFor
   * @param {String} event The event to start/stop listening for
   * @param {Boolean} [listen=true] If `true`, it'll listen for these events, else it'll stop listening
   * @return {Boolean} Returns `true` if the some change has been triggered or scheduled, else `false`
   */
  listenFor: function (event, listen) {
    var meta, sockMethod;
    listen = listen == null ? true : !!listen;
    if (listen && !this._listeners[event]) {
      meta = {
        method:      bind(this, '_handleSocketMessage', event),
        isListening: false
      };
      this._listeners[event] = meta;
      sockMethod = 'add';
    }
    else if (!listen && (meta = this._listeners[event])) {
      sockMethod = 'remove';
    }
    if (sockMethod) {
      if (this.get('isConnected')) {
        if (listen) {
          meta.isListening = true;
        }
        else {
          delete this._listeners[event];
        }
        this._sailsSocket._raw[sockMethod + 'EventListener'](event, meta.method);
      }
      else if (!listen) {
        delete this._listeners[event];
      }
    }
    return !!sockMethod;
  },

  /**
   * Call a method on the socket object with the given parameters once the socket is ready and
   * connected. Returns a promise which will resolve to the result of the method call, assuming the
   * method is accepting as last parameter (which would not be given) a function to call once the
   * process is done (as a NodeJS callback).
   *
   * @since 0.0.11
   * @method request
   * @param {String} method The name of the method to call
   * @param {mixed} [arg]* Any argument to give to the method
   * @returns {Ember.RSVP.Promise}
   */
  request: function (method/*, arg*/) {
    var self = this,
      args = [].slice.call(arguments, 1),
      incPending = bind(this, 'incrementProperty', 'pendingOperationCount');
    method = method.toLowerCase();
    incPending(1);
    return new Ember.RSVP.Promise(function (resolve, reject) {
      self._connectedSocket(function (error, socket) {
        if (isAlive(self) && !error) {
          args.push(function (data, jwr) {
            incPending(-1);
            if (!jwr || Math.round(jwr.statusCode / 100) !== 2) {
              reject(jwr || data);
            }
            else {
              resolve(data);
            }
          });
          socket[method].apply(socket, args);
        }
        else {
          incPending(-1);
          reject(error ? error : new Ember.Error('Sails socket service destroyed'));
        }
      });
    }, fmt('getting the connected Sails socket for `%@` request on %@', method, args[0]));
  },

  /**
   * @since 0.0.4
   * @method trigger
   * @inheritDoc
   */
  trigger: function (event/*, arg*/) {
    this.debug(fmt('triggering event `%@`', event));
    return this._super.apply(this, arguments);
  },

  /**
   * Get the socket ready and connected and then pass it as parameter of the given callback
   *
   * @since 0.0.4
   * @method _connectedSocket
   * @param {Function} callback The method to call with the socket or the error
   * @private
   */
  _connectedSocket: function (callback) {
    if (!isAlive(this)) {
      this.warn('cannot get socket, service destroyed');
      next(this, callback, new Ember.Error('Sails socket service destroyed'));
    }
    else if (this.get('isConnected')) {
      this.debug('socket connected, giving it in next run loop');
      next(this, callback, null, this._sailsSocket);
    }
    else {
      this.info('socket not connected, listening for connect event before giving it');
      if(!this._waitingForSockets) {
        this._waitingForSockets = [];
      }
      this._waitingForSockets.push(callback);
      if(this._waitingForSockets.length > 1) {
        return;
      }
      this.one('didConnect', bind(this, function () {
        for(var i = 0; i < this._waitingForSockets.length; i++) {
          this._waitingForSockets[i].call(this, null, this._sailsSocket);
        }
      }));
      if (this.get('isInitialized')) {
        this.info('looks like we are initialized but not connected, reconnecting socket');
        this._reconnect();
      }
      else {
        this._load();
      }
    }
  },

  /**
   * Force the reconnection of the socket
   *
   * @since 0.0.4
   * @method _reconnect
   */
  _reconnect: function () {
    if (this._sailsSocket._raw && !this._sailsSocket._raw.connected && !this._sailsSocket._raw.connecting) {
      this._sailsSocket._raw.reconnect();
    }
  },

  /**
   * Bind event listeners that have been waiting to be attached
   *
   * @since 0.0.11
   * @method _bindListeners
   * @chainable
   * @private
   */
  _bindListeners: function () {
    var meta;
    for (var event in this._listeners) {
      if (!(meta = this._listeners[event]).isListening) {
        this._sailsSocket._raw.addEventListener(event, meta.method);
        meta.isListening = true;
        this.info(fmt('attached event `%@` on socket', event));
      }
    }
    return this;
  },

  /**
   * Unbind all listeners (does not remove them from the known listeners)
   *
   * @since 0.0.11
   * @method _unbindListeners
   * @chainable
   * @private
   */
  _unbindListeners: function () {
    var meta;
    for (var event in this._listeners) {
      if ((meta = this._listeners[event]).isListening) {
        this._sailsSocket._raw.removeEventListener(event, meta.method);
        meta.isListening = false;
        this.info(fmt('detached event `%@` from socket', event));
      }
    }
    return this;
  },

  /**
   * Handles a message received by the socket and dispatch our own event
   *
   * @since 0.0.4
   * @method _handleSocketMessage
   * @param {String} event The event name
   * @param {Object} message The message received
   * @private
   */
  _handleSocketMessage: function (event, message) {
    if (!isAlive(this)) {
      return;
    }
    this.trigger(event + (message && message.verb ? '.' + message.verb : ''), message);
  },

  /**
   * Handles the readiness of the socket, initializing listeners etc. once the `io.socket` is ready
   * The way how the `io.socket` is checked for readiness is a hack, since listening to `connect`
   * event was doing a lot of garbage listeners for each subsequent call to `on`. Maybe a bug in
   * `sails` socket code...
   *
   * @since 0.0.4
   * @method _handleSocketReady
   * @private
   */
  _handleSocketReady: function () {
    var waitObject;
    if (!isAlive(this)) {
      return;
    }
    this.info('socket core object ready');
    this.set('isInitialized', true);
    this.trigger('didInitialize');
    this._sailsSocket = io.sails.connect(this.get('socketUrl'));
    waitObject = bind(this, function () {
      if (this._sailsSocket._raw) {
        this._sailsSocket._raw.addEventListener('connect', bind(this, '_handleSocketConnect'));
        this._sailsSocket._raw.addEventListener('disconnect', bind(this, '_handleSocketDisconnect'));
        if (this._sailsSocket._raw.connected) {
          next(this, '_handleSocketConnect');
        }
      }
      else {
        later(waitObject, 10);
      }
    });
    waitObject();
  },

  /**
   * Handles the connected event of the socket
   *
   * @since 0.0.4
   * @method _handleSocketConnect
   * @private
   */
  _handleSocketConnect: function () {
    if (!isAlive(this)) {
      return;
    }
    this._bindListeners();
    this.set('isConnected', true);
    this.trigger('didConnect');
  },

  /**
   * Handles the disconnected event of the socket
   *
   * @since 0.0.4
   * @method _handleSocketDisconnect
   * @private
   */
  _handleSocketDisconnect: function () {
    if (!isAlive(this)) {
      return;
    }
    this.set('isConnected', false);
    this.trigger('didDisconnect');
    this._unbindListeners();
  },

  /**
   * Loads the sails.io.js script and wait for the connection and io object to be ready
   *
   * @since 0.0.13
   * @method _load
   * @private
   */
  _load: function () {
    if (!this._loaded) {
      if (window.io && io.sails && io.sails.emberDataSailsReady) {
        next(this, '_handleSocketReady');
      }
      else {
        later(this, '_load', 10);
      }
    }
  }
});

export default SailsSocketService;
<commit_msg>- Cleared mutex before completing callbacks<commit_after>/* global io */
import Ember from 'ember';
import WithLoggerMixin from '../mixins/with-logger';

var computed = Ember.computed;
var run = Ember.run;
var bind = run.bind;
var next = run.next;
var later = run.later;
var EmberString = Ember.String;
var fmt = EmberString.fmt;

/**
 * Shortcut to know if an object is alive or not
 *
 * @since 0.0.4
 * @param {Ember.Object} obj The object to test
 * @returns {Boolean} Returns `true` if the object is still alive, else `false`
 * @private
 */
function isAlive(obj) {
  return !(!obj || obj.isDestroying || obj.isDestroyed);
}

/**
 * Layer on top of io.socket from Sails to play well with Ember
 *
 * @since 0.0.4
 * @class SailsSocketService
 * @extends Ember.Object
 * @uses Ember.Evented
 * @uses WithLoggerMixin
 * @constructor
 */
var SailsSocketService = Ember.Object.extend(Ember.Evented, WithLoggerMixin, {
  /**
   * Holds our sails socket
   * @since 0.0.4
   * @property _sailsSocket
   * @type SailsSocket
   * @private
   */
  _sailsSocket: null,

  /**
   * Holds the events we are listening on the socket for later re-binding
   * @since 0.0.4
   * @property _listeners
   * @type Object<Object>
   * @private
   */
  _listeners: null,

  /**
   * The URL to the sails socket
   * @since 0.0.13
   * @property socketUrl
   * @type String
   */
  socketUrl: computed(function () {
    var script = document.getElementById('eds-sails-io-script');
    return script.src.replace(/^([^:]+:\/\/[^\/]+).*$/g, '$1');
  }),

  /**
   * Whether the socket core object is initialized or not
   * @since 0.0.4
   * @property isInitialized
   * @type Boolean
   */
  isInitialized: null,

  /**
   * Whether the socket is connected or not
   * @since 0.0.4
   * @property isConnected
   * @type Boolean
   */
  isConnected: null,

  /**
   * The number of currently pending operations
   * @since 0.0.4
   * @property pendingOperationCount
   * @type Number
   */
  pendingOperationCount: null,

  /**
   * Whether the service is busy or not
   * @since 0.0.4
   * @property isBusy
   * @type Boolean
   */
  isBusy: computed('pendingOperationCount', 'isInitialized', function () {
    return !this.get('isInitialized') || this.get('pendingOperationCount') > 0;
  }),

  /**
   * @since 0.0.4
   * @method init
   * @inheritDoc
   */
  init: function () {
    this._super();
    this._listeners = {};
    this._sailsSocket = null;
    this.setProperties({
      pendingOperationCount: 0,
      isInitialized:         false,
      isConnected:           false
    });
  },

  /**
   * @since 0.0.4
   * @method destroy
   * @inheritDoc
   */
  destroy: function () {
    if (this.get('isConnected')) {
      this._sailsSocket.disconnect();
    }
    this._super();
  },

  /**
   * Enable/disable listening for a given socket event
   *
   * @since 0.0.4
   * @method listenFor
   * @param {String} event The event to start/stop listening for
   * @param {Boolean} [listen=true] If `true`, it'll listen for these events, else it'll stop listening
   * @return {Boolean} Returns `true` if the some change has been triggered or scheduled, else `false`
   */
  listenFor: function (event, listen) {
    var meta, sockMethod;
    listen = listen == null ? true : !!listen;
    if (listen && !this._listeners[event]) {
      meta = {
        method:      bind(this, '_handleSocketMessage', event),
        isListening: false
      };
      this._listeners[event] = meta;
      sockMethod = 'add';
    }
    else if (!listen && (meta = this._listeners[event])) {
      sockMethod = 'remove';
    }
    if (sockMethod) {
      if (this.get('isConnected')) {
        if (listen) {
          meta.isListening = true;
        }
        else {
          delete this._listeners[event];
        }
        this._sailsSocket._raw[sockMethod + 'EventListener'](event, meta.method);
      }
      else if (!listen) {
        delete this._listeners[event];
      }
    }
    return !!sockMethod;
  },

  /**
   * Call a method on the socket object with the given parameters once the socket is ready and
   * connected. Returns a promise which will resolve to the result of the method call, assuming the
   * method is accepting as last parameter (which would not be given) a function to call once the
   * process is done (as a NodeJS callback).
   *
   * @since 0.0.11
   * @method request
   * @param {String} method The name of the method to call
   * @param {mixed} [arg]* Any argument to give to the method
   * @returns {Ember.RSVP.Promise}
   */
  request: function (method/*, arg*/) {
    var self = this,
      args = [].slice.call(arguments, 1),
      incPending = bind(this, 'incrementProperty', 'pendingOperationCount');
    method = method.toLowerCase();
    incPending(1);
    return new Ember.RSVP.Promise(function (resolve, reject) {
      self._connectedSocket(function (error, socket) {
        if (isAlive(self) && !error) {
          args.push(function (data, jwr) {
            incPending(-1);
            if (!jwr || Math.round(jwr.statusCode / 100) !== 2) {
              reject(jwr || data);
            }
            else {
              resolve(data);
            }
          });
          socket[method].apply(socket, args);
        }
        else {
          incPending(-1);
          reject(error ? error : new Ember.Error('Sails socket service destroyed'));
        }
      });
    }, fmt('getting the connected Sails socket for `%@` request on %@', method, args[0]));
  },

  /**
   * @since 0.0.4
   * @method trigger
   * @inheritDoc
   */
  trigger: function (event/*, arg*/) {
    this.debug(fmt('triggering event `%@`', event));
    return this._super.apply(this, arguments);
  },

  /**
   * Get the socket ready and connected and then pass it as parameter of the given callback
   *
   * @since 0.0.4
   * @method _connectedSocket
   * @param {Function} callback The method to call with the socket or the error
   * @private
   */
  _connectedSocket: function (callback) {
    if (!isAlive(this)) {
      this.warn('cannot get socket, service destroyed');
      next(this, callback, new Ember.Error('Sails socket service destroyed'));
    }
    else if (this.get('isConnected')) {
      this.debug('socket connected, giving it in next run loop');
      next(this, callback, null, this._sailsSocket);
    }
    else {
      this.info('socket not connected, listening for connect event before giving it');
      if(!this._waitingForSockets) {
        this._waitingForSockets = [];
      }
      this._waitingForSockets.push(callback);
      if(this._waitingForSockets.length > 1) {
        return;
      }
      this.one('didConnect', bind(this, function () {
        var callbacks = this._waitingForSockets;
        delete this._waitingForSockets;
        for(var i = 0; i < callbacks.length; i++) {
          callbacks[i].call(this, null, this._sailsSocket);
        }
      }));
      if (this.get('isInitialized')) {
        this.info('looks like we are initialized but not connected, reconnecting socket');
        this._reconnect();
      }
      else {
        this._load();
      }
    }
  },

  /**
   * Force the reconnection of the socket
   *
   * @since 0.0.4
   * @method _reconnect
   */
  _reconnect: function () {
    if (this._sailsSocket._raw && !this._sailsSocket._raw.connected && !this._sailsSocket._raw.connecting) {
      this._sailsSocket._raw.reconnect();
    }
  },

  /**
   * Bind event listeners that have been waiting to be attached
   *
   * @since 0.0.11
   * @method _bindListeners
   * @chainable
   * @private
   */
  _bindListeners: function () {
    var meta;
    for (var event in this._listeners) {
      if (!(meta = this._listeners[event]).isListening) {
        this._sailsSocket._raw.addEventListener(event, meta.method);
        meta.isListening = true;
        this.info(fmt('attached event `%@` on socket', event));
      }
    }
    return this;
  },

  /**
   * Unbind all listeners (does not remove them from the known listeners)
   *
   * @since 0.0.11
   * @method _unbindListeners
   * @chainable
   * @private
   */
  _unbindListeners: function () {
    var meta;
    for (var event in this._listeners) {
      if ((meta = this._listeners[event]).isListening) {
        this._sailsSocket._raw.removeEventListener(event, meta.method);
        meta.isListening = false;
        this.info(fmt('detached event `%@` from socket', event));
      }
    }
    return this;
  },

  /**
   * Handles a message received by the socket and dispatch our own event
   *
   * @since 0.0.4
   * @method _handleSocketMessage
   * @param {String} event The event name
   * @param {Object} message The message received
   * @private
   */
  _handleSocketMessage: function (event, message) {
    if (!isAlive(this)) {
      return;
    }
    this.trigger(event + (message && message.verb ? '.' + message.verb : ''), message);
  },

  /**
   * Handles the readiness of the socket, initializing listeners etc. once the `io.socket` is ready
   * The way how the `io.socket` is checked for readiness is a hack, since listening to `connect`
   * event was doing a lot of garbage listeners for each subsequent call to `on`. Maybe a bug in
   * `sails` socket code...
   *
   * @since 0.0.4
   * @method _handleSocketReady
   * @private
   */
  _handleSocketReady: function () {
    var waitObject;
    if (!isAlive(this)) {
      return;
    }
    this.info('socket core object ready');
    this.set('isInitialized', true);
    this.trigger('didInitialize');
    this._sailsSocket = io.sails.connect(this.get('socketUrl'));
    waitObject = bind(this, function () {
      if (this._sailsSocket._raw) {
        this._sailsSocket._raw.addEventListener('connect', bind(this, '_handleSocketConnect'));
        this._sailsSocket._raw.addEventListener('disconnect', bind(this, '_handleSocketDisconnect'));
        if (this._sailsSocket._raw.connected) {
          next(this, '_handleSocketConnect');
        }
      }
      else {
        later(waitObject, 10);
      }
    });
    waitObject();
  },

  /**
   * Handles the connected event of the socket
   *
   * @since 0.0.4
   * @method _handleSocketConnect
   * @private
   */
  _handleSocketConnect: function () {
    if (!isAlive(this)) {
      return;
    }
    this._bindListeners();
    this.set('isConnected', true);
    this.trigger('didConnect');
  },

  /**
   * Handles the disconnected event of the socket
   *
   * @since 0.0.4
   * @method _handleSocketDisconnect
   * @private
   */
  _handleSocketDisconnect: function () {
    if (!isAlive(this)) {
      return;
    }
    this.set('isConnected', false);
    this.trigger('didDisconnect');
    this._unbindListeners();
  },

  /**
   * Loads the sails.io.js script and wait for the connection and io object to be ready
   *
   * @since 0.0.13
   * @method _load
   * @private
   */
  _load: function () {
    if (!this._loaded) {
      if (window.io && io.sails && io.sails.emberDataSailsReady) {
        next(this, '_handleSocketReady');
      }
      else {
        later(this, '_load', 10);
      }
    }
  }
});

export default SailsSocketService;
<|endoftext|>


<commit_before>window.heap = window.heap || [], heap.load = function(t, e) {
    window.heap.appid = t, window.heap.config = e;
    var a = document.createElement("script");
    a.type = "text/javascript", a.async = !0, a.src = ("https:" === document.location.protocol ? "https:" : "http:") + "//cdn.heapanalytics.com/js/heap.js";
    var n = document.getElementsByTagName("script")[0];
    n.parentNode.insertBefore(a, n);
    for (var o = function(t) {
        return function() {
            heap.push([t].concat(Array.prototype.slice.call(arguments, 0)))
        }
    }, p = ["clearEventProperties", "identify", "setEventProperties", "track", "unsetEventProperty"], c = 0; c < p.length; c++) heap[p[c]] = o(p[c])
};
heap.load("3770493230");
<commit_msg>Update heap analytics script.<commit_after>  window.heap=window.heap||[],heap.load=function(t,e){window.heap.appid=t,window.heap.config=e;var a=document.createElement("script");a.type="text/javascript",a.async=!0,a.src=("https:"===document.location.protocol?"https:":"http:")+"//cdn.heapanalytics.com/js/heap-"+t+".js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(a,n);for(var o=function(t){return function(){heap.push([t].concat(Array.prototype.slice.call(arguments,0)))}},p=["clearEventProperties","identify","setEventProperties","track","unsetEventProperty"],c=0;c<p.length;c++)heap[p[c]]=o(p[c])};
  heap.load("3770493230");
<|endoftext|>


<commit_before>import Em from 'ember';
import LlamaCell from './llama-cell';
var get = Em.get;
var observer = Em.observer;
var addObserver = Em.addObserver;
var removeObserver = Em.removeObserver;
var computed = Em.computed;
var alias = computed.alias;
var or = computed.or;
var bool = computed.bool;
var empty = computed.empty;
var ESC = 27;
var SPACE = 32;

var LlamaBodyCell = LlamaCell.extend({
	templateName: 'llama-body-cell',
	classNames: 'llama-body-cell',
	classNameBindings: ['hover', 'columnIsClickable', 'rowIsClickable', 'isClickable', 'isEmpty', 'showingSubcontent', 'isEditable'],
	attributeBindings: ['tabindex'],
	hover: false,
	height: alias('row.height'),
	columnIsClickable: alias('column.isClickable'),
	rowIsClickable: alias('controller.enableRowClick'),
	isClickable: or('columnIsClickable', 'rowIsClickable'),
	showingSubcontent: bool('row.isExpanded'),
	isEmpty: empty('value'),
	isEditable: bool('column.isEditable'),

	column: null,
	row: null,

	tabindex: computed('isEditable', function () {
		var onlyFocusEditable = this.get('controller.onlyFocusEditable');
		var isEditable = this.get('isEditable');
		var index = onlyFocusEditable && !isEditable ? null : 0;
		return index;
	}),

	// only calculated once
	observedFields: computed(function () {
		var observes = this.get('column.observes');
		if (!Em.isEmpty(observes)) {
			return observes;
		}
		var id = this.get('column.name');
		return id;
	}),

	marginBottom: computed('showingSubcontent', 'row.subcontentHeight', function () {
		var isExpanded = this.get('showingSubcontent');
		if (isExpanded) {
			return this.get('row.subcontentHeight');
		}
		return null;
	}),

	didInsertElement: function () {
		this._super();
		var row = this.get('row');
		var observes = this.get('observedFields');
		addObserver(row, observes, this, 'updateValue');
	},

	willDestroyElement: function () {
		var row = this.get('row');
		var observes = this.get('observedFields');
		removeObserver(row, observes, this, 'updateValue');
		this._super();
	},

	setHeight: observer('height', function () {
		var $cell = this.$();
		if ($cell) {
			$cell.css('height', this.get('height'));
		}
	}).on('didInsertElement'),

	setMarginBottom: observer('marginBottom', function () {
		var $cell = this.$();
		if ($cell) {
			$cell.css('marginBottom', this.get('marginBottom') || 0);
		}
	}).on('didInsertElement'),

	getValue: function () {
		var id = this.get('column.name');
		var row = this.get('row');
		var value = get(row, id);
		return value;
	},

	updateValue: observer('column', function () {
		var value = this.getValue();
		this.set('value', value);
	}).on('init'),

	mouseEnter: function () {
		var row = this.get('row');
		this.get('controller').send('highlightRow', row);
	},

	mouseLeave: function () {
		this.get('controller').send('stopHighlightingRows');
	},

	click: function () {
		var controller = this.get('controller');
		var row = this.get('row');
		var column = this.get('column');
		if (this.get('isClickable')) {
			controller.sendAction('cellClick', row, column);
		}
		if (controller.get('enableRowClick')) {
			controller.sendAction('rowClick', row);
		}
	},

	focusIn: function () {
		var controller = this.get('controller');
		var row = this.get('row');
		var column = this.get('column');
		controller.send('focusCell', row, column);
		return false;
	},

	keyDown: function (e) {
		if (e.which === ESC) {
			this.$().blur();
		}
		else if (e.which === SPACE) {
			this.send('primaryAction', e);
		}
		else {
			this._super(e);
		}
	},

	actions: {
		primaryAction: function (e) {
			// cancel action by default
			e.preventDefault();
		}
	}
});

export default LlamaBodyCell;
<commit_msg>Do not show clickable state on footer cells<commit_after>import Em from 'ember';
import LlamaCell from './llama-cell';
var get = Em.get;
var observer = Em.observer;
var addObserver = Em.addObserver;
var removeObserver = Em.removeObserver;
var computed = Em.computed;
var alias = computed.alias;
var or = computed.or;
var and = computed.and;
var bool = computed.bool;
var empty = computed.empty;
var gt = computed.gt;
var ESC = 27;
var SPACE = 32;

var LlamaBodyCell = LlamaCell.extend({
	templateName: 'llama-body-cell',
	classNames: 'llama-body-cell',
	classNameBindings: ['hover', 'columnIsClickable', 'rowIsClickable', 'isClickable', 'isEmpty', 'showingSubcontent', 'isEditable'],
	attributeBindings: ['tabindex'],
	hover: false,
	height: alias('row.height'),
	columnIsClickable: alias('column.isClickable'),
	rowIsBody: gt('row.contentIndex', -1),
	rowIsClickable: and('controller.enableRowClick', 'rowIsBody'),
	isClickable: or('columnIsClickable', 'rowIsClickable'),
	showingSubcontent: bool('row.isExpanded'),
	isEmpty: empty('value'),
	isEditable: bool('column.isEditable'),

	column: null,
	row: null,

	tabindex: computed('isEditable', function () {
		var onlyFocusEditable = this.get('controller.onlyFocusEditable');
		var isEditable = this.get('isEditable');
		var index = onlyFocusEditable && !isEditable ? null : 0;
		return index;
	}),

	// only calculated once
	observedFields: computed(function () {
		var observes = this.get('column.observes');
		if (!Em.isEmpty(observes)) {
			return observes;
		}
		var id = this.get('column.name');
		return id;
	}),

	marginBottom: computed('showingSubcontent', 'row.subcontentHeight', function () {
		var isExpanded = this.get('showingSubcontent');
		if (isExpanded) {
			return this.get('row.subcontentHeight');
		}
		return null;
	}),

	didInsertElement: function () {
		this._super();
		var row = this.get('row');
		var observes = this.get('observedFields');
		addObserver(row, observes, this, 'updateValue');
	},

	willDestroyElement: function () {
		var row = this.get('row');
		var observes = this.get('observedFields');
		removeObserver(row, observes, this, 'updateValue');
		this._super();
	},

	setHeight: observer('height', function () {
		var $cell = this.$();
		if ($cell) {
			$cell.css('height', this.get('height'));
		}
	}).on('didInsertElement'),

	setMarginBottom: observer('marginBottom', function () {
		var $cell = this.$();
		if ($cell) {
			$cell.css('marginBottom', this.get('marginBottom') || 0);
		}
	}).on('didInsertElement'),

	getValue: function () {
		var id = this.get('column.name');
		var row = this.get('row');
		var value = get(row, id);
		return value;
	},

	updateValue: observer('column', function () {
		var value = this.getValue();
		this.set('value', value);
	}).on('init'),

	mouseEnter: function () {
		var row = this.get('row');
		this.get('controller').send('highlightRow', row);
	},

	mouseLeave: function () {
		this.get('controller').send('stopHighlightingRows');
	},

	click: function () {
		var controller = this.get('controller');
		var row = this.get('row');
		var column = this.get('column');
		if (this.get('isClickable')) {
			controller.sendAction('cellClick', row, column);
		}
		if (controller.get('enableRowClick')) {
			controller.sendAction('rowClick', row);
		}
	},

	focusIn: function () {
		var controller = this.get('controller');
		var row = this.get('row');
		var column = this.get('column');
		controller.send('focusCell', row, column);
		return false;
	},

	keyDown: function (e) {
		if (e.which === ESC) {
			this.$().blur();
		}
		else if (e.which === SPACE) {
			this.send('primaryAction', e);
		}
		else {
			this._super(e);
		}
	},

	actions: {
		primaryAction: function (e) {
			// cancel action by default
			e.preventDefault();
		}
	}
});

export default LlamaBodyCell;
<|endoftext|>


<commit_before>// Leaflet Map js
var lats_longs;
function placeMarkers(dataArray) {
  lats_longs = dataArray;
  if(lats_longs.length < 30) {
    markerFeatureGroup = new L.FeatureGroup();
  }
  else {
    markerFeatureGroup = new L.MarkerClusterGroup( { showCoverageOnHover: false } );
  }
  for(var i = 0; i < dataArray.length; i++) {
    var subject = dataArray[i];
    var mapIcon = L.icon({
        iconUrl: '/assets/marker-icon-vacant.png',
        shadowUrl: '/assets/marker-shadow.png',
        iconAnchor:   [0, 0], // point of the icon which will correspond to marker's location
        shadowAnchor: [4, 62],  // the same for the shadow
        popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
    });
    // Turn on below once we've fixed the positioning and have implemented color icons
    //var marker = L.marker(new L.LatLng(a[1],a[2]) , {icon: mapIcon} , { address: address });
    if (subject.lat && subject.long) {
      var marker = L.marker(new L.LatLng(subject.lat,subject.long) , { name: subject.name });
      marker.bindPopup("" + subject.name + "");
      //marker.addTo(map);
      markerFeatureGroup.addLayer(marker);
    }
  }
  console.log(markerFeatureGroup);
  map.fitBounds(markerFeatureGroup.getBounds());
  markerFeatureGroup.addTo(map);
}

$(document).ready(function() {
  drawMap();
  audiojs.events.ready(function() {
    var as = audiojs.createAll();
  });
});

function drawMap () {
  console.log('drawMap')
  if(monroePilot) {
    window.map = L.mapbox.map('map','codeforamerica.map-stwhr1eg').setView([41.6696, -86.246], 16);
  }
  else {
    window.map = L.mapbox.map('map','codeforamerica.map-stwhr1eg').setView([41.665, -86.28], 13);
  }
  $.getJSON('subjects.json', placeMarkers);
  $( "#dialog" ).dialog();
  $( "#dialog" ).dialog({ width: 295 });
  $( "#dialog" ).dialog({ position: { my: "left top", at: "left+50 bottom+60", of: "head"} });
}

// Expand Section js

(function($){"use strict";function e(){var e=this;e.defaults={hideMode:"fadeToggle",defaultSearchMode:"parent",defaultTarget:".content",throwOnMissingTarget:!0,keepStateInCookie:!1,cookieName:"simple-expand"},e.settings={},$.extend(e.settings,e.defaults),e.findLevelOneDeep=function(e,t,n){return e.find(t).filter(function(){return!$(this).parentsUntil(e,n).length})},e.setInitialState=function(t,n){var r=e.readState(t);r?(t.removeClass("collapsed").addClass("expanded"),e.show(n)):(t.removeClass("expanded").addClass("collapsed"),e.hide(n))},e.hide=function(t){e.settings.hideMode==="fadeToggle"?t.hide():e.settings.hideMode==="basic"&&t.hide()},e.show=function(t){e.settings.hideMode==="fadeToggle"?t.show():e.settings.hideMode==="basic"&&t.show()},e.checkKeepStateInCookiePreconditions=function(){if(e.settings.keepStateInCookie&&$.cookie===undefined)throw new Error("simple-expand: keepStateInCookie option requires $.cookie to be defined.")},e.readCookie=function(){var t=$.cookie(e.settings.cookieName);return t===null||t===""?{}:JSON.parse(t)},e.readState=function(t){if(!e.settings.keepStateInCookie)return!1;var n=t.attr("Id");if(n===undefined)return;var r=e.readCookie(),i=r[n]===!0||!1;return i},e.saveState=function(t,n){if(!e.settings.keepStateInCookie)return;var r=t.attr("Id");if(r===undefined)return;var i=e.readCookie();i[r]=n,$.cookie(e.settings.cookieName,JSON.stringify(i),{raw:!0,path:window.location.pathname})},e.toggle=function(t,n){var r=e.toggleCss(t);return e.settings.hideMode==="fadeToggle"?n.fadeToggle(150):e.settings.hideMode==="basic"?n.toggle():$.isFunction(e.settings.hideMode)&&e.settings.hideMode(t,n,r),e.saveState(t,r),!1},e.toggleCss=function(e){return e.hasClass("expanded")?(e.toggleClass("collapsed expanded"),!1):(e.toggleClass("expanded collapsed"),!0)},e.findTargets=function(t,n,r){var i=[];if(n==="absolute")i=$(r);else if(n==="relative")i=e.findLevelOneDeep(t,r,r);else if(n==="parent"){var s=t.parent();do i=e.findLevelOneDeep(s,r,r),i.length===0&&(s=s.parent());while(i.length===0&&s.length!==0)}return i},e.activate=function(t,n){$.extend(e.settings,n),e.checkKeepStateInCookiePreconditions(),t.each(function(){var t=$(this),n=t.attr("data-expander-target")||e.settings.defaultTarget,r=t.attr("data-expander-target-search")||e.settings.defaultSearchMode,i=e.findTargets(t,r,n);if(i.length===0){if(e.settings.throwOnMissingTarget)throw"simple-expand: Targets not found";return this}e.setInitialState(t,i),t.click(function(){return e.toggle(t,i)})})}}window.SimpleExpand=e,$.fn.simpleexpand=function(t){var n=new e;return n.activate(this,t),this}})(jQuery);

  $(function() {
    $('.expander').simpleexpand();
    $('.expander').click();
  });

<commit_msg>Remove console.log statements<commit_after>// Leaflet Map js
var lats_longs;
function placeMarkers(dataArray) {
  lats_longs = dataArray;
  if(lats_longs.length < 30) {
    markerFeatureGroup = new L.FeatureGroup();
  }
  else {
    markerFeatureGroup = new L.MarkerClusterGroup( { showCoverageOnHover: false } );
  }
  for(var i = 0; i < dataArray.length; i++) {
    var subject = dataArray[i];
    var mapIcon = L.icon({
        iconUrl: '/assets/marker-icon-vacant.png',
        shadowUrl: '/assets/marker-shadow.png',
        iconAnchor:   [0, 0], // point of the icon which will correspond to marker's location
        shadowAnchor: [4, 62],  // the same for the shadow
        popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
    });
    // Turn on below once we've fixed the positioning and have implemented color icons
    //var marker = L.marker(new L.LatLng(a[1],a[2]) , {icon: mapIcon} , { address: address });
    if (subject.lat && subject.long) {
      var marker = L.marker(new L.LatLng(subject.lat,subject.long) , { name: subject.name });
      marker.bindPopup("" + subject.name + "");
      //marker.addTo(map);
      markerFeatureGroup.addLayer(marker);
    }
  }
  map.fitBounds(markerFeatureGroup.getBounds());
  markerFeatureGroup.addTo(map);
}

$(document).ready(function() {
  drawMap();
  audiojs.events.ready(function() {
    var as = audiojs.createAll();
  });
});

function drawMap () {
  if(monroePilot) {
    window.map = L.mapbox.map('map','codeforamerica.map-stwhr1eg').setView([41.6696, -86.246], 16);
  }
  else {
    window.map = L.mapbox.map('map','codeforamerica.map-stwhr1eg').setView([41.665, -86.28], 13);
  }
  $.getJSON('subjects.json', placeMarkers);
  $( "#dialog" ).dialog();
  $( "#dialog" ).dialog({ width: 295 });
  $( "#dialog" ).dialog({ position: { my: "left top", at: "left+50 bottom+60", of: "head"} });
}

// Expand Section js

(function($){"use strict";function e(){var e=this;e.defaults={hideMode:"fadeToggle",defaultSearchMode:"parent",defaultTarget:".content",throwOnMissingTarget:!0,keepStateInCookie:!1,cookieName:"simple-expand"},e.settings={},$.extend(e.settings,e.defaults),e.findLevelOneDeep=function(e,t,n){return e.find(t).filter(function(){return!$(this).parentsUntil(e,n).length})},e.setInitialState=function(t,n){var r=e.readState(t);r?(t.removeClass("collapsed").addClass("expanded"),e.show(n)):(t.removeClass("expanded").addClass("collapsed"),e.hide(n))},e.hide=function(t){e.settings.hideMode==="fadeToggle"?t.hide():e.settings.hideMode==="basic"&&t.hide()},e.show=function(t){e.settings.hideMode==="fadeToggle"?t.show():e.settings.hideMode==="basic"&&t.show()},e.checkKeepStateInCookiePreconditions=function(){if(e.settings.keepStateInCookie&&$.cookie===undefined)throw new Error("simple-expand: keepStateInCookie option requires $.cookie to be defined.")},e.readCookie=function(){var t=$.cookie(e.settings.cookieName);return t===null||t===""?{}:JSON.parse(t)},e.readState=function(t){if(!e.settings.keepStateInCookie)return!1;var n=t.attr("Id");if(n===undefined)return;var r=e.readCookie(),i=r[n]===!0||!1;return i},e.saveState=function(t,n){if(!e.settings.keepStateInCookie)return;var r=t.attr("Id");if(r===undefined)return;var i=e.readCookie();i[r]=n,$.cookie(e.settings.cookieName,JSON.stringify(i),{raw:!0,path:window.location.pathname})},e.toggle=function(t,n){var r=e.toggleCss(t);return e.settings.hideMode==="fadeToggle"?n.fadeToggle(150):e.settings.hideMode==="basic"?n.toggle():$.isFunction(e.settings.hideMode)&&e.settings.hideMode(t,n,r),e.saveState(t,r),!1},e.toggleCss=function(e){return e.hasClass("expanded")?(e.toggleClass("collapsed expanded"),!1):(e.toggleClass("expanded collapsed"),!0)},e.findTargets=function(t,n,r){var i=[];if(n==="absolute")i=$(r);else if(n==="relative")i=e.findLevelOneDeep(t,r,r);else if(n==="parent"){var s=t.parent();do i=e.findLevelOneDeep(s,r,r),i.length===0&&(s=s.parent());while(i.length===0&&s.length!==0)}return i},e.activate=function(t,n){$.extend(e.settings,n),e.checkKeepStateInCookiePreconditions(),t.each(function(){var t=$(this),n=t.attr("data-expander-target")||e.settings.defaultTarget,r=t.attr("data-expander-target-search")||e.settings.defaultSearchMode,i=e.findTargets(t,r,n);if(i.length===0){if(e.settings.throwOnMissingTarget)throw"simple-expand: Targets not found";return this}e.setInitialState(t,i),t.click(function(){return e.toggle(t,i)})})}}window.SimpleExpand=e,$.fn.simpleexpand=function(t){var n=new e;return n.activate(this,t),this}})(jQuery);

  $(function() {
    $('.expander').simpleexpand();
    $('.expander').click();
  });

<|endoftext|>


<commit_before>/**
 * Main JS file for Casper behaviours
 */

/* globals jQuery, document */
(function ($, undefined) {
  "use strict";

  const TRIGGER_CLICK = 'click',
      TRIGGER_HOVER = 'hover',
      TRIGGER_AUTO = 'auto',
      TRIGGER_ONSCREEN = 'onscreen',
      TRIGGER_DEFAULT = TRIGGER_CLICK;

  class Ajax {
    static call (opts) {
      opts = opts || {};
      let params = opts.params || {},
        callback = opts.callback || new Function(),
        errCb = opts.err || new Function(),
        url = opts.url,
        method = opts.method || opts.type || 'GET';

      $.ajax({
        url: url,
        type: method,
        data: params
      }).done(callback).fail(errCb);
    }

    static parser (url) {
      url = url || this.url || '';
      let parser = document.createElement('a'),
          structure = {};
      parser.href = url;

      structure = {
        protocol: parser.protocol,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        search: parser.search,
        hash: parser.hash,
        host: parser.host
      };

      return structure;
    }
  };

  class u {
    static rest (arr) {
      var clone = this.clone(arr, []);
      clone.splice(0, 1);
      return clone;
    };
    static clone (thing, extender) {
      extender = extender || {};
      return jQuery.extend(true, extender, thing);
    };
  };

  class J {
    constructor ($element, options) {
      if ($.isEmptyObject(options)) {

        if ($element.data('inline')) {
          options = $element.data('inline');
        }
        else {
          var args = $element.text().split(',');
          options = args[1] ? JSON.parse(u.rest(args).join(',')) || {} : {};
          options.body = args[0];
        }

      }

      options.$element =      $element || $("<div />");
      options.body =          options.body || $element.text();
      options.src =           options.src || $element.data('src') || $element.attr('href');
      options.autoplay =      options.autoplay || false;
      options.trigger =       options.trigger || TRIGGER_DEFAULT;

      this.config = options;
      this.$element = options.$element;
      this.$mediaContainer = $('<div />');
      this.generated = false;

      // clean out the config
      if (this.config.body) {
        $element.text(this.config.body);
      }
    };

    generate () {

      if (this.generated) {
        return;
      }
      // how is this flow going to work?
      // I guess have the click execute the generate?

      let config = this.config;

      if (config.src.match(/streamable/)) {
        this.handleStreamableMedia(config);
      }
      else if (config.src.match(/mp4/)) {
        this.handleVidFile(config);
      }
      else if (config.src.match(/gfycat/)) {
        this.handleGfyCat(config);
      }
      else if (config.src.match(/gifv/)) {
        this.handleImgur(config);
      }
      else if (config.src.match(/gif/)) {
        this.buildIMGWith(config);
      }
      else if (config.src.match(/jpg|jpeg|png/)) {
        this.buildIMGWith(config);
      }
      else if (config.src.match(/youtube/)) {
        this.handleYouTube(config);
      }
      else {
        console.log("JOE: Link doesn't have fun media.");
      }
    }

    destroy () {
      this.$mediaContainer.empty();
    }

    arm () {
      let trigger = this.config.trigger;
      switch (trigger) {
        case TRIGGER_CLICK:
          this.handleClick();
        break;
        case TRIGGER_HOVER:
          this.handleHover();
        break;
        case TRIGGER_ONSCREEN:
          this.showMedia();
        break;
        case TRIGGER_AUTO:
          this.showMedia();
        break;
      }
    }

    // Various handlers
    handleStreamableMedia () {
      let uriArray = this.config.src.split('/'),
          streamableId = uriArray[uriArray.length - 1],
          src = '//streamable.com/res/' + streamableId,
          $element = this.$element;

      this.buildiFrame({
        $element: $element,
        width: '100%',
        src: src,
        scrolling: 'no'
      });
    };

    handleGfyCat () {
      let uriArray = this.config.src.split('/'),
          gfyCatDealie = uriArray[uriArray.length - 1],
          $element = this.$element,
          that = this,
          webmSrc, mp4Src;

      Ajax.call({
        url: '//gfycat.com/cajax/get/' + gfyCatDealie,
        method: 'GET',
        callback: function (response) {
          webmSrc = response.gfyItem.webmUrl;
          mp4Src = response.gfyItem.mp4Url;
          that.buildHTML5Video({
            $element: $element,
            wrapChildSources: true,
            webmSrc: webmSrc,
            mp4Src: mp4Src
          });
        },
        errCb: function () {
          console.log("Error: Failure to retrieve response for gfycat: ", gfyCatDealie);
        }
      });

    };

    handleYouTube () {
      let src = this.config.src,
          result = Ajax.parser(src),
          ytKey = result.search.split('=')[1],
          $element = this.$element;

      this.buildiFrame({
        $element: $element,
        src: '//youtube.com/embed/' + ytKey
      });
    };

    handleImgur (opts) {
      let $element = this.$element,
          arr = $element.data('src').split('.');
      arr.pop();
      let src = arr.join('.'),
          webmSrc = src + '.webm',
          mp4Src = src + '.mp4';

      this.buildHTML5Video({
        $element: $element,
        wrapChildSources: true,
        webmSrc: webmSrc,
        mp4Src: mp4Src
      });

    };

    handleVidFile () {
      this.buildHTML5Video(this.config);
    };

    // f()s that build html elments
    buildHTML5Video (opts) {
      opts = opts || {};
      let height = opts.height || 450,
          width = opts.width || '100%',
          $element = opts.$element || $('<div />'),
          src = opts.src || $element.data('src'),
          autoplay = opts.autoplay,
          //webmSrc = opts.webmSrc || (src + '.webm'),
          //mp4Src = opts.mp4Src || (src + '.mp4'),
          webmSrc = opts.webmSrc || false,
          mp4Src = opts.mp4Src || false,
          wrapChildSources = opts.wrapChildSources || false,
          $video = $('<video>', {
            height: height,
            width: width,
            loop: '',
            autoplay: autoplay,
            controls: '',
            muted: 'muted'
          }),
          webmID = opts.webmID || 'webmsource',
          mp4ID = opts.mp4ID || 'mp4source',
          $webmSource, $mp4Source;

      if (wrapChildSources) {
        if (webmSrc) {
          $webmSource = $('<source>', {
            id: webmID,
            src: webmSrc,
            type: 'video/webm'
          });
          $video.append($webmSource);
        }
        if (mp4Src) {
          $mp4Source = $('<source>', {
            id: mp4ID,
            src: mp4Src,
            type: 'video/mp4'
          });
          $video.append($mp4Source);
        }
      }
      else {
        $video.attr('src', src);
      }

      this.finishItUp($video);
    };

    buildIMGWith (opts) {
      let $element = opts.$element,
          $img = $('<img>', {
            src: opts.src,
            width: "100%"
          });

      this.finishItUp($img);
    };

    buildiFrame (opts) {
      opts = opts || {}
      let height = opts.height || 450,
          width = opts.width || 710,
          scrolling = opts.scrolling || 'no',
          $element = opts.$element || $('<div />'),
          src = opts.src || $element.data('src'),
          $iframe = $('<iframe>', {
            src: src,
            frameboarder: 0,
            height: height,
            width: width,
            scrolling: scrolling,
            allowfullscreen: ''
          });

      this.finishItUp($iframe);
    };

    finishItUp ($mediaElement) {
      this.$mediaContainer.append($mediaElement);
      this.generated = true;
    };

    // event handlers
    handleClick () {
      var $trigger = this.$element,
          $ammo = this.$mediaContainer;

      $trigger.on('click', e => {
        e.preventDefault();

        if ($ammo.is(':visible')) {
          // this.destroy();
          $ammo.detach();
        }
        else {
          this.generate();
          $ammo.appendTo($trigger);
        }
      });
    };

    handleHover () {
      var $trigger = this.$element,
          $ammo = this.$mediaContainer;

      $trigger.on('click', e => e.preventDefault());
      $trigger.on('mouseenter', e => {
        if (!$ammo.is(':visible')) {
          this.generate()
          $ammo.appendTo($trigger);
        }
      });
      $trigger.on('mouseleave', e => {
        if ($ammo.is(':visible')) {
          // this.destroy();
          $ammo.detach();
        }
      });
    };

    showMedia () {
      var $trigger = this.$element,
          $ammo = this.$mediaContainer;

      this.generate();
      $ammo.appendTo($trigger);
    };

  };

  var $document = $(document),
      dealieArray = [];

  $document.ready(function () {
    checkInlineMedia();
    setArcticScroll();
  });

  var checkInlineMedia = function () {
    // $('a[data-inline]').each(function () {
    //   var $this = $(this),
    //       src = $this.data('src'),
    //       dealie = new J({
    //         $element: $this
    //       });

    //   dealieArray.push(dealie);
    // });

    $('a').each(function () {
      let $this = $(this),
          dealie = new J($this, {});

      dealie.arm();
      //dealie.arm();
      dealieArray.push(dealie);
    });
  };

  // Arctic Scroll Source
  var setArcticScroll = function () {
    var $postContent = $(".post-content");
    $postContent.fitVids();

    $(".scroll-down").arctic_scroll();

    $(".menu-button, .nav-cover, .nav-close").on("click", function(e){
      e.preventDefault();
      $("body").toggleClass("nav-opened nav-closed");
    });
  };
  // Arctic Scroll by Paul Adam Davis
  // https://github.com/PaulAdamDavis/Arctic-Scroll
  $.fn.arctic_scroll = function (options) {

    var defaults = {
      elem: $(this),
      speed: 500
    },

        allOptions = $.extend(defaults, options);

    allOptions.elem.click(function (event) {
      event.preventDefault();
      var $this = $(this),
          $htmlBody = $('html, body'),
          offset = ($this.attr('data-offset')) ? $this.attr('data-offset') : false,
          position = ($this.attr('data-position')) ? $this.attr('data-position') : false,
          toMove;

      if (offset) {
        toMove = parseInt(offset);
        $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top + toMove) }, allOptions.speed);
      } else if (position) {
        toMove = parseInt(position);
        $htmlBody.stop(true, false).animate({scrollTop: toMove }, allOptions.speed);
      } else {
        $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top) }, allOptions.speed);
      }
    });

  };

})(jQuery);
<commit_msg>adding destroy back in for now<commit_after>/**
 * Main JS file for Casper behaviours
 */

/* globals jQuery, document */
(function ($, undefined) {
  "use strict";

  const TRIGGER_CLICK = 'click',
      TRIGGER_HOVER = 'hover',
      TRIGGER_AUTO = 'auto',
      TRIGGER_ONSCREEN = 'onscreen',
      TRIGGER_DEFAULT = TRIGGER_CLICK;

  class Ajax {
    static call (opts) {
      opts = opts || {};
      let params = opts.params || {},
        callback = opts.callback || new Function(),
        errCb = opts.err || new Function(),
        url = opts.url,
        method = opts.method || opts.type || 'GET';

      $.ajax({
        url: url,
        type: method,
        data: params
      }).done(callback).fail(errCb);
    }

    static parser (url) {
      url = url || this.url || '';
      let parser = document.createElement('a'),
          structure = {};
      parser.href = url;

      structure = {
        protocol: parser.protocol,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        search: parser.search,
        hash: parser.hash,
        host: parser.host
      };

      return structure;
    }
  };

  class u {
    static rest (arr) {
      var clone = this.clone(arr, []);
      clone.splice(0, 1);
      return clone;
    };
    static clone (thing, extender) {
      extender = extender || {};
      return jQuery.extend(true, extender, thing);
    };
  };

  class J {
    constructor ($element, options) {
      if ($.isEmptyObject(options)) {

        if ($element.data('inline')) {
          options = $element.data('inline');
        }
        else {
          var args = $element.text().split(',');
          options = args[1] ? JSON.parse(u.rest(args).join(',')) || {} : {};
          options.body = args[0];
        }

      }

      options.$element =      $element || $("<div />");
      options.body =          options.body || $element.text();
      options.src =           options.src || $element.data('src') || $element.attr('href');
      options.autoplay =      options.autoplay || false;
      options.trigger =       options.trigger || TRIGGER_DEFAULT;

      this.config = options;
      this.$element = options.$element;
      this.$mediaContainer = $('<div />');
      this.generated = false;

      // clean out the config
      if (this.config.body) {
        $element.text(this.config.body);
      }
    };

    generate () {

      // if (this.generated) {
      //   return;
      // }

      let config = this.config;

      if (config.src.match(/streamable/)) {
        this.handleStreamableMedia(config);
      }
      else if (config.src.match(/mp4/)) {
        this.handleVidFile(config);
      }
      else if (config.src.match(/gfycat/)) {
        this.handleGfyCat(config);
      }
      else if (config.src.match(/gifv/)) {
        this.handleImgur(config);
      }
      else if (config.src.match(/gif/)) {
        this.buildIMGWith(config);
      }
      else if (config.src.match(/jpg|jpeg|png/)) {
        this.buildIMGWith(config);
      }
      else if (config.src.match(/youtube/)) {
        this.handleYouTube(config);
      }
      else {
        console.log("JOE: Link doesn't have fun media.");
      }
    }

    destroy () {
      this.$mediaContainer.empty();
    }

    arm () {
      let trigger = this.config.trigger;
      switch (trigger) {
        case TRIGGER_CLICK:
          this.handleClick();
        break;
        case TRIGGER_HOVER:
          this.handleHover();
        break;
        case TRIGGER_ONSCREEN:
          this.showMedia();
        break;
        case TRIGGER_AUTO:
          this.showMedia();
        break;
      }
    }

    // Various handlers
    handleStreamableMedia () {
      let uriArray = this.config.src.split('/'),
          streamableId = uriArray[uriArray.length - 1],
          src = '//streamable.com/res/' + streamableId,
          $element = this.$element;

      this.buildiFrame({
        $element: $element,
        width: '100%',
        src: src,
        scrolling: 'no'
      });
    };

    handleGfyCat () {
      let uriArray = this.config.src.split('/'),
          gfyCatDealie = uriArray[uriArray.length - 1],
          $element = this.$element,
          that = this,
          webmSrc, mp4Src;

      Ajax.call({
        url: '//gfycat.com/cajax/get/' + gfyCatDealie,
        method: 'GET',
        callback: function (response) {
          webmSrc = response.gfyItem.webmUrl;
          mp4Src = response.gfyItem.mp4Url;
          that.buildHTML5Video({
            $element: $element,
            wrapChildSources: true,
            webmSrc: webmSrc,
            mp4Src: mp4Src
          });
        },
        errCb: function () {
          console.log("Error: Failure to retrieve response for gfycat: ", gfyCatDealie);
        }
      });

    };

    handleYouTube () {
      let src = this.config.src,
          result = Ajax.parser(src),
          ytKey = result.search.split('=')[1],
          $element = this.$element;

      this.buildiFrame({
        $element: $element,
        src: '//youtube.com/embed/' + ytKey
      });
    };

    handleImgur (opts) {
      let $element = this.$element,
          arr = $element.data('src').split('.');
      arr.pop();
      let src = arr.join('.'),
          webmSrc = src + '.webm',
          mp4Src = src + '.mp4';

      this.buildHTML5Video({
        $element: $element,
        wrapChildSources: true,
        webmSrc: webmSrc,
        mp4Src: mp4Src
      });

    };

    handleVidFile () {
      this.buildHTML5Video(this.config);
    };

    // f()s that build html elments
    buildHTML5Video (opts) {
      opts = opts || {};
      let height = opts.height || 450,
          width = opts.width || '100%',
          $element = opts.$element || $('<div />'),
          src = opts.src || $element.data('src'),
          autoplay = opts.autoplay,
          //webmSrc = opts.webmSrc || (src + '.webm'),
          //mp4Src = opts.mp4Src || (src + '.mp4'),
          webmSrc = opts.webmSrc || false,
          mp4Src = opts.mp4Src || false,
          wrapChildSources = opts.wrapChildSources || false,
          $video = $('<video>', {
            height: height,
            width: width,
            loop: '',
            autoplay: autoplay,
            controls: '',
            muted: 'muted'
          }),
          webmID = opts.webmID || 'webmsource',
          mp4ID = opts.mp4ID || 'mp4source',
          $webmSource, $mp4Source;

      if (wrapChildSources) {
        if (webmSrc) {
          $webmSource = $('<source>', {
            id: webmID,
            src: webmSrc,
            type: 'video/webm'
          });
          $video.append($webmSource);
        }
        if (mp4Src) {
          $mp4Source = $('<source>', {
            id: mp4ID,
            src: mp4Src,
            type: 'video/mp4'
          });
          $video.append($mp4Source);
        }
      }
      else {
        $video.attr('src', src);
      }

      this.finishItUp($video);
    };

    buildIMGWith (opts) {
      let $element = opts.$element,
          $img = $('<img>', {
            src: opts.src,
            width: "100%"
          });

      this.finishItUp($img);
    };

    buildiFrame (opts) {
      opts = opts || {}
      let height = opts.height || 450,
          width = opts.width || 710,
          scrolling = opts.scrolling || 'no',
          $element = opts.$element || $('<div />'),
          src = opts.src || $element.data('src'),
          $iframe = $('<iframe>', {
            src: src,
            frameboarder: 0,
            height: height,
            width: width,
            scrolling: scrolling,
            allowfullscreen: ''
          });

      this.finishItUp($iframe);
    };

    finishItUp ($mediaElement) {
      this.$mediaContainer.append($mediaElement);
      this.generated = true;
    };

    // event handlers
    handleClick () {
      var $trigger = this.$element,
          $payload = this.$mediaContainer;

      $trigger.on('click', e => {
        e.preventDefault();

        if ($payload.is(':visible')) {
          this.destroy();
          $payload.detach();
        }
        else {
          this.generate();
          $payload.appendTo($trigger);
        }
      });
    };

    handleHover () {
      var $trigger = this.$element,
          $payload = this.$mediaContainer;

      $trigger.on('click', e => e.preventDefault());
      $trigger.on('mouseenter', e => {
        if (!$payload.is(':visible')) {
          this.generate()
          $payload.appendTo($trigger);
        }
      });
      $trigger.on('mouseleave', e => {
        if ($payload.is(':visible')) {
          this.destroy();
          $payload.detach();
        }
      });
    };

    showMedia () {
      var $trigger = this.$element,
          $payload = this.$mediaContainer;

      this.generate();
      $payload.appendTo($trigger);
    };

  };

  var $document = $(document),
      dealieArray = [];

  $document.ready(function () {
    checkInlineMedia();
    setArcticScroll();
  });

  var checkInlineMedia = function () {
    // $('a[data-inline]').each(function () {
    //   var $this = $(this),
    //       src = $this.data('src'),
    //       dealie = new J({
    //         $element: $this
    //       });

    //   dealieArray.push(dealie);
    // });

    $('a').each(function () {
      let $this = $(this),
          dealie = new J($this, {});

      dealie.arm();
      //dealie.arm();
      dealieArray.push(dealie);
    });
  };

  // Arctic Scroll Source
  var setArcticScroll = function () {
    var $postContent = $(".post-content");
    $postContent.fitVids();

    $(".scroll-down").arctic_scroll();

    $(".menu-button, .nav-cover, .nav-close").on("click", function(e){
      e.preventDefault();
      $("body").toggleClass("nav-opened nav-closed");
    });
  };
  // Arctic Scroll by Paul Adam Davis
  // https://github.com/PaulAdamDavis/Arctic-Scroll
  $.fn.arctic_scroll = function (options) {

    var defaults = {
      elem: $(this),
      speed: 500
    },

        allOptions = $.extend(defaults, options);

    allOptions.elem.click(function (event) {
      event.preventDefault();
      var $this = $(this),
          $htmlBody = $('html, body'),
          offset = ($this.attr('data-offset')) ? $this.attr('data-offset') : false,
          position = ($this.attr('data-position')) ? $this.attr('data-position') : false,
          toMove;

      if (offset) {
        toMove = parseInt(offset);
        $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top + toMove) }, allOptions.speed);
      } else if (position) {
        toMove = parseInt(position);
        $htmlBody.stop(true, false).animate({scrollTop: toMove }, allOptions.speed);
      } else {
        $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top) }, allOptions.speed);
      }
    });

  };

})(jQuery);
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs');
var nearley = require('../lib/nearley.js');
var nomnom = require('nomnom');
var randexp = require('randexp');

var opts = nomnom
	.script('nearley-unparse')
	.option('file', {
		position: 0,
		help: "A grammar .js file",
        required: true,
	})
	.option('start', {
		abbr: 's',
		help: "An optional start symbol (if not provided then use the parser start symbol)",
	})
    .option('count', {
        abbr: 'n',
        help: 'The number of samples to generate (separated by \n).',
        default: 1
    })
	.option('out', {
		abbr: 'o',
		help: "File to output to (defaults to stdout)",
	})
	.option('version', {
		abbr: 'v',
		flag: true,
		help: "Print version and exit",
		callback: function() {
			return require('../package.json').version;
		}
	})
	.parse();

var output = opts.out ? fs.createWriteStream(opts.out) : process.stdout;

var grammar = new require(require('path').resolve(opts.file));

function gen(grammar, name) {
    var stack = [name];
    var rules = grammar.ParserRules;

    while (stack.length > 0) {
        var currentname = stack.pop();
        if (typeof(currentname) === 'string') {
            var goodrules = grammar.ParserRules.filter(function(x) {
                return x.name === currentname;
            });
            if (goodrules.length > 0) {
                var chosen = goodrules[
                    Math.floor(Math.random()*goodrules.length)
                ];
                for (var i=chosen.symbols.length-1; i>=0; i--) {
                    stack.push(chosen.symbols[i]);
                }
            } else {
                throw new Error("Nothing matches rule: "+currentname+"!");
            }
        } else if (currentname.test) {
            var c = new randexp(currentname).gen();
            output.write(c);
            continue;
        } else if (currentname.literal) {
            var c = currentname.literal;
            output.write(c);
            continue;
        }
    }
}

for (var i=0; i<parseInt(opts.count); i++) {
    gen(grammar, opts.start ? opts.start : grammar.ParserStart);
    output.write("\n");
}
<commit_msg>double backslash<commit_after>#!/usr/bin/env node

var fs = require('fs');
var nearley = require('../lib/nearley.js');
var nomnom = require('nomnom');
var randexp = require('randexp');

var opts = nomnom
	.script('nearley-unparse')
	.option('file', {
		position: 0,
		help: "A grammar .js file",
        required: true,
	})
	.option('start', {
		abbr: 's',
		help: "An optional start symbol (if not provided then use the parser start symbol)",
	})
    .option('count', {
        abbr: 'n',
        help: 'The number of samples to generate (separated by \\n).',
        default: 1
    })
	.option('out', {
		abbr: 'o',
		help: "File to output to (defaults to stdout)",
	})
	.option('version', {
		abbr: 'v',
		flag: true,
		help: "Print version and exit",
		callback: function() {
			return require('../package.json').version;
		}
	})
	.parse();

var output = opts.out ? fs.createWriteStream(opts.out) : process.stdout;

var grammar = new require(require('path').resolve(opts.file));

function gen(grammar, name) {
    var stack = [name];
    var rules = grammar.ParserRules;

    while (stack.length > 0) {
        var currentname = stack.pop();
        if (typeof(currentname) === 'string') {
            var goodrules = grammar.ParserRules.filter(function(x) {
                return x.name === currentname;
            });
            if (goodrules.length > 0) {
                var chosen = goodrules[
                    Math.floor(Math.random()*goodrules.length)
                ];
                for (var i=chosen.symbols.length-1; i>=0; i--) {
                    stack.push(chosen.symbols[i]);
                }
            } else {
                throw new Error("Nothing matches rule: "+currentname+"!");
            }
        } else if (currentname.test) {
            var c = new randexp(currentname).gen();
            output.write(c);
            continue;
        } else if (currentname.literal) {
            var c = currentname.literal;
            output.write(c);
            continue;
        }
    }
}

for (var i=0; i<parseInt(opts.count); i++) {
    gen(grammar, opts.start ? opts.start : grammar.ParserStart);
    output.write("\n");
}
<|endoftext|>


<commit_before>//import 'babel-polyfill';

const template_articles = require("./templates/latest_articles.hbs");
const template_github_activity = require("./templates/github_activity.hbs");
const template_github_projects = require("./templates/github_projects.hbs");

axios.get('/assets/json/articles.json')
    .then(function (response) {
      articles(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });

axios.get('https://api.github.com/users/jdillard/repos')
  .then(function (response) {
    projects(response.data);
  })
  .catch(function (error) {
    // call local file on 403
    axios.get('/assets/json/projects.json')
      .then(function (response) {
        projects(response.data);
      })
      .catch(function (error) {
        projects();
        console.log(error);
      });
    console.log(error);
  });

axios.get('https://api.github.com/users/jdillard/events')
  .then(function (response) {
    activity(response.data);
  })
  .catch(function (error) {
    // call local file on 403
    axios.get('/assets/json/activity.json')
      .then(function (response) {
        activity(response.data);
      })
      .catch(function (error) {
        activity();
        console.log(error);
      });
    console.log(error);
  });

function timeSince(date, recentDate = new Date()) {
  var seconds = Math.floor((recentDate - date) / 1000);
  var interval = Math.floor(seconds / 31536000);

  if (interval > 1) {
    return interval + " years";
  }
  interval = Math.floor(seconds / 2592000);
  if (interval > 1) {
    return interval + " months";
  }
  interval = Math.floor(seconds / 86400);
  if (interval > 1) {
    return interval + " days";
  }
  interval = Math.floor(seconds / 3600);
  if (interval > 1) {
    return interval + " hours";
  }
  interval = Math.floor(seconds / 60);
  if (interval > 1) {
    return interval + " minutes";
  }
  return Math.floor(seconds) + " seconds";
}

function summarizeAction(type, words) {
  switch(type) {
    case "WatchEvent":
      return words + " watching";
    case "PushEvent":
      return (words > 1) ? "Made "+words+" commits on" : "Made a commit on";
    case "IssueCommentEvent":
      return words + " on";
    case "ForkEvent":
      return "Made a " + words + " of";
    case "PullRequestEvent":
      return words + " on";
    case "IssuesEvent":
      return words + " on";
    case "CreateEvent":
      return "Created a " + words + " at";
    case "PullRequestReviewCommentEvent":
      return (words > 1) ? "Left " + words + " pull request reviews on" : "Left a pull request review on";
    case "DeleteEvent":
      return "Deleted a " + words + " on";
    case "CommitCommentEvent":
      return "Made a " + words + " on a commit in";
  }
}

function articles(articles) {
  var archive = document.getElementById("latest-articles");
  var articles_by_date = [];

  articles.data.sort(function(a, b) {
    return new Date(b.date_published) - new Date(a.date_published);
  })
  .reduce((a, b, i) => {
      b.date_published = moment(b.date_published).format('MMM DD, YYYY');
      a.push(b);
      return a;
  }, []);

  archive.innerHTML = template_articles(articles.data.slice(0,5));
}

function projects(projects = []) {
  const projects_element = document.getElementById("github-projects");

  const projects_list = projects.sort(function(a, b) {
    return b.stargazers_count - a.stargazers_count;
  })
  .filter(project => !project.fork)
  .map(i => {
    let contributors = 0;
    const last_push = timeSince(new Date(i.pushed_at)) + " ago";

    /* TODO add contributor count
    axios.get('https://api.github.com/repos/' + i.full_name + '/contributors')
      .then(function (response) {
        contributors = response.data.length;
      })
      .catch(function (error) {
        console.log(error);
        contributors = 1;
      });*/

    return {
      'name': i.name,
      'full_name': i.full_name,
      'url': i.html_url,
      'desc': i.description,
      'stargazers': i.stargazers_count,
      'contributors': i.open_issues_count,
      'last_push': last_push
    };
  });

  projects_element.innerHTML = template_github_projects(projects_list);
}

function activity(activities = []) {
  const activity_element = document.getElementById("github-activity");
  let prev_date = "";

  const activity_list = activities.reduce((a, b, i) => {
      b.created_at = moment(b.created_at).format('MMM DD, YYYY');

      switch(b.type) {
        case "WatchEvent":
          b.words = b.payload.action.charAt(0).toUpperCase() + b.payload.action.slice(1);
          b.link = "https://github.com/" + b.repo.name;
          break;
        case "PushEvent":
          b.words = b.payload.commits.length;
          b.link = "https://github.com/" + b.repo.name + "/commits?author=" + b.actor.display_login;
          break;
        case "IssueCommentEvent":
          b.link = b.payload.comment.html_url;
          let issue_type = (b.link.includes("pull")) ? "pull request" : "issue";
          b.words = b.payload.action.charAt(0).toUpperCase() + b.payload.action.slice(1) + " a comment on " + issue_type + " #" + b.payload.issue.number + "";
          break;
        case "ForkEvent":
          b.words = "clone";
          b.link = "https://github.com/" + b.repo.name;
          break;
        case "PullRequestEvent":
          b.words = b.payload.action.charAt(0).toUpperCase() + b.payload.action.slice(1) + " pull request #" + b.payload.pull_request.number + "";
          b.link = b.payload.pull_request.html_url;
          break;
        case "IssuesEvent":
          b.words = b.payload.action.charAt(0).toUpperCase() + b.payload.action.slice(1) + " issue #" + b.payload.issue.number + "";
          b.link = b.payload.issue.html_url;
          break;
        case "CreateEvent":
          b.words = b.payload.ref_type;
          b.link = "https://github.com/" + b.repo.name;
          break;
        case "PullRequestReviewCommentEvent":
          b.words = 1;
          b.link = "https://github.com/" + b.repo.name + "/pulls";
          break;
        case "DeleteEvent":
          b.words = b.payload.ref_type;
          b.link = "https://github.com/" + b.repo.name;
          break;
        case "CommitCommentEvent":
          b.words = "comment";
          b.link = "https://github.com/" + b.repo.name;
          break;
      }
      if(b.created_at != prev_date) {
        let dates = [];
        dates.push(b);
        a.push({'date': b.created_at, 'data': dates});
      } else {
        a[a.length-1].data.push(b);
      }
      prev_date = b.created_at;

      return a;
    }, []);

    // reduce each day to collapse multiple of same type
    for (let d in activity_list) {
      let dupe_count = 1;

      if(activity_list[d].data.length > 1) {
        activity_list[d].data = activity_list[d].data.reduce((a, b, i) => {
          if(i === 1) {
            if(a.type === "PushEvent") { dupe_count = a.words; }
            if(a.type === "PullRequestReviewCommentEvent") { dupe_count = a.words; }
            a.action = summarizeAction(a.type, a.words);
            a = [a];
          }

          if(a[a.length-1].type === b.type && a[a.length-1].repo.name === b.repo.name && b.type === "PushEvent") {
            dupe_count += b.words;
            a[a.length-1].action = summarizeAction(b.type, dupe_count);
            return a;
          }
          else if(a[a.length-1].type === b.type && a[a.length-1].repo.name === b.repo.name && b.type === "PullRequestReviewCommentEvent") {
            dupe_count += b.words;
            a[a.length-1].action = summarizeAction(b.type, dupe_count);
            return a;
          } else {
            dupe_count = 1;
            b.action = summarizeAction(b.type, b.words);
            a.push(b);
            return a;
          }
        });
      } else {
        activity_list[d].data[0].action = summarizeAction(activity_list[d].data[0].type, activity_list[d].data[0].words);
      }
    }
  activity_element.innerHTML = template_github_activity(activity_list);
}
<commit_msg>add support for github member events<commit_after>//import 'babel-polyfill';

const template_articles = require("./templates/latest_articles.hbs");
const template_github_activity = require("./templates/github_activity.hbs");
const template_github_projects = require("./templates/github_projects.hbs");

axios.get('/assets/json/articles.json')
    .then(function (response) {
      articles(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });

axios.get('https://api.github.com/users/jdillard/repos')
  .then(function (response) {
    projects(response.data);
  })
  .catch(function (error) {
    // call local file on 403
    axios.get('/assets/json/projects.json')
      .then(function (response) {
        projects(response.data);
      })
      .catch(function (error) {
        projects();
        console.log(error);
      });
    console.log(error);
  });

axios.get('https://api.github.com/users/jdillard/events')
  .then(function (response) {
    activity(response.data);
  })
  .catch(function (error) {
    // call local file on 403
    axios.get('/assets/json/activity.json')
      .then(function (response) {
        activity(response.data);
      })
      .catch(function (error) {
        activity();
        console.log(error);
      });
    console.log(error);
  });

function timeSince(date, recentDate = new Date()) {
  var seconds = Math.floor((recentDate - date) / 1000);
  var interval = Math.floor(seconds / 31536000);

  if (interval > 1) {
    return interval + " years";
  }
  interval = Math.floor(seconds / 2592000);
  if (interval > 1) {
    return interval + " months";
  }
  interval = Math.floor(seconds / 86400);
  if (interval > 1) {
    return interval + " days";
  }
  interval = Math.floor(seconds / 3600);
  if (interval > 1) {
    return interval + " hours";
  }
  interval = Math.floor(seconds / 60);
  if (interval > 1) {
    return interval + " minutes";
  }
  return Math.floor(seconds) + " seconds";
}

function summarizeAction(type, words) {
  switch(type) {
    case "WatchEvent":
      return words + " watching";
    case "PushEvent":
      return (words > 1) ? "Made "+words+" commits on" : "Made a commit on";
    case "IssueCommentEvent":
      return words + " on";
    case "ForkEvent":
      return "Made a " + words + " of";
    case "PullRequestEvent":
      return words + " on";
    case "IssuesEvent":
      return words + " on";
    case "CreateEvent":
      return "Created a " + words + " at";
    case "PullRequestReviewCommentEvent":
      return (words > 1) ? "Left " + words + " pull request reviews on" : "Left a pull request review on";
    case "DeleteEvent":
      return "Deleted a " + words + " on";
    case "CommitCommentEvent":
      return "Made a " + words + " on a commit in";
    case "MemberEvent":
      return words + " a collaborator to";
  }
}

function articles(articles) {
  var archive = document.getElementById("latest-articles");
  var articles_by_date = [];

  articles.data.sort(function(a, b) {
    return new Date(b.date_published) - new Date(a.date_published);
  })
  .reduce((a, b, i) => {
      b.date_published = moment(b.date_published).format('MMM DD, YYYY');
      a.push(b);
      return a;
  }, []);

  archive.innerHTML = template_articles(articles.data.slice(0,5));
}

function projects(projects = []) {
  const projects_element = document.getElementById("github-projects");

  const projects_list = projects.sort(function(a, b) {
    return b.stargazers_count - a.stargazers_count;
  })
  .filter(project => !project.fork)
  .map(i => {
    let contributors = 0;
    const last_push = timeSince(new Date(i.pushed_at)) + " ago";

    /* TODO add contributor count
    axios.get('https://api.github.com/repos/' + i.full_name + '/contributors')
      .then(function (response) {
        contributors = response.data.length;
      })
      .catch(function (error) {
        console.log(error);
        contributors = 1;
      });*/

    return {
      'name': i.name,
      'full_name': i.full_name,
      'url': i.html_url,
      'desc': i.description,
      'stargazers': i.stargazers_count,
      'contributors': i.open_issues_count,
      'last_push': last_push
    };
  });

  projects_element.innerHTML = template_github_projects(projects_list);
}

function activity(activities = []) {
  const activity_element = document.getElementById("github-activity");
  let prev_date = "";

  const activity_list = activities.reduce((a, b, i) => {
      b.created_at = moment(b.created_at).format('MMM DD, YYYY');

      switch(b.type) {
        case "WatchEvent":
          b.words = b.payload.action.charAt(0).toUpperCase() + b.payload.action.slice(1);
          b.link = "https://github.com/" + b.repo.name;
          break;
        case "PushEvent":
          b.words = b.payload.commits.length;
          b.link = "https://github.com/" + b.repo.name + "/commits?author=" + b.actor.display_login;
          break;
        case "IssueCommentEvent":
          b.link = b.payload.comment.html_url;
          let issue_type = (b.link.includes("pull")) ? "pull request" : "issue";
          b.words = b.payload.action.charAt(0).toUpperCase() + b.payload.action.slice(1) + " a comment on " + issue_type + " #" + b.payload.issue.number + "";
          break;
        case "ForkEvent":
          b.words = "clone";
          b.link = "https://github.com/" + b.repo.name;
          break;
        case "PullRequestEvent":
          b.words = b.payload.action.charAt(0).toUpperCase() + b.payload.action.slice(1) + " pull request #" + b.payload.pull_request.number + "";
          b.link = b.payload.pull_request.html_url;
          break;
        case "IssuesEvent":
          b.words = b.payload.action.charAt(0).toUpperCase() + b.payload.action.slice(1) + " issue #" + b.payload.issue.number + "";
          b.link = b.payload.issue.html_url;
          break;
        case "CreateEvent":
          b.words = b.payload.ref_type;
          b.link = "https://github.com/" + b.repo.name;
          break;
        case "PullRequestReviewCommentEvent":
          b.words = 1;
          b.link = "https://github.com/" + b.repo.name + "/pulls";
          break;
        case "DeleteEvent":
          b.words = b.payload.ref_type;
          b.link = "https://github.com/" + b.repo.name;
          break;
        case "CommitCommentEvent":
          b.words = "comment";
          b.link = "https://github.com/" + b.repo.name;
          break;
        case "MemberEvent":
          b.words = b.payload.action.charAt(0).toUpperCase() + b.payload.action.slice(1);
          b.link = "https://github.com/" + b.repo.name;
      }
      if(b.created_at != prev_date) {
        let dates = [];
        dates.push(b);
        a.push({'date': b.created_at, 'data': dates});
      } else {
        a[a.length-1].data.push(b);
      }
      prev_date = b.created_at;

      return a;
    }, []);

    // reduce each day to collapse multiple of same type
    for (let d in activity_list) {
      let dupe_count = 1;

      if(activity_list[d].data.length > 1) {
        activity_list[d].data = activity_list[d].data.reduce((a, b, i) => {
          if(i === 1) {
            if(a.type === "PushEvent") { dupe_count = a.words; }
            if(a.type === "PullRequestReviewCommentEvent") { dupe_count = a.words; }
            a.action = summarizeAction(a.type, a.words);
            a = [a];
          }

          if(a[a.length-1].type === b.type && a[a.length-1].repo.name === b.repo.name && b.type === "PushEvent") {
            dupe_count += b.words;
            a[a.length-1].action = summarizeAction(b.type, dupe_count);
            return a;
          }
          else if(a[a.length-1].type === b.type && a[a.length-1].repo.name === b.repo.name && b.type === "PullRequestReviewCommentEvent") {
            dupe_count += b.words;
            a[a.length-1].action = summarizeAction(b.type, dupe_count);
            return a;
          } else {
            dupe_count = 1;
            b.action = summarizeAction(b.type, b.words);
            a.push(b);
            return a;
          }
        });
      } else {
        activity_list[d].data[0].action = summarizeAction(activity_list[d].data[0].type, activity_list[d].data[0].words);
      }
    }
  activity_element.innerHTML = template_github_activity(activity_list);
}
<|endoftext|>