<commit_before>/* global define:false */
define(['lodash', 'jquery', 'app/config'], function(_, $, Config) {
	"use strict";

	var KEY_MAP = Config.get('general.keyMap');
	var KEY_DISPLAY_GROUPS = Config.get('general.keyDisplayGroups');
	var KEY_SIGNATURE_MAP = Config.get('general.keySignatureMap');

	var KeySignatureWidget = function(keySignature, settings) {
		this.settings = settings || {};
		this.settings = _.merge({
			widgetCls: "widget-keysignature widget-keysignature-header",
			lockedCls: "ioncustom-siglocked",
			unlockedCls: "ioncustom-sigunlocked"
		}, settings);
		this.lock = keySignature.locked();
		this.keySignature = keySignature;
		this.el = $('

');
		this.initListeners();
	};

	_.extend(KeySignatureWidget.prototype, {
		// initialize event listeners
		initListeners: function() {
			var that = this;

			// delegate change events on the root element
			this.el.on('change', function(e) {
				var target = e.target;
				if(target === that.keyEl[0]) {
					that.keySignature.changeKey($(target).val(), that.lock);
					that.render();
				} else if(target === that.signatureEl[0]) {
					that.keySignature.changeSignatureKey($(target).val(), that.lock);
					that.render();
				}
			});
			this.el.on('click', function(e) {
				var target = e.target;
				if(target == that.lockEl[0]) {
					that._updateSignatureLock();
					that.keySignature.changeSignatureLock(that.lock);
				}
			});

			// observe changes to key signature and refresh when needed
			this.keySignature.bind('change', function() {
				that.lock = this.locked();
				that.render();
			});
		},
		// render the control elements
		render: function() {
			this._renderKeySelector();
			this._renderSignatureLock();
			this._renderSignatureSelector();
			this.el.empty();
			this.el.append(this.keyEl, this.lockContainerEl, this.signatureEl);
			return this;
		},
		// renders the lock checkbox that is used to bind the key and signature
		// together (change one and the other should change accordingly).
		_renderSignatureLock: function() {
			var lock = (this.lock ? true : false);
			var lockCls = ['btn ion-locked '+this.settings.lockedCls,'btn ion-unlocked '+this.settings.unlockedCls];
			var lockContainerEl = $("");
			var lockEl = $('');
			var style='style="margin: 0 10px"';

			lockContainerEl.append('').append(lockEl).append('');

			this.lockCls = lockCls;
			this.lockEl = lockEl;
			this.lockContainerEl = lockContainerEl;

			return this;
		},
		// updates the signature lock based on the value of the
		_updateSignatureLock: function() {
			var lockCls = this.lockCls.slice(0);

			this.lock = (this.lockEl.data('lock') == "yes" ? false : true);
			if(this.lock) {
				lockCls.reverse();
			}
			this.lockEl.removeClass(lockCls[0]).addClass(lockCls[1]);
			this.lockEl.data('lock', (this.lock?'yes':'no'));
		},
		// renders a selectable list of signatures
		_renderSignatureSelector: function() {
			var select = document.createElement('select');
			select.name = "keysignature";
			var selected_signature = this.keySignature.getSignatureSpec();

			_.each(KEY_SIGNATURE_MAP, function(key, signature) {
				var option = document.createElement('option');
				option.text = signature;
				option.value = key;
				if(signature === selected_signature) {
					option.selected = true;
				}
				select.appendChild(option);
			});

			this.signatureEl = $(select);
			return this;
		},
		// renders a selectable list of keys
		_renderKeySelector: function() {
			var select = document.createElement('select');
			select.name = "key";
			var selected_key = this.keySignature.getKey();

			_.each(KEY_DISPLAY_GROUPS, function(keyList, index) {
				var optgroup = document.createElement('optgroup');
				optgroup.label = keyList[0];

				_.each(keyList.slice(1), function(key, index) {
					var opt = document.createElement('option');
					opt.value = key;
					opt.text = KEY_MAP[key].name;
					if(key === selected_key) {
						opt.selected = true;
					}
					optgroup.appendChild(opt);
				});

				select.appendChild(optgroup);
			});

			this.keyEl = $(select);
			return this;
		}
	});

	return KeySignatureWidget;
});
<commit_msg>Update key_signature.js<commit_after>/* global define:false */
define(['lodash', 'jquery', 'app/config'], function(_, $, Config) {
	"use strict";

	var KEY_MAP = Config.get('general.keyMap');
	var KEY_DISPLAY_GROUPS = Config.get('general.keyDisplayGroups');
	var KEY_SIGNATURE_MAP = Config.get('general.keySignatureMap');

	var KeySignatureWidget = function(keySignature, settings) {
		this.settings = settings || {};
		this.settings = _.merge({
			widgetCls: "widget-keysignature widget-keysignature-header",
			lockedCls: "ioncustom-siglocked",
			unlockedCls: "ioncustom-sigunlocked"
		}, settings);
		this.lock = keySignature.locked();
		this.keySignature = keySignature;
		this.el = $('

');
		this.initListeners();
	};

	_.extend(KeySignatureWidget.prototype, {
		// initialize event listeners
		initListeners: function() {
			var that = this;

			// delegate change events on the root element
			this.el.on('change', function(e) {
				var target = e.target;
				if(target === that.keyEl[0]) {
					that.keySignature.changeKey($(target).val(), that.lock);
					that.render();
				} else if(target === that.signatureEl[0]) {
					that.keySignature.changeSignatureKey($(target).val(), that.lock);
					that.render();
				}
			});
			this.el.on('click', function(e) {
				var target = e.target;
				if(target == that.lockEl[0]) {
					that._updateSignatureLock();
					that.keySignature.changeSignatureLock(that.lock);
				}
			});

			// observe changes to key signature and refresh when needed
			this.keySignature.bind('change', function() {
				that.lock = this.locked();
				that.render();
			});
		},
		// render the control elements
		render: function() {
			this._renderKeySelector();
			this._renderSignatureLock();
			this._renderSignatureSelector();
			this.el.empty();
			this.el.append(this.keyEl, this.lockContainerEl, this.signatureEl);
			return this;
		},
		// renders the lock checkbox that is used to bind the key and signature
		// together (change one and the other should change accordingly).
		_renderSignatureLock: function() {
			var lock = (this.lock ? true : false);
			var lockCls = ['btn ion-locked '+this.settings.lockedCls,'btn ion-unlocked '+this.settings.unlockedCls];
			var lockContainerEl = $("");
			var lockEl = $('');
			var style='style="margin: 0 10px"';

			lockContainerEl.append(lockEl);

			this.lockCls = lockCls;
			this.lockEl = lockEl;
			this.lockContainerEl = lockContainerEl;

			return this;
		},
		// updates the signature lock based on the value of the
		_updateSignatureLock: function() {
			var lockCls = this.lockCls.slice(0);

			this.lock = (this.lockEl.data('lock') == "yes" ? false : true);
			if(this.lock) {
				lockCls.reverse();
			}
			this.lockEl.removeClass(lockCls[0]).addClass(lockCls[1]);
			this.lockEl.data('lock', (this.lock?'yes':'no'));
		},
		// renders a selectable list of signatures
		_renderSignatureSelector: function() {
			var select = document.createElement('select');
			select.name = "keysignature";
			var selected_signature = this.keySignature.getSignatureSpec();

			_.each(KEY_SIGNATURE_MAP, function(key, signature) {
				var option = document.createElement('option');
				option.text = signature;
				option.value = key;
				if(signature === selected_signature) {
					option.selected = true;
				}
				select.appendChild(option);
			});

			this.signatureEl = $(select);
			return this;
		},
		// renders a selectable list of keys
		_renderKeySelector: function() {
			var select = document.createElement('select');
			select.name = "key";
			var selected_key = this.keySignature.getKey();

			_.each(KEY_DISPLAY_GROUPS, function(keyList, index) {
				var optgroup = document.createElement('optgroup');
				optgroup.label = keyList[0];

				_.each(keyList.slice(1), function(key, index) {
					var opt = document.createElement('option');
					opt.value = key;
					opt.text = KEY_MAP[key].name;
					if(key === selected_key) {
						opt.selected = true;
					}
					optgroup.appendChild(opt);
				});

				select.appendChild(optgroup);
			});

			this.keyEl = $(select);
			return this;
		}
	});

	return KeySignatureWidget;
});
<|endoftext|>


<commit_before>'use strict';

require('babel-register');
require('ts-node/register');
const path = require('path');
const ld = require('lodash');
const exists = require('../lib/utils').exists;
const inTeamCity = require('../lib/utils').inTeamCity;
const serverApi = require('../lib/server-api');
const projectConfig = require('./project');
const globs = require('../lib/globs');

const userConfPath = path.resolve('protractor.conf.js');
const userConf = exists(userConfPath) ? require(userConfPath).config : null;
const onPrepare = (userConf && userConf.onPrepare) || ld.noop;
const onComplete = (userConf && userConf.onComplete) || ld.noop;
let cdnServer;

function clientFilesPath() {
  const clientProjectName = projectConfig.clientProjectName();

  return clientProjectName ?
    `node_modules/${clientProjectName}/${globs.multipleModules.clientDist()}` :
    globs.singleModule.clientDist();
}

const merged = ld.mergeWith({
  framework: 'jasmine',
  specs: [globs.e2e()],
  onPrepare: () => {
    require('babel-register');

    if (merged.framework === 'jasmine' && inTeamCity()) {
      const TeamCityReporter = require('jasmine-reporters').TeamCityReporter;
      jasmine.getEnv().addReporter(new TeamCityReporter());
    }

    const port = projectConfig.servers.cdn.port() || 3200;
    serverApi.start({port, filesPath: clientFilesPath()}).then(server => {
      cdnServer = server;
    });
    onPrepare.call(merged);
  },
  onComplete: () => {
    if (cdnServer) {
      cdnServer.close();
    }
    onComplete(merged);
  }
}, userConf, a => typeof a === 'function' ? a : undefined);

if (merged.framework === 'mocha') {
  merged.mochaOpts = merged.mochaOpts || {};
  merged.mochaOpts.reporter = 'mocha-env-reporter';
}

if (!process.env.IS_BUILD_AGENT) {
  merged.chromeDriver = require.resolve('chromedriver/bin/chromedriver');
}

function normaliseSpecs(config) {
  let specs = [].concat(config.specs || []);
  return Object.assign({}, config, {specs: specs.map(spec => path.resolve(spec))});
}

module.exports.config = normaliseSpecs(merged);
<commit_msg>add comment for removing Chromedriver hotfix<commit_after>'use strict';

require('babel-register');
require('ts-node/register');
const path = require('path');
const ld = require('lodash');
const exists = require('../lib/utils').exists;
const inTeamCity = require('../lib/utils').inTeamCity;
const serverApi = require('../lib/server-api');
const projectConfig = require('./project');
const globs = require('../lib/globs');

const userConfPath = path.resolve('protractor.conf.js');
const userConf = exists(userConfPath) ? require(userConfPath).config : null;
const onPrepare = (userConf && userConf.onPrepare) || ld.noop;
const onComplete = (userConf && userConf.onComplete) || ld.noop;
let cdnServer;

function clientFilesPath() {
  const clientProjectName = projectConfig.clientProjectName();

  return clientProjectName ?
    `node_modules/${clientProjectName}/${globs.multipleModules.clientDist()}` :
    globs.singleModule.clientDist();
}

const merged = ld.mergeWith({
  framework: 'jasmine',
  specs: [globs.e2e()],
  onPrepare: () => {
    require('babel-register');

    if (merged.framework === 'jasmine' && inTeamCity()) {
      const TeamCityReporter = require('jasmine-reporters').TeamCityReporter;
      jasmine.getEnv().addReporter(new TeamCityReporter());
    }

    const port = projectConfig.servers.cdn.port() || 3200;
    serverApi.start({port, filesPath: clientFilesPath()}).then(server => {
      cdnServer = server;
    });
    onPrepare.call(merged);
  },
  onComplete: () => {
    if (cdnServer) {
      cdnServer.close();
    }
    onComplete(merged);
  }
}, userConf, a => typeof a === 'function' ? a : undefined);

if (merged.framework === 'mocha') {
  merged.mochaOpts = merged.mochaOpts || {};
  merged.mochaOpts.reporter = 'mocha-env-reporter';
}

// TBD: remove this when CI support protractor 4. See commit https://github.com/wix/wix-node-build/commit/12dbae41543b4d8589b2268e0e1932e89bcd9d92
if (!process.env.IS_BUILD_AGENT) {
  merged.chromeDriver = require.resolve('chromedriver/bin/chromedriver');
}

function normaliseSpecs(config) {
  let specs = [].concat(config.specs || []);
  return Object.assign({}, config, {specs: specs.map(spec => path.resolve(spec))});
}

module.exports.config = normaliseSpecs(merged);
<|endoftext|>


<commit_before>// This is just a test module to make sure that stockTheFridge is keeping things ice cold.

var fridge = require('./data/stockTheFridge.js');
var fs = require('fs-extra-promise');

// fridge.topShelf('new_york_city_311', function(r) {
// 	fs.writeFileAsync('./top-shelf-example-nyc311.json', JSON.stringify(r));
// });

fridge.fridayNight();<commit_msg>export the topShelf test<commit_after>// This is just a test module to make sure that stockTheFridge is keeping things ice cold.

var fridge = require('./data/stockTheFridge.js');
var fs = require('fs-extra-promise');

exports.topShelf = function() {
	fridge.topShelf('new_york_city_311', function(r) {
		fs.writeFileAsync('./top-shelf-example-nyc311.json', JSON.stringify(r));
	});
}

// TODO: not really a test...
// exports.fridge = fridge.fridayNight();<|endoftext|>


<commit_before>/* eslint-disable no-unused-vars */
var config = {
  map: {
    '*': {
      // Libs
      'aos': 'Magento_Theme/js/lib/aos.min',
      'focusVisible': 'Magento_Theme/js/lib/focus-visible.min',
      'lazysizes': 'Magento_Theme/js/lib/lazysizes.min',
      'select2': 'Magento_Theme/js/lib/select2.full.min',
      'slick': 'Magento_Theme/js/lib/slick.min',

      // Modules
      'bannerCollapsible': 'Magento_Theme/js/banner-collapsible.babel',
      'cookieMessage': 'Magento_Theme/js/cookie-message.babel',
      'dropdownList': 'Magento_Theme/js/dropdown-list.babel',
      'fileUpload': 'Magento_Theme/js/file-upload.babel',
      'marketingBar': 'Magento_Theme/js/marketing-bar.babel',
      'modal': 'Magento_Theme/js/modal.babel',
      'select': 'Magento_Theme/js/select.babel',
      'scrollTop': 'Magento_Theme/js/scroll-top.babel',
      'scrollTo': 'Magento_Theme/js/scroll-to.babel',
      'skipNav': 'Magento_Theme/js/skip-nav.babel',
      'slider': 'Magento_Theme/js/slider.babel',
      'tab': 'Magento_Theme/js/tab.babel',
      'tooltip': 'Magento_Theme/js/tooltip.babel'
    }
  },
  config: {
    mixins: {
      'mage/gallery/gallery': {
        'Magento_Theme/js/mixins/gallery-mixin': true
      },
      'Magento_Theme/js/view/messages': {
        'Magento_Theme/js/mixins/messages-mixin': true
      },
      'Magento_Ui/js/grid/listing': {
        'Magento_Theme/js/mixins/grid-listing-mixin': true
      }
    }
  },
  shim: {
    'select2': {
      'deps': ['jquery']
    }
  }
};
<commit_msg>Fix range slider<commit_after>/* eslint-disable no-unused-vars */
var config = {
  map: {
    '*': {
      // Libs
      'aos': 'Magento_Theme/js/lib/aos.min',
      'focusVisible': 'Magento_Theme/js/lib/focus-visible.min',
      'lazysizes': 'Magento_Theme/js/lib/lazysizes.min',
      'select2': 'Magento_Theme/js/lib/select2.full.min',
      'slick': 'Magento_Theme/js/lib/slick.min',
      "noUiSlider": "Magento_Theme/js/lib/nouislider.min",

      // Modules
      'bannerCollapsible': 'Magento_Theme/js/banner-collapsible.babel',
      'cookieMessage': 'Magento_Theme/js/cookie-message.babel',
      'dropdownList': 'Magento_Theme/js/dropdown-list.babel',
      'fileUpload': 'Magento_Theme/js/file-upload.babel',
      'marketingBar': 'Magento_Theme/js/marketing-bar.babel',
      'modal': 'Magento_Theme/js/modal.babel',
      'select': 'Magento_Theme/js/select.babel',
      'scrollTop': 'Magento_Theme/js/scroll-top.babel',
      'scrollTo': 'Magento_Theme/js/scroll-to.babel',
      'skipNav': 'Magento_Theme/js/skip-nav.babel',
      'slider': 'Magento_Theme/js/slider.babel',
      'tab': 'Magento_Theme/js/tab.babel',
      'tooltip': 'Magento_Theme/js/tooltip.babel'
    }
  },
  config: {
    mixins: {
      'mage/gallery/gallery': {
        'Magento_Theme/js/mixins/gallery-mixin': true
      },
      'Magento_Theme/js/view/messages': {
        'Magento_Theme/js/mixins/messages-mixin': true
      },
      'Magento_Ui/js/grid/listing': {
        'Magento_Theme/js/mixins/grid-listing-mixin': true
      }
    }
  },
  shim: {
    'select2': {
      'deps': ['jquery']
    }
  }
};
<|endoftext|>


<commit_before>/* jshint asi: true */
/* global define: false */
define(function(require) {
    var Settings = (function(series) {
        function Settings(json) {
            this.data = JSON.parse(json)
        }

        var p = Settings.prototype

        p.get = function(name) {
            return this.data[name]
        }

        p.getHeadingSeries = function(level) {
            var mark = (this.data.headings || {})["h" + level]
            return series.get(mark)
        }

        Settings.get = function(html) {
            var json = (html.match(/<!--\s*settings([\s\S]+?)-->/) || [])[1]
            return new Settings(json)
        }

        return Settings;
    })(require("./series"))

    return Settings
})
<commit_msg>兼容处理没有配置的情况<commit_after>/* jshint asi: true */
/* global define: false */
define(function(require) {
    var Settings = (function(series) {
        function Settings(json) {
            try {
                this.data = json ? JSON.parse(json) : {}
            } catch (err) {
                console.error(err)
                this.data = {}
            }
        }

        var p = Settings.prototype

        p.get = function(name) {
            return this.data[name]
        }

        p.getHeadingSeries = function(level) {
            var mark = (this.data.headings || {})["h" + level]
            return series.get(mark)
        }

        Settings.get = function(html) {
            var json = (html.match(/<!--\s*settings([\s\S]+?)-->/) || [])[1]
            return new Settings(json)
        }

        return Settings;
    })(require("./series"))

    return Settings
})
<|endoftext|>


<commit_before>var types = [];
var inputs;

var works;

function filterClick(input) {
	//get the group and type of the
	var groupAndType = input.target.id;
	groupAndType = groupAndType.split(':');
	var type = groupAndType[1];
	var typeGroup = groupAndType[0];

	//Change the value
	if (types[typeGroup][type] == 0) {
		types[typeGroup][type] = 1;
		$(input.target).addClass('active');
	} else {
		types[typeGroup][type] = 0;
		$(input.target).removeClass('active');
	};

	refresh();
}

function refresh() {
	$(".work").each( function(i, work) {
		var classes = work.className;
		classes = classes.split(' ');

		var resultArray = [];

		for(j=1; j<classes.length; j++) {
			groupAndType = classes[j].split(':');
			type = groupAndType[1];
			typeGroup = groupAndType[0];

			if( resultArray[typeGroup] != null ) {
				resultArray[typeGroup] += types[typeGroup][type];
			} else {
				resultArray[typeGroup] = types[typeGroup][type];
			}
		}

		var result = 1;
		for( val in resultArray ) {
			result *= resultArray[val];
		}

		if(result == 0) {
			$(work).hide('normal');
		} else {
			$(work).show('normal');
		}

	});
}

$(document).ready(function() {

	//populate types
	$(".filter").each( function(i, filter) {
		var groupAndType = filter.id;
		groupAndType = groupAndType.split(':');
		var type = groupAndType[1];
		var typeGroup = groupAndType[0];
		types[typeGroup];
		if(types[typeGroup] == null) {
			group = [];
			group[type] = 1;
			types[typeGroup] = group;
		} else {
			types[typeGroup][type]= 1;
		}
	});

	//attach 'refresh' to filters
	inputs = $(".filter");
	inputs.click(filterClick);

});
<commit_msg>new comments<commit_after>var types = [];
var inputs;

var works;

function filterClick(input) {
	// Get the group and type of the button clicked
	var groupAndType = input.target.id;
	groupAndType = groupAndType.split(':');
	var type = groupAndType[1];
	var typeGroup = groupAndType[0];

	// Change the value
	if (types[typeGroup][type] == 0) {
		types[typeGroup][type] = 1;
		$(input.target).addClass('active');
	} else {
		types[typeGroup][type] = 0;
		$(input.target).removeClass('active');
	};

	refresh();
}

function refresh() {
	$(".work").each( function(i, work) {
		var classes = work.className;
		classes = classes.split(' ');

		var resultArray = [];

		for(j=1; j<classes.length; j++) {
			groupAndType = classes[j].split(':');
			type = groupAndType[1];
			typeGroup = groupAndType[0];

			if( resultArray[typeGroup] != null ) {
				resultArray[typeGroup] += types[typeGroup][type];
			} else {
				resultArray[typeGroup] = types[typeGroup][type];
			}
		}

		var result = 1;
		for( val in resultArray ) {
			result *= resultArray[val];
		}

		if(result == 0) {
			$(work).hide('normal');
		} else {
			$(work).show('normal');
		}

	});
}

$(document).ready(function() {

	// Populate types
	$(".filter").each( function(i, filter) {
		var groupAndType = filter.id;
		groupAndType = groupAndType.split(':');
		var type = groupAndType[1];
		var typeGroup = groupAndType[0];
		types[typeGroup];
		if(types[typeGroup] == null) {
			group = [];
			group[type] = 1;
			types[typeGroup] = group;
		} else {
			types[typeGroup][type]= 1;
		}
	});

	// Attach 'refresh' to filters
	inputs = $(".filter");
	inputs.click(filterClick);

});
<|endoftext|>


<commit_before>$(document).ready(function(){

    // -------
    // ALL APP
    // -------

    // Ability progressbar and tooltip
    $('.ability').each(function(){
        var value = $(this).data('value');

        $(this).progressbar({
            value : value,
            max : 100
        });
    });

    $(document).tooltip({
        items: '.ability',
        content: function() {
            return $( this ).data('description');
        },
        track: true,
        show: {
            effect: 'show'
        },
        hide: {
            effect: 'hide'
        }
    });

    // ---------
    // LOGGED IN
    // ---------

    // Toggle mobile menu
    $( '.mobile-icon' ).click(function() {
        $('nav.main').slideToggle();
    });

    // Reset when window switches to desktop view
    $(window).resize(function() {
        if ($(window).width() > 620) {
            $('nav.main').show();

        }
    });

    // ---------
    // DASHBOARD
    // ---------

    // Toggle 'close to me' form on radio select

    $('input[name="locationRadios"]').on('change', function(){
        if ($(this).val()=='all') {
             $('.close-to-me').hide();
        } else  {
             $('.close-to-me').show();
        }
    });

    // Expand and Collapse Member Profiles

    $('.toggle-user-expand').click(function(e){
        e.preventDefault();

        $(this).closest('.user-card').find('.user-expand').slideToggle(150);

        var $fullProfile = $(this).closest('.user-card').find('.full-profile');

        if ($fullProfile.html() == 'View Full Profile'){
            $fullProfile.html('Collapse')
        } else {
            $fullProfile.html('View Full Profile');
        }
    });

    // Display a Welcome dialog for new users

    $('#welcome-dialog').dialog({
        modal: true,
        width: 600
    });

    // ----------------------
    // MODERATION - UNIVERSAL
    // ----------------------

    // Show full application comments if they have been truncated
    $('.comments-dialog').dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        maxHeight: 600,
    });

    $('.read-more').click(function(e){
        e.preventDefault();

        id = $(this).data('id');
        $('#dialog'+ id).dialog('open');
    });

    // --------------------------
    // MODERATION - INVITE MEMBER
    // --------------------------

    $('#reinvite-member-dialog').dialog({
        autoOpen: false,
        modal: true,
        width: 300
    });

    $('#revoke-member-dialog').dialog({
        autoOpen: false,
        modal: true,
        width: 450
    });

    var user, email;

    $('.resend-link').click(function(e){
        e.preventDefault();

        user = $(this).data('user');
        email = $(this).data('email');
        $('#reinvite-member-dialog').dialog('open');
        $('.reinvite-member-form #id_user_id').val(user);
        $('.reinvite-member-form #id_email').val(email);
    });

    var name;

    $('.revoke-link').click(function(e){
        e.preventDefault();

        user = $(this).data('user');
        name = $(this).data('name');
        email = $(this).data('email');

        $('#revoke-member-dialog').dialog('open');
        $('.revoke-invitation-form #id_user_id').val(user);
        $('.revoke-invitation-form .name').html(name);
        $('.revoke-invitation-form .email').html(email);
    });

    // --------------------------------
    // MODERATION - REVIEW APPLICATIONS
    // --------------------------------

    $('.decision-link').click(function(e){
        e.preventDefault();

        user = $(this).data('user');
        decision = $(this).data('decision');
        title = $(this).html();

        $('#review-application-dialog').dialog({
            autoOpen: false,
            modal: true,
            width: 400,
            title: title
        });

        $('#review-application-dialog').dialog('open');
        $('.review-application-form #id_user_id').val(user);
        $('.review-application-form #id_decision').val(decision);
        $('.review-application-form .button').val(title);
    });

    // ---------------------------------
    // MODERATION - REVIEW ABUSE REPORTS
    // ---------------------------------

    // Show User warning on review abuse reports page
    $('.warning-dialog').dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        maxHeight: 600
    });

    $('.show-warnings').click(function(e){
        e.preventDefault();

        user = $(this).data('user');
        $('#dialog'+ user).dialog('open');
    });

    // Enable form on review abuse reports page

    var report, decision, title;

    $('.decision-link').click(function(e){
        e.preventDefault();

        report = $(this).data('report');
        decision = $(this).data('decision');
        title = $(this).data('title');

        $('#review-abuse-dialog').dialog({
            autoOpen: false,
            modal: true,
            width: 400,
            title: title
        });

        $('#review-abuse-dialog').dialog('open');
        $('.review-abuse-form #id_report_id').val(report);
        $('.review-abuse-form #id_decision').val(decision);
        $('.review-abuse-form .button').val(title);

    });

    // ---------------------------------
    // MODERATION - VIEW LOGS
    // ---------------------------------

    var period = $('#id_period').val();

    function toggleDateRange(period){
        var custom = $('.custom-date');
        var customInputs = $('.custom-date input');

        if (period == 'CUSTOM'){
            custom.show();
            customInputs.attr('disabled', false);
        } else {
            custom.hide();
            customInputs.attr('disabled', true);
        }
    }

    toggleDateRange(period);

    $('#id_period').change(function(){
        period = $(this).val();
        toggleDateRange(period);
    });

    // Add Datepicker to date fields
    var minDate = $('#id_start_date').val();
    var maxDate = $('#id_end_date').val();

    $('#id_start_date').datepicker({
        dateFormat: "d/m/yy",
        maxDate: maxDate,
        onClose: function( selectedDate ) {
            $( "#id_end_date" ).datepicker( "option", "minDate", selectedDate );
        }
    });

    $('#id_end_date').datepicker({
        minDate: minDate,
        dateFormat: "d/m/yy",
        onClose: function( selectedDate ) {
            $( "#id_start_date" ).datepicker( "option", "maxDate", selectedDate );
        }
    });

});
<commit_msg>Refactor JS modals<commit_after>$(document).ready(function(){

    // -------
    // ALL APP
    // -------

    // Ability progressbar and tooltip
    $('.ability').each(function(){
        var value = $(this).data('value');

        $(this).progressbar({
            value : value,
            max : 100
        });
    });

    $(document).tooltip({
        items: '.ability',
        content: function() {
            return $( this ).data('description');
        },
        track: true,
        show: {
            effect: 'show'
        },
        hide: {
            effect: 'hide'
        }
    });

    // ---------
    // LOGGED IN
    // ---------

    // Toggle mobile menu
    $( '.mobile-icon' ).click(function() {
        $('nav.main').slideToggle();
    });

    // Reset when window switches to desktop view
    $(window).resize(function() {
        if ($(window).width() > 620) {
            $('nav.main').show();

        }
    });

    // ---------
    // DASHBOARD
    // ---------

    // Toggle 'close to me' form on radio select

    $('input[name="locationRadios"]').on('change', function(){
        if ($(this).val()=='all') {
             $('.close-to-me').hide();
        } else  {
             $('.close-to-me').show();
        }
    });

    // Expand and Collapse Member Profiles

    $('.toggle-user-expand').click(function(e){
        e.preventDefault();

        $(this).closest('.user-card').find('.user-expand').slideToggle(150);

        var $fullProfile = $(this).closest('.user-card').find('.full-profile');

        if ($fullProfile.html() == 'View Full Profile'){
            $fullProfile.html('Collapse')
        } else {
            $fullProfile.html('View Full Profile');
        }
    });

    // Display a Welcome dialog for new users

    $('#welcome-dialog').dialog({
        modal: true,
        width: 600
    });

    // ----------------------
    // MODERATION - UNIVERSAL
    // ----------------------

    // Show full application comments if they have been truncated
    $('.comments-dialog').dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        maxHeight: 600,
    });

    $('.read-more').click(function(e){
        e.preventDefault();

        id = $(this).data('id');
        $('#dialog'+ id).dialog('open');
    });

    // --------------------------
    // MODERATION - INVITE MEMBER
    // --------------------------

    $('#reinvite-member-dialog').dialog({
        autoOpen: false,
        modal: true,
        width: 300
    });

    $('#revoke-member-dialog').dialog({
        autoOpen: false,
        modal: true,
        width: 450
    });

    var user, email;

    $('.resend-link').click(function(e){
        e.preventDefault();

        user = $(this).data('user');
        email = $(this).data('email');
        $('#reinvite-member-dialog').dialog('open');
        $('.reinvite-member-form #id_user_id').val(user);
        $('.reinvite-member-form #id_email').val(email);
    });

    var name;

    $('.revoke-link').click(function(e){
        e.preventDefault();

        user = $(this).data('user');
        name = $(this).data('name');
        email = $(this).data('email');

        $('#revoke-member-dialog').dialog('open');
        $('.revoke-invitation-form #id_user_id').val(user);
        $('.revoke-invitation-form .name').html(name);
        $('.revoke-invitation-form .email').html(email);
    });

    // --------------------------------
    // MODERATION - REVIEW APPLICATIONS
    // --------------------------------

    function applicationDialog(title){
        $('#review-application-dialog').dialog({
            autoOpen: false,
            modal: true,
            width: 400,
            title: title || 'Review Application'
        });
    };

    applicationDialog();

    $('.decision-link').click(function(e){
        e.preventDefault();

        user = $(this).data('user');
        decision = $(this).data('decision');
        title = $(this).html();

        applicationDialog(title);
        $('#review-application-dialog').dialog('open');
        $('.review-application-form #id_user_id').val(user);
        $('.review-application-form #id_decision').val(decision);
        $('.review-application-form .button').val(title);
    });

    // ---------------------------------
    // MODERATION - REVIEW ABUSE REPORTS
    // ---------------------------------

    // Show User warning on review abuse reports page
    $('.warning-dialog').dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        maxHeight: 600
    });

    $('.show-warnings').click(function(e){
        e.preventDefault();

        user = $(this).data('user');
        $('#dialog'+ user).dialog('open');
    });

    // Enable form on review abuse reports page
    function reportDialog(title){
        $('#review-abuse-dialog').dialog({
            autoOpen: false,
            modal: true,
            width: 400,
            title: title || 'Moderate Abuse Report'
        });
    };

    reportDialog();

    var report, decision, title;

    $('.decision-link').click(function(e){
        e.preventDefault();

        report = $(this).data('report');
        decision = $(this).data('decision');
        title = $(this).data('title');

        reportDialog(title);
        $('#review-abuse-dialog').dialog('open');
        $('.review-abuse-form #id_report_id').val(report);
        $('.review-abuse-form #id_decision').val(decision);
        $('.review-abuse-form .button').val(title);

    });

    // ---------------------------------
    // MODERATION - VIEW LOGS
    // ---------------------------------

    var period = $('#id_period').val();

    function toggleDateRange(period){
        var custom = $('.custom-date');
        var customInputs = $('.custom-date input');

        if (period == 'CUSTOM'){
            custom.show();
            customInputs.attr('disabled', false);
        } else {
            custom.hide();
            customInputs.attr('disabled', true);
        }
    }

    toggleDateRange(period);

    $('#id_period').change(function(){
        period = $(this).val();
        toggleDateRange(period);
    });

    // Add Datepicker to date fields
    var minDate = $('#id_start_date').val();
    var maxDate = $('#id_end_date').val();

    $('#id_start_date').datepicker({
        dateFormat: "d/m/yy",
        maxDate: maxDate,
        onClose: function( selectedDate ) {
            $( "#id_end_date" ).datepicker( "option", "minDate", selectedDate );
        }
    });

    $('#id_end_date').datepicker({
        minDate: minDate,
        dateFormat: "d/m/yy",
        onClose: function( selectedDate ) {
            $( "#id_start_date" ).datepicker( "option", "maxDate", selectedDate );
        }
    });

});
<|endoftext|>


<commit_before>;(function() {
    'use strict';

    var hypothesisLoaded = false;

    window.pymChild.onMessage('startHypothesis', startHypothesis);

    window.addEventListener('message', function(event) {
        if (event.data === 'startHypothesis') {
            startHypothesis(event);
        }
    });

    function startHypothesis(event) {
        if (hypothesisLoaded) {
            return;
        }

        // 'pagerendered' is an event emitted by pdf.js after the file metadata has been loaded and
        // the first page rendered.  We must delay setting the fake metadata until after the
        // document has been loaded, or pdf.js will overwrite our fake metadata with the real
        // metadata.
        document.addEventListener('pagerendered', function(e) {

            // Changes made here will not affect loading of the document, but will change how
            // Hypothes.is indexes the annotations.

            // If a pdf is being rendered and MFR has provided a stable identifier, override the
            // documentFingerprint with it before loading the hypothes.is client.  The client
            // will use this ID to identify the document when fetching/saving annotations.
            if (window.MFR_STABLE_ID) {
                // pdf.js uses the first property to set the second. Set both for now, just to be
                // safe. The second will be going away in a future pdf.js release.
                window.PDFViewerApplication.pdfDocument.pdfInfo.fingerprint = window.MFR_STABLE_ID;
                window.PDFViewerApplication.documentFingerprint = window.MFR_STABLE_ID;
            }

            // Override the document title to the file name and the document url to the parent
            // window. This will not affect loading of the document, but will change how Hypothes.is
            // indexes the annotation.  Previously, the page title on h.is would be the final path
            // part of the download url, which would be an opaque file identifier or just `export`.
            if (window.MFR_FILE_NAME) {
                if (window.PDFViewerApplication.documentInfo) {
                    window.PDFViewerApplication.documentInfo.Title = window.MFR_FILE_NAME;
                }
                else {
                    window.PDFViewerApplication.documentInfo = {"Title": window.MFR_FILE_NAME};
                }
                document.title = window.MFR_FILE_NAME;
            }

            // Override the document url to point to the parent window. Before, the linked url would
            // point to the export/download url, meaning the annotations could never be viewed in
            // context.  By linking to the referrer, the annotations can be viewed in the context of
            // the preprint.
            window.PDFViewerApplication.url = document.referrer;

            // Load the hypothes.is client
            var script = window.document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://hypothes.is/embed.js';
            window.document.head.appendChild(script);
            window.document.body.classList.add('show-hypothesis');
            hypothesisLoaded = true;

            var sidePanelOpened = false;
            var sendAnalyticsIfExpanded = function (expanded) {
                if (expanded && !sidePanelOpened) {
                    sidePanelOpened = expanded;
                    ga('send', 'event', {
                        eventCategory: 'Hypothesis',
                        eventAction: 'Open Hypothesis Panel',
                        eventLabel: window.DEFAULT_URL.split('/')[5],
                    });
                }
            };
            window.hypothesisConfig = function () {
                return {
                  "onLayoutChange": function (layout) { return sendAnalyticsIfExpanded(layout.expanded); }
                };
            };
        });
    };
})();
<commit_msg>Added a check with comments on obtaining and using preprints GUID<commit_after>;(function() {
    'use strict';

    var hypothesisLoaded = false;

    window.pymChild.onMessage('startHypothesis', startHypothesis);

    window.addEventListener('message', function(event) {
        if (event.data === 'startHypothesis') {
            startHypothesis(event);
        }
    });

    function startHypothesis(event) {
        if (hypothesisLoaded) {
            return;
        }

        // 'pagerendered' is an event emitted by pdf.js after the file metadata has been loaded and
        // the first page rendered.  We must delay setting the fake metadata until after the
        // document has been loaded, or pdf.js will overwrite our fake metadata with the real
        // metadata.
        document.addEventListener('pagerendered', function(e) {

            // Changes made here will not affect loading of the document, but will change how
            // Hypothes.is indexes the annotations.

            // If a pdf is being rendered and MFR has provided a stable identifier, override the
            // documentFingerprint with it before loading the hypothes.is client.  The client
            // will use this ID to identify the document when fetching/saving annotations.
            if (window.MFR_STABLE_ID) {
                // pdf.js uses the first property to set the second. Set both for now, just to be
                // safe. The second will be going away in a future pdf.js release.
                window.PDFViewerApplication.pdfDocument.pdfInfo.fingerprint = window.MFR_STABLE_ID;
                window.PDFViewerApplication.documentFingerprint = window.MFR_STABLE_ID;
            }

            // Override the document title to the file name and the document url to the parent
            // window. This will not affect loading of the document, but will change how Hypothes.is
            // indexes the annotation.  Previously, the page title on h.is would be the final path
            // part of the download url, which would be an opaque file identifier or just `export`.
            if (window.MFR_FILE_NAME) {
                if (window.PDFViewerApplication.documentInfo) {
                    window.PDFViewerApplication.documentInfo.Title = window.MFR_FILE_NAME;
                }
                else {
                    window.PDFViewerApplication.documentInfo = {"Title": window.MFR_FILE_NAME};
                }
                document.title = window.MFR_FILE_NAME;
            }

            // Override the document url to point to the parent window. Before, the linked url would
            // point to the export/download url, meaning the annotations could never be viewed in
            // context.  By linking to the referrer, the annotations can be viewed in the context of
            // the preprint.
            window.PDFViewerApplication.url = document.referrer;

            // Load the hypothes.is client
            var script = window.document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://hypothes.is/embed.js';
            window.document.head.appendChild(script);
            window.document.body.classList.add('show-hypothesis');
            hypothesisLoaded = true;

            var sidePanelOpened = false;
            // window.DEFAULT_URL should be the wb link in this format:
            // https://<wb-domain>/v1/resources/<preprint-guid>/providers/osfstorage/<file-id>?direct=&mode=render
            // TODO: parse and validate the WB URL before retrieving the preprints GUID
            var wbLink = window.DEFAULT_URL;
            var preprintGuid;
            if (wbLink.split('/').length >= 6) {
                preprintGuid = wbLink.split('/')[5];
            } else {
                preprintGuid = 'preprint-guid-unknown';
            }
            var sendAnalyticsIfExpanded = function (expanded) {
                if (expanded && !sidePanelOpened) {
                    sidePanelOpened = expanded;
                    ga('send', 'event', {
                        eventCategory: 'Hypothesis',
                        eventAction: 'Open Hypothesis Panel',
                        //`eventLabel` is the guid of the preprint to which the file belongs
                        eventLabel: preprintGuid,
                    });
                }
            };
            window.hypothesisConfig = function () {
                return {
                  "onLayoutChange": function (layout) { return sendAnalyticsIfExpanded(layout.expanded); }
                };
            };
        });
    };
})();
<|endoftext|>


<commit_before>//
//  Survival Advice:  Organize before they rise !
//

var person = db.people.findOne( { name: "Sean" } );

print('\nThe following people are near ', person.name,'\n');

db.people.find( { location: { $near: person.location } } ).forEach(function(closebyperson) {

  print( closebyperson.name, closebyperson.location, closebyperson.weapon );

  });

var radius = 20;

print('\nThe following people are in a ', radius, ' meters radius from ', person.name,'\n');

db.people.find( { location: { $near: person.location, $maxDistance: radius } } ).forEach(function(closebyperson) {

  print( closebyperson.name, closebyperson.location, closebyperson.weapon );

  });

<commit_msg>Added name field to weapon<commit_after>//
//  Survival Advice:  Organize before they rise !
//

var person = db.people.findOne( { name: "Sean" } );

print('\nThe following people are near ', person.name,'\n');

db.people.find( { location: { $near: person.location } } ).forEach(function(closebyperson) {

  print( closebyperson.name, closebyperson.location, closebyperson.weapon.name );

  });

var radius = 20;

print('\nThe following people are in a ', radius, ' meters radius from ', person.name,'\n');

db.people.find( { location: { $near: person.location, $maxDistance: radius } } ).forEach(function(closebyperson) {

  print( closebyperson.name, closebyperson.location, closebyperson.weapon.name );

  });

<|endoftext|>


<commit_before>var
    esPhinx,
    Iterable;

(function($) {
    "use strict";

    // $.prototype.extend(false, {
    $.prototype.extend({

        value: function(value) {
            if (value || value === "") {
                this.property("value", value);
                return this;
            } else {
                value = this.property("value");
                if (value) {
                    return value;
                }
            }

            return "";
        },

        data: function(attrName, value) {
            return this.attribute("data-" + attrName, value);
        },

        text: function(text) {
            var
                first,
                childNodes,

                callback = function(node) {
                    first = $(node).childNodes().asNode();
                    if (first instanceof window.Text) {
                        first.textContent = text;
                    } else {
                        $(node).prepend(window.document
                                        .createTextNode(text));
                    }
                },

                iteratorBlock = function(node) {
                    if (node instanceof window.Text) {
                        text += $(node).textContent();
                    }
                };

            if (typeof text == "string") {
                if (this.some()) {
                    this.each(callback);
                }
                return this;
            } else {
                text = "";
                childNodes = this.childNodes();
                if (childNodes.some()) {
                    childNodes.each(iteratorBlock);

                    return text.trim();
                } else {
                    return "";
                }
            }
        },

        parent: function(query) {
            var
                parent,
                callback,
                elements = $();

            if (query) {
                // comparator = $(query).asNode();
                // while (true) {
                //     if (Object.areEquivalents(parent, comparator)) {
                //         return $(parent);
                //     } else if (!parent) {
                //         break;
                //     }
                //     parent = parent.parentNode;
                // }
                callback = function(element) {
                    parent = element.closest(query);
                    if ($(parent).some()) {
                        elements.push(parent);
                    }
                };
            } else {
                callback = function(element) {
                    elements.push(element.parentNode);
                };
            }

            this.each(callback);

            return elements;
        },

        lastIndex: function() {
            return this.amount() - 1;
        },

        childNodes: function() {
            var
                childNodes = $(),

                callback = function(node) {
                    childNodes.concat(true, node.childNodes);
                };

            this.each(callback);

            return childNodes;
        },

        childElements: function(comparator) {
            var
                node,
                comparators,
                children = $(),

                callback = function(element) {
                    var
                        iteratorBlock = function(comparator) {
                            if (element.is(comparator)) {
                                children.push(comparator);
                            }
                        };

                    comparators.each(iteratorBlock);
                };

            if (this.some()) {
                node = this.asNode();

                if (comparator) {
                    comparators = $(comparator);

                    $(node.children).each(callback);

                    return children;
                }

                return children.concat(this.asNode().children);
            }

            return $();
        },

        previousSiblings: function() {
            var
                node = this.asNode(),
                sibling = node,
                siblings = $();

            sibling = sibling.previousElementSibling;
            while (sibling) {
                siblings.push(sibling);
                sibling = sibling.previousElementSibling;
            }

            if (siblings.some()) {
                return siblings;
            }

            return false;
        },

        nextSiblings: function() {
            var
                node = this.asNode(),
                sibling = node,
                siblings = $();

            sibling = sibling.nextElementSibling;
            while (sibling) {
                siblings.push(sibling);
                sibling = sibling.nextElementSibling;
            }

            if (siblings.some()) {
                return siblings;
            }

            return false;
        },

        width: function(value) {
            if (this.asNode() == window.document) {
                return this.asNode().documentElement.offsetWidth;
            }

            var
                width = this.css("width"),
                padding = this.css("padding-left") +
                this.css("padding-right"),
                border = this.css("border-left-width") +
                this.css("border-right-width"),

                callback = function(node) {
                    node = $(node);
                    if (Number.isNaN(parseFloat(value))) {
                        node.css("width", value);
                    } else {
                        padding = node.css("padding-left") +
                          node.css("padding-right");
                        border = node.css("border-left-width") +
                          node.css("border-right-width");
                        value  = parseFloat(value) - (padding + border);
                        if (value < 0) {
                            value = 0;
                        }
                        node.css("width", value + "px");
                    }
                };

            if (value || value === 0) {
                this.each(callback);
            } else {
                if (Number.isNaN(parseFloat(width))) {
                    return this.asNode().offsetWidth;
                }
                return width + padding + border;
            }
        },

        height: function(value) {
            if (this.asNode() == window.document) {
                return this.asNode().documentElement.offsetHeight;
            }

            var
                height = this.css("height"),
                padding = this.css("padding-top") +
                this.css("padding-bottom"),
                border = this.css("border-top-width") +
                this.css("border-bottom-width"),

                callback = function(node) {
                    node = $(node);
                    if (Number.isNaN(parseFloat(value))) {
                        node.css("height", value);
                    } else {
                        padding = node.css("padding-top") +
                          node.css("padding-bottom");
                        border = node.css("border-top-width") +
                          node.css("border-bottom-width");
                        value  = parseFloat(value) - (padding + border);
                        if (value < 0) {
                            value = 0;
                        }
                        node.css("height", value + "px");
                    }
                };

            if (value || value === 0) {
                this.each(callback);
            } else {
                if (Number.isNaN(parseFloat(height))) {
                    return this.asNode().offsetHeight;
                }
                return height + padding + border;
            }
        },

        minWidth: function() {
            var
                padding = this.css("padding-left") +
                this.css("padding-right");

            return this.innerWidth() - padding;
        },

        innerWidth: function() {
            var
                border = this.css("border-left-width") +
                this.css("border-right-width");

            return this.width() - border;
        },

        minHeight: function() {
            var
                padding = this.css("padding-top") +
                this.css("padding-bottom");

            return this.innerHeight() - padding;
        },

        innerHeight: function() {
            var
                border = this.css("border-top-width") +
                this.css("border-bottom-width");

            return this.height() - border;
        },

        transitionDuration: function() {
            return this.css("transition-duration") * 1000;
        }

    });

}(esPhinx));
<commit_msg>fix property<commit_after>var
    esPhinx;

(function($) {
    "use strict";

    // $.prototype.extend(false, {
    $.prototype.extend({

        value: function(value) {
            if (value || value === "") {
                this.property("value", value);
                return this;
            } else {
                value = this.property("value");
                if (value) {
                    return value;
                }
            }

            return "";
        },

        data: function(attrName, value) {
            return this.attribute("data-" + attrName, value);
        },

        text: function(text) {
            var
                first,
                childNodes,

                callback = function(node) {
                    first = $(node).childNodes().asNode();
                    if (first instanceof window.Text) {
                        first.textContent = text;
                    } else {
                        $(node).prepend(window.document
                                        .createTextNode(text));
                    }
                },

                iteratorBlock = function(node) {
                    if (node instanceof window.Text) {
                        text += $(node).textContent();
                    }
                };

            if (typeof text == "string") {
                if (this.some()) {
                    this.each(callback);
                }
                return this;
            } else {
                text = "";
                childNodes = this.childNodes();
                if (childNodes.some()) {
                    childNodes.each(iteratorBlock);

                    return text.trim();
                } else {
                    return "";
                }
            }
        },

        parent: function(query) {
            var
                parent,
                callback,
                elements = $();

            if (query) {
                // comparator = $(query).asNode();
                // while (true) {
                //     if (Object.areEquivalents(parent, comparator)) {
                //         return $(parent);
                //     } else if (!parent) {
                //         break;
                //     }
                //     parent = parent.parentNode;
                // }
                callback = function(element) {
                    parent = element.closest(query);
                    if ($(parent).some()) {
                        elements.push(parent);
                    }
                };
            } else {
                callback = function(element) {
                    elements.push(element.parentNode);
                };
            }

            this.each(callback);

            return elements;
        },

        lastIndex: function() {
            return this.amount() - 1;
        },

        childNodes: function() {
            var
                childNodes = $(),

                callback = function(node) {
                    childNodes.concat(true, node.childNodes);
                };

            this.each(callback);

            return childNodes;
        },

        childElements: function(comparator) {
            var
                node,
                comparators,
                children = $(),

                callback = function(element) {
                    var
                        iteratorBlock = function(comparator) {
                            if ($(element).is(comparator)) {
                                children.push(comparator);
                            }
                        };

                    comparators.each(iteratorBlock);
                };

            if (this.some()) {
                node = this.asNode();

                if (comparator) {
                    comparators = $(comparator);

                    $(node.children).each(callback);

                    return children;
                }

                return children.concat(this.asNode().children);
            }

            return $();
        },

        previousSiblings: function() {
            var
                node = this.asNode(),
                sibling = node,
                siblings = $();

            sibling = sibling.previousElementSibling;
            while (sibling) {
                siblings.push(sibling);
                sibling = sibling.previousElementSibling;
            }

            if (siblings.some()) {
                return siblings;
            }

            return false;
        },

        nextSiblings: function() {
            var
                node = this.asNode(),
                sibling = node,
                siblings = $();

            sibling = sibling.nextElementSibling;
            while (sibling) {
                siblings.push(sibling);
                sibling = sibling.nextElementSibling;
            }

            if (siblings.some()) {
                return siblings;
            }

            return false;
        },

        width: function(value) {
            if (this.asNode() == window.document) {
                return this.asNode().documentElement.offsetWidth;
            }

            var
                width = this.css("width"),
                padding = this.css("padding-left") +
                this.css("padding-right"),
                border = this.css("border-left-width") +
                this.css("border-right-width"),

                callback = function(node) {
                    node = $(node);
                    if (Number.isNaN(parseFloat(value))) {
                        node.css("width", value);
                    } else {
                        padding = node.css("padding-left") +
                          node.css("padding-right");
                        border = node.css("border-left-width") +
                          node.css("border-right-width");
                        value  = parseFloat(value) - (padding + border);
                        if (value < 0) {
                            value = 0;
                        }
                        node.css("width", value + "px");
                    }
                };

            if (value || value === 0) {
                this.each(callback);
            } else {
                if (Number.isNaN(parseFloat(width))) {
                    return this.asNode().offsetWidth;
                }
                return width + padding + border;
            }
        },

        height: function(value) {
            if (this.asNode() == window.document) {
                return this.asNode().documentElement.offsetHeight;
            }

            var
                height = this.css("height"),
                padding = this.css("padding-top") +
                this.css("padding-bottom"),
                border = this.css("border-top-width") +
                this.css("border-bottom-width"),

                callback = function(node) {
                    node = $(node);
                    if (Number.isNaN(parseFloat(value))) {
                        node.css("height", value);
                    } else {
                        padding = node.css("padding-top") +
                          node.css("padding-bottom");
                        border = node.css("border-top-width") +
                          node.css("border-bottom-width");
                        value  = parseFloat(value) - (padding + border);
                        if (value < 0) {
                            value = 0;
                        }
                        node.css("height", value + "px");
                    }
                };

            if (value || value === 0) {
                this.each(callback);
            } else {
                if (Number.isNaN(parseFloat(height))) {
                    return this.asNode().offsetHeight;
                }
                return height + padding + border;
            }
        },

        minWidth: function() {
            var
                padding = this.css("padding-left") +
                this.css("padding-right");

            return this.innerWidth() - padding;
        },

        innerWidth: function() {
            var
                border = this.css("border-left-width") +
                this.css("border-right-width");

            return this.width() - border;
        },

        minHeight: function() {
            var
                padding = this.css("padding-top") +
                this.css("padding-bottom");

            return this.innerHeight() - padding;
        },

        innerHeight: function() {
            var
                border = this.css("border-top-width") +
                this.css("border-bottom-width");

            return this.height() - border;
        },

        transitionDuration: function() {
            return this.css("transition-duration") * 1000;
        }

    });

}(esPhinx));
<|endoftext|>


<commit_before>/**
 * Connector for Belgian radio-streaming website Radioplus.be
 * Made by Jonas
 * Based loosely on the Google Music connector by Sharjeel Aziz
 */

// State for event handlers
var state = 'init';

// Used only to remember last song title
var clipTitle = '';

// Timeout to scrobble track ater minimum time passes
var scrobbleTimeout = null;

// Global constant for the song container ....
var CONTAINER_SELECTOR = '.item\\+0';

$(function(){
  $(CONTAINER_SELECTOR).live('DOMSubtreeModified', function(e) {
		if ($(CONTAINER_SELECTOR).length > 0) {
      console.log("Last.fm Scrobbler: Detected updated song")
			updateNowPlaying();
			return;
		}
   });

   console.log("Last.fm Scrobbler: starting Radioplus.be connector")

   // first load
   updateNowPlaying();

   $(window).unload(function() {

      // reset the background scrobbler song data
      chrome.runtime.sendMessage({type: 'reset'});

      return true;
   });
});

/**
 * Called every time we load a new song
 */
function updateNowPlaying(){
  var parsedInfo = parseInfo();
  artist   = parsedInfo['artist']; 	//global
  track    = parsedInfo['track'];	//global

  if (artist == '' || track == '') {return;}

  // check if the same track is being played and we have been called again
  // if the same track is being played we return
  if (clipTitle == track)
  {
    return;
  }

  clipTitle = track;

  chrome.runtime.sendMessage({type: 'validate', artist: artist, track: track}, function(response) {
	  if (response != false) {
      chrome.runtime.sendMessage({type: 'nowPlaying', artist: artist, track: track});
    }
    // on failure send nowPlaying 'unknown song'
    else {
      //chrome.extension.sendRequest({type: 'nowPlaying', duration: duration});
    }
  });
}

function parseInfo() {
  var artist   = '';
  var track    = '';
  var duration = 0;

  // Get artist and song names
  var artistValue = $(CONTAINER_SELECTOR + " .summary .artist").text(); //combinedValue[0];
  var trackParent = $(CONTAINER_SELECTOR + " .summary .song").text(); //combinedValue[1];

  try {
    if (null != artistValue) {
      artist = artistValue.replace(/^\s+|\s+$/g,'');
    }
    if (null != trackParent) {
      track = trackParent.replace(/^\s+|\s+$/g,'');
    }
  } catch(err) {
    return {artist: '', track: ''};
  }

  console.log("artist: " + artist + ", track: " + track + ", divContents: " + divContents);

  return {artist: artist, track: track};
}

/**
 * Simply request the scrobbler.js to submit song previusly specified by calling updateNowPlaying()
 */
function scrobbleTrack() {
   // stats
   chrome.runtime.sendMessage({type: 'trackStats', text: 'The Radio+ song scrobbled'});
   // scrobble
   chrome.runtime.sendMessage({type: 'submit'});
}

/**
 * Listen for requests from scrobbler.js
 */
chrome.runtime.onMessage.addListener(
	function(request, sender, sendResponse) {
	  switch(request.type) {
    	// called after track has been successfully marked as 'now playing' at the server
        case 'nowPlayingOK':
          break;

        // not used yet
        case 'submitOK':
		  break;

        // not used yet
        case 'submitFAIL':
          break;
    }
	}
);
<commit_msg>Removed debugging messages<commit_after>/**
 * Connector for Belgian radio-streaming website Radioplus.be
 * Made by Jonas
 * Based loosely on the Google Music connector by Sharjeel Aziz
 */

// State for event handlers
var state = 'init';

// Used only to remember last song title
var clipTitle = '';

// Timeout to scrobble track ater minimum time passes
var scrobbleTimeout = null;

// Global constant for the song container ....
var CONTAINER_SELECTOR = '.item\\+0';

$(function(){
  $(CONTAINER_SELECTOR).live('DOMSubtreeModified', function(e) {
		if ($(CONTAINER_SELECTOR).length > 0) {
			updateNowPlaying();
			return;
		}
   });

   console.log("Last.fm Scrobbler: starting Radioplus.be connector")

   // first load
   updateNowPlaying();

   $(window).unload(function() {

      // reset the background scrobbler song data
      chrome.runtime.sendMessage({type: 'reset'});

      return true;
   });
});

/**
 * Called every time we load a new song
 */
function updateNowPlaying(){
  var parsedInfo = parseInfo();
  artist   = parsedInfo['artist']; 	//global
  track    = parsedInfo['track'];	//global

  if (artist == '' || track == '') {return;}

  // check if the same track is being played and we have been called again
  // if the same track is being played we return
  if (clipTitle == track)
  {
    return;
  }

  clipTitle = track;

  chrome.runtime.sendMessage({type: 'validate', artist: artist, track: track}, function(response) {
	  if (response != false) {
      chrome.runtime.sendMessage({type: 'nowPlaying', artist: artist, track: track});
    }
    // on failure send nowPlaying 'unknown song'
    else {
      //chrome.extension.sendRequest({type: 'nowPlaying', duration: duration});
    }
  });
}

function parseInfo() {
  var artist   = '';
  var track    = '';
  var duration = 0;

  // Get artist and song names
  var artistValue = $(CONTAINER_SELECTOR + " .summary .artist").text(); //combinedValue[0];
  var trackParent = $(CONTAINER_SELECTOR + " .summary .song").text(); //combinedValue[1];

  try {
    if (null != artistValue) {
      artist = artistValue.replace(/^\s+|\s+$/g,'');
    }
    if (null != trackParent) {
      track = trackParent.replace(/^\s+|\s+$/g,'');
    }
  } catch(err) {
    return {artist: '', track: ''};
  }

  //console.log("artist: " + artist + ", track: " + track + ", divContents: " + divContents);

  return {artist: artist, track: track};
}

/**
 * Simply request the scrobbler.js to submit song previusly specified by calling updateNowPlaying()
 */
function scrobbleTrack() {
   // stats
   chrome.runtime.sendMessage({type: 'trackStats', text: 'The Radio+ song scrobbled'});
   // scrobble
   chrome.runtime.sendMessage({type: 'submit'});
}

/**
 * Listen for requests from scrobbler.js
 */
chrome.runtime.onMessage.addListener(
	function(request, sender, sendResponse) {
	  switch(request.type) {
    	// called after track has been successfully marked as 'now playing' at the server
        case 'nowPlayingOK':
          break;

        // not used yet
        case 'submitOK':
		  break;

        // not used yet
        case 'submitFAIL':
          break;
    }
	}
);
<|endoftext|>


<commit_before>(function () {
  'use strict';

  var mediaBrowser = function () {
    return {
      restrict: 'E',
      templateUrl: 'voicebase-media-player/directives/media-browser.tpl.html',
      scope: {
      },
      controllerAs: 'mediaBroserCtrl',
      controller: function ($scope, $timeout, $compile, voicebaseTokensApi, keywordsSpottingApi, voicebasePlayerService) {
        var me = this;

        me.groupsPerPage = 5;
        me.currentPage = 1;

        var tokenFromStorage = voicebaseTokensApi.getTokenFromStorage();
        var tokenData = voicebaseTokensApi.getCurrentToken();
        me.isLogin = (tokenData) ? true : false;
        me.mediaLoaded = false;
        me.media = [];

        var getMedia = function () {
          me.mediaLoaded = true;
          keywordsSpottingApi.getMedia(tokenData.token)
            .then(function (_media) {
              me.mediaLoaded = false;
              me.media = _media.media;
            }, function () {
              me.mediaLoaded = false;
              me.errorMessage = 'Can\'t getting media!';
            });
        };

        me.loadMedia = function (event, media) {
          if(!media.url) {
            keywordsSpottingApi.getMediaUrl(tokenData.token, media.mediaId)
              .then(function (_url) {
                media.url = _url;
                me.toggleAccordionPane(event, media);
              });
          }
          else {
            me.toggleAccordionPane(event, media);
          }
        };

        me.toggleAccordionPane = function (event, media) {
          var $panel = jQuery(event.target).closest('.panel').find('.panel-collapse');
          var isOpen = $panel.hasClass('in');
          var $panels = jQuery('#media-browser-list').find('.panel-collapse');
          $panels.removeClass('in');
          voicebasePlayerService.destroyVoicebase();
          $panels.find('.panel-body').empty();
          if(isOpen) {
            $panel.removeClass('in');
          }
          else {
            $panel.addClass('in');
            $timeout(function () {
              var player = $compile('<voicebase-media-player ' +
              'token="' + tokenData.token + '"' +
              'player-type="jwplayer"' +
              'media-id="' + media.mediaId + '"' +
              'media-url="' + media.mediaUrl + '"' +
              'media-type="video">' +
              '</voicebase-media-player>')($scope);
              $panel.find('.panel-body').append(player);
              voicebasePlayerService.setMediaReady(true);
            }, 0);
          }
        };

        getMedia();
      }
    };
  };

  angular.module('voicebasePlayerModule')
    .directive('mediaBrowser', mediaBrowser);

})();

<commit_msg>[3461] - fix mediaUrl<commit_after>(function () {
  'use strict';

  var mediaBrowser = function () {
    return {
      restrict: 'E',
      templateUrl: 'voicebase-media-player/directives/media-browser.tpl.html',
      scope: {
      },
      controllerAs: 'mediaBroserCtrl',
      controller: function ($scope, $timeout, $compile, voicebaseTokensApi, keywordsSpottingApi, voicebasePlayerService) {
        var me = this;

        me.groupsPerPage = 5;
        me.currentPage = 1;

        var tokenFromStorage = voicebaseTokensApi.getTokenFromStorage();
        var tokenData = voicebaseTokensApi.getCurrentToken();
        me.isLogin = (tokenData) ? true : false;
        me.mediaLoaded = false;
        me.media = [];

        var getMedia = function () {
          me.mediaLoaded = true;
          keywordsSpottingApi.getMedia(tokenData.token)
            .then(function (_media) {
              me.mediaLoaded = false;
              me.media = _media.media;
            }, function () {
              me.mediaLoaded = false;
              me.errorMessage = 'Can\'t getting media!';
            });
        };

        me.loadMedia = function (event, media) {
          if(!media.mediaUrl) {
            keywordsSpottingApi.getMediaUrl(tokenData.token, media.mediaId)
              .then(function (_url) {
                media.mediaUrl = _url;
                me.toggleAccordionPane(event, media);
              });
          }
          else {
            me.toggleAccordionPane(event, media);
          }
        };

        me.toggleAccordionPane = function (event, media) {
          var $panel = jQuery(event.target).closest('.panel').find('.panel-collapse');
          var isOpen = $panel.hasClass('in');
          var $panels = jQuery('#media-browser-list').find('.panel-collapse');
          $panels.removeClass('in');
          voicebasePlayerService.destroyVoicebase();
          $panels.find('.panel-body').empty();
          if(isOpen) {
            $panel.removeClass('in');
          }
          else {
            $panel.addClass('in');
            $timeout(function () {
              var player = $compile('<voicebase-media-player ' +
              'token="' + tokenData.token + '"' +
              'player-type="jwplayer"' +
              'media-id="' + media.mediaId + '"' +
              'media-url="' + media.mediaUrl + '"' +
              'media-type="video">' +
              '</voicebase-media-player>')($scope);
              $panel.find('.panel-body').append(player);
              voicebasePlayerService.setMediaReady(true);
            }, 0);
          }
        };

        getMedia();
      }
    };
  };

  angular.module('voicebasePlayerModule')
    .directive('mediaBrowser', mediaBrowser);

})();

<|endoftext|>


<commit_before>var buster = require("buster-core");
buster.ansiOut = require("../ansi-out");
var consoleReporter = require("./console");

function messages(reporter, context, test) {
    reporter.messageLog = reporter.messageLog || {};
    reporter.messageLog[context] = reporter.messageLog[context] || {};
    reporter.messageLog[context][test] = reporter.messageLog[context][test] || [];

    return reporter.messageLog[context][test];
}

module.exports = buster.extend(buster.create(consoleReporter), {
    create: function (opt) {
        opt = opt || {};
        var reporter = buster.create(this);
        reporter.io = opt.io || require("sys");
        reporter.ansi = buster.ansiOut.create(opt);
        reporter.cwd = opt.cwd;
        reporter.displayProgress = typeof opt.displayProgress == "boolean" ? opt.displayProgress : true;
        reporter.reset();

        return reporter;
    },

    listen: function (runner) {
        runner.bind(this, {
            "suite:start": "reset", "suite:end": "printDetails",
            "context:start": "startContext", "context:end": "endContext",
            "test:success": "testSuccess", "test:error": "testError",
            "test:failure": "testFailure", "test:async": "testAsync",
            "test:timeout": "testTimeout", "test:setUp": "testSetUp",
            "test:deferred": "testDeferred", "uncaughtException": "uncaughtException"
        });

        if (runner.console) {
            runner.console.bind(this, "log");
        }

        return this;
    },

    testSetUp: function (test) {
        this.currentTest = test.name;
    },

    testSuccess: function (test) {
        this.replaceAsyncMarker();
        this.printProgress(this.ansi.green("."));
    },

    testError: function (test) {
        this.replaceAsyncMarker();
        test.contextName = (this.contextNames || []).join(" ");
        this.errors.push(test);
        this.printProgress(this.ansi.yellow("E"));
    },

    testFailure: function (test) {
        this.replaceAsyncMarker();
        test.contextName = (this.contextNames || []).join(" ");
        this.failures.push(test);
        this.printProgress(this.ansi.red("F"));
    },

    testTimeout: function (test) {
        this.replaceAsyncMarker();
        test.contextName = (this.contextNames || []).join(" ");
        this.timeouts.push(test);
        this.printProgress(this.ansi.red("T"));
    },

    testAsync: function (test) {
        this.async = true;
        this.printProgress(this.ansi.purple("A"));
    },

    testDeferred: function (test) {
        this.deferred = this.deferred || [];

        this.deferred.push({
            name: test.name,
            context: this.contextNames.join(" ")
        });
    },

    startContext: function (context) {
        this.contextNames = this.contextNames || [];

        if (this.contextNames.length == 0) {
            this.printProgress(context.name + ": ");
        }

        this.contextNames.push(context.name);
    },

    endContext: function (context) {
        this.contextNames.pop();

        if (this.contextNames.length == 0) {
            this.printProgress("\n");
        }
    },

    unsupportedContext: function (data) {
        this.unsupported = this.unsupported || [];

        this.unsupported.push({
            context: (this.contextNames || []).concat([data.context.name]).join(" "),
            unsupported: data.unsupported
        });
    },

    printDetails: function (stats) {
        this.io.puts("");
        this.printTimeouts();
        this.printFailures();
        this.printErrors();
        this.printMessages();
        this.printDeferred();
        this.printUnsupported();
        this.printStats(stats);
    },

    printMessages: function () {
        var log = this.messageLog || {};

        for (var ctx in log) {
            for (var test in log[ctx]) {
                if (log[ctx][test].length) {
                    this.io.puts(this.ansi.green("Passed: " + ctx + " " + test));
                }

                this.printLog(ctx, test);
            }
        }
    },

    printDeferred: function () {
        var funcs = this.deferred || {};

        for (var i = 0, l = funcs.length; i < l; ++i) {
            this.io.puts("Deferred: " + funcs[i].context + " " + funcs[i].name);
        }
    },

    printUnsupported: function () {
        consoleReporter.printUnsupported.call(this, this.unsupported || {});
    },

    printLog: function (context, test) {
        var msgs = messages(this, context, test);

        if (msgs.length > 0) {
            this.io.puts("    " + msgs.join("\n    "));
            this.io.puts("");
        }

        delete this.messageLog[context][test];
    },

    replaceAsyncMarker: function () {
        if (this.async) {
            this.printProgress("\033[1D");
        }

        delete this.async;
    },

    log: function (msg) {
        var context = (this.contextNames || []).join(" ");
        var test = this.currentTest;

        messages(this, context, test).push(
            "[" + msg.level.toUpperCase() + "] " + msg.message);
    },

    printProgress: function (str) {
        if (!this.displayProgress) {
            return;
        }

        this.io.print(str);
    }
});
<commit_msg>Reporter should bind to unsupported contexts<commit_after>var buster = require("buster-core");
buster.ansiOut = require("../ansi-out");
var consoleReporter = require("./console");

function messages(reporter, context, test) {
    reporter.messageLog = reporter.messageLog || {};
    reporter.messageLog[context] = reporter.messageLog[context] || {};
    reporter.messageLog[context][test] = reporter.messageLog[context][test] || [];

    return reporter.messageLog[context][test];
}

module.exports = buster.extend(buster.create(consoleReporter), {
    create: function (opt) {
        opt = opt || {};
        var reporter = buster.create(this);
        reporter.io = opt.io || require("sys");
        reporter.ansi = buster.ansiOut.create(opt);
        reporter.cwd = opt.cwd;
        reporter.displayProgress = typeof opt.displayProgress == "boolean" ? opt.displayProgress : true;
        reporter.reset();

        return reporter;
    },

    listen: function (runner) {
        runner.bind(this, {
            "suite:start": "reset", "suite:end": "printDetails",
            "context:start": "startContext", "context:end": "endContext",
            "context:unsupported": "unsupportedContext",
            "test:success": "testSuccess", "test:error": "testError",
            "test:failure": "testFailure", "test:async": "testAsync",
            "test:timeout": "testTimeout", "test:setUp": "testSetUp",
            "test:deferred": "testDeferred", "uncaughtException": "uncaughtException"
        });

        if (runner.console) {
            runner.console.bind(this, "log");
        }

        return this;
    },

    testSetUp: function (test) {
        this.currentTest = test.name;
    },

    testSuccess: function (test) {
        this.replaceAsyncMarker();
        this.printProgress(this.ansi.green("."));
    },

    testError: function (test) {
        this.replaceAsyncMarker();
        test.contextName = (this.contextNames || []).join(" ");
        this.errors.push(test);
        this.printProgress(this.ansi.yellow("E"));
    },

    testFailure: function (test) {
        this.replaceAsyncMarker();
        test.contextName = (this.contextNames || []).join(" ");
        this.failures.push(test);
        this.printProgress(this.ansi.red("F"));
    },

    testTimeout: function (test) {
        this.replaceAsyncMarker();
        test.contextName = (this.contextNames || []).join(" ");
        this.timeouts.push(test);
        this.printProgress(this.ansi.red("T"));
    },

    testAsync: function (test) {
        this.async = true;
        this.printProgress(this.ansi.purple("A"));
    },

    testDeferred: function (test) {
        this.deferred = this.deferred || [];

        this.deferred.push({
            name: test.name,
            context: this.contextNames.join(" ")
        });
    },

    startContext: function (context) {
        this.contextNames = this.contextNames || [];

        if (this.contextNames.length == 0) {
            this.printProgress(context.name + ": ");
        }

        this.contextNames.push(context.name);
    },

    endContext: function (context) {
        this.contextNames.pop();

        if (this.contextNames.length == 0) {
            this.printProgress("\n");
        }
    },

    unsupportedContext: function (data) {
        this.unsupported = this.unsupported || [];

        this.unsupported.push({
            context: (this.contextNames || []).concat([data.context.name]).join(" "),
            unsupported: data.unsupported
        });
    },

    printDetails: function (stats) {
        this.io.puts("");
        this.printTimeouts();
        this.printFailures();
        this.printErrors();
        this.printMessages();
        this.printDeferred();
        this.printUnsupported();
        this.printStats(stats);
    },

    printMessages: function () {
        var log = this.messageLog || {};

        for (var ctx in log) {
            for (var test in log[ctx]) {
                if (log[ctx][test].length) {
                    this.io.puts(this.ansi.green("Passed: " + ctx + " " + test));
                }

                this.printLog(ctx, test);
            }
        }
    },

    printDeferred: function () {
        var funcs = this.deferred || {};

        for (var i = 0, l = funcs.length; i < l; ++i) {
            this.io.puts("Deferred: " + funcs[i].context + " " + funcs[i].name);
        }
    },

    printUnsupported: function () {
        consoleReporter.printUnsupported.call(this, this.unsupported || {});
    },

    printLog: function (context, test) {
        var msgs = messages(this, context, test);

        if (msgs.length > 0) {
            this.io.puts("    " + msgs.join("\n    "));
            this.io.puts("");
        }

        delete this.messageLog[context][test];
    },

    replaceAsyncMarker: function () {
        if (this.async) {
            this.printProgress("\033[1D");
        }

        delete this.async;
    },

    log: function (msg) {
        var context = (this.contextNames || []).join(" ");
        var test = this.currentTest;

        messages(this, context, test).push(
            "[" + msg.level.toUpperCase() + "] " + msg.message);
    },

    printProgress: function (str) {
        if (!this.displayProgress) {
            return;
        }

        this.io.print(str);
    }
});
<|endoftext|>


<commit_before>/* ***** ----------------------------------------------- ***** **
** ***** Global Scripts JS
** ***** ----------------------------------------------- ***** */

/* global Main, Modernizr */
(function($){
	'use strict';

	Main.modules.globalScripts = function() {

		var $body = $('.js-body'),
			upgradeMessage = '
For a better browsing experience, please upgrade your browser to the latest version. Click here upgrade.
',
			utilities = Main.modules.utilities(),
			isDevice = utilities.isDevice(),

			modernizrCheck = function() {

				// Display message for user to upgrade if browser does not support flexbox
				if (Modernizr['flexbox'] == false
					|| Modernizr['svg'] == false) {
					$body.append(upgradeMessage);
				}

			},

			addNotDeviceClassToBody = function() {

				if (!isDevice) {
					$body.addClass('l-not_device');
				}

			};

		return {
			init: function() {
				modernizrCheck();
				addNotDeviceClassToBody();
			}
		}

	};

})(jQuery);<commit_msg>Update upgrade message<commit_after>/* ***** ----------------------------------------------- ***** **
** ***** Global Scripts JS
** ***** ----------------------------------------------- ***** */

/* global Main, Modernizr */
(function($){
	'use strict';

	Main.modules.globalScripts = function() {

		var $body = $('.js-body'),
			upgradeMessage = '
For a better browsing experience, please upgrade your browser to the latest version. Click here to upgrade.
',
			utilities = Main.modules.utilities(),
			isDevice = utilities.isDevice(),

			modernizrCheck = function() {

				// Display message for user to upgrade if browser does not support flexbox
				if (Modernizr['flexbox'] == false
					|| Modernizr['svg'] == false) {
					$body.append(upgradeMessage);
				}

			},

			addNotDeviceClassToBody = function() {

				if (!isDevice) {
					$body.addClass('l-not_device');
				}

			};

		return {
			init: function() {
				modernizrCheck();
				addNotDeviceClassToBody();
			}
		}

	};

})(jQuery);<|endoftext|>


<commit_before>// JavaScript Document

// Scripts written by __gulp_init_author_name__ @ __gulp_init_author_company__

import transition from "transition-to-from-auto";
import inViewport from "in-vp";

/**
 * Create an array of attribtes to target lists for
 */
const ATTRIBUTES = {
    classes:  ["menu-list", "menu-list__container--mega"],
    datasets: ["accordion", "hover", "touch"],
};

const SELECTOR = [];

/**
 * Create an array out of the CLASSES and DATAS in order to reduce duplicate code.
 */
ATTRIBUTES.classes.forEach((CLASS) => {
    ATTRIBUTES.datasets.forEach((DATA) => {
        SELECTOR.push(`.${CLASS}[data-${DATA}=true]`);
    });
});

/**
 * Find all MENU_LISTS which can be hovered or touched
 */
const MENU_LISTS = document.querySelectorAll(SELECTOR.join());

/**
 * Mark an item active
 *
 * @param {Object} LIST_ITEM - A DOM object to mark as active
 * @param {Object} MENU_LIST - A DOM object to mark as visible and reverse based on viewport
 * @param {Boolean} EVENT - An event to prevent from firing
 */
const MARK_ACTIVE = (LIST_ITEM, MENU_LIST, EVENT = false) => {
    /**
     * Prevent the EVENT from finishing unless the LIST_ITEM is already active
     */
    if (EVENT && !LIST_ITEM.classList.contains("is-active")) {
        EVENT.preventDefault();
    }

    /**
     * Mark the LIST_ITEM as active
     */
    LIST_ITEM.classList.add("is-active");

    /**
     * Transition open the MENU_LIST if it's an accordion
     */
    if (MENU_LIST.dataset.accordion === "true") {
        transition({ element: MENU_LIST, val: "auto" });
    }

    /**
     * Mark the MENU_LIST as aria-hidden="false"
     */
    MENU_LIST.setAttribute("aria-hidden", "false");

    /**
     * Reverse the MENU_LIST if it's not fully within the viewport
     */
    if (inViewport(MENU_LIST).fully === false) {
        MENU_LIST.classList.add("menu-list--reverse");
    }
};

/**
 * Mark an item and its children inactive
 *
 * @param {Object} LIST_ITEM - A DOM object to mark as inactive
 * @param {Object} MENU_LIST - A DOM object to mark as hidden and unreverse
 */
const MARK_INACTIVE = (LIST_ITEM, MENU_LIST) => {
    /**
     * Find any active CHILDREN
     */
    const CHILDREN = LIST_ITEM.querySelectorAll("is-active");

    /**
     * Recursively mark active CHILDREN as inactive
     */
    if (CHILDREN.length > 0) {
        CHILDREN.foreach((CHILD) => {
            MARK_INACTIVE(CHILD);
        });
    }

    /**
     * Mark the LIST_ITEM as inactive
     */
    LIST_ITEM.classList.remove("is-active");

    /**
     * Transition open the MENU_LIST if it's an accordion
     */
    if (MENU_LIST.dataset.accordion === "true") {
        transition({ element: MENU_LIST, val: 0 });
    }

    /**
     * Mark the MENU_LIST as aria-hidden="false"
     */
    MENU_LIST.setAttribute("aria-hidden", "true");

    /**
     * Unreverse the MENU_LIST
     */
    MENU_LIST.classList.remove("menu-list--reverse");
};

/**
 * Store various events to listen for
 */
const EVENTS = {
    document:  ["click", "touchstart"],
    list_item: {
        activate: {
            accordion: "touchstart",
            hover:     "mouseenter",
            touch:     "touchstart",
        },
        deactivate: ["mouseleave"],
    },
};

/**
 * Listen for interactions on each menu
 */
MENU_LISTS.forEach((MENU_LIST) => {
    const LIST_ITEM   = MENU_LIST.closest(".menu-list__item");
    const MENU_TOGGLE = LIST_ITEM.querySelector(".menu-list__toggle");

    /**
     * Mark the LIST_ITEM as active when moused into or touched
     */
    for (const DATA in EVENTS.list_item.activate) {
        if (MENU_LIST.dataset[DATA] === "true") {
            LIST_ITEM.addEventListener(EVENTS.list_item.activate[DATA], (e) => {
                MARK_ACTIVE(LIST_ITEM, MENU_LIST, e);
            });
        }
    }

    /**
     * Mark the LIST_ITEM as inactive when moused away
     */
    EVENTS.list_item.deactivate.forEach((EVENT) => {
        LIST_ITEM.addEventListener(EVENT, () => {
            MARK_INACTIVE(LIST_ITEM, MENU_LIST);
        });
    });

    /**
     * Mark the LIST_ITEM as active or inactive when MENU_TOGGLE is clicked
     */
    MENU_TOGGLE.addEventListener("click", () => {
        if (!LIST_ITEM.classList.contains("is-active")) {
            MARK_ACTIVE(LIST_ITEM, MENU_LIST);
        } else {
            MARK_INACTIVE(LIST_ITEM, MENU_LIST);
        }
    });

    /**
     * Mark the LIST_ITEM as inactive when clicked away or touched away
     */
    EVENTS.document.forEach((EVENT) => {
        document.addEventListener(EVENT, (e) => {
            if (LIST_ITEM.classList.contains("is-active")) {
                /**
                 * Determine if the LIST_ITEM is in the path of touched elements
                 */
                const LIST_ITEM_TOUCHED = e.path.some((ELEMENT) => {
                    if (LIST_ITEM === ELEMENT) {
                        return true;
                    }
                });

                /**
                 * Mark the LIST_ITEM as inactive if it's not in the path of touched elements
                 */
                if (!LIST_ITEM_TOUCHED) {
                    MARK_INACTIVE(LIST_ITEM, MENU_LIST);
                }
            }
        });
    });
});
<commit_msg>Use e.composedPath if e.path isn't available<commit_after>// JavaScript Document

// Scripts written by __gulp_init_author_name__ @ __gulp_init_author_company__

import transition from "transition-to-from-auto";
import inViewport from "in-vp";

/**
 * Create an array of attribtes to target lists for
 */
const ATTRIBUTES = {
    classes:  ["menu-list", "menu-list__container--mega"],
    datasets: ["accordion", "hover", "touch"],
};

const SELECTOR = [];

/**
 * Create an array out of the CLASSES and DATAS in order to reduce duplicate code.
 */
ATTRIBUTES.classes.forEach((CLASS) => {
    ATTRIBUTES.datasets.forEach((DATA) => {
        SELECTOR.push(`.${CLASS}[data-${DATA}=true]`);
    });
});

/**
 * Find all MENU_LISTS which can be hovered or touched
 */
const MENU_LISTS = document.querySelectorAll(SELECTOR.join());

/**
 * Mark an item active
 *
 * @param {Object} LIST_ITEM - A DOM object to mark as active
 * @param {Object} MENU_LIST - A DOM object to mark as visible and reverse based on viewport
 * @param {Boolean} EVENT - An event to prevent from firing
 */
const MARK_ACTIVE = (LIST_ITEM, MENU_LIST, EVENT = false) => {
    /**
     * Prevent the EVENT from finishing unless the LIST_ITEM is already active
     */
    if (EVENT && !LIST_ITEM.classList.contains("is-active")) {
        EVENT.preventDefault();
    }

    /**
     * Mark the LIST_ITEM as active
     */
    LIST_ITEM.classList.add("is-active");

    /**
     * Transition open the MENU_LIST if it's an accordion
     */
    if (MENU_LIST.dataset.accordion === "true") {
        transition({ element: MENU_LIST, val: "auto" });
    }

    /**
     * Mark the MENU_LIST as aria-hidden="false"
     */
    MENU_LIST.setAttribute("aria-hidden", "false");

    /**
     * Reverse the MENU_LIST if it's not fully within the viewport
     */
    if (inViewport(MENU_LIST).fully === false) {
        MENU_LIST.classList.add("menu-list--reverse");
    }
};

/**
 * Mark an item and its children inactive
 *
 * @param {Object} LIST_ITEM - A DOM object to mark as inactive
 * @param {Object} MENU_LIST - A DOM object to mark as hidden and unreverse
 */
const MARK_INACTIVE = (LIST_ITEM, MENU_LIST) => {
    /**
     * Find any active CHILDREN
     */
    const CHILDREN = LIST_ITEM.querySelectorAll("is-active");

    /**
     * Recursively mark active CHILDREN as inactive
     */
    if (CHILDREN.length > 0) {
        CHILDREN.foreach((CHILD) => {
            MARK_INACTIVE(CHILD);
        });
    }

    /**
     * Mark the LIST_ITEM as inactive
     */
    LIST_ITEM.classList.remove("is-active");

    /**
     * Transition open the MENU_LIST if it's an accordion
     */
    if (MENU_LIST.dataset.accordion === "true") {
        transition({ element: MENU_LIST, val: 0 });
    }

    /**
     * Mark the MENU_LIST as aria-hidden="false"
     */
    MENU_LIST.setAttribute("aria-hidden", "true");

    /**
     * Unreverse the MENU_LIST
     */
    MENU_LIST.classList.remove("menu-list--reverse");
};

/**
 * Store various events to listen for
 */
const EVENTS = {
    document:  ["click", "touchstart"],
    list_item: {
        activate: {
            accordion: "touchstart",
            hover:     "mouseenter",
            touch:     "touchstart",
        },
        deactivate: ["mouseleave"],
    },
};

/**
 * Listen for interactions on each menu
 */
MENU_LISTS.forEach((MENU_LIST) => {
    const LIST_ITEM   = MENU_LIST.closest(".menu-list__item");
    const MENU_TOGGLE = LIST_ITEM.querySelector(".menu-list__toggle");

    /**
     * Mark the LIST_ITEM as active when moused into or touched
     */
    for (const DATA in EVENTS.list_item.activate) {
        if (MENU_LIST.dataset[DATA] === "true") {
            LIST_ITEM.addEventListener(EVENTS.list_item.activate[DATA], (e) => {
                MARK_ACTIVE(LIST_ITEM, MENU_LIST, e);
            });
        }
    }

    /**
     * Mark the LIST_ITEM as inactive when moused away
     */
    EVENTS.list_item.deactivate.forEach((EVENT) => {
        LIST_ITEM.addEventListener(EVENT, () => {
            MARK_INACTIVE(LIST_ITEM, MENU_LIST);
        });
    });

    /**
     * Mark the LIST_ITEM as active or inactive when MENU_TOGGLE is clicked
     */
    MENU_TOGGLE.addEventListener("click", () => {
        if (!LIST_ITEM.classList.contains("is-active")) {
            MARK_ACTIVE(LIST_ITEM, MENU_LIST);
        } else {
            MARK_INACTIVE(LIST_ITEM, MENU_LIST);
        }
    });

    /**
     * Mark the LIST_ITEM as inactive when clicked away or touched away
     */
    EVENTS.document.forEach((EVENT) => {
        document.addEventListener(EVENT, (e) => {
            if (LIST_ITEM.classList.contains("is-active")) {
                /**
                 * Get the event path
                 */
                const PATH = e.path || (e.composedPath && e.composedPath());

                /**
                 * Determine if the LIST_ITEM is in the path of touched elements
                 */
                const LIST_ITEM_TOUCHED = PATH.some((ELEMENT) => {
                    if (LIST_ITEM === ELEMENT) {
                        return true;
                    }
                });

                /**
                 * Mark the LIST_ITEM as inactive if it's not in the path of touched elements
                 */
                if (!LIST_ITEM_TOUCHED) {
                    MARK_INACTIVE(LIST_ITEM, MENU_LIST);
                }
            }
        });
    });
});
<|endoftext|>