<commit_before>var Readmill = {

  button: function(url, callback, displayClass) {
    var params = [], src, iframe;

    if(displayClass === undefined) {
      displayClass = "small";
    }

    var container = document.createElement("div");

    if(callback) {
      container = callback(container);
    }

    params.push('display=' + displayClass);
    params.push('origin_domain=' + encodeURIComponent(document.domain));
    params.push('download_url=' + encodeURIComponent(url));

    src = 'https://widgets.readmill.com/send';
    src += '?' + params.join('&');

    iframe = document.createElement('iframe');
    Readmill.styleIFrame(iframe, displayClass);
    iframe.src = src;
    container.appendChild(iframe);
    return container;
  },

  appendChild: function(targets, button, insertAt) {
    var targets = document.querySelectorAll(targets);
    Array.prototype.forEach.call(targets, function(el) {
      el.parentNode.appendChild(button(el));
    });
  },

  styleIFrame: function(iframe, displayClass) {
    var style = 'margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; position: static; left: 0px; top: 0px;',
        placeHolderUrl;
    switch(displayClass) {
      case 'small':
        style += 'width: 72px !important; height: 26px !important; ';
        placeHolderUrl = 'https://platform.readmill.com/assets/btn_ph_str_small.png';
        break;
      case 'large':
        style += 'width: 170px !important; height: 40px !important;';
        placeHolderUrl = 'https://platform.readmill.com/assets/btn_ph_str_large.png';
        break;
    }

    iframe.style.cssText = "background: transparent url(" + placeHolderUrl + ") !important; " + style;

    // Move into a function for better minimization
    function _applyAttribute(attrName, value) {
      iframe.setAttribute(attrName, value);
    }

    // NOTE Be careful about capitalization here. Internet explorer
    // does not care about attributes unless they are camel cased
    _applyAttribute('allowTransparency', 'true');  // Let transparency shine through
    _applyAttribute('frameBorder', '0');           // Hide ugly iframe border
    _applyAttribute('tabIndex', '0');              // Disable tabbing to the iframe
    _applyAttribute('scrolling', 'no');            // Disable scrolling overflowing content

    if(iframe.className) {
      iframe.className = 'send-to-readmill ' + displayClass;
    } else {
      iframe.setAttribute('class', 'send-to-readmill ' + displayClass);
    }
  }
}
<commit_msg>Update to match readmills script more<commit_after>var Readmill = {

  button: function(url, callback, displayClass) {
    var params = [], src, iframe;

    if(displayClass === undefined) {
      displayClass = "small";
    }

    var container = document.createElement("div");
    container.classList.add("send-to-readmill-wrapper");

    if(callback) {
      container = callback(container);
    }

    params.push('display=' + displayClass);
    params.push('origin_domain=' + encodeURIComponent(window.location.protocol+"//"+document.domain));
    params.push('download_url=' + encodeURIComponent(url));
    params.push('alt=a');

    src = 'https://widgets.readmill.com/send';
    src += '?' + params.join('&');

    iframe = document.createElement('iframe');
    Readmill.styleIFrame(iframe, displayClass);
    iframe.src = src;
    container.appendChild(iframe);
    return container;
  },

  appendChild: function(targets, button, insertAt) {
    var targets = document.querySelectorAll(targets);
    Array.prototype.forEach.call(targets, function(el) {
      el.parentNode.appendChild(button(el));
    });
  },

  styleIFrame: function(iframe, displayClass) {
    var style = 'margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; position: static; left: 0px; top: 0px;',
        placeHolderUrl;
    switch(displayClass) {
      case 'small':
        style += 'width: 72px !important; height: 26px !important; ';
        placeHolderUrl = '//d3kdyw6hgzoh5r.cloudfront.net/assets/widgets/btn_str_small-05a10061a2250cba9d18f9e22ec5e87a.png';
        break;
      case 'large':
        style += 'width: 170px !important; height: 40px !important;';
        placeHolderUrl = '//d3kdyw6hgzoh5r.cloudfront.net/assets/widgets/btn_str_large-48f37b15588d9797c5e10d12680ebac3.png';
        break;
    }

    iframe.style.cssText = "background: transparent url(" + placeHolderUrl + ") !important; " + style;

    // Move into a function for better minimization
    function _applyAttribute(attrName, value) {
      iframe.setAttribute(attrName, value);
    }

    // NOTE Be careful about capitalization here. Internet explorer
    // does not care about attributes unless they are camel cased
    _applyAttribute('allowTransparency', 'true');  // Let transparency shine through
    _applyAttribute('frameBorder', '0');           // Hide ugly iframe border
    _applyAttribute('tabIndex', '0');              // Disable tabbing to the iframe
    _applyAttribute('scrolling', 'no');            // Disable scrolling overflowing content

    if(iframe.className) {
      iframe.className = 'send-to-readmill ' + displayClass;
    } else {
      iframe.setAttribute('class', 'send-to-readmill ' + displayClass);
    }
  }
}
<|endoftext|>


<commit_before>const _ = require('lodash');
const path = require('path');
const build = require('./build');
const settings = require('../../config/settings');
const templates = require('./templates');
const applyProduction = require('./production');
const file = require('./file');
const utils = require('./utils');

// -----------------------------------------------------------------------------
// Build pages based on tags
// -----------------------------------------------------------------------------
function buildTagPages(pages, postsApp, webpackAssets) {

  const tagsTemplate = templates.loadTemplate('partials/_tag.html', postsApp.templateDirs);

  const tags = _.reduce(pages, (collect, page) => {
    _.each(page.metadata.tags, (tag) => {
      (collect[tag] || (collect[tag] = [])).push(page);
    });
    return collect;
  }, {});

  const site = postsApp.templateData.site;

  _.each(tags, (posts, tag) => {
    const data = {
      site       : postsApp.templateData.site,
      metadata   : { },
      title      : tag,
      currentTag : tag,
      cleanTag   : utils.cleanTag,
      url        : path.join(site.domain, site.tagsPath),
      posts,
      _
    };

    // Build the tag content
    data.content = tagsTemplate(data);

    // Apply template
    const fileName = `${utils.cleanTag(tag)}.html`;
    let html = templates.apply(data, fileName, postsApp.templateMap, postsApp.templateDirs);
    html = applyProduction(html, postsApp.stage, webpackAssets, postsApp.buildSuffix);
    file.write(path.join(postsApp.outputPath, site.tagsPath, fileName), html);
  });
}

// -----------------------------------------------------------------------------
// Build blog archive pages for paging through posts
// -----------------------------------------------------------------------------
function buildArchive(pages, postsApp, webpackAssets) {
  const archiveTemplate = templates.loadTemplate('partials/_posts.html', postsApp.templateDirs);
  const perPage = postsApp.htmlOptions.paginate;
  const max = _.floor(pages.length / perPage);
  _(pages)
  .chunk(perPage)
  .each((posts, index) => {
    const prevPage = `${(index > 1 ? index - 1 : 'index')}.html`;
    const nextPage = index < max ? `${index + 1}.html` : '#';
    const fileName = `${(index === 0 ? 'index' : index)}.html`;

    let title;
    if (_.isString(postsApp.htmlOptions.recentPostsTitle)) {
      title = postsApp.htmlOptions.recentPostsTitle;
    } else {
      title = index === 0 ? 'Recent Posts' : '';
    }

    const data = {
      site: postsApp.templateData.site,
      metadata: { },
      cleanTag: utils.cleanTag,
      url: postsApp.templateData.site.domain,
      posts,
      title,
      _,
      prevPage,
      nextPage
    };

    // Build the content
    data.content = archiveTemplate(data);

    // Apply template
    let html = templates.apply(
      data,
      fileName,
      postsApp.templateMap,
      postsApp.templateDirs);
    html = applyProduction(html, postsApp.stage, webpackAssets, postsApp.buildSuffix);
    file.write(path.join(postsApp.outputPath, fileName), html);
  });
}

function buildPosts(options, webpackAssets) {
  const postsApp = settings.postsApp(options);
  const pages = build.buildHtml(postsApp, webpackAssets).sort((a, b) => {
    // Sort pages by date
    if (a.date.unix() > b.date.unix()) return -1;
    if (a.date.unix() < b.date.unix()) return 1;
    return 0;
  });

  buildArchive(pages, postsApp, webpackAssets);
  buildTagPages(pages, postsApp, webpackAssets);
}

module.exports = {
  buildPosts
};
<commit_msg>Match changes in starter app<commit_after>const _ = require('lodash');
const path = require('path');
const build = require('./build');
const settings = require('../../config/settings');
const templates = require('./templates');
const applyHtmlPaths = require('./html_paths');
const file = require('./file');
const utils = require('./utils');

// -----------------------------------------------------------------------------
// Build pages based on tags
// -----------------------------------------------------------------------------
function buildTagPages(pages, postsApp, webpackAssets) {

  const tagsTemplate = templates.loadTemplate('partials/_tag.html', postsApp.templateDirs);

  const tags = _.reduce(pages, (collect, page) => {
    _.each(page.metadata.tags, (tag) => {
      (collect[tag] || (collect[tag] = [])).push(page);
    });
    return collect;
  }, {});

  const site = postsApp.templateData.site;

  _.each(tags, (posts, tag) => {
    const data = {
      site       : postsApp.templateData.site,
      metadata   : { },
      title      : tag,
      currentTag : tag,
      cleanTag   : utils.cleanTag,
      url        : path.join(site.domain, site.tagsPath),
      posts,
      _
    };

    // Build the tag content
    data.content = tagsTemplate(data);

    // Apply template
    const fileName = `${utils.cleanTag(tag)}.html`;
    let html = templates.apply(data, fileName, postsApp.templateMap, postsApp.templateDirs);
    html = applyHtmlPaths(html, postsApp.stage, webpackAssets, postsApp.buildSuffix);
    file.write(path.join(postsApp.outputPath, site.tagsPath, fileName), html);
  });
}

// -----------------------------------------------------------------------------
// Build blog archive pages for paging through posts
// -----------------------------------------------------------------------------
function buildArchive(pages, postsApp, webpackAssets) {
  const archiveTemplate = templates.loadTemplate('partials/_posts.html', postsApp.templateDirs);
  const perPage = postsApp.htmlOptions.paginate;
  const max = _.floor(pages.length / perPage);
  _(pages)
  .chunk(perPage)
  .each((posts, index) => {
    const prevPage = `${(index > 1 ? index - 1 : 'index')}.html`;
    const nextPage = index < max ? `${index + 1}.html` : '#';
    const fileName = `${(index === 0 ? 'index' : index)}.html`;

    let title;
    if (_.isString(postsApp.htmlOptions.recentPostsTitle)) {
      title = postsApp.htmlOptions.recentPostsTitle;
    } else {
      title = index === 0 ? 'Recent Posts' : '';
    }

    const data = {
      site: postsApp.templateData.site,
      metadata: { },
      cleanTag: utils.cleanTag,
      url: postsApp.templateData.site.domain,
      posts,
      title,
      _,
      prevPage,
      nextPage
    };

    // Build the content
    data.content = archiveTemplate(data);

    // Apply template
    let html = templates.apply(
      data,
      fileName,
      postsApp.templateMap,
      postsApp.templateDirs);
    html = applyHtmlPaths(html, postsApp.stage, webpackAssets, postsApp.buildSuffix);
    file.write(path.join(postsApp.outputPath, fileName), html);
  });
}

function buildPosts(options, webpackAssets) {
  const postsApp = settings.postsApp(options);
  const pages = build.buildHtml(postsApp, webpackAssets).sort((a, b) => {
    // Sort pages by date
    if (a.date.unix() > b.date.unix()) return -1;
    if (a.date.unix() < b.date.unix()) return 1;
    return 0;
  });

  buildArchive(pages, postsApp, webpackAssets);
  buildTagPages(pages, postsApp, webpackAssets);
}

module.exports = {
  buildPosts
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Wrapper around the {@link https://github.com/dscape/lynx|lynx}
 * statsd client library. Forwards basic functionality and offers some
 * convenience functions top.
 *
 * @module
 */

// public interface
module.exports = {
	init: init,
	increment: increment,
	decrement: decrement,
	createTimer: createTimer,
	setupGaugeInterval: setupGaugeInterval,
	setupTimerInterval: setupTimerInterval,
};

require('harmony-reflect');
var config = require('config');
var Lynx = require('lynx');

var STATSD_FLUSH_INT = 10000;  // statsd flush interval in ms

var lynx = getMockLynx();
var intervals = {};

/**
 * Initializes the statsd client (if monitoring is enabled in the GS
 * configuration).
 */
function init() {
	intervals = {};
	var cfg = config.get('mon:statsd');
	if (!cfg.enabled) {
		log.info('monitoring disabled, using mock statsd client');
	}
	else {
		var scope = (cfg.prefix ? cfg.prefix + '.' : '') + config.getGsid();
		log.info('initializing statsd client (scope: %s)', scope);
		lynx = new Lynx(
			config.get('mon:statsd:host'), config.get('mon:statsd:port'),
			{scope: scope, on_error: lynxErrorHandler});
	}
	startSystemMetrics();
}

function lynxErrorHandler(err) {
	// crude way of filtering out unnecessary errors for stats that aren't sent
	// because of their sample rate
	// see: https://github.com/dscape/lynx/issues/10
	if (err.message !== 'Nothing to send') {
		log.error(err, 'error in statsd client');
	}
}

/**
 * Creates a mock statsd client object that just trace logs incoming
 * stats instead of sending them off. Suitable for testing or when
 * monitoring is disabled.
 *
 * @private
 */
function getMockLynx() {
	return new Proxy({}, {
		get: function get(target, name, receiver) {
			return function dummy() {
				if (global.log) {
					log.trace({fname: name, args: arguments}, 'statsd call');
				}
			};
		},
	});
}

/**
 * Increment a counter metric by 1.
 * see {@link https://github.com/dscape/lynx/ lynx} and {@link
 * https://github.com/etsy/statsd statsd} docs for details.
 */
function increment(stats, sampleRate) {
	return lynx.increment(stats, sampleRate);
}

/**
 * Decrement a counter metric by 1.
 * see {@link https://github.com/dscape/lynx/ lynx} and {@link
 * https://github.com/etsy/statsd statsd} docs for details.
 */
function decrement(stats, sampleRate) {
	return lynx.decrement(stats, sampleRate);
}

/**
 * Create a timer object for timing measurements.
 * see {@link https://github.com/dscape/lynx/ lynx} and {@link
 * https://github.com/etsy/statsd statsd} docs for details.
 *
 * NB: returns `undefined` in case monitoring is not enabled;
 * callers need to handle that case.
 */
function createTimer(stat, sampleRate) {
	return lynx.createTimer(stat, sampleRate);
}

/**
 * Sets up an interval for periodic collection of a gauge metric.
 *
 * @param {string} stat name of the metric
 * @param {function} valueGetter called to retrieve the current gauge
 *        value when the interval fires (no arguments, must return a
 *        single numeric value)
 * @param {number} [sampleRate] metric sample rate (must be between
 *        0 and 1; defaults to 1, i.e. no sampling)
 * @param {number} [delay] period between metric generation calls
 *        (default statsd flush interval by default)
 */
function setupGaugeInterval(stat, valueGetter, sampleRate, delay) {
	setupInterval(stat, 'gauge', delay, function gauge() {
		lynx.gauge(stat, valueGetter(), sampleRate);
	});
}

/**
 * Sets up an interval for periodic collection of a timing metric.
 * The timer object is created when the interval fires, and passed
 * to the given `resolver` function.
 *
 * @param {string} stat name of the metric
 * @param {function} resolver takes a timer object as its only
 *        argument; expected to stop the timer once whatever is being
 *        measured has finished
 * @param {number} [sampleRate] metric sample rate (must be between
 *        0 and 1; defaults to 1, i.e. no sampling)
 * @param {number} [delay] period between metric generation calls
 *        (default statsd flush interval by default)
 */
function setupTimerInterval(stat, resolver, sampleRate, delay) {
	setupInterval(stat, 'timer', delay, function timer() {
		resolver(createTimer(stat, sampleRate));
	});
}

/**
 * Sets up an interval for periodic collection of arbitrary metrics.
 * If an interval for the given metric already exists, it is removed
 * and recreated.
 *
 * @param {string} stat name of the metric
 * @param {string} type metric type (must be "gauge" or "timer"; will
 *        be used as part of the metric name sent to statsd)
 * @param {number} delay stats generation period in ms (defaults to
 *        the default statsd flush interval of 10s if undefined)
 * @param {function} func a function generating and submitting the
 *        metric (no arguments, no return value)
 * @private
 */
function setupInterval(stat, type, delay, func) {
	delay = delay || STATSD_FLUSH_INT;
	var id = type + '.' + stat;
	if (id in intervals) {
		log.info('replacing %s interval for %s', type, stat);
		clearInterval(intervals[id]);
	}
	else {
		log.info('setting up %s interval for %s', type, stat);
	}
	var intObj = setInterval(func, delay);
	intervals[id] = intObj;
}

/**
 * Sets up periodic collection of system level metrics (memory, system
 * load etc.).
 * @private
 */
function startSystemMetrics() {
	// process memory gauges
	/*jshint -W083 */  // ok to make function within this (specific, run-once) loop
	for (var k in process.memoryUsage()) {
		setupGaugeInterval('process.memory.' + k, function getter() {
			return process.memoryUsage()[k];
		});
	}
	/*jshint +W083 */
	// naive event loop latency
	setupTimerInterval('process.eventLoopLatency', function resolver(timer) {
		setImmediate(function stop() {
			timer.stop();
		});
	}, undefined, 1000);
}
<commit_msg>stub the lynx Timer object when metrics are disabled<commit_after>'use strict';

/**
 * Wrapper around the {@link https://github.com/dscape/lynx|lynx}
 * statsd client library. Forwards basic functionality and offers some
 * convenience functions top.
 *
 * @module
 */

// public interface
module.exports = {
	init: init,
	increment: increment,
	decrement: decrement,
	createTimer: createTimer,
	setupGaugeInterval: setupGaugeInterval,
	setupTimerInterval: setupTimerInterval,
};

require('harmony-reflect');
var config = require('config');
var Lynx = require('lynx');

var STATSD_FLUSH_INT = 10000;  // statsd flush interval in ms

var lynx = getMockLynx();
var intervals = {};

/**
 * Initializes the statsd client (if monitoring is enabled in the GS
 * configuration).
 */
function init() {
	intervals = {};
	var cfg = config.get('mon:statsd');
	if (!cfg.enabled) {
		log.info('monitoring disabled, using mock statsd client');
	}
	else {
		var scope = (cfg.prefix ? cfg.prefix + '.' : '') + config.getGsid();
		log.info('initializing statsd client (scope: %s)', scope);
		lynx = new Lynx(
			config.get('mon:statsd:host'), config.get('mon:statsd:port'),
			{scope: scope, on_error: lynxErrorHandler});
	}
	startSystemMetrics();
}

function lynxErrorHandler(err) {
	// crude way of filtering out unnecessary errors for stats that aren't sent
	// because of their sample rate
	// see: https://github.com/dscape/lynx/issues/10
	if (err.message !== 'Nothing to send') {
		log.error(err, 'error in statsd client');
	}
}

/**
 * Creates a mock statsd client object that just trace logs incoming
 * stats instead of sending them off. Suitable for testing or when
 * monitoring is disabled.
 *
 * @private
 */
function getMockLynx() {
	return new Proxy({}, {
		get: function get(target, name, receiver) {
			return function dummy() {
				if (global.log) {
					log.trace({fname: name, args: arguments}, 'statsd call');
					if (name === 'createTimer') {
						return {
							stop: function stop() {}
						};
					}
				}
			};
		},
	});
}

/**
 * Increment a counter metric by 1.
 * see {@link https://github.com/dscape/lynx/ lynx} and {@link
 * https://github.com/etsy/statsd statsd} docs for details.
 */
function increment(stats, sampleRate) {
	return lynx.increment(stats, sampleRate);
}

/**
 * Decrement a counter metric by 1.
 * see {@link https://github.com/dscape/lynx/ lynx} and {@link
 * https://github.com/etsy/statsd statsd} docs for details.
 */
function decrement(stats, sampleRate) {
	return lynx.decrement(stats, sampleRate);
}

/**
 * Create a timer object for timing measurements.
 * see {@link https://github.com/dscape/lynx/ lynx} and {@link
 * https://github.com/etsy/statsd statsd} docs for details.
 *
 * NB: returns `undefined` in case monitoring is not enabled;
 * callers need to handle that case.
 */
function createTimer(stat, sampleRate) {
	return lynx.createTimer(stat, sampleRate);
}

/**
 * Sets up an interval for periodic collection of a gauge metric.
 *
 * @param {string} stat name of the metric
 * @param {function} valueGetter called to retrieve the current gauge
 *        value when the interval fires (no arguments, must return a
 *        single numeric value)
 * @param {number} [sampleRate] metric sample rate (must be between
 *        0 and 1; defaults to 1, i.e. no sampling)
 * @param {number} [delay] period between metric generation calls
 *        (default statsd flush interval by default)
 */
function setupGaugeInterval(stat, valueGetter, sampleRate, delay) {
	setupInterval(stat, 'gauge', delay, function gauge() {
		lynx.gauge(stat, valueGetter(), sampleRate);
	});
}

/**
 * Sets up an interval for periodic collection of a timing metric.
 * The timer object is created when the interval fires, and passed
 * to the given `resolver` function.
 *
 * @param {string} stat name of the metric
 * @param {function} resolver takes a timer object as its only
 *        argument; expected to stop the timer once whatever is being
 *        measured has finished
 * @param {number} [sampleRate] metric sample rate (must be between
 *        0 and 1; defaults to 1, i.e. no sampling)
 * @param {number} [delay] period between metric generation calls
 *        (default statsd flush interval by default)
 */
function setupTimerInterval(stat, resolver, sampleRate, delay) {
	setupInterval(stat, 'timer', delay, function timer() {
		resolver(createTimer(stat, sampleRate));
	});
}

/**
 * Sets up an interval for periodic collection of arbitrary metrics.
 * If an interval for the given metric already exists, it is removed
 * and recreated.
 *
 * @param {string} stat name of the metric
 * @param {string} type metric type (must be "gauge" or "timer"; will
 *        be used as part of the metric name sent to statsd)
 * @param {number} delay stats generation period in ms (defaults to
 *        the default statsd flush interval of 10s if undefined)
 * @param {function} func a function generating and submitting the
 *        metric (no arguments, no return value)
 * @private
 */
function setupInterval(stat, type, delay, func) {
	delay = delay || STATSD_FLUSH_INT;
	var id = type + '.' + stat;
	if (id in intervals) {
		log.info('replacing %s interval for %s', type, stat);
		clearInterval(intervals[id]);
	}
	else {
		log.info('setting up %s interval for %s', type, stat);
	}
	var intObj = setInterval(func, delay);
	intervals[id] = intObj;
}

/**
 * Sets up periodic collection of system level metrics (memory, system
 * load etc.).
 * @private
 */
function startSystemMetrics() {
	// process memory gauges
	/*jshint -W083 */  // ok to make function within this (specific, run-once) loop
	for (var k in process.memoryUsage()) {
		setupGaugeInterval('process.memory.' + k, function getter() {
			return process.memoryUsage()[k];
		});
	}
	/*jshint +W083 */
	// naive event loop latency
	setupTimerInterval('process.eventLoopLatency', function resolver(timer) {
		setImmediate(function stop() {
			timer.stop();
		});
	}, undefined, 1000);
}
<|endoftext|>


<commit_before>sumeru.router.add(
	{
		pattern: '/createchannel',
		action: 'App.createchannel'
	}
);

App.createchannel = sumeru.controller.create(function(env,session){
	var getMsgs = function(){
		session.messages = env.subscribe('pub-chatchannel', function(msgCollection){
			msgCollection.addSorters("time","DESC");
			//manipulate synced collection and bind it to serveral view blocks.
          	session.bind('createChannel', {
              	data    :   msgCollection.find(),
          	});
	    });
	}

	env.onload = function(){
		return [getMsgs];
	};

	env.onrender = function(doRender){
		doRender('createchannel',["push","left"]);
	};

	env.onready = function(){
		document.getElementById("messages").style.height = document.body.clientHeight - 40 + "px";
		var event = 'click';
		var keyboardMap = {
            'enter' : 13
        };

		session.event('craeteChannel', function(){
			session.eventMap('#inputChannelName', {
     				//enter on pcs, return on mobile
				'keydown' : function(e){
                    if(e.keyCode == keyboardMap.enter){
                        createChannel();
                    }
                },

                'focus' : function(e){
                    session.messages.hold();
                },

                'blur' : function(e){
                    if (this.value.trim() == '') {
                        session.messages.releaseHold();
                    };
                }
            });

        	document.getElementById('backTochannel').addEventListener(event, backTochannel);
        	document.getElementById('ok').addEventListener(event, createChannel);
	    });

	};

	var backTochannel = function(){
		env.redirect("/chatchannel");
	};

	var createChannel = function(){
		var input = document.getElementById('inputChannelName'),
	        inputVal = input.value.trim();

	  	if (inputVal == '') {
	  		return false;
	  	};

	  	session.messages.add({
		  	channelname: inputVal,
		  	time : (new Date()).valueOf() ,
		  	describe : '',
	  	});

	  	session.messages.save();
	  	input.value = '';

	  	session.messages.releaseHold();
		env.redirect("/chatchannel");
	};
});
<commit_msg>fix "createChannel"<commit_after>sumeru.router.add(
	{
		pattern: '/createchannel',
		action: 'App.createchannel'
	}
);

App.createchannel = sumeru.controller.create(function(env,session){
	var getMsgs = function(){
		session.messages = env.subscribe('pub-chatchannel', function(msgCollection){
			msgCollection.addSorters("time","DESC");
			//manipulate synced collection and bind it to serveral view blocks.
          	session.bind('createChannel', {
              	data    :   msgCollection.find(),
          	});
	    });
	}

	env.onload = function(){
		return [getMsgs];
	};

	env.onrender = function(doRender){
		doRender('createchannel',["push","left"]);
	};

	env.onready = function(){
		document.getElementById("messages").style.height = document.body.clientHeight - 40 + "px";
		var event = 'click';
		var keyboardMap = {
            'enter' : 13
        };

		session.event('createChannel', function(){
			session.eventMap('#inputChannelName', {
     				//enter on pcs, return on mobile
				'keydown' : function(e){
                    if(e.keyCode == keyboardMap.enter){
                        createChannel();
                    }
                },

                'focus' : function(e){
                    session.messages.hold();
                },

                'blur' : function(e){
                    if (this.value.trim() == '') {
                        session.messages.releaseHold();
                    };
                }
            });

        	document.getElementById('backTochannel').addEventListener(event, backTochannel);
        	document.getElementById('ok').addEventListener(event, createChannel);
	    });

	};

	var backTochannel = function(){
		env.redirect("/chatchannel");
	};

	var createChannel = function(){
		var input = document.getElementById('inputChannelName'),
	        inputVal = input.value.trim();

	  	if (inputVal == '') {
	  		return false;
	  	};

	  	session.messages.add({
		  	channelname: inputVal,
		  	time : (new Date()).valueOf() ,
		  	describe : '',
	  	});

	  	session.messages.save();
	  	input.value = '';

	  	session.messages.releaseHold();
		env.redirect("/chatchannel");
	};
});
<|endoftext|>


<commit_before>// $(window).load(function() {
//   $(".loader").fadeOut("slow");
// })

$(document).ready(function() {

  //Reading map file and data

  queue()
  .defer(d3.json, "_json/us.json")
  .defer(d3.json, "_data/master_data.json")
  .await(ready);

  function ready(error, us, food_data) {
   food = food_data
    // ##### Initial View #####

    // *** map_setup.js ****
    food_selection = 'DIRSALES_FARMS07'
    var all_counties = make_county_objects(food, food_selection)

    // *** map.js ****
    draw_map(us, all_counties, food)
    top_list(all_counties, food_selection, food)

    // ##### CORE OF THE PAGE #####

    // make county tags draggable from the start
    drag_and_drop(all_counties, food)

    // Toggle map
    $('#switch-data').on('mousedown', '.radio', function(){
      food_selection = ''
      var toggle = $(this).attr('id')
      if(toggle == 'direct-farm'){
        food_selection = 'DIRSALES_FARMS07'
        var all_counties = make_county_objects(food, food_selection)
        $('#food-search').slideUp(200)
        clear_top_list()
        draw_map(us, all_counties, food)
        top_list(all_counties, food_selection, food)
        $(".draggable").draggable({ disabled: false, stack: '.draggable'});
      }
      else if(toggle == 'food-switch'){
        $('#food-search').slideDown(200)
      }
    })

    // Tooltip + mousevents

    // More info tooltips
    $('#switch-data').on('mouseover', '.more-info', function(){
      var tooltip = $(this).children('.tooltip')
      tooltip.fadeIn(100)
    })

    $('#switch-data').on('mouseout', '.more-info', function(){
      var tooltip = $(this).children('.tooltip')
      tooltip.fadeOut(100)
    })

    // County tag tooltips

    var top_tooltip = d3.select("#top-list").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

    $('#top-list').on('mouseover', '.tag', function(d){
      id = county_id($(this).attr('id'))
      county = find_county_obj(all_counties, id)

      d3.select(this)
        .transition().duration(200)
        .style("opacity", 1);

      top_tooltip.transition().duration(200)
      .style("opacity", 1);
      top_tooltip.text(county.county + " County, " + county.state + "                 " + county.food + ": " + county.food_quant)
      .style("background-color", "#2C3E50")
      .style("left", (d.pageX + -30) + "px")
      .style("top", (d.pageY + 20) + "px");
    })

    $('#top-list').on('mouseout', '.tag', function(d){
        top_tooltip.transition().duration(300)
        .style("opacity", 0);
    })

    // Dock tooltips
    var dock_tooltip = d3.select("#held-counties").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

    $('#county-drilldown').on('mouseover', '.tag', function(d){
      id = county_id($(this).attr('id'))
      county = find_county_obj(all_counties, id)

      d3.select(this)
        .transition().duration(200)
        .style("opacity", 1);

      dock_tooltip.transition().duration(200)
      .style("opacity", 1);
      dock_tooltip.text(county.county + " County, " + county.state + "                 " + county.food + ": " + county.food_quant)
      .style("background-color", "#2C3E50")
      .style("left", (d.pageX + -30) + "px")
      .style("top", (d.pageY + -60) + "px");
    })

    $('#county-drilldown').on('mouseout', '.tag', function(d){
        dock_tooltip.transition().duration(300)
        .style("opacity", 0);
    })

    // Make counties holdable
    $('#top-list').on('click', '.holdable', function(){
      el_id = $(this).attr('id')
      el = d3.select('#'+el_id)

      id = county_id(el_id)
      county = find_county_obj(all_counties, id)
      if(county_not_in_dock(county)){
        hold_county(county)

        // Indiate held
        held_status(county);
        $(".held").draggable({ disabled: true, stack: '.draggable' });

        // Change Map color
        map_html = '#map #county-'+county.id
        map_el = d3.select(map_html)
        map_el.classed({'holdable': false, 'held': true})
        map_el.style('fill', '#3498DB')

        // Make docked elements draggable
        $(".draggable").draggable({ disabled: false, stack: '.draggable'});
      }
    })

    $('#map-container').on('click', '.holdable', function(){
      el_id = $(this).attr('id')
      el = d3.select('#'+el_id)

      id = county_id(el_id)
      county = find_county_obj(all_counties, id)
      if(county_not_in_dock(county)){
        hold_county(county)

        // Indiate held
        held_status(county);
        $(".held").draggable({ disabled: true, stack: '.draggable' });

        // Change Map color
        map_html = '#map #county-'+county.id
        map_el = d3.select(map_html)
        map_el.classed({'holdable': false, 'held': true})
        map_el.style('fill', '#3498DB')

        // Make docked elements draggable
        $(".draggable").draggable({ disabled: false, stack: '.draggable'});
      }
    })
    // Make counties removeable
    $('#held-counties').on('click', '.removeable', function(){
      id = county_id($(this).attr('id'));
      county = find_county_obj(all_counties, id);

      // Remove county
      remove_county(county);
      $('#held-counties').find('.tooltip').remove()

      // clear chart box
      chart_area = $('.drag-here#county-'+county.id)
      input_form = chart_area.prev().children('input')
      input_form.val('')
      reset_search_box(input_form)
      clear_chart_area($(chart_area))
      reset_chart_area($(chart_area))

      // Indiate holdable and draggable again
      holdable_status(county);
      $(".holdable").draggable({ disabled: false, stack: '.draggable'});

      // Change map color and status
      map_html = '#map #county-'+county.id
      map_el = d3.select(map_html)
      map_el.classed({'held': false, 'holdable': true})
      map_el.style ( "fill" , function (d) {return colorRating (all_counties, county.food_quant);});

    })// end removeable

    // Search interactions

    $('#food-search').hide() // hide on load

    $('#food-search-box').on('keyup',function(e) {
      if (e.which == 13){
          food_selection = $(this).val()

          var all_counties = make_county_objects(food, food_selection)

          clear_top_list()
          top_list(all_counties, food_selection, food)

          draw_map(us, all_counties, food)
          $(".draggable").draggable({ disabled: false, stack: '.draggable'});
      }
    });
    $('.county-wrapper').on('keyup','input[type=search]',function(e) {
      if (e.which == 13){
        var chart_area = $(this).parent().next()

        // //remove search box place holder
        input_form = $(this)

        // Change icon
        icon = input_form.next().children('i')
        icon.removeClass('fa-search').addClass('fa-times-circle')

        // Take out message in chart area
        chart_area.find('h4').fadeOut(100)

        // Put county name in search box
        new_placeholder = input_form.val()
        input_form.attr('placeholder', new_placeholder)

        wanted = {}
        all_counties.forEach(function(county){
          if(county.county + ', ' + county.state == new_placeholder){
            wanted = county
          }
          return wanted
        })
        // Find dragged county's foods
        dragged_foods = find_county_foods(food, wanted.id)
        dragged_food_names = get_food_names_list(wanted.id, dragged_foods)
        dragged_food_values = get_food_values_list(wanted.id, dragged_foods)

        // // Render chart based on id
        chart_area.attr('id', 'county-'+wanted.id)
        draw_chart(dragged_food_names, dragged_food_values, chart_area)

        // indicate held county
        docked = $(removeable_county(wanted).addClass('disabled').removeClass('draggable'))
        $('#held-counties').append(docked)
        $(".disabled").draggable({ disabled: true, stack: '.draggable' });
      }
    });

    // Food Autocomplete
    var foods = get_food_list()
    $( "#food-search-box" ).autocomplete({
        source: foods
      });

    // County Autocomplete
    var county_search = []
    all_counties.forEach(function(county){
      county_search.push(county.county + ", " + county.state)
    });
    $( "#left-search-box" ).autocomplete({
        source: county_search
    });

    $( "#right-search-box" ).autocomplete({
        source: county_search
    });
    // Search Interactions
    $('input[type=search]').on('focusin', function(){
      $(this).attr('placeholder', '')
      $(this).attr('value', '')
      $($(this).next()).fadeOut(100)
    }) // end focusin

    $('input[type=search]').on('focusout', function(){
      input_form = $(this)
      current_placeholder = input_form.attr('placeholder')
      if(input_form.attr('name') == 'county-search'){

        drag_here = input_form.parent().next()
        if(drag_here.has('.highcharts-container').length > 0){
          id = county_id(drag_here.attr('id'))
          county = find_county_obj(all_counties, id)
          new_placeholder = county.county + ', ' + county.state
          input_form.attr('placeholder', new_placeholder)
        }
        else{
          input_form.attr('placeholder', 'Search by county')
        }
      }
      else{
        input_form.attr('placeholder', 'Search by food')
      }
      input_form.next().fadeIn(100)
    }) // end focusout

    $('.input-icon i').on('click', function(){
      $(this).removeClass('fa-times-circle').addClass('fa-search')
      chart_area = $(this).parent().parent().next()

      input_form = $(this).parent().prev()
      input_form.val('')
      reset_search_box(input_form)

      icon = $(this)
      icon.removeClass('fa-times-circle').addClass('fa-search')

      // Clear chart area and reset area
      clear_chart_area($(chart_area))
      reset_chart_area($(chart_area))

      var tag_id = $(this).parent().parent().next().attr('id')
      console.log(tag_id)
      // Indicate disabled for dock
      $('#held-counties #'+tag_id).removeClass('disabled').addClass('draggable')

      // Indicate holdable and draggable in top list
      $('#top-list #'+tag_id).removeClass('disabled').removeClass('held').addClass('draggable').addClass('holdable')
      $(".draggable").draggable({ disabled: false, stack: '.draggable'});

    })

  }
});
<commit_msg>CHange map color on search<commit_after>// $(window).load(function() {
//   $(".loader").fadeOut("slow");
// })

$(document).ready(function() {

  //Reading map file and data

  queue()
  .defer(d3.json, "_json/us.json")
  .defer(d3.json, "_data/master_data.json")
  .await(ready);

  function ready(error, us, food_data) {
   food = food_data
    // ##### Initial View #####

    // *** map_setup.js ****
    food_selection = 'DIRSALES_FARMS07'
    var all_counties = make_county_objects(food, food_selection)

    // *** map.js ****
    draw_map(us, all_counties, food)
    top_list(all_counties, food_selection, food)

    // ##### CORE OF THE PAGE #####

    // make county tags draggable from the start
    drag_and_drop(all_counties, food)

    // Toggle map
    $('#switch-data').on('mousedown', '.radio', function(){
      food_selection = ''
      var toggle = $(this).attr('id')
      if(toggle == 'direct-farm'){
        food_selection = 'DIRSALES_FARMS07'
        var all_counties = make_county_objects(food, food_selection)
        $('#food-search').slideUp(200)
        clear_top_list()
        draw_map(us, all_counties, food)
        top_list(all_counties, food_selection, food)
        $(".draggable").draggable({ disabled: false, stack: '.draggable'});
      }
      else if(toggle == 'food-switch'){
        $('#food-search').slideDown(200)
      }
    })

    // Tooltip + mousevents

    // More info tooltips
    $('#switch-data').on('mouseover', '.more-info', function(){
      var tooltip = $(this).children('.tooltip')
      tooltip.fadeIn(100)
    })

    $('#switch-data').on('mouseout', '.more-info', function(){
      var tooltip = $(this).children('.tooltip')
      tooltip.fadeOut(100)
    })

    // County tag tooltips

    var top_tooltip = d3.select("#top-list").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

    $('#top-list').on('mouseover', '.tag', function(d){
      id = county_id($(this).attr('id'))
      county = find_county_obj(all_counties, id)

      d3.select(this)
        .transition().duration(200)
        .style("opacity", 1);

      top_tooltip.transition().duration(200)
      .style("opacity", 1);
      top_tooltip.text(county.county + " County, " + county.state + "                 " + county.food + ": " + county.food_quant)
      .style("background-color", "#2C3E50")
      .style("left", (d.pageX + -30) + "px")
      .style("top", (d.pageY + 20) + "px");
    })

    $('#top-list').on('mouseout', '.tag', function(d){
        top_tooltip.transition().duration(300)
        .style("opacity", 0);
    })

    // Dock tooltips
    var dock_tooltip = d3.select("#held-counties").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

    $('#county-drilldown').on('mouseover', '.tag', function(d){
      id = county_id($(this).attr('id'))
      county = find_county_obj(all_counties, id)

      d3.select(this)
        .transition().duration(200)
        .style("opacity", 1);

      dock_tooltip.transition().duration(200)
      .style("opacity", 1);
      dock_tooltip.text(county.county + " County, " + county.state + "                 " + county.food + ": " + county.food_quant)
      .style("background-color", "#2C3E50")
      .style("left", (d.pageX + -30) + "px")
      .style("top", (d.pageY + -60) + "px");
    })

    $('#county-drilldown').on('mouseout', '.tag', function(d){
        dock_tooltip.transition().duration(300)
        .style("opacity", 0);
    })

    // Make counties holdable
    $('#top-list').on('click', '.holdable', function(){
      el_id = $(this).attr('id')
      el = d3.select('#'+el_id)

      id = county_id(el_id)
      county = find_county_obj(all_counties, id)
      if(county_not_in_dock(county)){
        hold_county(county)

        // Indiate held
        held_status(county);
        $(".held").draggable({ disabled: true, stack: '.draggable' });

        // Change Map color
        map_html = '#map #county-'+county.id
        map_el = d3.select(map_html)
        map_el.classed({'holdable': false, 'held': true})
        map_el.style('fill', '#3498DB')

        // Make docked elements draggable
        $(".draggable").draggable({ disabled: false, stack: '.draggable'});
      }
    })

    $('#map-container').on('click', '.holdable', function(){
      el_id = $(this).attr('id')
      el = d3.select('#'+el_id)

      id = county_id(el_id)
      county = find_county_obj(all_counties, id)
      if(county_not_in_dock(county)){
        hold_county(county)

        // Indiate held
        held_status(county);
        $(".held").draggable({ disabled: true, stack: '.draggable' });

        // Change Map color
        map_html = '#map #county-'+county.id
        map_el = d3.select(map_html)
        map_el.classed({'holdable': false, 'held': true})
        map_el.style('fill', '#3498DB')

        // Make docked elements draggable
        $(".draggable").draggable({ disabled: false, stack: '.draggable'});
      }
    })
    // Make counties removeable
    $('#held-counties').on('click', '.removeable', function(){
      id = county_id($(this).attr('id'));
      county = find_county_obj(all_counties, id);

      // Remove county
      remove_county(county);
      $('#held-counties').find('.tooltip').remove()

      // clear chart box
      chart_area = $('.drag-here#county-'+county.id)
      input_form = chart_area.prev().children('input')
      input_form.val('')
      reset_search_box(input_form)
      clear_chart_area($(chart_area))
      reset_chart_area($(chart_area))

      // Indiate holdable and draggable again
      holdable_status(county);
      $(".holdable").draggable({ disabled: false, stack: '.draggable'});

      // Change map color and status
      map_html = '#map #county-'+county.id
      map_el = d3.select(map_html)
      map_el.classed({'held': false, 'holdable': true})
      map_el.style ( "fill" , function (d) {return colorRating (all_counties, county.food_quant);});

    })// end removeable

    // Search interactions

    $('#food-search').hide() // hide on load

    $('#food-search-box').on('keyup',function(e) {
      if (e.which == 13){
          food_selection = $(this).val()

          var all_counties = make_county_objects(food, food_selection)

          clear_top_list()
          top_list(all_counties, food_selection, food)

          draw_map(us, all_counties, food)
          $(".draggable").draggable({ disabled: false, stack: '.draggable'});
      }
    });
    $('.county-wrapper').on('keyup','input[type=search]',function(e) {
      if (e.which == 13){
        var chart_area = $(this).parent().next()

        // //remove search box place holder
        input_form = $(this)

        // Change icon
        icon = input_form.next().children('i')
        icon.removeClass('fa-search').addClass('fa-times-circle')

        // Take out message in chart area
        chart_area.find('h4').fadeOut(100)

        // Put county name in search box
        new_placeholder = input_form.val()
        input_form.attr('placeholder', new_placeholder)

        wanted = {}
        all_counties.forEach(function(county){
          if(county.county + ', ' + county.state == new_placeholder){
            wanted = county
          }
          return wanted
        })
        // Find dragged county's foods
        dragged_foods = find_county_foods(food, wanted.id)
        dragged_food_names = get_food_names_list(wanted.id, dragged_foods)
        dragged_food_values = get_food_values_list(wanted.id, dragged_foods)

        // // Render chart based on id
        chart_area.attr('id', 'county-'+wanted.id)
        draw_chart(dragged_food_names, dragged_food_values, chart_area)

        // indicate held county
        docked = $(removeable_county(wanted).addClass('disabled').removeClass('draggable'))
        $('#held-counties').append(docked)
        $(".disabled").draggable({ disabled: true, stack: '.draggable' });
      }
    });

    // Food Autocomplete
    var foods = get_food_list()
    $( "#food-search-box" ).autocomplete({
        source: foods
      });

    // County Autocomplete
    var county_search = []
    all_counties.forEach(function(county){
      county_search.push(county.county + ", " + county.state)
    });
    $( "#left-search-box" ).autocomplete({
        source: county_search
    });

    $( "#right-search-box" ).autocomplete({
        source: county_search
    });
    // Search Interactions
    $('input[type=search]').on('focusin', function(){
      $(this).attr('placeholder', '')
      $(this).attr('value', '')
      $($(this).next()).fadeOut(100)
    }) // end focusin

    $('input[type=search]').on('focusout', function(){
      input_form = $(this)
      current_placeholder = input_form.attr('placeholder')
      $('#food-search').slideUp(200)
      if(input_form.attr('name') == 'county-search'){

        drag_here = input_form.parent().next()
        if(drag_here.has('.highcharts-container').length > 0){
          id = county_id(drag_here.attr('id'))
          county = find_county_obj(all_counties, id)
          new_placeholder = county.county + ', ' + county.state
          input_form.attr('placeholder', new_placeholder)
        }
        else{
          input_form.attr('placeholder', 'Search by county')
        }
      }
      else{
        input_form.attr('placeholder', 'Search by food')
      }
      input_form.next().fadeIn(100)
    }) // end focusout

    $('.input-icon i').on('click', function(){
      $(this).removeClass('fa-times-circle').addClass('fa-search')
      chart_area = $(this).parent().parent().next()

      input_form = $(this).parent().prev()
      input_form.val('')
      reset_search_box(input_form)

      icon = $(this)
      icon.removeClass('fa-times-circle').addClass('fa-search')

      // Clear chart area and reset area
      clear_chart_area($(chart_area))
      reset_chart_area($(chart_area))

      var tag_id = $(this).parent().parent().next().attr('id')
      console.log(tag_id)
      // Indicate disabled for dock
      $('#held-counties #'+tag_id).removeClass('disabled').addClass('draggable')

      // Indicate holdable and draggable in top list
      $('#top-list #'+tag_id).removeClass('disabled').removeClass('held').addClass('draggable').addClass('holdable')
      $(".draggable").draggable({ disabled: false, stack: '.draggable'});

    })

  }
});
<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// setup variables
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		// init ui
		this.initMyAccount();

	} // init()

, initMyAccount: function() {

		this.initTabs();

		this.initCko();

		this.initHolds();

		this.initProfile();

  } // initMyAccount()

, initTabs: function() {
		// apply hash onload
		if ( window.location.hash ) {
			$('a[href="'+window.location.hash+'"]').tab('show')
		}

		// apply hashchange on tab event
		//$('body').on('click', '[data-toggle="tab"]', function(e) {
		$('[data-toggle="tab"]').click(function(e) {
			window.location.hash = $(this).attr('href');
		});

	} // initTabs()

, initCko: function() {
		var $form = $('#spl-form-cko');

		this.toggleCheckboxGroup('.spl-field-cko-select-all'
														,'.spl-field-cko-select-item');

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var barcodes = new Array;
				$('.spl-field-cko-select-item:checked').each(function() {
					barcodes.push( $(this).data('barcode') );
				});

				if ( barcodes.length > 0 ) {
					_self.ckoRenew(barcodes);
				} else {
					alert('Please select item(s) to renew.');
				}
			}

		});

	} // initCko()

, ckoRenew: function(barcodes) {
		var $form = $('#spl-form-cko');
		var $submit = $('.spl-submit-cko');
		var $hidden = $('#spl-field-cko-renewal');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'renew' //'renew' //'trace'
    , data: { params: { token: this.user.sessionToken
    									,	barcodes: barcodes
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			$hidden.val(JSON.stringify(obj));
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

	} // ckoRenew()

, initHolds: function() {
		this.initHoldsPending();

	} // initHolds()

, initHoldsPending: function() {
		var $form = $('#spl-form-holds-pending');

		this.toggleCheckboxGroup('.spl-field-holds-pending-select-all'
														,'.spl-field-holds-pending-select-item');

		$('.spl-field-holds-pending-control').click(function(e) {
			$form.data('action', $(this).data('action')).submit();
		});

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var holdkeys = new Array;
				$('.spl-field-holds-pending-select-item:checked').each(function() {
					holdkeys.push( $(this).data('holdkey') );
				});

				if ( holdkeys.length > 0 ) {
					_self.holdsPendingUpdate($(this).data('action'), holdkeys);
					$(this).data('action', '');
				} else {
					alert('Please select hold(s).');
				}

			}

		});

	} // initHoldsPending()

, holdsPendingUpdate: function(action, holdkeys) {
		var $form = $('#spl-form-holds-pending');
		var $submit = $('.spl-field-holds-pending-control');
		var $hidden = $('#spl-field-holds-pending-update');

		var $suspend = $('.spl-field-holds-pending-suspend');

		var $date = $('.spl-field-holds-pending-date');

		/*
		$date.on('change', function(e) {
			if ( $(this).val() ) {
				$suspend.prop('disabled', false);
			}
		});
		*/

		$submit.button('loading'); //$submit.button('reset');

		var data = { params: {token: this.user.sessionToken
	    									,	holdKeys: holdkeys
	    									}
	    					}

		var endpoint;
		switch ( action ) {
			case 'cancel':
				endpoint = 'cancelHolds';
				break;
			case 'pickup':
				endpoint = 'changePickupLocations';
				data.params.newLocation = 'hy';
				break;
			case 'suspend':
				endpoint = 'suspendHolds';
				data.params.suspendEndDate = $date.val();
				break;
			default:
				endpoint = null;
				break;
		}

		if ( null != typeof(endpoint) ) {
			$.ajax({
		    url: this.config.endpoint.hzws+endpoint
	    , data: data
		  })
		  .done(function(obj) {
		  	// pass results through
				$hidden.val(JSON.stringify(obj));
				console.log(obj);
				$submit.button('reset');
				//$form.data('process', 'http').submit();
		  })
		  .fail(function() {
		  })
		  .always(function() {
		  });
		}

	} // holdsPendingUpdate()

, initProfile: function() {
		this.initProfileEmail();
		this.initProfilePin();

	} // initProfile()

, initProfileEmail: function() {
		// it turns out hzws has no methods for updating email
		// will need addres ord? or maybe just select on old address?
		var $form = $('#spl-form-profile-email');
		var $email = $('#spl-field-profile-email');
		var $submit = $('#spl-submit-profile-email');

		$form.validate();

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

	} // initProfileEmail()

, initProfilePin: function() {
	// note: we will need a new session token here (loginUserResetMyPin)
	var $form = $('#spl-form-profile-pin');

	var $submit = $('#spl-submit-profile-pin');

	$form.validate({
		rules: {
			pinConfirm: {
	      equalTo: "#spl-field-profile-pin-new"
	    }
  	}
	});

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

} // initProfilePin()

, toggleCheckboxGroup: function(all, item) {
		var $selectAll = $(all);
		var $selectItem = $(item);

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<commit_msg>suspend holds<commit_after>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// setup variables
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		// init ui
		this.initMyAccount();

	} // init()

, initMyAccount: function() {

		this.initTabs();

		this.initCko();

		this.initHolds();

		this.initProfile();

  } // initMyAccount()

, initTabs: function() {
		// apply hash onload
		if ( window.location.hash ) {
			$('a[href="'+window.location.hash+'"]').tab('show')
		}

		// apply hashchange on tab event
		//$('body').on('click', '[data-toggle="tab"]', function(e) {
		$('[data-toggle="tab"]').click(function(e) {
			window.location.hash = $(this).attr('href');
		});

	} // initTabs()

, initCko: function() {
		var $form = $('#spl-form-cko');

		this.toggleCheckboxGroup('.spl-field-cko-select-all'
														,'.spl-field-cko-select-item');

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var barcodes = new Array;
				$('.spl-field-cko-select-item:checked').each(function() {
					barcodes.push( $(this).data('barcode') );
				});

				if ( barcodes.length > 0 ) {
					_self.ckoRenew(barcodes);
				} else {
					alert('Please select item(s) to renew.');
				}
			}

		});

	} // initCko()

, ckoRenew: function(barcodes) {
		var $form = $('#spl-form-cko');
		var $submit = $('.spl-submit-cko');
		var $hidden = $('#spl-field-cko-renewal');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'renew' //'renew' //'trace'
    , data: { params: { token: this.user.sessionToken
    									,	barcodes: barcodes
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			$hidden.val(JSON.stringify(obj));
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

	} // ckoRenew()

, initHolds: function() {
		this.initHoldsPending();

	} // initHolds()

, initHoldsPending: function() {
		var $form = $('#spl-form-holds-pending');

		this.toggleCheckboxGroup('.spl-field-holds-pending-select-all'
														,'.spl-field-holds-pending-select-item');

		$('.spl-field-holds-pending-control').click(function(e) {
			$form.data('action', $(this).data('action')).submit();
		});

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var holdkeys = new Array;
				$('.spl-field-holds-pending-select-item:checked').each(function() {
					holdkeys.push( $(this).data('holdkey') );
				});

				if ( holdkeys.length > 0 ) {
					_self.holdsPendingUpdate($(this).data('action'), holdkeys);
					$(this).data('action', '');
				} else {
					alert('Please select hold(s).');
				}

			}

		});

	} // initHoldsPending()

, holdsPendingUpdate: function(action, holdkeys) {
		var $form = $('#spl-form-holds-pending');
		var $submit = $('.spl-field-holds-pending-control');
		var $hidden = $('#spl-field-holds-pending-update');

		var $suspend = $('.spl-field-holds-pending-suspend');

		var $date = $('.spl-field-holds-pending-date');

		$.datepicker({autoclose:true})

		/*
		$date.on('change', function(e) {
			if ( $(this).val() ) {
				$suspend.prop('disabled', false);
			}
		});
		*/

		$submit.button('loading'); //$submit.button('reset');

		var data = { params: {token: this.user.sessionToken
	    									,	holdKeys: holdkeys
	    									}
	    					}

		var endpoint;
		switch ( action ) {
			case 'cancel':
				endpoint = 'cancelHolds';
				break;
			case 'pickup':
				endpoint = 'changePickupLocations';
				data.params.newLocation = 'hy';
				break;
			case 'suspend':
				endpoint = 'suspendHolds';
				data.params.suspendEndDate = $date.val();
				break;
			default:
				endpoint = null;
				break;
		}

		if ( null != typeof(endpoint) ) {
			$.ajax({
		    url: this.config.endpoint.hzws+endpoint
	    , data: data
		  })
		  .done(function(obj) {
		  	// pass results through
				$hidden.val(JSON.stringify(obj));
				console.log(obj);
				$submit.button('reset');
				//$form.data('process', 'http').submit();
		  })
		  .fail(function() {
		  })
		  .always(function() {
		  });
		}

	} // holdsPendingUpdate()

, initProfile: function() {
		this.initProfileEmail();
		this.initProfilePin();

	} // initProfile()

, initProfileEmail: function() {
		// it turns out hzws has no methods for updating email
		// will need addres ord? or maybe just select on old address?
		var $form = $('#spl-form-profile-email');
		var $email = $('#spl-field-profile-email');
		var $submit = $('#spl-submit-profile-email');

		$form.validate();

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

	} // initProfileEmail()

, initProfilePin: function() {
	// note: we will need a new session token here (loginUserResetMyPin)
	var $form = $('#spl-form-profile-pin');

	var $submit = $('#spl-submit-profile-pin');

	$form.validate({
		rules: {
			pinConfirm: {
	      equalTo: "#spl-field-profile-pin-new"
	    }
  	}
	});

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

} // initProfilePin()

, toggleCheckboxGroup: function(all, item) {
		var $selectAll = $(all);
		var $selectItem = $(item);

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	}

};
<|endoftext|>


<commit_before>import Events from '../Public/Events.js'

/**
 * 5+ Broadcast.js by NewsNing 宁大大
 */

let BroadCastNext = function () {
    const namespace = 'ni.Broadcast'

    // 获取当前webview
    const getIndexView = (() => {
            // 缓存
            let indexView = null
            return (update = false) => {
                if (update || indexView === null) {
                    indexView = plus.webview.currentWebview()
                }
                return indexView
            }
        })(),
        // 获取全部webview
        getAllWebview = (() => {
            // 缓存
            let allView = null
            return (update = false) => {
                if (update || allView === null) {
                    allView = plus.webview.all()
                }
                return allView
            }
        })(),
        events = new Events()

    //页面通知类
    class Broadcast {
        /**
         * 构造器函数
         */
        constructor() {
        }

        /**
         * 事件监听
         * @param {String} eventName 事件名称
         * @param {Function} callback 事件触发后执行的回调函数
         */
        on(eventName, callback) {
            events.on(eventName, callback)
        }

        /**
         * 事件监听 (单次)
         * @param {String} eventName 事件名称
         * @param {Function} callback 事件触发后执行的回调函数
         */
        once(eventName, callback) {
           events.once(eventName, callback)
        }

        /**
         * 事件触发
         * @param {String} eventName 事件名称
         * @param {Object} data 传参参数值
         * @param {Object} options 其它配置参数
         */
        emit(eventName, data, {
            self = false, // 是否通知自己，默认不通知
            views = [], // 为空数组时，默认通知全部，为string数组时，认为是id，为object时，认为是webview对象
        } = {}) {
            let jsstr = `${namespace} && ${namespace}._emitSelf && ${namespace}._emitSelf('${eventName}', '${JSON.stringify(data)}')`
            this._sendMessage(jsstr, self, views)
        }

        /**
         * 当前页面事件触发
         * @param {String} eventName 事件名称
         * @param {Object} data 传参参数值
         */
        emitSelf(eventName, data) {
            Broadcast._emitSelf(eventName, data)
        }

        /**
         * 事件关闭移除
         * @param {String} eventName 事件名称
         * @param {Object} options 其它配置参数
         */
        off(eventName, {
            self = false, // 是否通知自己，默认不通知
            views = [] // 为空数组时，默认通知全部，为string数组时，认为是id，为object时，认为是webview对象
        } = {}) {
            let jsstr = `${namespace} && ${namespace}._offSelf && ${namespace}._offSelf('${eventName}')`
            this._sendMessage(jsstr, self, views)
        }

        /**
         * 清空当前页面事件
         * @param {String} eventName 事件名称
         */
        offSelf(eventName) {
            Broadcast._offSelf(eventName)
        }

        /**
         * 页面通知
         * @param {String} jsstr 需要运行的js代码
         * @param {Boolean} self 是否通知自己，默认不通知
         * @param {Array} views 为空数组时，默认通知全部，为string数组时，认为是id，为object时，认为是webview对象
         */
        _sendMessage(
            jsstr = '',
            self = false,
            views = []
        ) {
            let all = []
            // 获取 特定 webview 数组
            if (views.length > 0) {
                // 如果是string 类型，则统一处理获取为 webview对象
                // all = views.map(item => typeof item === 'string' ? plus.webview.getWebviewById(item) : item)
                // 防止babel转Sym bol类型
                for(let i = 0, l = views.length; i < l; i++){
                    let item = views[i]
                    if(typeof item  === 'string'){
                        item = plus.webview.getWebviewById(item)
                        if(!item){
                            // 页面不存在则 中止当前循环
                            continue;
                        }
                    }
                    all.push(item)
                }

            } else {
                // 不特定通知的webview数组时，直接获取全部已存在的webview
                all = getAllWebview(true)
            }
            // 如果不需要通知到当前webview 则过滤
            if (!self) {
                let v = getIndexView()
                // all = all.filter(item => item.id !== v.id)
                // 防止babel转Sym bol类型
                var index = -1
                for(let i = 0, l = all.length; i < l; i++){
                    let item = all[i];
                    if(item.id === v.id){
                        index = i
                        break
                    }
                }
                if(index >= 0){
                    all.splice(index, 1)
                }
            }
            // 遍历全部页面
            //for (let v of all) {
             //   v.evalJS(jsstr)
            //}

            for(let i = 0, l = all.length; i < l; i++){
                all[i].evalJS(jsstr)
            }
        }

        static _emitSelf(eventName, data) {
            if (typeof data === 'string') {
                data = JSON.parse(data)
            }
            events.emit(eventName, data)
        }

        static _offSelf(eventName) {
            events.off(eventName)
        }

    }
    return Broadcast
}()

if(window !== undefined){
    window.ni = {
        Broadcast: BroadCastNext
    }
}

export default BroadCastNext<commit_msg>修复 Broadcast.next.js 中 JSON 转义解析错误的问题<commit_after>import Events from '../Public/Events.js'

/**
 * 5+ Broadcast.js by NewsNing 宁大大
 */

let BroadCastNext = function () {
    const namespace = 'ni.Broadcast'

    // 获取当前webview
    const getIndexView = (() => {
            // 缓存
            let indexView = null
            return (update = false) => {
                if (update || indexView === null) {
                    indexView = plus.webview.currentWebview()
                }
                return indexView
            }
        })(),
        // 获取全部webview
        getAllWebview = (() => {
            // 缓存
            let allView = null
            return (update = false) => {
                if (update || allView === null) {
                    allView = plus.webview.all()
                }
                return allView
            }
        })(),
        events = new Events()

    //页面通知类
    class Broadcast {
        /**
         * 构造器函数
         */
        constructor() {
        }

        /**
         * 事件监听
         * @param {String} eventName 事件名称
         * @param {Function} callback 事件触发后执行的回调函数
         */
        on(eventName, callback) {
            events.on(eventName, callback)
        }

        /**
         * 事件监听 (单次)
         * @param {String} eventName 事件名称
         * @param {Function} callback 事件触发后执行的回调函数
         */
        once(eventName, callback) {
           events.once(eventName, callback)
        }

        /**
         * 事件触发
         * @param {String} eventName 事件名称
         * @param {Object} data 传参参数值
         * @param {Object} options 其它配置参数
         */
        emit(eventName, data, {
            self = false, // 是否通知自己，默认不通知
            views = [], // 为空数组时，默认通知全部，为string数组时，认为是id，为object时，认为是webview对象
        } = {}) {
            let jsstr = `${namespace} && ${namespace}._emitSelf && ${namespace}._emitSelf('${eventName}', ${JSON.stringify(data)})`
            this._sendMessage(jsstr, self, views)
        }

        /**
         * 当前页面事件触发
         * @param {String} eventName 事件名称
         * @param {Object} data 传参参数值
         */
        emitSelf(eventName, data) {
            Broadcast._emitSelf(eventName, data)
        }

        /**
         * 事件关闭移除
         * @param {String} eventName 事件名称
         * @param {Object} options 其它配置参数
         */
        off(eventName, {
            self = false, // 是否通知自己，默认不通知
            views = [] // 为空数组时，默认通知全部，为string数组时，认为是id，为object时，认为是webview对象
        } = {}) {
            let jsstr = `${namespace} && ${namespace}._offSelf && ${namespace}._offSelf('${eventName}')`
            this._sendMessage(jsstr, self, views)
        }

        /**
         * 清空当前页面事件
         * @param {String} eventName 事件名称
         */
        offSelf(eventName) {
            Broadcast._offSelf(eventName)
        }

        /**
         * 页面通知
         * @param {String} jsstr 需要运行的js代码
         * @param {Boolean} self 是否通知自己，默认不通知
         * @param {Array} views 为空数组时，默认通知全部，为string数组时，认为是id，为object时，认为是webview对象
         */
        _sendMessage(
            jsstr = '',
            self = false,
            views = []
        ) {
            let all = []
            // 获取 特定 webview 数组
            if (views.length > 0) {
                // 如果是string 类型，则统一处理获取为 webview对象
                // all = views.map(item => typeof item === 'string' ? plus.webview.getWebviewById(item) : item)
                // 防止babel转Sym bol类型
                for(let i = 0, l = views.length; i < l; i++){
                    let item = views[i]
                    if(typeof item  === 'string'){
                        item = plus.webview.getWebviewById(item)
                        if(!item){
                            // 页面不存在则 中止当前循环
                            continue;
                        }
                    }
                    all.push(item)
                }

            } else {
                // 不特定通知的webview数组时，直接获取全部已存在的webview
                all = getAllWebview(true)
            }
            // 如果不需要通知到当前webview 则过滤
            if (!self) {
                let v = getIndexView()
                // all = all.filter(item => item.id !== v.id)
                // 防止babel转Sym bol类型
                var index = -1
                for(let i = 0, l = all.length; i < l; i++){
                    let item = all[i];
                    if(item.id === v.id){
                        index = i
                        break
                    }
                }
                if(index >= 0){
                    all.splice(index, 1)
                }
            }
            // 遍历全部页面
            //for (let v of all) {
             //   v.evalJS(jsstr)
            //}

            for(let i = 0, l = all.length; i < l; i++){
                all[i].evalJS(jsstr)
            }
        }

        static _emitSelf(eventName, data) {
            if (typeof data === 'string') {
                data = JSON.parse(data)
            }
            events.emit(eventName, data)
        }

        static _offSelf(eventName) {
            events.off(eventName)
        }

    }
    return Broadcast
}()

if(window !== undefined){
    window.ni = {
        Broadcast: BroadCastNext
    }
}

export default BroadCastNext<|endoftext|>


<commit_before>// Placeholder manifest file.
// the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/frontend/all.js'

//= require spree/frontend/jquery.menu-aim
<commit_msg>Assets<commit_after>// Placeholder manifest file.
// the installer will append this file to the app vendored assets here: vendor/assets/javascripts/spree/frontend/all.js'

//= require spree/frontend/jquery.menu-aim
//= require_tree .
<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	/*
	config: {
						api: { hzws: 'http://api.spokanelibrary.org/v2/request/'
									,oclc: 'http://api.spokanelibrary.org/oclc/'
								 }
					 }
	*/
	// added on authentication
	//user: {}

	// called on script load
	init: function() {
		_self = this;

		this.config = ORG.config;

		this.setUser();

		// init ui
		this.initRequestItem();

	} // init()

, setUser: function(user) {
		if ( !ORG.user ) {
			ORG.setUser(user);
		}
		this.user = ORG.user;
}

, initRequestItem: function() {

		console.log(this.user);

		this.initRequestItemPanels();
		this.initOCLC();

  } // initRequestItem()

, initOCLC: function() {

		$('body').on('click', '#spl-form-oclc-search', function(e) {
      e.preventDefault();
      _self.oclcSearchKeyword();
    });
    $('body').on('keypress', '#spl-form-search', function(e) {
      // 13 == enter
      if (e.keyCode == 13) {
        e.preventDefault();
        _self.oclcSearchKeyword();
      }
    });

} // initOCLC()

, oclcSearchKeyword: function(start) {

		var query = $('#spl-form-search').val();
		var $modal = $('#spl-form-oclc-result');

		if ( !start ) {
      start = 1;
    }

    if ( query ) {

    	var search = { query }

    	var tmpl = Handlebars.compile( $('#oclc-search-tmpl').html() );
      $modal.html(tmpl(search)).modal('show');

    	//console.log(this.config);

    	//$modal.modal('show');

    	/*
    	console.log(this.config.api.oclc);
    	console.log(query);

    	$.ajax({
        url: this.config.api.oclc
        ,data: { sru: query // q: $('#spl-form-title').val()
                ,mt: $('#spl-form-material').val()
                ,index: $('#spl-form-search-index').val()
                ,sort: $('#spl-form-search-sort').val()
                ,start: start
                ,count: 20
                }
      })
      .done(function(results) {
        //var tmpl = Handlebars.compile( $('#oclc-results-tmpl').html() );
        //$modal.html(tmpl(results)).modal('show');
        console.log(results);
      })
      .fail(function() {
      })
      .always(function() {
        //$('#spl-form-lookup-loading').hide();
        //_self.global.formEnable();
      });
			*/

    }

}

, initRequestItemPanels: function() {
		/*
		$('body').on('change', 'input:radio[name = "spl-form[material]"]', function() {
			var materialTypeDescription = $(this).parent().text();
			console.log(materialTypeDescription);
		});
		*/

		// hide material type selectors and generic request form on select
		$('body').on('show.bs.collapse', '#spl-form-request-panels', function() {
			$('#spl-form-request-panel-choose').collapse('hide');
		});

		// show generic request form when requested
		$('body').on('show.bs.collapse', '.spl-form-request-generic', function() {

			if ( $(this).hasClass('spl-form-request-download') ) {
				$('#spl-form-request-submit-item').hide();
				$('#spl-form-request-submit-download').show();
			} else {
				$('#spl-form-request-submit-item').show();
				$('#spl-form-request-submit-download').hide();
			}

			$('#spl-form-panel-request').collapse('show');

		});

		// hide generic request form when not requested
		$('body').on('shown.bs.collapse', '.spl-form-request-specific', function() {
			$('#spl-form-panel-request').collapse('hide');
		});

} // initRequestItemPanels

};
<commit_msg>results<commit_after>// account.js

var org = {

	// added on script load
	/*
	config: {
						api: { hzws: 'http://api.spokanelibrary.org/v2/request/'
									,oclc: 'http://api.spokanelibrary.org/oclc/'
								 }
					 }
	*/
	// added on authentication
	//user: {}

	// called on script load
	init: function() {
		_self = this;

		this.config = ORG.config;

		this.setUser();

		// init ui
		this.initRequestItem();

	} // init()

, setUser: function(user) {
		if ( !ORG.user ) {
			ORG.setUser(user);
		}
		this.user = ORG.user;
}

, initRequestItem: function() {

		console.log(this.user);

		this.initRequestItemPanels();
		this.initOCLC();

  } // initRequestItem()

, initOCLC: function() {

		$('body').on('click', '#spl-form-oclc-search', function(e) {
      e.preventDefault();
      _self.oclcSearchKeyword();
    });
    $('body').on('keypress', '#spl-form-search', function(e) {
      // 13 == enter
      if (e.keyCode == 13) {
        e.preventDefault();
        _self.oclcSearchKeyword();
      }
    });

} // initOCLC()

, oclcSearchKeyword: function(start) {

		var query = $('#spl-form-search').val();
		var $modal = $('#spl-form-oclc-result');

		if ( !start ) {
      start = 1;
    }

    if ( query ) {

    	var search = { query };

    	var tmpl = Handlebars.compile( $('#oclc-search-tmpl').html() );
      $modal.html(tmpl(search)).modal('show');

    	//console.log(this.config);

    	//$modal.modal('show');

    	/*
    	console.log(this.config.api.oclc);
    	console.log(query);

    	$.ajax({
        url: this.config.api.oclc
        ,data: { sru: query // q: $('#spl-form-title').val()
                ,mt: $('#spl-form-material').val()
                ,index: $('#spl-form-search-index').val()
                ,sort: $('#spl-form-search-sort').val()
                ,start: start
                ,count: 20
                }
      })
      .done(function(results) {
        //var tmpl = Handlebars.compile( $('#oclc-results-tmpl').html() );
        //$modal.html(tmpl(results)).modal('show');
        console.log(results);
      })
      .fail(function() {
      })
      .always(function() {
        //$('#spl-form-lookup-loading').hide();
        //_self.global.formEnable();
      });
			*/

    }

}

, initRequestItemPanels: function() {
		/*
		$('body').on('change', 'input:radio[name = "spl-form[material]"]', function() {
			var materialTypeDescription = $(this).parent().text();
			console.log(materialTypeDescription);
		});
		*/

		// hide material type selectors and generic request form on select
		$('body').on('show.bs.collapse', '#spl-form-request-panels', function() {
			$('#spl-form-request-panel-choose').collapse('hide');
		});

		// show generic request form when requested
		$('body').on('show.bs.collapse', '.spl-form-request-generic', function() {

			if ( $(this).hasClass('spl-form-request-download') ) {
				$('#spl-form-request-submit-item').hide();
				$('#spl-form-request-submit-download').show();
			} else {
				$('#spl-form-request-submit-item').show();
				$('#spl-form-request-submit-download').hide();
			}

			$('#spl-form-panel-request').collapse('show');

		});

		// hide generic request form when not requested
		$('body').on('shown.bs.collapse', '.spl-form-request-specific', function() {
			$('#spl-form-panel-request').collapse('hide');
		});

} // initRequestItemPanels

};
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Controller.extend({
  store: Ember.inject.service(),
  performanceSortProperties: ['slot', 'performer.total_score:desc',],
  sortedPerformances: Ember.computed.sort(
    'model.performances',
    'performanceSortProperties'
  ),
  isEditing: false,
  isRaw: false,
  actions: {
    sortBy(performanceSortProperties) {
      this.set('performanceSortProperties', [performanceSortProperties]);
    },
    editOrder() {
      this.set('isEditing', true);
    },
    saveOrder() {
      let children = this.get('model.performances');
      children.forEach(function(item) {
        item.save();
      });
      this.set('isEditing', false);
    },
    cancelOrder() {
      let children = this.get('model.performances');
      children.forEach(function(item) {
        item.rollbackAttributes();
      });
      this.set('isEditing', false);
    },
    reorderItems(itemModels) {
      itemModels.forEach(function(item, index) {
        let slot = item.get('slot');
        console.log('Slot %@: %@ %@'.fmt(index+1, slot));
        item.set('slot', index+1);
      });
    },
    saveDate(start, end) {
      this.model.set('date.lower', start);
      this.model.set('date.upper', end);
      this.model.save();
    },
    letsGo() {
      this.toggleProperty('isRaw');
    },
    deletePerformance(performance) {
      performance.destroyRecord();
    },
    drawRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.draw()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
      this.model.reload();
    },
    promoteRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.promote()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
      this.model.reload();
    },
    resortRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.resort()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
      this.model.reload();
    },
    startRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.start()
      .then((response) => {
        this.store.pushPayload('round', response);
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
    },
    finishRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.finish()
      .then((response) => {
        this.store.pushPayload('round', response);
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
    },
    promoteRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.promote()
      .then((response) => {
        this.store.pushPayload('round', response);
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
    },
    moveTop(performance) {
      const flashMessages = Ember.get(this, 'flashMessages');
      performance.move_top()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      })
      .finally(()=>{
        this.get('model.performances').sortBy('performance.slot');
      });
    },
    moveUp(performance) {
      const flashMessages = Ember.get(this, 'flashMessages');

      performance.move_up()
      .then(() => {
        flashMessages.success('Success');
        let reloaded =  this.get('model.performances').map( performance => performance.reload() );
        return Ember.RSVP.all(reloaded);
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
    },
    moveDown(performance) {
      const flashMessages = Ember.get(this, 'flashMessages');
      performance.move_down()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      })
      .finally(()=>{
        this.get('model.performances').sortBy('performance.slot');
      });
    },
    moveBottom(performance) {
      const flashMessages = Ember.get(this, 'flashMessages');
      performance.move_bottom()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
      performance.reload();
    },
    scratch(performance) {
      const flashMessages = Ember.get(this, 'flashMessages');
      performance.scratch()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      })
      .finally(()=>{
        this.get('model.performances').removeObject(performance);
      });
    },
  },
});
<commit_msg>Remove duplicate promote method from Round<commit_after>import Ember from 'ember';

export default Ember.Controller.extend({
  store: Ember.inject.service(),
  performanceSortProperties: ['slot', 'performer.total_score:desc',],
  sortedPerformances: Ember.computed.sort(
    'model.performances',
    'performanceSortProperties'
  ),
  isEditing: false,
  isRaw: false,
  actions: {
    sortBy(performanceSortProperties) {
      this.set('performanceSortProperties', [performanceSortProperties]);
    },
    editOrder() {
      this.set('isEditing', true);
    },
    saveOrder() {
      let children = this.get('model.performances');
      children.forEach(function(item) {
        item.save();
      });
      this.set('isEditing', false);
    },
    cancelOrder() {
      let children = this.get('model.performances');
      children.forEach(function(item) {
        item.rollbackAttributes();
      });
      this.set('isEditing', false);
    },
    reorderItems(itemModels) {
      itemModels.forEach(function(item, index) {
        let slot = item.get('slot');
        console.log('Slot %@: %@ %@'.fmt(index+1, slot));
        item.set('slot', index+1);
      });
    },
    saveDate(start, end) {
      this.model.set('date.lower', start);
      this.model.set('date.upper', end);
      this.model.save();
    },
    letsGo() {
      this.toggleProperty('isRaw');
    },
    deletePerformance(performance) {
      performance.destroyRecord();
    },
    drawRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.draw()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
      this.model.reload();
    },
    resortRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.resort()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
      this.model.reload();
    },
    startRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.start()
      .then((response) => {
        this.store.pushPayload('round', response);
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
    },
    finishRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.finish()
      .then((response) => {
        this.store.pushPayload('round', response);
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
    },
    promoteRound() {
      const flashMessages = Ember.get(this, 'flashMessages');
      this.model.promote()
      .then((response) => {
        this.store.pushPayload('round', response);
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
    },
    moveTop(performance) {
      const flashMessages = Ember.get(this, 'flashMessages');
      performance.move_top()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      })
      .finally(()=>{
        this.get('model.performances').sortBy('performance.slot');
      });
    },
    moveUp(performance) {
      const flashMessages = Ember.get(this, 'flashMessages');

      performance.move_up()
      .then(() => {
        flashMessages.success('Success');
        let reloaded =  this.get('model.performances').map( performance => performance.reload() );
        return Ember.RSVP.all(reloaded);
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
    },
    moveDown(performance) {
      const flashMessages = Ember.get(this, 'flashMessages');
      performance.move_down()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      })
      .finally(()=>{
        this.get('model.performances').sortBy('performance.slot');
      });
    },
    moveBottom(performance) {
      const flashMessages = Ember.get(this, 'flashMessages');
      performance.move_bottom()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      });
      performance.reload();
    },
    scratch(performance) {
      const flashMessages = Ember.get(this, 'flashMessages');
      performance.scratch()
      .then(() => {
        flashMessages.success('Success');
      })
      .catch(() => {
        flashMessages.danger('Error');
      })
      .finally(()=>{
        this.get('model.performances').removeObject(performance);
      });
    },
  },
});
<|endoftext|>


<commit_before>pc.script.create('first_person_camera', function (app) {
	var SPEED = 1200;

	//var camPos = new pc.Vec3();
	var FirstPersonCamera = function (entity) {
		this.entity = entity;

		// Camera euler angle rotation around x and y axes
		var eulers = this.entity.getEulerAngles();
		this.ex = eulers.x;
		this.ey = eulers.y;

		// Disabling the app menu stops the browser displaying a menu when
		// you right-click the page
		app.mouse.disableContextMenu();
		app.mouse.on(pc.EVENT_MOUSEMOVE, this.onMouseMove, this);
		app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown, this);

	};

	FirstPersonCamera.prototype = {
		mouseLook: false,
		moveForwardLock: false,
		update: function (dt) {
			if(this.mouseLook) {
				this.entity.setEulerAngles(this.ex, this.ey, 0);
			}

			if (this.moveForwardLock) {
				this.entity.translate(SPEED*dt, 0, 0);
			}
			else if (app.keyboard.isPressed(pc.KEY_UP)) {
				this.entity.translateLocal(0, 0, -SPEED*dt);
			} else if (app.keyboard.isPressed(pc.KEY_DOWN)) {
				this.entity.translateLocal(0, 0, SPEED*dt);
			}

			if (app.keyboard.isPressed(pc.KEY_LEFT)) {
				this.entity.translateLocal(-SPEED*dt, 0, 0);
			} else if (app.keyboard.isPressed(pc.KEY_RIGHT)) {
				this.entity.translateLocal(SPEED*dt, 0, 0);
			}
		},

		onMouseMove: function (event) {
			// Update the current Euler angles, clamp the pitch.
			this.ex -= event.dy / 5;
			this.ex = pc.math.clamp(this.ex, -90, 90);
			this.ey -= event.dx / 5;
		},

		onMouseDown: function () { //event is given as arg
			// When the mouse button is clicked try and capture the pointer
			if (!pc.Mouse.isPointerLocked()) {
				app.mouse.enablePointerLock();
			}
		},

		setPosition: function(position) {
			this.entity.setPosition(position[0], position[1], position[2]);
		},

		setEulerAngles: function(x, y, z) {
			this.entity.setEulerAngles(x,y,z);
		}
	};

	return FirstPersonCamera;
});
<commit_msg>Bump speed further<commit_after>pc.script.create('first_person_camera', function (app) {
	var SPEED = 2500;

	//var camPos = new pc.Vec3();
	var FirstPersonCamera = function (entity) {
		this.entity = entity;

		// Camera euler angle rotation around x and y axes
		var eulers = this.entity.getEulerAngles();
		this.ex = eulers.x;
		this.ey = eulers.y;

		// Disabling the app menu stops the browser displaying a menu when
		// you right-click the page
		app.mouse.disableContextMenu();
		app.mouse.on(pc.EVENT_MOUSEMOVE, this.onMouseMove, this);
		app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown, this);

	};

	FirstPersonCamera.prototype = {
		mouseLook: false,
		moveForwardLock: false,
		update: function (dt) {
			if(this.mouseLook) {
				this.entity.setEulerAngles(this.ex, this.ey, 0);
			}

			if (this.moveForwardLock) {
				this.entity.translate(SPEED*dt, 0, 0);
			}
			else if (app.keyboard.isPressed(pc.KEY_UP)) {
				this.entity.translateLocal(0, 0, -SPEED*dt);
			} else if (app.keyboard.isPressed(pc.KEY_DOWN)) {
				this.entity.translateLocal(0, 0, SPEED*dt);
			}

			if (app.keyboard.isPressed(pc.KEY_LEFT)) {
				this.entity.translateLocal(-SPEED*dt, 0, 0);
			} else if (app.keyboard.isPressed(pc.KEY_RIGHT)) {
				this.entity.translateLocal(SPEED*dt, 0, 0);
			}
		},

		onMouseMove: function (event) {
			// Update the current Euler angles, clamp the pitch.
			this.ex -= event.dy / 5;
			this.ex = pc.math.clamp(this.ex, -90, 90);
			this.ey -= event.dx / 5;
		},

		onMouseDown: function () { //event is given as arg
			// When the mouse button is clicked try and capture the pointer
			if (!pc.Mouse.isPointerLocked()) {
				app.mouse.enablePointerLock();
			}
		},

		setPosition: function(position) {
			this.entity.setPosition(position[0], position[1], position[2]);
		},

		setEulerAngles: function(x, y, z) {
			this.entity.setEulerAngles(x,y,z);
		}
	};

	return FirstPersonCamera;
});
<|endoftext|>


<commit_before>import { PureComponent } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import reducerRegistry from 'app/registry';

import * as actions from './whitelists-provider-actions';
import reducers, { initialState } from './whitelists-provider-reducers';

const mapStateToProps = ({ location }) => ({
  location: location && location.payload
});

class WhitelistProvider extends PureComponent {
  componentDidMount() {
    const {
      location: { adm0, adm1, adm2 },
      getCountryWhitelist,
      getRegionWhitelist
    } = this.props;
    getCountryWhitelist(adm0);
    if (adm1) {
      getRegionWhitelist({ adm0, adm1, adm2 });
    }
  }

  componentDidUpdate(prevProps) {
    const { location: { adm0, adm1, adm2 } } = this.props;
    const { getCountryWhitelist, getRegionWhitelist } = prevProps;
    const hasCountryChanged = adm0 && adm0 !== prevProps.location.adm0;
    const hasRegionChanged = adm0 && adm1 !== prevProps.location.adm1;
    const hasSubRegionChanged =
      adm0 && adm1 && adm2 !== prevProps.location.adm2;

    if (hasCountryChanged) {
      getCountryWhitelist(adm0);
    }

    if (hasRegionChanged || hasSubRegionChanged) {
      getRegionWhitelist({ adm0, adm1, adm2 });
    }
  }

  render() {
    return null;
  }
}

WhitelistProvider.propTypes = {
  location: PropTypes.object.isRequired,
  getCountryWhitelist: PropTypes.func.isRequired,
  getRegionWhitelist: PropTypes.func.isRequired
};

reducerRegistry.registerModule('whitelists', {
  actions,
  reducers,
  initialState
});

export default connect(mapStateToProps, actions)(WhitelistProvider);
<commit_msg>fix fetch for country white list on global level<commit_after>import { PureComponent } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import reducerRegistry from 'app/registry';

import * as actions from './whitelists-provider-actions';
import reducers, { initialState } from './whitelists-provider-reducers';

const mapStateToProps = ({ location }) => ({
  location: location && location.payload
});

class WhitelistProvider extends PureComponent {
  componentDidMount() {
    const {
      location: { adm0, adm1, adm2 },
      getCountryWhitelist,
      getRegionWhitelist
    } = this.props;
    if (adm0) {
      getCountryWhitelist(adm0);
    }
    if (adm1) {
      getRegionWhitelist({ adm0, adm1, adm2 });
    }
  }

  componentDidUpdate(prevProps) {
    const { location: { adm0, adm1, adm2 } } = this.props;
    const { getCountryWhitelist, getRegionWhitelist } = prevProps;
    const hasCountryChanged = adm0 && adm0 !== prevProps.location.adm0;
    const hasRegionChanged = adm0 && adm1 !== prevProps.location.adm1;
    const hasSubRegionChanged =
      adm0 && adm1 && adm2 !== prevProps.location.adm2;

    if (hasCountryChanged) {
      getCountryWhitelist(adm0);
    }

    if (hasRegionChanged || hasSubRegionChanged) {
      getRegionWhitelist({ adm0, adm1, adm2 });
    }
  }

  render() {
    return null;
  }
}

WhitelistProvider.propTypes = {
  location: PropTypes.object.isRequired,
  getCountryWhitelist: PropTypes.func.isRequired,
  getRegionWhitelist: PropTypes.func.isRequired
};

reducerRegistry.registerModule('whitelists', {
  actions,
  reducers,
  initialState
});

export default connect(mapStateToProps, actions)(WhitelistProvider);
<|endoftext|>