<commit_before>/**
 * Immutable global app settings used to configure how Lurka behaves.
 *
 * To see the effects you must either rebuild the project or run in dev mode.
 * See package.json -> scripts
 */

if (typeof window === 'undefined') {
    global.window = {}  // For tests
}

window.appSettings = {
    // The spacing between board posts
    boardOuterMargin: 30,
    boardPostMargin: 25,

    // when you click on a reference in a thread
    threadpostScrollDuration: 600,

    // how long to keep a thread highlighted on scroll
    threadpostScrollHighlightDuration: 2000,

    // The following settings can't be changed explcitly.
    // Needs to be kept in sync with src/sass/partials/_config.sass
    headerHeight: 64,
    subheaderHeight: 50,
    threadWidth: 981,
    settingsWidth: 256,

    homeViewID: 'HomeView',
    contentViewID: 'ContentView',
    settingsViewID: 'SettingsView',

    iconPackName: 'lurka',
    icons: {

        home: "", // TODO: Set this

        // navbarMenu: "navicon",
        navbarForwards: "arrow-big-right",
        navbarBackwards: "arrow-big-left",

        navbarInfo: 'information',
        navbarRefresh: 'refresh',

        navbarAccount:  'person-add',
        navbarBookmark: 'bookmark',
        navbarDB:       'data',
        navbarEye:      'eye-2',
        navbarSettings: 'cog',
        navbarTheme: 'paint-brush-2',
        navbarMenu: 'menu',

        subNavbarOpen: 'chevron-down',
        subNavbarClose: 'chevron-up',

        searchMagnify: "search-1",
        searchClose: "times",

        videoFullscreen: "arrow-expand",
        videoPlay: "playback-play",
        videoPause: "playback-pause",
        videoError: "warning-alt",
        videoVolumeOff: "volume-disabled",
        videoVolumeMute: "volume-mute",
        videoVolumeLow: "volume-low",
        videoVolumeMedium: "volume-med",
        videoVolumeHigh: "volume-high",

        boardPostReplyCount: "mesage-1",
        boardPostImageCount: "image",

        // threadPostImageFullscreen: 'arrow-expand',

        threadPostMenu: 'dot-3',
        threadPostControlsReport: "flag",
        threadPostControlsBookmark: "bookmark",
        threadPostControlsReply: "quote",
        threadPostControlsImageSearch: "search-2",
        threadPostControlsHide: "minus-circle",

        watchPanelClose: "times",
        // watcchPanelUpdate: "update",

        "footerSort": "bar-chart",
        "footerFilter": "filter-outline",
        "footerLayout": "layout",
        "footerInfo": "info",
        "footerOpen": "chevron-up",
        "footerClose": "chevron-down",
    }
}
<commit_msg>config: Update icons<commit_after>/**
 * Immutable global app settings used to configure how Lurka behaves.
 *
 * To see the effects you must either rebuild the project or run in dev mode.
 * See package.json -> scripts
 */

if (typeof window === 'undefined') {
    global.window = {}  // For tests
}

window.appSettings = {
    // The spacing between board posts
    boardOuterMargin: 30,
    boardPostMargin: 25,

    // when you click on a reference in a thread
    threadpostScrollDuration: 600,

    // how long to keep a thread highlighted on scroll
    threadpostScrollHighlightDuration: 2000,

    // The following settings can't be changed explcitly.
    // Needs to be kept in sync with src/sass/partials/_config.sass
    headerHeight: 64,
    subheaderHeight: 50,
    threadWidth: 981,
    settingsWidth: 256,

    homeViewID: 'HomeView',
    contentViewID: 'ContentView',
    settingsViewID: 'SettingsView',

    iconPackName: 'lurka',
    icons: {

        home: "", // TODO: Set this

        // navbarMenu: "navicon",
        navbarForwards: "arrow-big-right",
        navbarBackwards: "arrow-big-left",

        navbarInfo: 'information',
        navbarRefresh: 'refresh',

        navbarAccount:  'person-add',
        navbarBookmark: 'bookmark',
        navbarDB:       'data',
        navbarEye:      'eye-2',
        navbarSettings: 'cog',
        navbarTheme: 'paint-brush-2',
        navbarMenu: 'menu',

        subNavbarOpen: 'chevron-down',
        subNavbarClose: 'chevron-up',

        searchMagnify: "search-1",
        searchClose: "times",

        videoFullscreen: "expand-2",
        videoDownload: "download-1",
        videoPlay: "playback-play",
        videoPause: "playback-pause",
        videoError: "warning-alt",
        videoVolumeOff: "volume-disabled",
        videoVolumeMute: "volume-mute",
        videoVolumeLow: "volume-low",
        videoVolumeMedium: "volume-med",
        videoVolumeHigh: "volume-high",

        boardPostReplyCount: "mesage-1",
        boardPostImageCount: "image",

        // threadPostImageFullscreen: 'arrow-expand',

        threadPostMenu: 'dot-3',
        threadPostControlsReport: "flag",
        threadPostControlsBookmark: "bookmark",
        threadPostControlsReply: "quote",
        threadPostControlsImageSearch: "search-2",
        threadPostControlsHide: "minus-circle",

        watchPanelClose: "times",
        // watcchPanelUpdate: "update",

        footerSort: "bar-chart",
        footerFilter: "filter-outline",
        footerLayout: "layout",
        footerInfo: "info",
        footerOpen: "chevron-up",
        footerClose: "chevron-down",
    }
}
<|endoftext|>


<commit_before>// balance.js
App.Views.Charts.Balance = Backbone.View.extend({

	events: {
	},
	chart: false,
	aTransactions: [],
	_data: {},
	dataReady: false,
	dataFetched: false,

	initialize: function() {
		if (!this.model || !this.id)
			console.error('views/charts/balance.js | model(wallet) and id of canvas should be provided for this view');
	},
	fetchTransactions: function() {
		if (this.aTransactions.length)
		{
			this.trigger('transactionsReady');
			return this.aTransactions;
		}

		var transactions = new App.Collections.Transactions();
		this.aTransactions = [];
        transactions.setWalletId(this.model.id);

        var that = this;
        transactions.once('sync',function(){
        	console.log('Synced current month');
        	transactions.forEach(function(t){
        		that.aTransactions.push(t);
        	});

        	transactions.once('sync',function(){
        	console.log('Synced prev month');
	        	transactions.forEach(function(t){
	        		that.aTransactions.push(t);
	        	});

	        	that.trigger('transactionsReady');
        	});
        	transactions.gotoPrev();
        });

        transactions.fetch();
	},
	fetchData: function() {
		if (this.dataFetched)
			return false;
		if (this.dataReady)
		{
			return this._data;
		}

		this.dataFetched = true;

		var that = this;
		this.once('transactionsReady',function(){
			_.each(this.aTransactions, function(item){
				console.log(item.get('amount'));
			});
			//// first step. Filter expenses
			var a = _.filter(this.aTransactions, function(t){ return t.get('amount') < 0; });

			//// second step. For each day
			var days = {};
			var curTime = new Date();
			var curDay = curTime.getDate();
			var curMonth = curTime.getMonth();
			curTime = curTime.getTime();
			for (var i = 0; i <= 60; i++)
			{
				var d = new Date(curTime - 24*60*60*1000*i);
				var day = d.getDate();
				var month = d.getMonth();
				var dayTotal = 0;
				_.each(a, function(t){
					var tDate = new Date(t.get('datetime')*1000);
					if (tDate.getDate() == day && tDate.getMonth() == month)
						dayTotal += Math.abs(t.get('amount'));
				});
				days[day+'-'+month] = {day: day, month: month, total: dayTotal};
			}
			/// third step. Find first day from a set at which transaction occurs.
			var firstDay = 0;
			var firstMonth = 0;
			_.each(days, function(day){
				if (day.total > 0)
				{
					if (firstDay == 0 && firstMonth == 0)
					{
						firstDay = day.day;
						firstMonth = day.month;
					}

					if (day.month < firstMonth || day.day < firstDay)
					{
						firstDay = day.day;
						firstMonth = day.month;
					}
				}
			});

			/// forth step. Fill days without transactions by values from next days started from firstDay
			if (firstDay)
			_.each(days, function(d){
				if (firstMonth < d.month || (firstDay < d.day && firstMonth == d.month))
				{
					if (d.total == 0 && typeof(d.filledMissed) === 'undefined')
					{
						var foundTotal = 0;
						var foundEmpty = [];
						var iDay = d.day + 1;
						var iMonth = d.month;
						foundEmpty.push(d.day+'-'+d.month);

						while ((foundTotal == 0) && ((curMonth == iMonth && curDay >= iDay) || (curMonth > iMonth)) )
						if (typeof(days[iDay+'-'+iMonth]) !== 'undefined')
						{

							if (days[iDay+'-'+iMonth].total == 0)
							{
								/// another empty day
								foundEmpty.push(iDay+'-'+iMonth);
							} else {
								/// day with total set
								foundEmpty.push(iDay+'-'+iMonth);
								foundTotal = days[iDay+'-'+iMonth].total;
							}

							iDay++;

						} else {
							/// next month
							iMonth++;
							iDay = 1;
						}

						//// fill missed sum
						foundEmpty = _.uniq(foundEmpty);
						if (foundTotal > 0 && foundEmpty.length > 0)
						{
							var total = foundTotal / foundEmpty.length;
							_.each(foundEmpty, function(found){
								days[found].total = total;
								days[found].filledMissed = true;
							});
						}
					}
				}
			});

			/// fifth step. Filter days with total set and truncate to 30 max
			//days = _.filter(days, function(d){ return d.total > 0; });
			//days = _.last(days, 30);

			/// generate labels
			//days.reverse();
			var values = [];
			_.each(days, function(day, key){
				values.push({label: day.day+'/'+(day.month+1), value: day.total});
			});
			values.reverse();
			values = _.last(values, 31);

			/// remove empty from the start
			var alreadyStarted = false;
			values = _.filter(values, function(item){ if (item.value > 0 || alreadyStarted) { alreadyStarted = true; return true; } else return false; });

			/// group by
			if (values.length > 10)
			{
				var rvalues = [];
				var i = 0;
				if (values.length > 20)
				{
					/// by 3
					while (typeof(values[i]) !== 'undefined')
					{
						var rvalue = values[i].value;
						if (typeof(values[i+1]) !== 'undefined') rvalue+=values[i+1].value;
						if (typeof(values[i+2]) !== 'undefined') rvalue+=values[i+2].value;

						var rlabel = values[i].label;
						if (typeof(values[i+2]) !== 'undefined') rlabel+=' -
'+values[i+2].label;
						else
						if (typeof(values[i+1]) !== 'undefined') rlabel+=' -
'+values[i+1].label;

						rvalues.push({label: rlabel, value: rvalue});
						i = i + 3;
					}
				} else {
					/// by 2
					while (typeof(values[i]) !== 'undefined')
					{
						var rvalue = values[i].value;
						if (typeof(values[i+1]) !== 'undefined') rvalue+=values[i+1].value;

						var rlabel = values[i].label;
						if (typeof(values[i+1]) !== 'undefined') rlabel+=' -
'+values[i+1].label;

						rvalues.push({label: rlabel, value: rvalue});
						i = i + 2;
					}
				}

				values = rvalues;
			}

			var labels = _.map(values, function(item){ return item.label; });
			var series = [[]];
			series[0] = _.map(values, function(item){ return item.value; });

			that._data = {labels: labels, series: series};
			console.log(that._data);
			that.dataFetched = false;

			that.dataReady = true;
        	that.trigger('dataReady');
		});
		this.fetchTransactions();
	},
	data: function() {
		this.fetchData();
		return  {
			labels: ['11/12', '12/12', '13/12', '14/12', '15/12','11/12', '12/12', '13/12', '14/12', '15/12'],
			series: [
				[560,560,500,450.55,500,560,560,500,450.55,100]
			]
		};
	},
	wakeUp: function() {
		this.render();
	},
	render: function() {
		console.log('Rendering chart');
		console.log(this.id);
		console.log($('#'+this.id));
		if (!$('#'+this.id).length)
			return;

		this.once('dataReady', function(){
			this.chart = new Chartist.Bar('#'+this.id, this._data, {
				low: 0,
				chartPadding: 0,
				fullWidth: false
			});
		});
		this.fetchData();
	}
});
<commit_msg>charts<commit_after>// balance.js
App.Views.Charts.Balance = Backbone.View.extend({

	events: {
	},
	chart: false,
	aTransactions: [],
	_data: {},
	dataReady: false,
	dataFetched: false,

	initialize: function() {
		if (!this.model || !this.id)
			console.error('views/charts/balance.js | model(wallet) and id of canvas should be provided for this view');
	},
	fetchTransactions: function() {
		if (this.aTransactions.length)
		{
			this.trigger('transactionsReady');
			return this.aTransactions;
		}

		var transactions = new App.Collections.Transactions();
		this.aTransactions = [];
        transactions.setWalletId(this.model.id);

        var that = this;
        transactions.once('sync',function(){
        	console.log('Synced current month');
        	transactions.forEach(function(t){
        		that.aTransactions.push(t);
        	});

        	transactions.once('sync',function(){
        	console.log('Synced prev month');
	        	transactions.forEach(function(t){
	        		that.aTransactions.push(t);
	        	});

	        	that.trigger('transactionsReady');
        	});
        	transactions.gotoPrev();
        });

        transactions.fetch();
	},
	fetchData: function() {
		if (this.dataFetched)
			return false;
		if (this.dataReady)
		{
			return this._data;
		}

		this.dataFetched = true;

		var that = this;
		this.once('transactionsReady',function(){
			_.each(this.aTransactions, function(item){
				console.log(item.get('amount'));
			});
			//// first step. Filter expenses
			var a = _.filter(this.aTransactions, function(t){ return t.get('amount') < 0; });

			//// second step. For each day
			var days = {};
			var curTime = new Date();
			var curDay = curTime.getDate();
			var curMonth = curTime.getMonth();
			curTime = curTime.getTime();
			for (var i = 0; i <= 60; i++)
			{
				var d = new Date(curTime - 24*60*60*1000*i);
				var day = d.getDate();
				var month = d.getMonth();
				var dayTotal = 0;
				_.each(a, function(t){
					var tDate = new Date(t.get('datetime')*1000);
					if (tDate.getDate() == day && tDate.getMonth() == month)
						dayTotal += Math.abs(t.get('amount'));
				});
				days[day+'-'+month] = {day: day, month: month, total: dayTotal};
			}
			/// third step. Find first day from a set at which transaction occurs.
			var firstDay = 0;
			var firstMonth = 0;
			_.each(days, function(day){
				if (day.total > 0)
				{
					if (firstDay == 0 && firstMonth == 0)
					{
						firstDay = day.day;
						firstMonth = day.month;
					}

					if (day.month < firstMonth || day.day < firstDay)
					{
						firstDay = day.day;
						firstMonth = day.month;
					}
				}
			});

			/// forth step. Fill days without transactions by values from next days started from firstDay
			if (firstDay)
			_.each(days, function(d){
				if (firstMonth < d.month || (firstDay < d.day && firstMonth == d.month))
				{
					if (d.total == 0 && typeof(d.filledMissed) === 'undefined')
					{
						var foundTotal = 0;
						var foundEmpty = [];
						var iDay = d.day + 1;
						var iMonth = d.month;
						foundEmpty.push(d.day+'-'+d.month);

						while ((foundTotal == 0) && ((curMonth == iMonth && curDay >= iDay) || (curMonth > iMonth)) )
						if (typeof(days[iDay+'-'+iMonth]) !== 'undefined')
						{

							if (days[iDay+'-'+iMonth].total == 0)
							{
								/// another empty day
								foundEmpty.push(iDay+'-'+iMonth);
							} else {
								/// day with total set
								foundEmpty.push(iDay+'-'+iMonth);
								foundTotal = days[iDay+'-'+iMonth].total;
							}

							iDay++;

						} else {
							/// next month
							iMonth++;
							iDay = 1;
						}

						//// fill missed sum
						foundEmpty = _.uniq(foundEmpty);
						if (foundTotal > 0 && foundEmpty.length > 0)
						{
							var total = foundTotal / foundEmpty.length;
							_.each(foundEmpty, function(found){
								days[found].total = total;
								days[found].filledMissed = true;
							});
						}
					}
				}
			});

			/// fifth step. Filter days with total set and truncate to 30 max
			//days = _.filter(days, function(d){ return d.total > 0; });
			//days = _.last(days, 30);

			/// generate labels
			//days.reverse();
			var values = [];
			_.each(days, function(day, key){
				values.push({label: day.day+'/'+(day.month+1), value: day.total});
			});
			values.reverse();
			values = _.last(values, 31);

			/// remove empty from the start
			var alreadyStarted = false;
			values = _.filter(values, function(item){ if (item.value > 0 || alreadyStarted) { alreadyStarted = true; return true; } else return false; });

			/// group by
			if (values.length > 10)
			{
				var rvalues = [];
				var i = 0;
				if (values.length > 20)
				{
					/// by 3
					while (typeof(values[i]) !== 'undefined')
					{
						var rvalue = values[i].value;
						if (typeof(values[i+1]) !== 'undefined') rvalue+=values[i+1].value;
						if (typeof(values[i+2]) !== 'undefined') rvalue+=values[i+2].value;

						if (typeof(values[i+1]) !== 'undefined' && typeof(values[i+2]) !== 'undefined')
							rvalue = rvalue / 3;
						else if (typeof(values[i+1]) !== 'undefined')
							rvalue = rvalue / 2;

						var rlabel = values[i].label;
						if (typeof(values[i+2]) !== 'undefined') rlabel+=' -
'+values[i+2].label;
						else
						if (typeof(values[i+1]) !== 'undefined') rlabel+=' -
'+values[i+1].label;

						rvalues.push({label: rlabel, value: rvalue});
						i = i + 3;
					}
				} else {
					/// by 2
					while (typeof(values[i]) !== 'undefined')
					{
						var rvalue = values[i].value;
						if (typeof(values[i+1]) !== 'undefined') rvalue+=values[i+1].value;

						if (typeof(values[i+1]) !== 'undefined')
							rvalue = rvalue / 2;

						var rlabel = values[i].label;
						if (typeof(values[i+1]) !== 'undefined') rlabel+=' -
'+values[i+1].label;

						rvalues.push({label: rlabel, value: rvalue});
						i = i + 2;
					}
				}

				values = rvalues;
			}

			var labels = _.map(values, function(item){ return item.label; });
			var series = [[]];
			series[0] = _.map(values, function(item){ return item.value; });

			that._data = {labels: labels, series: series};
			console.log(that._data);
			that.dataFetched = false;

			that.dataReady = true;
        	that.trigger('dataReady');
		});
		this.fetchTransactions();
	},
	data: function() {
		this.fetchData();
		return  {
			labels: ['11/12', '12/12', '13/12', '14/12', '15/12','11/12', '12/12', '13/12', '14/12', '15/12'],
			series: [
				[560,560,500,450.55,500,560,560,500,450.55,100]
			]
		};
	},
	wakeUp: function() {
		this.render();
	},
	render: function() {
		console.log('Rendering chart');
		console.log(this.id);
		console.log($('#'+this.id));
		if (!$('#'+this.id).length)
			return;

		this.once('dataReady', function(){
			this.chart = new Chartist.Bar('#'+this.id, this._data, {
				low: 0,
				chartPadding: 0,
				fullWidth: false
			});
		});
		this.fetchData();
	}
});
<|endoftext|>


<commit_before>const Uppy = require('uppy/lib/core')
const Dashboard = require('uppy/lib/plugins/Dashboard')
const GoogleDrive = require('uppy/lib/plugins/GoogleDrive')
const Dropbox = require('uppy/lib/plugins/Dropbox')
const Instagram = require('uppy/lib/plugins/Instagram')
const Webcam = require('uppy/lib/plugins/Webcam')
const Tus10 = require('uppy/lib/plugins/Tus10')
const MetaData = require('uppy/lib/plugins/MetaData')

const UPPY_SERVER = require('../env')

const PROTOCOL = location.protocol === 'https:' ? 'https' : 'http'
const TUS_ENDPOINT = PROTOCOL + '://master.tus.io/files/'

function uppyInit () {
  const opts = window.uppyOptions
  const dashboardEl = document.querySelector('.UppyDashboard')
  if (dashboardEl) {
    const dashboardElParent = dashboardEl.parentNode
    dashboardElParent.removeChild(dashboardEl)
  }

  const restrictions = {
    maxFileSize: 1000000,
    maxNumberOfFiles: 3,
    minNumberOfFiles: 2,
    allowedFileTypes: ['image/*', 'video/*']
  }

  const uppy = Uppy({
    debug: true,
    autoProceed: opts.autoProceed,
    restrictions: opts.restrictions ? restrictions : ''
  })

  uppy.use(Dashboard, {
    trigger: '.UppyModalOpenerBtn',
    inline: opts.DashboardInline,
    target: opts.DashboardInline ? '.DashboardContainer' : 'body'
  })

  if (opts.GoogleDrive) {
    uppy.use(GoogleDrive, {target: Dashboard, host: UPPY_SERVER})
  }

  if (opts.Dropbox) {
    uppy.use(Dropbox, {target: Dashboard, host: UPPY_SERVER})
  }

  if (opts.Instagram) {
    uppy.use(Instagram, {target: Dashboard, host: UPPY_SERVER})
  }

  if (opts.Webcam) {
    uppy.use(Webcam, {target: Dashboard})
  }

  uppy.use(Tus10, {endpoint: TUS_ENDPOINT, resume: true})
  uppy.use(MetaData, {
    fields: [
      { id: 'resizeTo', name: 'Resize to', value: 1200, placeholder: 'specify future image size' },
      { id: 'description', name: 'Description', value: 'none', placeholder: 'describe what the file is for' }
    ]
  })
  uppy.run()

  uppy.on('core:success', (fileList) => {
    console.log('Yo, uploaded: ')
    console.log(fileList)
  })
}

uppyInit()
window.uppyInit = uppyInit
<commit_msg>add `note` if restrictions are selected in Dashboard example<commit_after>const Uppy = require('uppy/lib/core')
const Dashboard = require('uppy/lib/plugins/Dashboard')
const GoogleDrive = require('uppy/lib/plugins/GoogleDrive')
const Dropbox = require('uppy/lib/plugins/Dropbox')
const Instagram = require('uppy/lib/plugins/Instagram')
const Webcam = require('uppy/lib/plugins/Webcam')
const Tus10 = require('uppy/lib/plugins/Tus10')
const MetaData = require('uppy/lib/plugins/MetaData')

const UPPY_SERVER = require('../env')

const PROTOCOL = location.protocol === 'https:' ? 'https' : 'http'
const TUS_ENDPOINT = PROTOCOL + '://master.tus.io/files/'

function uppyInit () {
  const opts = window.uppyOptions
  const dashboardEl = document.querySelector('.UppyDashboard')
  if (dashboardEl) {
    const dashboardElParent = dashboardEl.parentNode
    dashboardElParent.removeChild(dashboardEl)
  }

  const restrictions = {
    maxFileSize: 1000000,
    maxNumberOfFiles: 3,
    minNumberOfFiles: 2,
    allowedFileTypes: ['image/*', 'video/*']
  }

  const uppy = Uppy({
    debug: true,
    autoProceed: opts.autoProceed,
    restrictions: opts.restrictions ? restrictions : ''
  })

  uppy.use(Dashboard, {
    trigger: '.UppyModalOpenerBtn',
    inline: opts.DashboardInline,
    target: opts.DashboardInline ? '.DashboardContainer' : 'body',
    note: opts.restrictions ? 'Images and video only, 300kb or less' : ''
  })

  if (opts.GoogleDrive) {
    uppy.use(GoogleDrive, {target: Dashboard, host: UPPY_SERVER})
  }

  if (opts.Dropbox) {
    uppy.use(Dropbox, {target: Dashboard, host: UPPY_SERVER})
  }

  if (opts.Instagram) {
    uppy.use(Instagram, {target: Dashboard, host: UPPY_SERVER})
  }

  if (opts.Webcam) {
    uppy.use(Webcam, {target: Dashboard})
  }

  uppy.use(Tus10, {endpoint: TUS_ENDPOINT, resume: true})
  uppy.use(MetaData, {
    fields: [
      { id: 'resizeTo', name: 'Resize to', value: 1200, placeholder: 'specify future image size' },
      { id: 'description', name: 'Description', value: 'none', placeholder: 'describe what the file is for' }
    ]
  })
  uppy.run()

  uppy.on('core:success', (fileList) => {
    console.log('Yo, uploaded: ')
    console.log(fileList)
  })
}

uppyInit()
window.uppyInit = uppyInit
<|endoftext|>


<commit_before>// Opening for events
const eventTitle = getElementByClassName('event-title', 0)
const eventSubtitle = getElementByClassName('event-subtitle', 0)
const eventDetails = getElementByClassName('event-details', 0)
// Fade in first slide
eventTitle.classList.add('fade-move')
eventSubtitle.classList.add('fade-move')
eventDetails.classList.add('fade-move')
// Email signup form
setTimeout(() => changeEmailContainerBackground(getElementByClassName('email-container-background', 0)), 600)

// Event listener for if reg form is closed
const regFormModalStatus = getElementByClassName('modal-status registration', 0)
const regFormModal = getElementByClassName('modal registration', 0)
const regFormModalWindow = getElementByClassName('modal-window registration', 0)
const regFormContainer = getElementByClassName('container reg-form', 0)
const regFormButtons = getElementsByClassName('button register')
for (let i = 0; i < regFormButtons.length; i++) {
	onClick(regFormButtons[i], () => {
		// Prepare for fade in
		regFormModal.style.opacity = '0'
		// Unhide modal
		showElement(regFormModalStatus)
		// Fade in modal window
		setTimeout(() => regFormModal.style.opacity = '1.0', 100)
		setTimeout(() => {
			// Show reg form: browser error that doesn’t show opacity of elements inside modal window unless body is scrolled by 1 px and window opacity is set to 1 during scroll
			regFormContainer.scrollTop = 0
			window.scrollBy(0, 1)
			onScroll(regFormContainer, () => regFormModalWindow.style.opacity = '1.0')
		}, 300)
		// Prevent background from scrolling
		setTimeout(() => document.body.style.overflow = 'hidden', 500)
	})
}

const regFormClose = getElementByClassName('reg-form-close', 0)
onClick(regFormClose, () => {
	document.body.style.overflow = 'visible'
	regFormModal.style.opacity = '0'
	setTimeout(() => hideElement(regFormModalStatus), 200)
})

// Event summary “Read more...” expansion
getElementByClassName('text read-more', 0).addEventListener('mouseover', () => {
	hideElement(getElementByClassName('text read-more'))
	hideElement(getElementByClassName('text summary'))
	getElementByClassName('text description').classList.add('display')
	setTimeout(() => getElementByClassName('text description display').classList.add('fade'), 100)
})

// Prevent accidental submission of form through 'enter' key
onKeyPress(document, e => {
	if (isInput(e.target) && e.which === 13) {
		e.preventDefault()
		return false
	}
})

let countries = [{value:'AF',label:'Afghanistan'},{value:'AX',label:'Åland Islands'},{value:'AL',label:'Albania'},{value:'DZ',label:'Algeria'},{value:'AS',label:'American Samoa'},{value:'AD',label:'Andorra'},{value:'AO',label:'Angola'},{value:'AI',label:'Anguilla'},{value:'AQ',label:'Antarctica'},{value:'AG',label:'Antigua and Barbuda'},{value:'AR',label:'Argentina'},{value:'AM',label:'Armenia'},{value:'AW',label:'Aruba'},{value:'AU',label:'Australia'},{value:'AT',label:'Austria'},{value:'AZ',label:'Azerbaijan'},{value:'BS',label:'Bahamas'},{value:'BH',label:'Bahrain'},{value:'BD',label:'Bangladesh'},{value:'BB',label:'Barbados'},{value:'BY',label:'Belarus'},{value:'BE',label:'Belgium'},{value:'BZ',label:'Belize'},{value:'BJ',label:'Benin'},{value:'BM',label:'Bermuda'},{value:'BT',label:'Bhutan'},{value:'BO',label:'Bolivia'},{value:'BA',label:'Bosnia and Herzegovina'},{value:'BW',label:'Botswana'},{value:'BV',label:'Bouvet Island'},{value:'BR',label:'Brazil'},{value:'IO',label:'British Indian Ocean Territory'},{value:'BN',label:'Brunei Darussalam'},{value:'BG',label:'Bulgaria'},{value:'BF',label:'Burkina Faso'},{value:'BI',label:'Burundi'},{value:'KH',label:'Cambodia'},{value:'CM',label:'Cameroon'},{value:'CA',label:'Canada'},{value:'CV',label:'Cape Verde'},{value:'KY',label:'Cayman Islands'},{value:'CF',label:'Central African Republic'},{value:'TD',label:'Chad'},{value:'CL',label:'Chile'},{value:'CN',label:'China, People’s Republic of'},{value:'CX',label:'Christmas Island'},{value:'CC',label:'Cocos (Keeling) Islands'},{value:'CO',label:'Colombia'},{value:'KM',label:'Comoros'},{value:'CG',label:'Congo'},{value:'CD',label:'Congo, The Democratic Republic of the'},{value:'CK',label:'Cook Islands'},{value:'CR',label:'Costa Rica'},{value:'CI',label:'Cote D’Ivoire'},{value:'HR',label:'Croatia'},{value:'CU',label:'Cuba'},{value:'CY',label:'Cyprus'},{value:'CZ',label:'Czech Republic'},{value:'DK',label:'Denmark'},{value:'DJ',label:'Djibouti'},{value:'DM',label:'Dominica'},{value:'DO',label:'Dominican Republic'},{value:'EC',label:'Ecuador'},{value:'EG',label:'Egypt'},{value:'SV',label:'El Salvador'},{value:'GQ',label:'Equatorial Guinea'},{value:'ER',label:'Eritrea'},{value:'EE',label:'Estonia'},{value:'ET',label:'Ethiopia'},{value:'FK',label:'Falkland Islands (Malvinas)'},{value:'FO',label:'Faroe Islands'},{value:'FJ',label:'Fiji'},{value:'FI',label:'Finland'},{value:'FR',label:'France'},{value:'GF',label:'French Guiana'},{value:'PF',label:'French Polynesia'},{value:'TF',label:'French Southern Territories'},{value:'GA',label:'Gabon'},{value:'GM',label:'Gambia'},{value:'GE',label:'Georgia'},{value:'DE',label:'Germany'},{value:'GH',label:'Ghana'},{value:'GI',label:'Gibraltar'},{value:'GR',label:'Greece'},{value:'GL',label:'Greenland'},{value:'GD',label:'Grenada'},{value:'GP',label:'Guadeloupe'},{value:'GU',label:'Guam'},{value:'GT',label:'Guatemala'},{value:'GG',label:'Guernsey'},{value:'GN',label:'Guinea'},{value:'GW',label:'Guinea-Bissau'},{value:'GY',label:'Guyana'},{value:'HT',label:'Haiti'},{value:'HM',label:'Heard Island and Mcdonald Islands'},{value:'VA',label:'Holy See (Vatican City State)'},{value:'HN',label:'Honduras'},{value:'HK',label:'Hong Kong'},{value:'HU',label:'Hungary'},{value:'IS',label:'Iceland'},{value:'IN',label:'India'},{value:'ID',label:'Indonesia'},{value:'IR',label:'Iran, Islamic Republic Of'},{value:'IQ',label:'Iraq'},{value:'IE',label:'Ireland'},{value:'IM',label:'Isle of Man'},{value:'IL',label:'Israel'},{value:'IT',label:'Italy'},{value:'JM',label:'Jamaica'},{value:'JP',label:'Japan'},{value:'JE',label:'Jersey'},{value:'JO',label:'Jordan'},{value:'KZ',label:'Kazakhstan'},{value:'KE',label:'Kenya'},{value:'KI',label:'Kiribati'},{value:'KP',label:'Democratic People’s Republic of Korea'},{value:'KR',label:'Korea, Republic of'},{value:'XK',label:'Kosovo'},{value:'KW',label:'Kuwait'},{value:'KG',label:'Kyrgyzstan'},{value:'LA',label:'Lao People’s Democratic Republic'},{value:'LV',label:'Latvia'},{value:'LB',label:'Lebanon'},{value:'LS',label:'Lesotho'},{value:'LR',label:'Liberia'},{value:'LY',label:'Libyan Arab Jamahiriya'},{value:'LI',label:'Liechtenstein'},{value:'LT',label:'Lithuania'},{value:'LU',label:'Luxembourg'},{value:'MO',label:'Macao'},{value:'MK',label:'Macedonia, The Former Yugoslav Republic of'},{value:'MG',label:'Madagascar'},{value:'MW',label:'Malawi'},{value:'MY',label:'Malaysia'},{value:'MV',label:'Maldives'},{value:'ML',label:'Mali'},{value:'MT',label:'Malta'},{value:'MH',label:'Marshall Islands'},{value:'MQ',label:'Martinique'},{value:'MR',label:'Mauritania'},{value:'MU',label:'Mauritius'},{value:'YT',label:'Mayotte'},{value:'MX',label:'Mexico'},{value:'FM',label:'Micronesia, Federated States of'},{value:'MD',label:'Moldova, Republic of'},{value:'MC',label:'Monaco'},{value:'MN',label:'Mongolia'},{value:'ME',label:'Montenegro'},{value:'MS',label:'Montserrat'},{value:'MA',label:'Morocco'},{value:'MZ',label:'Mozambique'},{value:'MM',label:'Myanmar'},{value:'NA',label:'Namibia'},{value:'NR',label:'Nauru'},{value:'NP',label:'Nepal'},{value:'NL',label:'Netherlands'},{value:'AN',label:'Netherlands Antilles'},{value:'NC',label:'New Caledonia'},{value:'NZ',label:'New Zealand'},{value:'NI',label:'Nicaragua'},{value:'NE',label:'Niger'},{value:'NG',label:'Nigeria'},{value:'NU',label:'Niue'},{value:'NF',label:'Norfolk Island'},{value:'MP',label:'Northern Mariana Islands'},{value:'NO',label:'Norway'},{value:'OM',label:'Oman'},{value:'PK',label:'Pakistan'},{value:'PW',label:'Palau'},{value:'PS',label:'Palestine, State of'},{value:'PA',label:'Panama'},{value:'PG',label:'Papua New Guinea'},{value:'PY',label:'Paraguay'},{value:'PE',label:'Peru'},{value:'PH',label:'Philippines'},{value:'PN',label:'Pitcairn'},{value:'PL',label:'Poland'},{value:'PT',label:'Portugal'},{value:'PR',label:'Puerto Rico'},{value:'QA',label:'Qatar'},{value:'RE',label:'Reunion'},{value:'RO',label:'Romania'},{value:'RU',label:'Russian Federation'},{value:'RW',label:'Rwanda'},{value:'SH',label:'Saint Helena'},{value:'KN',label:'Saint Kitts and Nevis'},{value:'LC',label:'Saint Lucia'},{value:'PM',label:'Saint Pierre and Miquelon'},{value:'VC',label:'Saint Vincent and the Grenadines'},{value:'WS',label:'Samoa'},{value:'SM',label:'San Marino'},{value:'ST',label:'Sao Tome and Principe'},{value:'SA',label:'Saudi Arabia'},{value:'SN',label:'Senegal'},{value:'RS',label:'Serbia'},{value:'SC',label:'Seychelles'},{value:'SL',label:'Sierra Leone'},{value:'SG',label:'Singapore'},{value:'SK',label:'Slovakia'},{value:'SI',label:'Slovenia'},{value:'SB',label:'Solomon Islands'},{value:'SO',label:'Somalia'},{value:'ZA',label:'South Africa'},{value:'GS',label:'South Georgia and the South Sandwich Islands'},{value:'ES',label:'Spain'},{value:'LK',label:'Sri Lanka'},{value:'SD',label:'Sudan'},{value:'SR',label:'Suriname'},{value:'SJ',label:'Svalbard and Jan Mayen'},{value:'SZ',label:'Swaziland'},{value:'SE',label:'Sweden'},{value:'CH',label:'Switzerland'},{value:'SY',label:'Syrian Arab Republic'},{value:'TW',label:'Taiwan, Republic of China'},{value:'TJ',label:'Tajikistan'},{value:'TZ',label:'Tanzania, United Republic of'},{value:'TH',label:'Thailand'},{value:'TL',label:'Timor-Leste'},{value:'TG',label:'Togo'},{value:'TK',label:'Tokelau'},{value:'TO',label:'Tonga'},{value:'TT',label:'Trinidad and Tobago'},{value:'TN',label:'Tunisia'},{value:'TR',label:'Turkey'},{value:'TM',label:'Turkmenistan'},{value:'TC',label:'Turks and Caicos Islands'},{value:'TV',label:'Tuvalu'},{value:'UG',label:'Uganda'},{value:'UA',label:'Ukraine'},{value:'AE',label:'United Arab Emirates'},{value:'GB',label:'United Kingdom'},{value:'US',label:'United States'},{value:'UM',label:'United States Minor Outlying Islands'},{value:'UY',label:'Uruguay'},{value:'UZ',label:'Uzbekistan'},{value:'VU',label:'Vanuatu'},{value:'VE',label:'Venezuela'},{value:'VN',label:'Viet Nam'},{value:'VG',label:'Virgin Islands, British'},{value:'VI',label:'Virgin Islands, U.S.'},{value:'WF',label:'Wallis and Futuna'},{value:'EH',label:'Western Sahara'},{value:'YE',label:'Yemen'},{value:'ZM',label:'Zambia'},{value:'ZW',label:'Zimbabwe'}]

// Countries
if (getElementById('country')) {
	for(let i in countries) {
		let option = document.createElement('option')
		option.text = countries[i].label
		option.value = countries[i].value
		option.selected = countries[i] === 'United States'
			? true
			: false
		appendSelect(getElementById('country'), option)
	}
}

// Load reg form scripts
const baseScriptUrl = 'https://ecstaticliving.github.io/ecstaticliving.com/dev/events/'
const scripts = ['elements', 'functions', 'onchange', 'webflow', 'payment']
// Load scripts synchronously, one after another, to make sure hierarchy is respected.
const loadScript = index => {
	let js = document.createElement('script')
	js.src = baseScriptUrl + scripts[index] + '.js'
	js.onload = () => {
		// Once final script has loaded, initialise
		if (scripts[index] === 'payment' && (page() === 'Event' || page() === 'Update')) {
			resetForm()
			scriptsHaveBeenLoaded = true
		}
		else {
			loadScript(index + 1)
		}
	}
	document.head.appendChild(js)
}
loadScript(0)
<commit_msg>Reg form modal display.<commit_after>// Opening for events
const eventTitle = getElementByClassName('event-title', 0)
const eventSubtitle = getElementByClassName('event-subtitle', 0)
const eventDetails = getElementByClassName('event-details', 0)
// Fade in first slide
eventTitle.classList.add('fade-move')
eventSubtitle.classList.add('fade-move')
eventDetails.classList.add('fade-move')
// Email signup form
setTimeout(() => changeEmailContainerBackground(getElementByClassName('email-container-background', 0)), 600)

// Event listener for if reg form is closed
const regFormModalStatus = getElementByClassName('modal-status registration', 0)
const regFormModal = getElementByClassName('modal registration', 0)
const regFormModalWindow = getElementByClassName('modal-window registration', 0)
const regFormContainer = getElementByClassName('container reg-form', 0)
const regFormButtons = getElementsByClassName('button register')
for (let i = 0; i < regFormButtons.length; i++) {
	onClick(regFormButtons[i], () => {
		// Prepare for fade in
		regFormModal.style.opacity = '0'
		// Unhide modal
		showElement(regFormModalStatus)
		// Fade in modal window
		setTimeout(() => regFormModal.style.opacity = '1.0', 100)
		setTimeout(() => {
			regFormContainer.scrollTop = 0
			// Show reg form: browser error that doesn’t show opacity of elements inside modal window unless body is scrolled by 1 px and window opacity is set to 1 during scroll
			window.scrollBy(0, 1)
			onScroll(regFormContainer, () => regFormModalWindow.style.opacity = '1.0')
		}, 300)
		// Prevent background from scrolling
		setTimeout(() => document.body.style.overflow = 'hidden', 500)
	})
}

const regFormClose = getElementByClassName('reg-form-close', 0)
onClick(regFormClose, () => {
	document.body.style.overflow = 'visible'
	regFormModal.style.opacity = '0'
	setTimeout(() => hideElement(regFormModalStatus), 200)
})

// Event summary “Read more...” expansion
getElementByClassName('text read-more', 0).addEventListener('mouseover', () => {
	hideElement(getElementByClassName('text read-more'))
	hideElement(getElementByClassName('text summary'))
	getElementByClassName('text description').classList.add('display')
	setTimeout(() => getElementByClassName('text description display').classList.add('fade'), 100)
})

// Prevent accidental submission of form through 'enter' key
onKeyPress(document, e => {
	if (isInput(e.target) && e.which === 13) {
		e.preventDefault()
		return false
	}
})

let countries = [{value:'AF',label:'Afghanistan'},{value:'AX',label:'Åland Islands'},{value:'AL',label:'Albania'},{value:'DZ',label:'Algeria'},{value:'AS',label:'American Samoa'},{value:'AD',label:'Andorra'},{value:'AO',label:'Angola'},{value:'AI',label:'Anguilla'},{value:'AQ',label:'Antarctica'},{value:'AG',label:'Antigua and Barbuda'},{value:'AR',label:'Argentina'},{value:'AM',label:'Armenia'},{value:'AW',label:'Aruba'},{value:'AU',label:'Australia'},{value:'AT',label:'Austria'},{value:'AZ',label:'Azerbaijan'},{value:'BS',label:'Bahamas'},{value:'BH',label:'Bahrain'},{value:'BD',label:'Bangladesh'},{value:'BB',label:'Barbados'},{value:'BY',label:'Belarus'},{value:'BE',label:'Belgium'},{value:'BZ',label:'Belize'},{value:'BJ',label:'Benin'},{value:'BM',label:'Bermuda'},{value:'BT',label:'Bhutan'},{value:'BO',label:'Bolivia'},{value:'BA',label:'Bosnia and Herzegovina'},{value:'BW',label:'Botswana'},{value:'BV',label:'Bouvet Island'},{value:'BR',label:'Brazil'},{value:'IO',label:'British Indian Ocean Territory'},{value:'BN',label:'Brunei Darussalam'},{value:'BG',label:'Bulgaria'},{value:'BF',label:'Burkina Faso'},{value:'BI',label:'Burundi'},{value:'KH',label:'Cambodia'},{value:'CM',label:'Cameroon'},{value:'CA',label:'Canada'},{value:'CV',label:'Cape Verde'},{value:'KY',label:'Cayman Islands'},{value:'CF',label:'Central African Republic'},{value:'TD',label:'Chad'},{value:'CL',label:'Chile'},{value:'CN',label:'China, People’s Republic of'},{value:'CX',label:'Christmas Island'},{value:'CC',label:'Cocos (Keeling) Islands'},{value:'CO',label:'Colombia'},{value:'KM',label:'Comoros'},{value:'CG',label:'Congo'},{value:'CD',label:'Congo, The Democratic Republic of the'},{value:'CK',label:'Cook Islands'},{value:'CR',label:'Costa Rica'},{value:'CI',label:'Cote D’Ivoire'},{value:'HR',label:'Croatia'},{value:'CU',label:'Cuba'},{value:'CY',label:'Cyprus'},{value:'CZ',label:'Czech Republic'},{value:'DK',label:'Denmark'},{value:'DJ',label:'Djibouti'},{value:'DM',label:'Dominica'},{value:'DO',label:'Dominican Republic'},{value:'EC',label:'Ecuador'},{value:'EG',label:'Egypt'},{value:'SV',label:'El Salvador'},{value:'GQ',label:'Equatorial Guinea'},{value:'ER',label:'Eritrea'},{value:'EE',label:'Estonia'},{value:'ET',label:'Ethiopia'},{value:'FK',label:'Falkland Islands (Malvinas)'},{value:'FO',label:'Faroe Islands'},{value:'FJ',label:'Fiji'},{value:'FI',label:'Finland'},{value:'FR',label:'France'},{value:'GF',label:'French Guiana'},{value:'PF',label:'French Polynesia'},{value:'TF',label:'French Southern Territories'},{value:'GA',label:'Gabon'},{value:'GM',label:'Gambia'},{value:'GE',label:'Georgia'},{value:'DE',label:'Germany'},{value:'GH',label:'Ghana'},{value:'GI',label:'Gibraltar'},{value:'GR',label:'Greece'},{value:'GL',label:'Greenland'},{value:'GD',label:'Grenada'},{value:'GP',label:'Guadeloupe'},{value:'GU',label:'Guam'},{value:'GT',label:'Guatemala'},{value:'GG',label:'Guernsey'},{value:'GN',label:'Guinea'},{value:'GW',label:'Guinea-Bissau'},{value:'GY',label:'Guyana'},{value:'HT',label:'Haiti'},{value:'HM',label:'Heard Island and Mcdonald Islands'},{value:'VA',label:'Holy See (Vatican City State)'},{value:'HN',label:'Honduras'},{value:'HK',label:'Hong Kong'},{value:'HU',label:'Hungary'},{value:'IS',label:'Iceland'},{value:'IN',label:'India'},{value:'ID',label:'Indonesia'},{value:'IR',label:'Iran, Islamic Republic Of'},{value:'IQ',label:'Iraq'},{value:'IE',label:'Ireland'},{value:'IM',label:'Isle of Man'},{value:'IL',label:'Israel'},{value:'IT',label:'Italy'},{value:'JM',label:'Jamaica'},{value:'JP',label:'Japan'},{value:'JE',label:'Jersey'},{value:'JO',label:'Jordan'},{value:'KZ',label:'Kazakhstan'},{value:'KE',label:'Kenya'},{value:'KI',label:'Kiribati'},{value:'KP',label:'Democratic People’s Republic of Korea'},{value:'KR',label:'Korea, Republic of'},{value:'XK',label:'Kosovo'},{value:'KW',label:'Kuwait'},{value:'KG',label:'Kyrgyzstan'},{value:'LA',label:'Lao People’s Democratic Republic'},{value:'LV',label:'Latvia'},{value:'LB',label:'Lebanon'},{value:'LS',label:'Lesotho'},{value:'LR',label:'Liberia'},{value:'LY',label:'Libyan Arab Jamahiriya'},{value:'LI',label:'Liechtenstein'},{value:'LT',label:'Lithuania'},{value:'LU',label:'Luxembourg'},{value:'MO',label:'Macao'},{value:'MK',label:'Macedonia, The Former Yugoslav Republic of'},{value:'MG',label:'Madagascar'},{value:'MW',label:'Malawi'},{value:'MY',label:'Malaysia'},{value:'MV',label:'Maldives'},{value:'ML',label:'Mali'},{value:'MT',label:'Malta'},{value:'MH',label:'Marshall Islands'},{value:'MQ',label:'Martinique'},{value:'MR',label:'Mauritania'},{value:'MU',label:'Mauritius'},{value:'YT',label:'Mayotte'},{value:'MX',label:'Mexico'},{value:'FM',label:'Micronesia, Federated States of'},{value:'MD',label:'Moldova, Republic of'},{value:'MC',label:'Monaco'},{value:'MN',label:'Mongolia'},{value:'ME',label:'Montenegro'},{value:'MS',label:'Montserrat'},{value:'MA',label:'Morocco'},{value:'MZ',label:'Mozambique'},{value:'MM',label:'Myanmar'},{value:'NA',label:'Namibia'},{value:'NR',label:'Nauru'},{value:'NP',label:'Nepal'},{value:'NL',label:'Netherlands'},{value:'AN',label:'Netherlands Antilles'},{value:'NC',label:'New Caledonia'},{value:'NZ',label:'New Zealand'},{value:'NI',label:'Nicaragua'},{value:'NE',label:'Niger'},{value:'NG',label:'Nigeria'},{value:'NU',label:'Niue'},{value:'NF',label:'Norfolk Island'},{value:'MP',label:'Northern Mariana Islands'},{value:'NO',label:'Norway'},{value:'OM',label:'Oman'},{value:'PK',label:'Pakistan'},{value:'PW',label:'Palau'},{value:'PS',label:'Palestine, State of'},{value:'PA',label:'Panama'},{value:'PG',label:'Papua New Guinea'},{value:'PY',label:'Paraguay'},{value:'PE',label:'Peru'},{value:'PH',label:'Philippines'},{value:'PN',label:'Pitcairn'},{value:'PL',label:'Poland'},{value:'PT',label:'Portugal'},{value:'PR',label:'Puerto Rico'},{value:'QA',label:'Qatar'},{value:'RE',label:'Reunion'},{value:'RO',label:'Romania'},{value:'RU',label:'Russian Federation'},{value:'RW',label:'Rwanda'},{value:'SH',label:'Saint Helena'},{value:'KN',label:'Saint Kitts and Nevis'},{value:'LC',label:'Saint Lucia'},{value:'PM',label:'Saint Pierre and Miquelon'},{value:'VC',label:'Saint Vincent and the Grenadines'},{value:'WS',label:'Samoa'},{value:'SM',label:'San Marino'},{value:'ST',label:'Sao Tome and Principe'},{value:'SA',label:'Saudi Arabia'},{value:'SN',label:'Senegal'},{value:'RS',label:'Serbia'},{value:'SC',label:'Seychelles'},{value:'SL',label:'Sierra Leone'},{value:'SG',label:'Singapore'},{value:'SK',label:'Slovakia'},{value:'SI',label:'Slovenia'},{value:'SB',label:'Solomon Islands'},{value:'SO',label:'Somalia'},{value:'ZA',label:'South Africa'},{value:'GS',label:'South Georgia and the South Sandwich Islands'},{value:'ES',label:'Spain'},{value:'LK',label:'Sri Lanka'},{value:'SD',label:'Sudan'},{value:'SR',label:'Suriname'},{value:'SJ',label:'Svalbard and Jan Mayen'},{value:'SZ',label:'Swaziland'},{value:'SE',label:'Sweden'},{value:'CH',label:'Switzerland'},{value:'SY',label:'Syrian Arab Republic'},{value:'TW',label:'Taiwan, Republic of China'},{value:'TJ',label:'Tajikistan'},{value:'TZ',label:'Tanzania, United Republic of'},{value:'TH',label:'Thailand'},{value:'TL',label:'Timor-Leste'},{value:'TG',label:'Togo'},{value:'TK',label:'Tokelau'},{value:'TO',label:'Tonga'},{value:'TT',label:'Trinidad and Tobago'},{value:'TN',label:'Tunisia'},{value:'TR',label:'Turkey'},{value:'TM',label:'Turkmenistan'},{value:'TC',label:'Turks and Caicos Islands'},{value:'TV',label:'Tuvalu'},{value:'UG',label:'Uganda'},{value:'UA',label:'Ukraine'},{value:'AE',label:'United Arab Emirates'},{value:'GB',label:'United Kingdom'},{value:'US',label:'United States'},{value:'UM',label:'United States Minor Outlying Islands'},{value:'UY',label:'Uruguay'},{value:'UZ',label:'Uzbekistan'},{value:'VU',label:'Vanuatu'},{value:'VE',label:'Venezuela'},{value:'VN',label:'Viet Nam'},{value:'VG',label:'Virgin Islands, British'},{value:'VI',label:'Virgin Islands, U.S.'},{value:'WF',label:'Wallis and Futuna'},{value:'EH',label:'Western Sahara'},{value:'YE',label:'Yemen'},{value:'ZM',label:'Zambia'},{value:'ZW',label:'Zimbabwe'}]

// Countries
if (getElementById('country')) {
	for(let i in countries) {
		let option = document.createElement('option')
		option.text = countries[i].label
		option.value = countries[i].value
		option.selected = countries[i] === 'United States'
			? true
			: false
		appendSelect(getElementById('country'), option)
	}
}

// Load reg form scripts
const baseScriptUrl = 'https://ecstaticliving.github.io/ecstaticliving.com/dev/events/'
const scripts = ['elements', 'functions', 'onchange', 'webflow', 'payment']
// Load scripts synchronously, one after another, to make sure hierarchy is respected.
const loadScript = index => {
	let js = document.createElement('script')
	js.src = baseScriptUrl + scripts[index] + '.js'
	js.onload = () => {
		// Once final script has loaded, initialise
		if (scripts[index] === 'payment' && (page() === 'Event' || page() === 'Update')) {
			resetForm()
			scriptsHaveBeenLoaded = true
		}
		else {
			loadScript(index + 1)
		}
	}
	document.head.appendChild(js)
}
loadScript(0)
<|endoftext|>


<commit_before>'use strict';
var _ = require('underscore');
var userUtils = require('cloud/v2/userUtils.js');

exports.examples = _examples;
exports.getCardsForSet = _getCardsForSet;
exports.getCardById = _getCardById;
exports.getCardsForSuggestion = _getCardsForSuggestion;

// Use Parse.Cloud.define to define as many cloud functions as you want.
function _examples(request, response) {
	Parse.Cloud.useMasterKey();
	var setId = request.params.id;
	_loadSetItems();

	function _loadSetItems() {
		var query = _buildCardsQuery();
		var SetObject = Parse.Object.extend('Set');
		var mockSet = new SetObject();
		mockSet.id = setId;
		query.equalTo('owner', mockSet);
		query.include('card.owner');
		query.find({
			success: _onSuggestionsLoaded,
			error: _onError
		});
	}

	function _onSuggestionsLoaded(setItems) {
		var card;
		var zeroSuggestions = [];
		var oneSuggestions = [];

		_.each(setItems, function stripData(item) {
			card = item.attributes.card;
			userUtils.stripPrivateData(card.attributes.owner);
			if (card.attributes.type === 0) {
				zeroSuggestions.push(card);
			} else {
				oneSuggestions.push(card);
			}
		});

		response.success({
			zero: zeroSuggestions,
			one: oneSuggestions
		});
	}

	function _onError(error) {
		console.log('examples Error');
		response.error(error);
	}

}

function _getCardsForSet(request, response) {
	// console.log('getCardsForSet');
		Parse.Cloud.useMasterKey();
	var setId = request.params.id;

	if(setId !== undefined) {
		// console.log('getCardsForSet fetchData');
		var query = _buildCardsQuery(setId);
		var SetObject = Parse.Object.extend('Set');
		var mockSet = new SetObject();
		mockSet.id = setId;
		query.equalTo('owner', mockSet);
		query.find({
			success: _onSuccess,
			error: _onError
		});
	} else {
		response.error('you must pass a set id to get');
	}

	function _onSuccess(setItems) {
		// console.log('setItems found:' + setItems.length);
		var card;
		_.each(setItems, function(item) {
			card = item.attributes.card;
			userUtils.stripPrivateData(card.attributes.owner);
		});
		response.success(setItems);
	}

	function _onError(error) {
		console.log('getAllSets Error');
		response.error(error);
	}

}

function _getCardById(request, response) {
	Parse.Cloud.useMasterKey();
	var cardId = request.params.id;
	if(cardId !== undefined) {
		// console.log('getCardsForSet fetchData');
		var SuggestionObject = Parse.Object.extend('Suggestion');
		var query = new Parse.Query(SuggestionObject);
		query.include('owner');
		query.get(request.params.id, {
			success: _onSuccess,
			error: _onError
		});
	} else {
		response.error('you must pass a set id to get');
	}

	function _onSuccess(card) {
		userUtils.stripPrivateData(card.attributes.owner);
		response.success(card);
	}

	function _onError(error) {
		console.log('getCard Error');
		response.error(error);
	}

}

function _getCardsForSuggestion(request, response) {
	// console.log('getCardsForSet');
		Parse.Cloud.useMasterKey();
	var suggestionId = request.params.id;
	var includeOwner = request.params.includeOwner;

	if(suggestionId !== undefined) {
		// console.log('getCardsForSet fetchData');
		var SuggestionObject = Parse.Object.extend('Suggestion');
		var mockSuggestion = new SuggestionObject();
		mockSuggestion.id = suggestionId;

		// actor query
		var query = _buildCardsQuery();
		query.equalTo('card', mockSuggestion);

		query.find({
			success: _onSuccess,
			error: _onError
		});
	} else {
		response.error('you must pass a suggestion id to get');
	}

	function _onSuccess(setItems) {
		// console.log('setItems found:' + setItems.length);
		var card;
		_.each(setItems, function(item) {
			card = item.attributes.card;
			userUtils.stripPrivateData(card.attributes.owner);
		});
		response.success(setItems);
	}

	function _onError(error) {
		console.log('getAllSets Error');
		response.error(error);
	}

}

function _buildCardsQuery() {
	var SetItemObject = Parse.Object.extend('SetItem');
	var query = new Parse.Query(SetItemObject);
	query.limit(1000);
	return query;
}<commit_msg>Revert "removed owner from set fetch"<commit_after>'use strict';
var _ = require('underscore');
var userUtils = require('cloud/v2/userUtils.js');

exports.examples = _examples;
exports.getCardsForSet = _getCardsForSet;
exports.getCardById = _getCardById;
exports.getCardsForSuggestion = _getCardsForSuggestion;

// Use Parse.Cloud.define to define as many cloud functions as you want.
function _examples(request, response) {
	Parse.Cloud.useMasterKey();
	var setId = request.params.id;
	_loadSetItems();

	function _loadSetItems() {
		var query = _buildCardsQuery();
		var SetObject = Parse.Object.extend('Set');
		var mockSet = new SetObject();
		mockSet.id = setId;
		query.equalTo('owner', mockSet);
		query.include('card.owner');
		query.find({
			success: _onSuggestionsLoaded,
			error: _onError
		});
	}

	function _onSuggestionsLoaded(setItems) {
		var card;
		var zeroSuggestions = [];
		var oneSuggestions = [];

		_.each(setItems, function stripData(item) {
			card = item.attributes.card;
			userUtils.stripPrivateData(card.attributes.owner);
			if (card.attributes.type === 0) {
				zeroSuggestions.push(card);
			} else {
				oneSuggestions.push(card);
			}
		});

		response.success({
			zero: zeroSuggestions,
			one: oneSuggestions
		});
	}

	function _onError(error) {
		console.log('examples Error');
		response.error(error);
	}

}

function _getCardsForSet(request, response) {
	// console.log('getCardsForSet');
		Parse.Cloud.useMasterKey();
	var setId = request.params.id;
	var includeOwner = request.params.includeOwner;

	if(setId !== undefined) {
		// console.log('getCardsForSet fetchData');
		var query = _buildCardsQuery(setId);
		var SetObject = Parse.Object.extend('Set');
		var mockSet = new SetObject();
		mockSet.id = setId;
		query.equalTo('owner', mockSet);
		if(includeOwner === true) {
			query.include('card.owner');
		} else {
			query.include('card');
		}
		query.find({
			success: _onSuccess,
			error: _onError
		});
	} else {
		response.error('you must pass a set id to get');
	}

	function _onSuccess(setItems) {
		// console.log('setItems found:' + setItems.length);
		var card;
		_.each(setItems, function(item) {
			card = item.attributes.card;
			userUtils.stripPrivateData(card.attributes.owner);
		});
		response.success(setItems);
	}

	function _onError(error) {
		console.log('getAllSets Error');
		response.error(error);
	}

}

function _getCardById(request, response) {
	Parse.Cloud.useMasterKey();
	var cardId = request.params.id;
	if(cardId !== undefined) {
		// console.log('getCardsForSet fetchData');
		var SuggestionObject = Parse.Object.extend('Suggestion');
		var query = new Parse.Query(SuggestionObject);
		query.include('owner');
		query.get(request.params.id, {
			success: _onSuccess,
			error: _onError
		});
	} else {
		response.error('you must pass a set id to get');
	}

	function _onSuccess(card) {
		userUtils.stripPrivateData(card.attributes.owner);
		response.success(card);
	}

	function _onError(error) {
		console.log('getCard Error');
		response.error(error);
	}

}

function _getCardsForSuggestion(request, response) {
	// console.log('getCardsForSet');
		Parse.Cloud.useMasterKey();
	var suggestionId = request.params.id;
	var includeOwner = request.params.includeOwner;

	if(suggestionId !== undefined) {
		// console.log('getCardsForSet fetchData');
		var SuggestionObject = Parse.Object.extend('Suggestion');
		var mockSuggestion = new SuggestionObject();
		mockSuggestion.id = suggestionId;

		// actor query
		var query = _buildCardsQuery();
		query.equalTo('card', mockSuggestion);
		includeOwner ? query.include('card.owner') : query.include('card');

		query.find({
			success: _onSuccess,
			error: _onError
		});
	} else {
		response.error('you must pass a suggestion id to get');
	}

	function _onSuccess(setItems) {
		// console.log('setItems found:' + setItems.length);
		var card;
		_.each(setItems, function(item) {
			card = item.attributes.card;
			userUtils.stripPrivateData(card.attributes.owner);
		});
		response.success(setItems);
	}

	function _onError(error) {
		console.log('getAllSets Error');
		response.error(error);
	}

}

function _buildCardsQuery() {
	var SetItemObject = Parse.Object.extend('SetItem');
	var query = new Parse.Query(SetItemObject);
	query.limit(1000);
	return query;
}<|endoftext|>


<commit_before>JXWM6W>8$Le0LHBRlmEIlm
p<K+X$(R4W)%WiJ[X+y੐0uur#lUE8ၳ?[VYq~v{bWs:IȃzG4ocR<ݺfP/E*A]܄c	'"VZݷ"D"E̙ة_f0:_*v=bp돁;d9)Zi4Il)oKfZ=U_>vǧ?~N˩ۚFǺ]>LX+72mQwv%؊伳A[-X3g	^DunushX-X"@Cqh۲΂/	ϿOxX؆1.c1\+9.)$)ywz2ʳ-U
VL2WYYauF]cV{Vg/Fqj7H6`ǫcsyjF$&cr
L6H:p{Ln>%{O=9>tyhh<3ЋzM'7סLւcack3UCBMuR+\#&vkN{Kr4~pl¯p~o) -]oiŎwYgG> 0t3
tU7,w,~ll#KX>
dcU|.r]@r9|@b(B\ɘ2	a)Θy34q:^
N/*;^	]%$\Smq,X,]~۰'Pq^|ȀqiPK[©zlWUJKiM)<Ψ{Cc5nDt3Զ%-%!@N lt4swd݈ӏ4gkГ/3ֱSyvz0sT]FP$
K$嫛Xz}vѡ>Nyܺ))j_[&׊/E`LY):_GZmr9
T0f¬
.iQ[mHBi͞Q+_JCY9֐@

_C*nFˇ><LU!`{6ܑl
<I>ZU^Y\]M_Ў&04-H!H|Cc#-RVPy.=d!9|Ԅ,g$<'ڵlOr[^p	[=Ip$J(moIh2=0O̴:ВUu5	4BXj/v`?
@/P$ѦB7Ѕn?
˥<commit_msg>build for publish<commit_after>JXWM6W>8$Le0LHBRlmEIlm
p<K+X$(R4W)%WiJ[X+y੐0uur#lUE8ၳ?[VYq~v{bWs:IȃzG4ocR<ݺfP/E*A]܄c	'"VZݷ"D"E̙ة_f0:_*v=bp돁;d9)Zi4Il)oKfZ=U_>vǧ?~N˩ۚFǺ]>LX+72mQwv%؊伳A[-X3g	^DunushX-X"@Cqh۲΂/	ϿOxX؆1.c1\+9.)$)ywz2ʳ-U
VL2WYYauF]cV{Vg/Fqj7H6`ǫcsyjF$&cr
L6H:p{Ln>%{O=9>tyhh<3ЋzM'7סLւcack3UCBMuR+\#&vkN{Kr4~pl¯p~o) -]oiŎwYgG> 0t3
tU7,w,~ll#KX>
dcU|.r]@r9|@b(B\ɘ2	a)Θy34q:^
N/*;^	]%$\Smq,X,]~۰'Pq^|ȀqiPK[©zlWUJKiM)<Ψ{Cc5nDt3Զ%-%!@N lt4swd݈ӏ4gkГ/3ֱSyvz0sT]FP$
K$嫛Xz}vѡ>Nyܺ))j_[&׊/E`LY):_GZmr9
T0f¬
.iQ[mHBi͞Q+_JCY9֐@

_C*nFˇ><LU!`{6ܑl
<I>ZU^Y\]M_Ў&04-H!H|Cc#-RVPy.=d!9|Ԅ,g$<'ڵlOr[^p	[=Ip$J(moIh2=0O̴:ВUu5	4BXj/v`?
@/P$ѦB7Ѕn?
˥<|endoftext|>


<commit_before>var sinon = require('sinon');
var assert = require('chai').assert;

var AnimationPlayer = require('../src/lib/AnimationPlayer');

suite('Animation Player', function() {

    var sut,
    player,
    windowFake,
    windowMock,
    reqAnimFrameSpy,
    cancelAnimFrameSpy;

    setup(function() {

        windowFake = {
            requestAnimationFrame: function(cb) {
                // Note that we don't execute cb to avoid recursion
                return this.generateFakeId();
            },
            cancelAnimationFrame: function(requestId) {
                return requestId;
            },
            generateFakeId: function() {
                return Math.floor((Math.random() * 10) + 1);
            }
        };

        reqAnimFrameSpy = sinon.spy(windowFake, 'requestAnimationFrame');
        cancelAnimFrameSpy = sinon.spy(windowFake, 'cancelAnimationFrame');
        windowMock = sinon.mock(windowFake);
        player = Object.create(AnimationPlayer);
        sut = player.create(windowFake);

    });

    suite('General', function() {

        test('must be a JavaScript Object with \'creat\' function', function() {
            assert.isObject(sut);
            assert.property(sut, 'create');
        });

        test('must have Play and Stop function', function() {
            assert.property(sut, 'play');
            assert.property(sut, 'stop');
        });

        test('must set an update function', function() {
            var cb = function() {};
            assert.property(sut, 'setUpdateFn');
            sut.setUpdateFn(cb);
            assert.isFunction(sut.updateFn);
        });

    });

    suite('Play', function() {

        test('must call window.requestAnimationFrame and save requestId', function() {
            var cb = function() {};
            sut.setUpdateFn(cb);
            sut.updateFn();
            assert.isTrue(reqAnimFrameSpy.called);
            assert.isNumber(sut.requestId);
        });

        test('must set \'playing\' to true after play() called', function() {
            sut.play();
            assert.isTrue(sut.playing);
        });

    });

    suite('Stop', function() {

        test('must return false if called when and not playing', function() {
            var returned = sut.stop();
            assert.isFalse(returned);
        });

        test('must call window.cancelAnimationFrame', function() {
            sut.play();
            sut.stop();
            assert.isTrue(cancelAnimFrameSpy.called);
        });

        test('must unset \'requestId\' & set \'playing\' to false', function() {
            sut.play();
            sut.stop();
            assert.isNull(sut.requestId);
        });

    });
});
<commit_msg>Corrected typo in AnimationPlayer test<commit_after>var sinon = require('sinon');
var assert = require('chai').assert;

var AnimationPlayer = require('../src/lib/AnimationPlayer');

suite('Animation Player', function() {

    var sut,
    player,
    windowFake,
    windowMock,
    reqAnimFrameSpy,
    cancelAnimFrameSpy;

    setup(function() {

        windowFake = {
            requestAnimationFrame: function(cb) {
                // Note that we don't execute cb to avoid recursion
                return this.generateFakeId();
            },
            cancelAnimationFrame: function(requestId) {
                return requestId;
            },
            generateFakeId: function() {
                return Math.floor((Math.random() * 10) + 1);
            }
        };

        reqAnimFrameSpy = sinon.spy(windowFake, 'requestAnimationFrame');
        cancelAnimFrameSpy = sinon.spy(windowFake, 'cancelAnimationFrame');
        windowMock = sinon.mock(windowFake);
        player = Object.create(AnimationPlayer);
        sut = player.create(windowFake);

    });

    suite('General', function() {

        test('must be a JavaScript Object with \'create\' function', function() {
            assert.isObject(sut);
            assert.property(sut, 'create');
        });

        test('must have Play and Stop function', function() {
            assert.property(sut, 'play');
            assert.property(sut, 'stop');
        });

        test('must set an update function', function() {
            var cb = function() {};
            assert.property(sut, 'setUpdateFn');
            sut.setUpdateFn(cb);
            assert.isFunction(sut.updateFn);
        });

    });

    suite('Play', function() {

        test('must call window.requestAnimationFrame and save requestId', function() {
            var cb = function() {};
            sut.setUpdateFn(cb);
            sut.updateFn();
            assert.isTrue(reqAnimFrameSpy.called);
            assert.isNumber(sut.requestId);
        });

        test('must set \'playing\' to true after play() called', function() {
            sut.play();
            assert.isTrue(sut.playing);
        });

    });

    suite('Stop', function() {

        test('must return false if called when and not playing', function() {
            var returned = sut.stop();
            assert.isFalse(returned);
        });

        test('must call window.cancelAnimationFrame', function() {
            sut.play();
            sut.stop();
            assert.isTrue(cancelAnimFrameSpy.called);
        });

        test('must unset \'requestId\' & set \'playing\' to false', function() {
            sut.play();
            sut.stop();
            assert.isNull(sut.requestId);
        });

    });
});
<|endoftext|>


<commit_before>'use strict';

var util = require('./util');
var Request = require('./Request');
var WriteMultipleRegistersResponse =
  require('./WriteMultipleRegistersResponse');

module.exports = WriteMultipleRegistersRequest;

/**
 * The write multiple registers request (code 0x10).
 *
 * A binary representation of this request varies in length and consists of:
 *
 *   - a function code (1 byte),
 *   - a starting address (2 bytes),
 *   - a quantity of registers (2 bytes),
 *   - a byte count (`N`; 1 byte),
 *   - values of the registers (`N` bytes).
 *
 * @constructor
 * @extends {Request}
 * @param {number} address A starting address. A number between 0 and 0xFFFF.
 * @param {Buffer} values Values of the registers.
 * A buffer of even length between 2 and 246.
 * @throws {Error} If the `address` is not a number between 0 and 0xFFFF.
 * @throws {Error} If the `values` is not a Buffer of even length
 * between 2 and 246.
 */
function WriteMultipleRegistersRequest(address, values)
{
  Request.call(this, 0x10);

  if (values.length % 2 !== 0 || values.length < 2 || values.length > 246)
  {
    throw new Error(util.format(
      "The length of the `values` Buffer must be an even number "
        + "between 2 and 246, got: %d",
      values.length
    ));
  }

  /**
   * A starting address. A number between 0 and 0xFFFF.
   *
   * @private
   * @type {number}
   */
  this.address = util.prepareAddress(address);

  /**
   * Values of the registers. A buffer of even length between 2 and 256.
   *
   * @private
   * @type {Buffer}
   */
  this.values = values;
}

util.inherits(WriteMultipleRegistersRequest, Request);

/**
 * Creates a new request from the specified `options`.
 *
 * Available options for this request are:
 *
 *   - `address` (number, optional) -
 *     A starting address. If specified, must be a number between 0 and 0xFFFF.
 *     Defaults to 0.
 *
 *   - `values` (Buffer, required) -
 *     Values of the registers. Must be a buffer of even length
 *     between 2 and 246.
 *
 * @param {object} options An options object.
 * @param {number} [options.address]
 * @param {Buffer} options.values
 * @returns {WriteMultipleRegistersRequest} A response
 * created from the specified `options`.
 * @throws {Error} If any of the specified options are not valid.
 */
WriteMultipleRegistersRequest.fromOptions = function(options)
{
  return new WriteMultipleRegistersRequest(options.address, options.values);
};

/**
 * Creates a new request from its binary representation.
 *
 * @param {Buffer} buffer A binary representation of this request.
 * @returns {WriteMultipleRegistersRequest} A request
 * created from its binary representation.
 * @throws {Error} If the specified buffer is not a valid binary representation
 * of this request.
 */
WriteMultipleRegistersRequest.fromBuffer = function(buffer)
{
  util.assertBufferLength(buffer, 8);
  util.assertFunctionCode(buffer[0], 0x10);

  var address = buffer.readUInt16BE(1, true);
  var byteCount = buffer[5];
  var values = new Buffer(byteCount);

  buffer.copy(values, 0, 6, 6 + byteCount);

  return new WriteMultipleRegistersRequest(address, values);
};

/**
 * Returns a binary representation of this request.
 *
 * @returns {Buffer} A binary representation of this request.
 */
WriteMultipleRegistersRequest.prototype.toBuffer = function()
{
  var buffer = new Buffer(6 + this.values.length);

  buffer[0] = 0x10;
  buffer.writeUInt16BE(this.address, 1, true);
  buffer.writeUInt16BE(this.values.length / 2, 3, true);
  buffer[4] = this.values.length;
  this.values.copy(buffer, 5);

  return buffer;
};

/**
 * Returns a string representation of this request.
 *
 * @returns {string} A string representation of this request.
 */
WriteMultipleRegistersRequest.prototype.toString = function()
{
  return util.format(
    "0x10 (REQ) Set %d registers starting from address %d to:",
    this.values.length / 2,
    this.address,
    this.values
  );
};

/**
 * @param {Buffer} responseBuffer
 * @returns {Response}
 * @throws {Error}
 */
WriteMultipleRegistersRequest.prototype.createResponse =
  function(responseBuffer)
{
  return this.createExceptionOrResponse(
    responseBuffer,
    WriteMultipleRegistersResponse
  );
};

/**
 * @returns {number} A starting address.
 */
WriteMultipleRegistersRequest.prototype.getAddress = function()
{
  return this.address;
};

/**
 * @returns {Buffer} Values of the registers
 */
WriteMultipleRegistersRequest.prototype.getValues = function()
{
  return this.values;
};
<commit_msg>Changed the value buffer's max length from 256 bytes to 246 bytes.<commit_after>'use strict';

var util = require('./util');
var Request = require('./Request');
var WriteMultipleRegistersResponse =
  require('./WriteMultipleRegistersResponse');

module.exports = WriteMultipleRegistersRequest;

/**
 * The write multiple registers request (code 0x10).
 *
 * A binary representation of this request varies in length and consists of:
 *
 *   - a function code (1 byte),
 *   - a starting address (2 bytes),
 *   - a quantity of registers (2 bytes),
 *   - a byte count (`N`; 1 byte),
 *   - values of the registers (`N` bytes).
 *
 * @constructor
 * @extends {Request}
 * @param {number} address A starting address. A number between 0 and 0xFFFF.
 * @param {Buffer} values Values of the registers.
 * A buffer of even length between 2 and 246.
 * @throws {Error} If the `address` is not a number between 0 and 0xFFFF.
 * @throws {Error} If the `values` is not a Buffer of even length
 * between 2 and 246.
 */
function WriteMultipleRegistersRequest(address, values)
{
  Request.call(this, 0x10);

  if (values.length % 2 !== 0 || values.length < 2 || values.length > 246)
  {
    throw new Error(util.format(
      "The length of the `values` Buffer must be an even number "
        + "between 2 and 246, got: %d",
      values.length
    ));
  }

  /**
   * A starting address. A number between 0 and 0xFFFF.
   *
   * @private
   * @type {number}
   */
  this.address = util.prepareAddress(address);

  /**
   * Values of the registers. A buffer of even length between 2 and 246.
   *
   * @private
   * @type {Buffer}
   */
  this.values = values;
}

util.inherits(WriteMultipleRegistersRequest, Request);

/**
 * Creates a new request from the specified `options`.
 *
 * Available options for this request are:
 *
 *   - `address` (number, optional) -
 *     A starting address. If specified, must be a number between 0 and 0xFFFF.
 *     Defaults to 0.
 *
 *   - `values` (Buffer, required) -
 *     Values of the registers. Must be a buffer of even length
 *     between 2 and 246.
 *
 * @param {object} options An options object.
 * @param {number} [options.address]
 * @param {Buffer} options.values
 * @returns {WriteMultipleRegistersRequest} A response
 * created from the specified `options`.
 * @throws {Error} If any of the specified options are not valid.
 */
WriteMultipleRegistersRequest.fromOptions = function(options)
{
  return new WriteMultipleRegistersRequest(options.address, options.values);
};

/**
 * Creates a new request from its binary representation.
 *
 * @param {Buffer} buffer A binary representation of this request.
 * @returns {WriteMultipleRegistersRequest} A request
 * created from its binary representation.
 * @throws {Error} If the specified buffer is not a valid binary representation
 * of this request.
 */
WriteMultipleRegistersRequest.fromBuffer = function(buffer)
{
  util.assertBufferLength(buffer, 8);
  util.assertFunctionCode(buffer[0], 0x10);

  var address = buffer.readUInt16BE(1, true);
  var byteCount = buffer[5];
  var values = new Buffer(byteCount);

  buffer.copy(values, 0, 6, 6 + byteCount);

  return new WriteMultipleRegistersRequest(address, values);
};

/**
 * Returns a binary representation of this request.
 *
 * @returns {Buffer} A binary representation of this request.
 */
WriteMultipleRegistersRequest.prototype.toBuffer = function()
{
  var buffer = new Buffer(6 + this.values.length);

  buffer[0] = 0x10;
  buffer.writeUInt16BE(this.address, 1, true);
  buffer.writeUInt16BE(this.values.length / 2, 3, true);
  buffer[4] = this.values.length;
  this.values.copy(buffer, 5);

  return buffer;
};

/**
 * Returns a string representation of this request.
 *
 * @returns {string} A string representation of this request.
 */
WriteMultipleRegistersRequest.prototype.toString = function()
{
  return util.format(
    "0x10 (REQ) Set %d registers starting from address %d to:",
    this.values.length / 2,
    this.address,
    this.values
  );
};

/**
 * @param {Buffer} responseBuffer
 * @returns {Response}
 * @throws {Error}
 */
WriteMultipleRegistersRequest.prototype.createResponse =
  function(responseBuffer)
{
  return this.createExceptionOrResponse(
    responseBuffer,
    WriteMultipleRegistersResponse
  );
};

/**
 * @returns {number} A starting address.
 */
WriteMultipleRegistersRequest.prototype.getAddress = function()
{
  return this.address;
};

/**
 * @returns {Buffer} Values of the registers
 */
WriteMultipleRegistersRequest.prototype.getValues = function()
{
  return this.values;
};
<|endoftext|>


<commit_before>var authcommon = require('../authcommon'),
    common = require('../common'),
    config = require('../config'),
    db = require('../db');

exports.can_access = function (ident, board) {
	if (board == 'graveyard' && is_admin_ident(ident))
		return true;
	return db.is_board(board);
};

function is_mod_ident(ident) {
	return ident && (ident.auth === 'Admin' || ident.auth === 'Moderator');
}
exports.is_mod_ident = is_mod_ident;

function is_admin_ident(ident) {
	return ident && ident.auth === 'Admin';
}
exports.is_admin_ident = is_admin_ident;

function denote_priv(header, data) {
	if (data.priv)
		header.push(' (priv)');
	return header;
}

exports.augment_oneesama = function (oneeSama, ident) {
	if (is_mod_ident(ident))
		oneeSama.hook('header', authcommon.ip_mnemonic);
	if (is_admin_ident(ident))
		oneeSama.hook('header', denote_priv);
};
<commit_msg>IP parser<commit_after>var authcommon = require('../authcommon'),
    common = require('../common'),
    config = require('../config'),
    db = require('../db');

exports.can_access = function (ident, board) {
	if (board == 'graveyard' && is_admin_ident(ident))
		return true;
	return db.is_board(board);
};

function is_mod_ident(ident) {
	return ident && (ident.auth === 'Admin' || ident.auth === 'Moderator');
}
exports.is_mod_ident = is_mod_ident;

function is_admin_ident(ident) {
	return ident && ident.auth === 'Admin';
}
exports.is_admin_ident = is_admin_ident;

function denote_priv(header, data) {
	if (data.priv)
		header.push(' (priv)');
	return header;
}

exports.augment_oneesama = function (oneeSama, ident) {
	if (is_mod_ident(ident))
		oneeSama.hook('header', authcommon.ip_mnemonic);
	if (is_admin_ident(ident))
		oneeSama.hook('header', denote_priv);
};

function parse_ip(ip) {
	var m = ip.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)(?:\/(\d+))?$/);
	if (!m)
		return false;
	// damn you signed int32s!
	var num = 0;
	for (var i = 4, shift = 1; i > 0; i--) {
		num += parseInt(m[i], 10) * shift;
		shift *= 256;
	}
	var info = {ip: num};
	if (m[5]) {
		var bits = parseInt(m[5], 10);
		if (bits > 0 && bits <= 32)
			info.mask = 0x100000000 - Math.pow(2, 32 - bits);
	}
	return info;
}
exports.parse_ip = parse_ip;
<|endoftext|>


<commit_before>/*
 *  Project: Long Press
 *  Description: Pops a list of alternate characters when a key is long-pressed
 *  Author: Quentin Thiaucourt, http://toki-woki.net
 *    Licence: MIT License http://opensource.org/licenses/mit-license.php
 *
 *  Modified Oct 2014 to work with editable divs also
 */

;(function ($, window, undefined) {

    var pluginName = 'longPress',
        document = window.document,
        defaults = {/*
            propertyName: "value"
        */};

    var moreChars={
        // extended latin (and african latin)
        // upper
        'A':'ĀĂÀÁÂÃÄÅĄⱭ∀Æ',
        'B':'Ɓ',
        'C':'ÇĆĈĊČƆ',
        'D':'ÐĎĐḎƊ',
        'E':'ÈÉÊËĒĖĘẸĚƏÆƎƐ€',
        'F':'ƑƩ',
        'G':'ĜĞĠĢƢ',
        'H':'ĤĦ',
        'I':'ÌÍÎÏĪĮỊİIƗĲ',
        'J':'ĴĲ',
        'K':'ĶƘ',
        'L':'ĹĻĽŁΛ',
        'N':'ÑŃŅŇŊƝ₦',
        'O':'ÒÓÔÕÖŌØŐŒƠƟ',
        'P':'Ƥ¶',
        'R':'ŔŘɌⱤ',
        'S':'ßſŚŜŞṢŠÞ§',
        'T':'ŢŤṮƬƮ',
        'U':'ÙÚÛÜŪŬŮŰŲɄƯƱ',
        'V':'Ʋ',
        'W':'ŴẄΩ',
        'Y':'ÝŶŸƔƳ',
        'Z':'ŹŻŽƵƷẔ',

        // lower
        'a':'āăàáâãäåąɑæαª',
        'b':'ßβɓ',
        'c':'çςćĉċč¢ɔ',
        'd':'ðďđɖḏɖɗ',
        'e':'èéêëēėęẹěəæεɛ€',
        'f':'ƒʃƭ',
        'g':'ĝğġģɠƣ',
        'h':'ĥħɦẖ',
        'i':'ìíîïīįịiiɨĳι',
        'j':'ĵɟĳ',
        'k':'ķƙ',
        'l':'ĺļľłλ',
        'n':'ñńņňŋɲ',
        'o':'òóôõöōøőœơɵ°',
        'p':'ƥ¶',
        'r':'ŕřɍɽ',
        's':'ßſśŝşṣšþ§',
        't':'ţťṯƭʈ',
        'u':'ùúûüūŭůűųưμυʉʊ',
        'v':'ʋ',
        'w':'ŵẅω',
        'y':'ýŷÿɣyƴ',
        'z':'źżžƶẕʒƹ',

        // Misc
        '$':'£¥€₩₨₳Ƀ¤',
        '!':'¡‼‽',
        '?':'¿‽',
        '%':'‰',
        '.':'…••',
        '-':'±‐–—',
        '+':'±†‡',
        '\'':'′″‴‘’‚‛',
        '"':'“”„‟',
        '<':'≤‹',
        '>':'≥›',
        '=':'≈≠≡'

    };
    var ignoredKeys=[8, 13, 37, 38, 39, 40];

    var selectedCharIndex;
    var lastWhich;
    var timer;
    var activeElement;
    var caretPosition; // Technically, the object is a range, but for us it should always be a point

    var popup=$('
');

    $(window).mousewheel(onWheel);

    function onKeyDown(e) {

        // Arrow key with popup visible
        if ($('.long-press-popup').length>0 && (e.which==37 || e.which==39)) {
            if (e.which==37) activePreviousLetter();
            else if (e.which==39) activateNextLetter();

            e.preventDefault();
            return;
        }

        if (ignoredKeys.indexOf(e.which)>-1) return;
        activeElement=e.target;

        if (e.which==lastWhich) {
            e.preventDefault();
            if (!timer) timer=setTimeout(onTimer, 10);
            return;
        }
        lastWhich=e.which;
    }
    function onKeyUp(e) {
        if (ignoredKeys.indexOf(e.which)>-1) return;
        if (activeElement==null) return;

        lastWhich=null;
        clearTimeout(timer);
        timer=null;

        hidePopup();
    }
    function onTimer() {
        var typedChar = isTextArea() ?
            $(activeElement).val().split('')[getTextAreaCaretPosition(activeElement)-1] :
            $(activeElement).text().split('')[getCaretPosition(activeElement)-1];

        if (moreChars[typedChar]) {
            if (!isTextArea())
                storeCaretPosition();
            showPopup((moreChars[typedChar]));
        } else {
            hidePopup();
        }
    }
    function showPopup(chars) {
        popup.empty();
        var letter;
        for (var i=0; i<chars.length; i++) {
            letter=$('
').text(chars[i]);
            letter.mouseenter(activateLetter);
            popup.append(letter);
        }
        $('body').append(popup);
        selectedCharIndex=-1;
    }
    function activateLetter(e) {
        selectCharIndex($(e.target).index());
    }
    function activateRelativeLetter(i) {
        selectCharIndex(($('.long-press-letter').length+selectedCharIndex+i) % $('.long-press-letter').length);
    }
    function activateNextLetter() {
        activateRelativeLetter(1);
    }
    function activePreviousLetter() {
        activateRelativeLetter(-1);
    }
    function hidePopup() {
        popup.detach();
    }
    function onWheel(e, delta, deltaX, deltaY) {
        if ($('.long-press-popup').length==0) return;
        e.preventDefault();
        delta<0 ? activateNextLetter() : activePreviousLetter();
    }
    function selectCharIndex(i) {
        $('.long-press-letter.selected').removeClass('selected');
        $('.long-press-letter').eq(i).addClass('selected');
        selectedCharIndex=i;
        updateChar();
    }

    function updateChar() {
        var newChar=$('.long-press-letter.selected').text();
        replacePreviousLetterWithText(newChar);
    }

    function isTextArea() {
        return $(activeElement).is('textarea');
    }

    function storeCaretPosition() {
        var sel;
        caretPosition = null;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                caretPosition = sel.getRangeAt(0);
            }
        }
    }
    function replacePreviousLetterWithText(text) {
        if (isTextArea()) {
            var pos=getTextAreaCaretPosition(activeElement);
            var arVal=$(activeElement).val().split('');
            arVal[pos-1]=text;
            $(activeElement).val(arVal.join(''));
            setTextAreaCaretPosition(activeElement, pos);
        } else {
            var sel, textNode, clone;
            var range = caretPosition;
            if (window.getSelection && range && range.startOffset != 0) {
                sel = window.getSelection();
                if (sel.getRangeAt && sel.rangeCount) {
                    textNode = document.createTextNode(text);

                    clone = range.cloneRange();
                    clone.setStart(range.startContainer, range.startOffset - 1);
                    clone.setEnd(range.startContainer, range.startOffset);
                    clone.deleteContents();
                    range.insertNode(textNode);

                    // Move caret to the end of the newly inserted text node
                    range.setStart(textNode, textNode.length);
                    range.setEnd(textNode, textNode.length);

                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        }
    }

    function getCaretPosition(element) {
        var caretOffset = 0;
        var doc = element.ownerDocument || element.document;
        var win = doc.defaultView || doc.parentWindow;
        var sel;
        if (typeof win.getSelection != "undefined") {
            sel = win.getSelection();
            if (sel.rangeCount > 0) {
                var range = win.getSelection().getRangeAt(0);
                var preCaretRange = range.cloneRange();
                preCaretRange.selectNodeContents(element);
                preCaretRange.setEnd(range.endContainer, range.endOffset);
                caretOffset = preCaretRange.toString().length;
            }
        } else if ( (sel = doc.selection) && sel.type != "Control") {
            var textRange = sel.createRange();
            var preCaretTextRange = doc.body.createTextRange();
            preCaretTextRange.moveToElementText(element);
            preCaretTextRange.setEndPoint("EndToEnd", textRange);
            caretOffset = preCaretTextRange.text.length;
        }
        return caretOffset;
    }

    function getTextAreaCaretPosition (ctrl) {
        var caretPos = 0;
        if (document.selection) {
            // IE Support
            ctrl.focus ();
            var sel = document.selection.createRange ();
            sel.moveStart ('character', -ctrl.value.length);
            caretPos = sel.text.length;
        } else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
            // Firefox support
            caretPos = ctrl.selectionStart;
        }
        return caretPos;
    }
    function setTextAreaCaretPosition(ctrl, pos) {
        if (ctrl.setSelectionRange) {
            ctrl.focus();
            ctrl.setSelectionRange(pos,pos);
        } else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }

    function LongPress( element, options ) {

        this.element = element;
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    LongPress.prototype = {

        init: function () {
            $(this.element).keydown(onKeyDown);
            $(this.element).keyup(onKeyUp);
        }

    };

    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new LongPress( this, options ));
            }
        });
    };

}(jQuery, window));<commit_msg>Add ability to click on letters to select them in longpress<commit_after>/*
 *  Project: Long Press
 *  Description: Pops a list of alternate characters when a key is long-pressed
 *  Author: Quentin Thiaucourt, http://toki-woki.net
 *    Licence: MIT License http://opensource.org/licenses/mit-license.php
 *
 *  Modified Oct 2014 to work with editable divs also
 */

;(function ($, window, undefined) {

    var pluginName = 'longPress',
        document = window.document,
        defaults = {/*
            propertyName: "value"
        */};

    var moreChars={
        // extended latin (and african latin)
        // upper
        'A':'ĀĂÀÁÂÃÄÅĄⱭ∀Æ',
        'B':'Ɓ',
        'C':'ÇĆĈĊČƆ',
        'D':'ÐĎĐḎƊ',
        'E':'ÈÉÊËĒĖĘẸĚƏÆƎƐ€',
        'F':'ƑƩ',
        'G':'ĜĞĠĢƢ',
        'H':'ĤĦ',
        'I':'ÌÍÎÏĪĮỊİIƗĲ',
        'J':'ĴĲ',
        'K':'ĶƘ',
        'L':'ĹĻĽŁΛ',
        'N':'ÑŃŅŇŊƝ₦',
        'O':'ÒÓÔÕÖŌØŐŒƠƟ',
        'P':'Ƥ¶',
        'R':'ŔŘɌⱤ',
        'S':'ßſŚŜŞṢŠÞ§',
        'T':'ŢŤṮƬƮ',
        'U':'ÙÚÛÜŪŬŮŰŲɄƯƱ',
        'V':'Ʋ',
        'W':'ŴẄΩ',
        'Y':'ÝŶŸƔƳ',
        'Z':'ŹŻŽƵƷẔ',

        // lower
        'a':'āăàáâãäåąɑæαª',
        'b':'ßβɓ',
        'c':'çςćĉċč¢ɔ',
        'd':'ðďđɖḏɖɗ',
        'e':'èéêëēėęẹěəæεɛ€',
        'f':'ƒʃƭ',
        'g':'ĝğġģɠƣ',
        'h':'ĥħɦẖ',
        'i':'ìíîïīįịiiɨĳι',
        'j':'ĵɟĳ',
        'k':'ķƙ',
        'l':'ĺļľłλ',
        'n':'ñńņňŋɲ',
        'o':'òóôõöōøőœơɵ°',
        'p':'ƥ¶',
        'r':'ŕřɍɽ',
        's':'ßſśŝşṣšþ§',
        't':'ţťṯƭʈ',
        'u':'ùúûüūŭůűųưμυʉʊ',
        'v':'ʋ',
        'w':'ŵẅω',
        'y':'ýŷÿɣyƴ',
        'z':'źżžƶẕʒƹ',

        // Misc
        '$':'£¥€₩₨₳Ƀ¤',
        '!':'¡‼‽',
        '?':'¿‽',
        '%':'‰',
        '.':'…••',
        '-':'±‐–—',
        '+':'±†‡',
        '\'':'′″‴‘’‚‛',
        '"':'“”„‟',
        '<':'≤‹',
        '>':'≥›',
        '=':'≈≠≡'

    };
    var ignoredKeys=[8, 13, 37, 38, 39, 40];

    var selectedCharIndex;
    var lastWhich;
    var timer;
    var activeElement;
    var caretPosition; // Technically, the object is a range, but for us it should always be a point
    var textAreaCaretPosition;

    var popup=$('
');

    $(window).mousewheel(onWheel);

    function onKeyDown(e) {

        // Arrow key with popup visible
        if ($('.long-press-popup').length>0 && (e.which==37 || e.which==39)) {
            if (e.which==37) activePreviousLetter();
            else if (e.which==39) activateNextLetter();

            e.preventDefault();
            return;
        }

        if (ignoredKeys.indexOf(e.which)>-1) return;
        activeElement=e.target;

        if (e.which==lastWhich) {
            e.preventDefault();
            if (!timer) timer=setTimeout(onTimer, 10);
            return;
        }
        lastWhich=e.which;
    }
    function onKeyUp(e) {
        if (ignoredKeys.indexOf(e.which)>-1) return;
        if (activeElement==null) return;

        lastWhich=null;
        clearTimeout(timer);
        timer=null;

        hidePopup();
    }
    function onTimer() {
        var typedChar = isTextArea() ?
            $(activeElement).val().split('')[getTextAreaCaretPosition(activeElement)-1] :
            $(activeElement).text().split('')[getCaretPositionOffset(activeElement)-1];

        if (moreChars[typedChar]) {
            storeCaretPosition();
            showPopup((moreChars[typedChar]));
        } else {
            hidePopup();
        }
    }
    function showPopup(chars) {
        popup.empty();
        var letter;
        for (var i=0; i<chars.length; i++) {
            letter=$('
').text(chars[i]);
            letter.mouseenter(activateLetter);
            letter.click(onPopupLetterClick);
            popup.append(letter);
        }
        $('body').append(popup);
        selectedCharIndex=-1;
    }
    function onPopupLetterClick(e) {
        restoreCaretPosition();
        hidePopup();
    }
    function activateLetter(e) {
        selectCharIndex($(e.target).index());
    }
    function activateRelativeLetter(i) {
        selectCharIndex(($('.long-press-letter').length+selectedCharIndex+i) % $('.long-press-letter').length);
    }
    function activateNextLetter() {
        activateRelativeLetter(1);
    }
    function activePreviousLetter() {
        activateRelativeLetter(-1);
    }
    function hidePopup() {
        popup.detach();
    }
    function onWheel(e, delta, deltaX, deltaY) {
        if ($('.long-press-popup').length==0) return;
        e.preventDefault();
        delta<0 ? activateNextLetter() : activePreviousLetter();
    }
    function selectCharIndex(i) {
        $('.long-press-letter.selected').removeClass('selected');
        $('.long-press-letter').eq(i).addClass('selected');
        selectedCharIndex=i;
        updateChar();
    }

    function updateChar() {
        var newChar=$('.long-press-letter.selected').text();
        replacePreviousLetterWithText(newChar);
    }

    function isTextArea() {
        return $(activeElement).is('textarea');
    }

    function storeCaretPosition() {
        if (isTextArea()) {
            textAreaCaretPosition = getTextAreaCaretPosition(activeElement);
        } else {
            caretPosition = getCaretPosition();
        }
    }

    function restoreCaretPosition() {
        if (isTextArea()) {
            setTextAreaCaretPosition(activeElement, textAreaCaretPosition);
        } else {
            setCaretPosition();
        }
    }

    function replacePreviousLetterWithText(text) {
        if (isTextArea()) {
            var pos=getTextAreaCaretPosition(activeElement);
            var arVal=$(activeElement).val().split('');
            arVal[pos-1]=text;
            $(activeElement).val(arVal.join(''));
            setTextAreaCaretPosition(activeElement, pos);
        } else {
            var sel, textNode, clone;
            var range = getCaretPosition();
            if (window.getSelection && range && range.startOffset != 0) {
                sel = window.getSelection();
                if (sel.getRangeAt && sel.rangeCount) {
                    textNode = document.createTextNode(text);

                    clone = range.cloneRange();
                    clone.setStart(range.startContainer, range.startOffset - 1);
                    clone.setEnd(range.startContainer, range.startOffset);
                    clone.deleteContents();
                    range.insertNode(textNode);

                    // Move caret to the end of the newly inserted text node
                    range.setStart(textNode, textNode.length);
                    range.setEnd(textNode, textNode.length);

                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        }
    }

    function getCaretPosition() {
        var sel = window.getSelection();
        return sel.getRangeAt(0);
    }

    function setCaretPosition() {
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(caretPosition);
        window.setTimeout(function() {
            if (activeElement && typeof activeElement.focus != "undefined") {
                activeElement.focus();
            }
        }, 1);
    }

    function getCaretPositionOffset(element) {
        var caretOffset = 0;
        var doc = element.ownerDocument || element.document;
        var win = doc.defaultView || doc.parentWindow;
        var sel;
        if (typeof win.getSelection != "undefined") {
            sel = win.getSelection();
            if (sel.rangeCount > 0) {
                var range = win.getSelection().getRangeAt(0);
                var preCaretRange = range.cloneRange();
                preCaretRange.selectNodeContents(element);
                preCaretRange.setEnd(range.endContainer, range.endOffset);
                caretOffset = preCaretRange.toString().length;
            }
        } else if ( (sel = doc.selection) && sel.type != "Control") {
            var textRange = sel.createRange();
            var preCaretTextRange = doc.body.createTextRange();
            preCaretTextRange.moveToElementText(element);
            preCaretTextRange.setEndPoint("EndToEnd", textRange);
            caretOffset = preCaretTextRange.text.length;
        }
        return caretOffset;
    }

    function getTextAreaCaretPosition (ctrl) {
        var caretPos = 0;
        if (document.selection) {
            // IE Support
            ctrl.focus ();
            var sel = document.selection.createRange ();
            sel.moveStart ('character', -ctrl.value.length);
            caretPos = sel.text.length;
        } else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
            // Firefox support
            caretPos = ctrl.selectionStart;
        }
        return caretPos;
    }
    function setTextAreaCaretPosition(ctrl, pos) {
        if (ctrl.setSelectionRange) {
            ctrl.focus();
            ctrl.setSelectionRange(pos,pos);
        } else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }

    function LongPress( element, options ) {

        this.element = element;
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    LongPress.prototype = {

        init: function () {
            $(this.element).keydown(onKeyDown);
            $(this.element).keyup(onKeyUp);
        }

    };

    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new LongPress( this, options ));
            }
        });
    };

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


<commit_before>var Fangorn = require('js/fangorn');
var m = require('mithril');

function FileViewTreebeard(data) {

    // Set item.branch to show the branch of the rendered GitHub file instead of the default branch
    var addonRootFolders = data['data'][0].children;
    for (var i=0; i < addonRootFolders.length; i++) {
        var item = addonRootFolders[i];
        if (item.provider === 'github' && item.isAddonRoot && window.contextVars.file.extra.branch) {
            item.branch = window.contextVars.file.extra.branch;
        }
    }

    var fangornOpts = {
    divID: 'grid',
    filesData: data.data,
    uploads: false,
    showFilter: false,
    title: undefined,
    hideColumnTitles: true,
    onload: function(tree) {
        var tb = this;
        Fangorn.DefaultOptions.onload.call(tb, tree);
        $('.osf-panel-header.osf-panel-header-flex').show();
    },
    ondataload: function () {
        var tb = this;
        tb.options.folderIndex = 0;
        if (window.contextVars.file.provider === 'figshare') {
            tb.options.folderArray = [window.contextVars.file.name]
        } else if (window.contextVars.file.path) {
            window.contextVars.file.path = decodeURIComponent(window.contextVars.file.path);
            tb.options.folderArray = window.contextVars.file.path.split("/");
            if (tb.options.folderArray.length > 1) {
                tb.options.folderArray.splice(0, 1);
            }
        } else {
            tb.options.folderArray = [''];
        }
        m.render($('#filesSearch').get(0), tb.options.filterTemplate.call(tb));
        $('#filesSearch input[placeholder=Search]').removeClass('pull-right').addClass('pull-left');
    },
    columnTitles: function () {
        return [{
            title: 'Name',
            width: '100%'
        }];
    },
    ontogglefolder : function (tree) {
        Fangorn.DefaultOptions.ontogglefolder.call(this, tree);
        var containerHeight = this.select('#tb-tbody').height();
        this.options.showTotal = Math.floor(containerHeight / this.options.rowHeight) + 1;
        this.redraw();
    },
    lazyLoadOnLoad: function(tree) {
        var tb = this;
        Fangorn.DefaultOptions.lazyLoadOnLoad.call(tb, tree);
        Fangorn.Utils.findCurrentFileID.call(tb, tree, window.contextVars.node.id, window.contextVars.file);
        Fangorn.Utils.scrollToFile.call(tb, tb.currentFileID);
    },
    resolveRows: function (item) {
        var selectClass = '';
        var tb = this;
        var node = item.parent().parent();
        if (item.data.kind === 'file' && tb.currentFileID === item.id) {
            selectClass = 'fangorn-hover';
        }

        var defaultColumns = [
            {
                data: 'name',
                folderIcons: true,
                filter: true,
                css: selectClass,
                custom: Fangorn.DefaultColumns._fangornTitleColumn
            }
        ];

        if (item.parentID) {
            item.data.permissions = item.data.permissions || item.parent().data.permissions;
            if (item.data.kind === 'folder') {
                item.data.accept = item.data.accept || item.parent().data.accept;
            }
        }

        if (item.data.tmpID) {
            defaultColumns = [
                {
                    data: 'name',  // Data field name
                    folderIcons: true,
                    filter: true,
                    custom: function () {
                        return m('span.text-muted', 'Uploading ' + item.data.name + '...');
                    }
                }
            ];
        }

        var configOption = Fangorn.Utils.resolveconfigOption.call(this, item, 'resolveRows', [item]);
        return configOption || defaultColumns;
    }
    };
    var filebrowser = new Fangorn(fangornOpts);
}

module.exports = FileViewTreebeard;<commit_msg>Override tb.options.filterTemplate<commit_after>var Fangorn = require('js/fangorn');
var m = require('mithril');

function FileViewTreebeard(data) {

    // Set item.branch to show the branch of the rendered GitHub file instead of the default branch
    var addonRootFolders = data['data'][0].children;
    for (var i=0; i < addonRootFolders.length; i++) {
        var item = addonRootFolders[i];
        if (item.provider === 'github' && item.isAddonRoot && window.contextVars.file.extra.branch) {
            item.branch = window.contextVars.file.extra.branch;
        }
    }

    var fangornOpts = {
    divID: 'grid',
    filesData: data.data,
    uploads: false,
    showFilter: false,
    title: undefined,
    hideColumnTitles: true,
    filterTemplate: function () {
        var tb = this;
        return m("input.pull-left.form-control[placeholder='" + tb.options.filterPlaceholder + "'][type='text']", {
            style: "width:100%;display:inline;",
            onkeyup: tb.filter,
            value: tb.filterText()
        });
    },
    onload: function(tree) {
        var tb = this;
        Fangorn.DefaultOptions.onload.call(tb, tree);
        $('.osf-panel-header.osf-panel-header-flex').show();
    },
    ondataload: function () {
        var tb = this;
        tb.options.folderIndex = 0;
        if (window.contextVars.file.provider === 'figshare') {
            tb.options.folderArray = [window.contextVars.file.name]
        } else if (window.contextVars.file.path) {
            window.contextVars.file.path = decodeURIComponent(window.contextVars.file.path);
            tb.options.folderArray = window.contextVars.file.path.split("/");
            if (tb.options.folderArray.length > 1) {
                tb.options.folderArray.splice(0, 1);
            }
        } else {
            tb.options.folderArray = [''];
        }
        m.render($('#filesSearch').get(0), tb.options.filterTemplate.call(tb));
    },
    columnTitles: function () {
        return [{
            title: 'Name',
            width: '100%'
        }];
    },
    ontogglefolder : function (tree) {
        Fangorn.DefaultOptions.ontogglefolder.call(this, tree);
        var containerHeight = this.select('#tb-tbody').height();
        this.options.showTotal = Math.floor(containerHeight / this.options.rowHeight) + 1;
        this.redraw();
    },
    lazyLoadOnLoad: function(tree) {
        var tb = this;
        Fangorn.DefaultOptions.lazyLoadOnLoad.call(tb, tree);
        Fangorn.Utils.findCurrentFileID.call(tb, tree, window.contextVars.node.id, window.contextVars.file);
        Fangorn.Utils.scrollToFile.call(tb, tb.currentFileID);
    },
    resolveRows: function (item) {
        var selectClass = '';
        var tb = this;
        var node = item.parent().parent();
        if (item.data.kind === 'file' && tb.currentFileID === item.id) {
            selectClass = 'fangorn-hover';
        }

        var defaultColumns = [
            {
                data: 'name',
                folderIcons: true,
                filter: true,
                css: selectClass,
                custom: Fangorn.DefaultColumns._fangornTitleColumn
            }
        ];

        if (item.parentID) {
            item.data.permissions = item.data.permissions || item.parent().data.permissions;
            if (item.data.kind === 'folder') {
                item.data.accept = item.data.accept || item.parent().data.accept;
            }
        }

        if (item.data.tmpID) {
            defaultColumns = [
                {
                    data: 'name',  // Data field name
                    folderIcons: true,
                    filter: true,
                    custom: function () {
                        return m('span.text-muted', 'Uploading ' + item.data.name + '...');
                    }
                }
            ];
        }

        var configOption = Fangorn.Utils.resolveconfigOption.call(this, item, 'resolveRows', [item]);
        return configOption || defaultColumns;
    }
    };
    var filebrowser = new Fangorn(fangornOpts);
}

module.exports = FileViewTreebeard;<|endoftext|>