<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(() => {
			regFormContainer.scrollTop = 0
			// Show reg form: browser error that doesn’t show opacity of elements inside modal window unless body is scrolled by at least 1 px
			window.scrollBy(0, 1)
			// Prevent background from scrolling
			document.body.style.overflow = 'hidden'
		}, 1000)
	})
}

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(() => {
			// Fade in
			regFormModal.style.opacity = '1.0'
			// Scroll to top
			regFormContainer.scrollTop = 0
			// Show reg form: browser error that doesn’t show opacity of elements inside modal window unless body is scrolled by at least 1 px
			window.scrollBy(0, 1)
			// Prevent background from scrolling
			document.body.style.overflow = 'hidden'
		}, 100)

	})
}

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>/*
 * TODO: Create lazy loading of objects including
 * - obj.hint()
 * - obj.alertify()
 * - obj.session()
 * - obj.tutorial()
 * - obj.vc() // toggle
 * - obj.matchCreate() (using webpack)
 * - obj.koral() (show result, parse for errors ...)
 * - obj.alignment() // toggle
 */

define([
  'match',
  'hint',
  'vc',
  'tutorial',
  'lib/domReady',
  'vc/array',
  'lib/alertify',
  'session',
  'tagger',
  'selectMenu',
  'api',
  'mailToChiffre',
  'lib/highlight/highlight.pack',
  'util'
], function (matchClass,
             hintClass,
             vcClass,
             tutClass,
             domReady,
             vcArray,
             alertifyClass,
             sessionClass,
             tagger,
             selectMenuClass) {

  // Localization values
  const loc = KorAP.Locale;
  loc.VC_allCorpora    = loc.VC_allCorpora    || 'all corpora';
  loc.VC_oneCollection = loc.VC_oneCollection || 'a virtual corpus';
  loc.TOGGLE_ALIGN     = loc.TOGGLE_ALIGN     || 'toggle alignment';
  loc.SHOW_KQ          = loc.SHOW_KQ          || 'show KoralQuery';

  const d = document;

  // Override KorAP.log
  window.alertify = alertifyClass;
  KorAP.log = function (code, msg) {

    // Use alertify to log errors
    alertifyClass.log(
      (code === 0 ? '' : code + ': ') +
        msg,
      'error',
      10000
    );
  };

  domReady(function (event) {
    var obj = {};

    var session = sessionClass.create('KalamarJS');

    // What should be visible?
    var show = session.get('show') || {};

    /**
     * Release notifications
     */
    if (KorAP.Notifications !== undefined) {
      var n = KorAP.Notifications;
      for (var i = 0; i < n.length; i++) {
        alertifyClass.log(n[i][1], n[i][0], 10000);
      };
    };

    /**
     * Replace Virtual Collection field
     */
    var vcname, vcchoose;
    var input = d.getElementById('collection');
    if (input) {
      input.style.display = 'none';
      vcname = d.createElement('span');
      vcname.setAttribute('id', 'vc-choose');
      vcname.classList.add('select');

      var currentVC = loc.VC_allCorpora;
      if (KorAP.koralQuery !== undefined && KorAP.koralQuery["collection"]) {
        currentVC = loc.VC_oneCollection;
      };

      vcchoose = vcname.addE('span');

      vcchoose.addT(
        d.getElementById('collection-name').value || currentVC
      );

      input.parentNode.insertBefore(vcname, input);
    };

    /**
     * Add actions to match entries
     */
    var inactiveLi = d.querySelectorAll(
      '#search > ol > li:not(.active)'
    );
    var i = 0;

    for (i = 0; i < inactiveLi.length; i++) {
      inactiveLi[i].addEventListener('click', function (e) {
        if (this._match !== undefined)
          this._match.open();
        else {
          // lazyLoad
          matchClass.create(this).open();
        };
        // This would prevent the sidebar to go back
        // e.halt();
      });
      inactiveLi[i].addEventListener('keydown', function (e) {
        var code = _codeFromEvent(e);

        switch (code) {
        case 32:
          if (this._match !== undefined)
            this._match.toggle();
          else {
            // lazyLoad
            matchClass.create(this).open();
          };
          e.halt();
          break;
        };
      });
    };

    // Add focus listener to aside
    var aside = d.getElementsByTagName('aside')[0];

    if (aside && aside.classList.contains('active') == false) {

      // Horrible lock to deal with sidebar clicks
      var asideClicked = false;

      // Make aside active on focus
      aside.addEventListener('focus', function(e) {
        this.classList.add('active');
      });

      // Deactivate focus when clicking anywhere else
      var body = d.getElementsByTagName('body')[0];
      if (body !== null) {
        body.addEventListener('click', function() {
          if (!asideClicked) {
            aside.classList.remove('active');
          }
          else {
            asideClicked = false;
          };
        });
      };

      /* Stop click event on aside
       * (to not trickle down to body)
       */
      aside.addEventListener('click', function(e) {
        asideClicked = true;
      });
    };

    // Replace QL select menus with KorAP menus
    var qlField = d.getElementById('ql-field');
    if (qlField !== null) {
      KorAP.QLmenu = selectMenuClass.create(
        d.getElementById('ql-field').parentNode
      ).limit(5);
    };

    var result = d.getElementById('resultinfo');
    var resultButton = null;
    var leftButton = null;
    if (result != null) {

      // Add right buttons
      resultButton = result.addE('div');
      resultButton.classList.add('result', 'button');

      leftButton =  result.addE('div');
      leftButton.classList.add('result', 'button', 'left');
    };

    // There is a koralQuery
    if (KorAP.koralQuery !== undefined) {

      if (resultButton !== null) {
        var kq;
        var toggle = d.createElement('a');
        toggle.setAttribute('title', loc.SHOW_KQ)
        toggle.classList.add('show-kq', 'button');
        toggle.addE('span')
          .addT(loc.SHOW_KQ);
        resultButton.appendChild(toggle);

        var showKQ = function () {
          if (kq === undefined) {
            kq = d.createElement('div');
            kq.setAttribute('id', 'koralquery');
            kq.style.display = 'none';
            var kqInner = d.createElement('div');
            kq.appendChild(kqInner);
            kqInner.innerHTML = JSON.stringify(KorAP.koralQuery, null, '  ');
            hljs.highlightBlock(kqInner);
            var sb = d.getElementById('search');
            sb.insertBefore(kq, sb.firstChild);
          };

          if (kq.style.display === 'none') {
            kq.style.display = 'block';
            show['kq'] = true;
          }
          else {
            kq.style.display = 'none';
            delete show['kq'];
          };
        };

        if (toggle !== undefined) {

          // Show koralquery
          toggle.addEventListener('click', showKQ);
        };
      };

      if (KorAP.koralQuery["errors"]) {
        var errors = KorAP.koralQuery["errors"];
        for (var i in errors) {

          // Malformed query
          if (errors[i][0] === 302 && errors[i][2]) {
            obj.hint = hintClass.create();
            obj.hint.alert(errors[i][2], errors[i][1]);
            break;
          }

          // no query
          else if (errors[i][0] === 301) {
            obj.hint = hintClass.create();
            obj.hint.alert(0, errors[i][1]);
          }
        }
      };

      // Session has KQ visibility stored
      if (show["kq"])
        showKQ.apply();
    };

    // There is more than 0 matches and there is a resultButton
    if (i > 0) {

      if (resultButton !== null) {

        /**
         * Toggle the alignment (left <=> right)
         */
        // querySelector('div.button.right');

        var toggle = d.createElement('a');
        toggle.setAttribute('title', loc.TOGGLE_ALIGN);
        // Todo: Reuse old alignment from query
        var cl = toggle.classList;
        cl.add('align', 'right', 'button');
        toggle.addEventListener(
          'click',
          function (e) {
            var ol = d.querySelector('#search > ol');
            ol.toggleClass("align-left", "align-right");
            this.toggleClass("left", "right");
          });
        toggle.addE('span').addT(loc.TOGGLE_ALIGN);
        resultButton.appendChild(toggle);
      };

      // Not ready yet
      /*
      if (leftButton !== null) {
        var metaInfo = d.createElement('a');
        metaInfo.setAttribute('title', loc.SHOW_META)

        var cl = metaInfo.classList;
        cl.add('show-meta', 'button');
        metaInfo.appendChild(d.createElement('span'))
          .appendChild(d.createTextNode(loc.SHOW_META));
        leftButton.appendChild(metaInfo);
      };
      */
    };

    /**
     * Toggle the Virtual Collection builder
     */
    if (vcname) {
      var vc;
      var vcclick = function () {
        var view = d.getElementById('vc-view');

        // The vc is visible
        if (vcname.classList.contains('active')) {
          view.removeChild(vc.element());
          vcname.classList.remove('active');
          delete show['collection'];
        }

        // The vc is not visible
        else {
          if (vc === undefined)
            vc = _getCurrentVC(vcClass, vcArray);
          view.appendChild(vc.element());
          vcname.classList.add('active');
          show['collection'] = true;
        };
      };

      vcname.onclick = vcclick;

      // Click, if the VC should be shown
      if (show['collection']) {
        vcclick.apply();
      }

      // else
      else if (_checkVCrewrite(vcClass)) {
        vcchoose.classList.add('rewritten');
      };
    };

    /**
     * Init Tutorial view
     */
    if (d.getElementById('view-tutorial')) {
      window.tutorial = tutClass.create(
        d.getElementById('view-tutorial'),
        session
      );
      obj.tutorial = window.tutorial;
    }

    // Tutorial is in parent
    else if (window.parent) {
      obj.tutorial = window.parent.tutorial;
    };

    // Initialize queries for d
    if (obj.tutorial) {
      obj.tutorial.initQueries(d);

      // Initialize documentation links
      obj.tutorial.initDocLinks(d);
    };

    /**
     * Add VC creation on submission.
     */
    var form = d.getElementById('searchform');
    if (form !== null) {
      form.addEventListener('submit', function (e) {
        var qf = d.getElementById('q-field');

        // No query was defined
        if (qf.value === undefined || qf.value === '') {
          qf.focus();
          e.halt();
          KorAP.log(700, "No query given");
          return;
        };

        // Store session information
        session.set("show", show);

        // Set Virtual collection
        if (vc === undefined) {
          vc = _getCurrentVC(vcClass, vcArray);
        };

        if (vc !== undefined) {
          input.value = vc.toQuery();
        }
        else {
          delete input['value'];
        };
      });
    };

    /**
     * Init hint helper
     * has to be final because of
     * reposition
     */
    // Todo: Pass an element, so this works with
    // tutorial pages as well!
    if (obj.hint === undefined)
      obj.hint = hintClass.create();

    // Add the hinthelper to the KorAP object to make it manipulatable globally
    KorAP.Hint = obj.hint;

    return obj;
  });
});

// Render Virtual collection
function _getCurrentVC (vcClass, vcArray) {
  var vc = vcClass.create(vcArray);
  if (KorAP.koralQuery !== undefined && KorAP.koralQuery["collection"]) {
    vc.fromJson(KorAP.koralQuery["collection"]);
  };
  return vc;
};

function _checkVCrewrite (vcClass) {
  if (KorAP.koralQuery !== undefined && KorAP.koralQuery["collection"]) {
    return vcClass.checkRewrite(KorAP.koralQuery["collection"]);
  };
  return false;
}
<commit_msg>Globalize session object<commit_after>/*
 * TODO: Create lazy loading of objects including
 * - obj.hint()
 * - obj.alertify()
 * - obj.session()
 * - obj.tutorial()
 * - obj.vc() // toggle
 * - obj.matchCreate() (using webpack)
 * - obj.koral() (show result, parse for errors ...)
 * - obj.alignment() // toggle
 */

define([
  'match',
  'hint',
  'vc',
  'tutorial',
  'lib/domReady',
  'vc/array',
  'lib/alertify',
  'session',
  'tagger',
  'selectMenu',
  'api',
  'mailToChiffre',
  'lib/highlight/highlight.pack',
  'util'
], function (matchClass,
             hintClass,
             vcClass,
             tutClass,
             domReady,
             vcArray,
             alertifyClass,
             sessionClass,
             tagger,
             selectMenuClass) {

  // Localization values
  const loc = KorAP.Locale;
  loc.VC_allCorpora    = loc.VC_allCorpora    || 'all corpora';
  loc.VC_oneCollection = loc.VC_oneCollection || 'a virtual corpus';
  loc.TOGGLE_ALIGN     = loc.TOGGLE_ALIGN     || 'toggle alignment';
  loc.SHOW_KQ          = loc.SHOW_KQ          || 'show KoralQuery';

  const d = document;

  KorAP.session = sessionClass.create('KalamarJS');

  // Override KorAP.log
  window.alertify = alertifyClass;
  KorAP.log = function (code, msg) {

    // Use alertify to log errors
    alertifyClass.log(
      (code === 0 ? '' : code + ': ') +
        msg,
      'error',
      10000
    );
  };

  domReady(function (event) {
    var obj = {};

    // What should be visible?
    var show = KorAP.session.get('show') || {};

    /**
     * Release notifications
     */
    if (KorAP.Notifications !== undefined) {
      var n = KorAP.Notifications;
      for (var i = 0; i < n.length; i++) {
        alertifyClass.log(n[i][1], n[i][0], 10000);
      };
    };

    /**
     * Replace Virtual Collection field
     */
    var vcname, vcchoose;
    var input = d.getElementById('collection');
    if (input) {
      input.style.display = 'none';
      vcname = d.createElement('span');
      vcname.setAttribute('id', 'vc-choose');
      vcname.classList.add('select');

      var currentVC = loc.VC_allCorpora;
      if (KorAP.koralQuery !== undefined && KorAP.koralQuery["collection"]) {
        currentVC = loc.VC_oneCollection;
      };

      vcchoose = vcname.addE('span');

      vcchoose.addT(
        d.getElementById('collection-name').value || currentVC
      );

      input.parentNode.insertBefore(vcname, input);
    };

    /**
     * Add actions to match entries
     */
    var inactiveLi = d.querySelectorAll(
      '#search > ol > li:not(.active)'
    );
    var i = 0;

    for (i = 0; i < inactiveLi.length; i++) {
      inactiveLi[i].addEventListener('click', function (e) {
        if (this._match !== undefined)
          this._match.open();
        else {
          // lazyLoad
          matchClass.create(this).open();
        };
        // This would prevent the sidebar to go back
        // e.halt();
      });
      inactiveLi[i].addEventListener('keydown', function (e) {
        var code = _codeFromEvent(e);

        switch (code) {
        case 32:
          if (this._match !== undefined)
            this._match.toggle();
          else {
            // lazyLoad
            matchClass.create(this).open();
          };
          e.halt();
          break;
        };
      });
    };

    // Add focus listener to aside
    var aside = d.getElementsByTagName('aside')[0];

    if (aside && aside.classList.contains('active') == false) {

      // Horrible lock to deal with sidebar clicks
      var asideClicked = false;

      // Make aside active on focus
      aside.addEventListener('focus', function(e) {
        this.classList.add('active');
      });

      // Deactivate focus when clicking anywhere else
      var body = d.getElementsByTagName('body')[0];
      if (body !== null) {
        body.addEventListener('click', function() {
          if (!asideClicked) {
            aside.classList.remove('active');
          }
          else {
            asideClicked = false;
          };
        });
      };

      /* Stop click event on aside
       * (to not trickle down to body)
       */
      aside.addEventListener('click', function(e) {
        asideClicked = true;
      });
    };

    // Replace QL select menus with KorAP menus
    var qlField = d.getElementById('ql-field');
    if (qlField !== null) {
      KorAP.QLmenu = selectMenuClass.create(
        d.getElementById('ql-field').parentNode
      ).limit(5);
    };

    var result = d.getElementById('resultinfo');
    var resultButton = null;
    var leftButton = null;
    if (result != null) {

      // Add right buttons
      resultButton = result.addE('div');
      resultButton.classList.add('result', 'button');

      leftButton =  result.addE('div');
      leftButton.classList.add('result', 'button', 'left');
    };

    // There is a koralQuery
    if (KorAP.koralQuery !== undefined) {

      if (resultButton !== null) {
        var kq;
        var toggle = d.createElement('a');
        toggle.setAttribute('title', loc.SHOW_KQ)
        toggle.classList.add('show-kq', 'button');
        toggle.addE('span')
          .addT(loc.SHOW_KQ);
        resultButton.appendChild(toggle);

        var showKQ = function () {
          if (kq === undefined) {
            kq = d.createElement('div');
            kq.setAttribute('id', 'koralquery');
            kq.style.display = 'none';
            var kqInner = d.createElement('div');
            kq.appendChild(kqInner);
            kqInner.innerHTML = JSON.stringify(KorAP.koralQuery, null, '  ');
            hljs.highlightBlock(kqInner);
            var sb = d.getElementById('search');
            sb.insertBefore(kq, sb.firstChild);
          };

          if (kq.style.display === 'none') {
            kq.style.display = 'block';
            show['kq'] = true;
          }
          else {
            kq.style.display = 'none';
            delete show['kq'];
          };
        };

        if (toggle !== undefined) {

          // Show koralquery
          toggle.addEventListener('click', showKQ);
        };
      };

      if (KorAP.koralQuery["errors"]) {
        var errors = KorAP.koralQuery["errors"];
        for (var i in errors) {

          // Malformed query
          if (errors[i][0] === 302 && errors[i][2]) {
            obj.hint = hintClass.create();
            obj.hint.alert(errors[i][2], errors[i][1]);
            break;
          }

          // no query
          else if (errors[i][0] === 301) {
            obj.hint = hintClass.create();
            obj.hint.alert(0, errors[i][1]);
          }
        }
      };

      // Session has KQ visibility stored
      if (show["kq"])
        showKQ.apply();
    };

    // There is more than 0 matches and there is a resultButton
    if (i > 0) {

      if (resultButton !== null) {

        /**
         * Toggle the alignment (left <=> right)
         */
        // querySelector('div.button.right');

        var toggle = d.createElement('a');
        toggle.setAttribute('title', loc.TOGGLE_ALIGN);
        // Todo: Reuse old alignment from query
        var cl = toggle.classList;
        cl.add('align', 'right', 'button');
        toggle.addEventListener(
          'click',
          function (e) {
            var ol = d.querySelector('#search > ol');
            ol.toggleClass("align-left", "align-right");
            this.toggleClass("left", "right");
          });
        toggle.addE('span').addT(loc.TOGGLE_ALIGN);
        resultButton.appendChild(toggle);
      };

      // Not ready yet
      /*
      if (leftButton !== null) {
        var metaInfo = d.createElement('a');
        metaInfo.setAttribute('title', loc.SHOW_META)

        var cl = metaInfo.classList;
        cl.add('show-meta', 'button');
        metaInfo.appendChild(d.createElement('span'))
          .appendChild(d.createTextNode(loc.SHOW_META));
        leftButton.appendChild(metaInfo);
      };
      */
    };

    /**
     * Toggle the Virtual Collection builder
     */
    if (vcname) {
      var vc;
      var vcclick = function () {
        var view = d.getElementById('vc-view');

        // The vc is visible
        if (vcname.classList.contains('active')) {
          view.removeChild(vc.element());
          vcname.classList.remove('active');
          delete show['collection'];
        }

        // The vc is not visible
        else {
          if (vc === undefined)
            vc = _getCurrentVC(vcClass, vcArray);
          view.appendChild(vc.element());
          vcname.classList.add('active');
          show['collection'] = true;
        };
      };

      vcname.onclick = vcclick;

      // Click, if the VC should be shown
      if (show['collection']) {
        vcclick.apply();
      }

      // else
      else if (_checkVCrewrite(vcClass)) {
        vcchoose.classList.add('rewritten');
      };
    };

    /**
     * Init Tutorial view
     */
    if (d.getElementById('view-tutorial')) {
      window.tutorial = tutClass.create(
        d.getElementById('view-tutorial'),
        KorAP.session
      );
      obj.tutorial = window.tutorial;
    }

    // Tutorial is in parent
    else if (window.parent) {
      obj.tutorial = window.parent.tutorial;
    };

    // Initialize queries for d
    if (obj.tutorial) {
      obj.tutorial.initQueries(d);

      // Initialize documentation links
      obj.tutorial.initDocLinks(d);
    };

    /**
     * Add VC creation on submission.
     */
    var form = d.getElementById('searchform');
    if (form !== null) {
      form.addEventListener('submit', function (e) {
        var qf = d.getElementById('q-field');

        // No query was defined
        if (qf.value === undefined || qf.value === '') {
          qf.focus();
          e.halt();
          KorAP.log(700, "No query given");
          return;
        };

        // Store session information
        KorAP.session.set("show", show);

        // Set Virtual collection
        if (vc === undefined) {
          vc = _getCurrentVC(vcClass, vcArray);
        };

        if (vc !== undefined) {
          input.value = vc.toQuery();
        }
        else {
          delete input['value'];
        };
      });
    };

    /**
     * Init hint helper
     * has to be final because of
     * reposition
     */
    // Todo: Pass an element, so this works with
    // tutorial pages as well!
    if (obj.hint === undefined)
      obj.hint = hintClass.create();

    // Add the hinthelper to the KorAP object to make it manipulatable globally
    KorAP.Hint = obj.hint;

    return obj;
  });
});

// Render Virtual collection
function _getCurrentVC (vcClass, vcArray) {
  var vc = vcClass.create(vcArray);
  if (KorAP.koralQuery !== undefined && KorAP.koralQuery["collection"]) {
    vc.fromJson(KorAP.koralQuery["collection"]);
  };
  return vc;
};

function _checkVCrewrite (vcClass) {
  if (KorAP.koralQuery !== undefined && KorAP.koralQuery["collection"]) {
    return vcClass.checkRewrite(KorAP.koralQuery["collection"]);
  };
  return false;
}
<|endoftext|>


<commit_before>/**
 * @fileoverview Setup a virtual DOM for testing in NodeJS.
 */
import { JSDOM } from 'jsdom';

// React needs these.
global.window = new JSDOM('').window;
global.document = global.window.document;
global.navigator = {
  userAgent: 'node.js'
};

// SinonJS needs this.
global.HTMLElement = global.window.HTMLElement;
<commit_msg>Polyfill requestAnimationFrame in unit tests<commit_after>/**
 * @fileoverview Setup a virtual DOM for testing in NodeJS.
 */
import { JSDOM } from 'jsdom';

// React needs these.
global.window = new JSDOM('').window;
global.document = global.window.document;
global.navigator = {
  userAgent: 'node.js'
};
global.requestAnimationFrame = function(callback) {
  setTimeout(callback, 0);
};

// SinonJS needs this.
global.HTMLElement = global.window.HTMLElement;
<|endoftext|>


<commit_before>var http = require("http");
var url = require("url");
var request = require("supertest");
var cheerio = require("cheerio");
var chai = require("chai");
var should = chai.should();
var router = require("../router");

var testServer = null;
describe("World Minesweeper", function () {
  before(function launchServer() {
    testServer = http.createServer(router.onRequest).listen(5001);
  });

  after(function stopServer() {
    testServer.close();
  });

  describe("Minesweeper board", function () {
    it("should return a successful html response on /minesweeper", function (done) {
      request(testServer)
        .get("/minesweeper")
        .expect(200)
        .expect("Content-Type", "text/html", done);
    });

    it("page should have a title element with Minesweeper text", function (done) {
      request(testServer)
        .get("/minesweeper")
        .expect(function (response) {
          var $ = cheerio.load(response.text);
          $("#title")[0].children[0].nodeValue.should.contain("Minesweeper");
        })
        .end(done);
    });
  });
});
<commit_msg>minor test name change<commit_after>var http = require("http");
var url = require("url");
var request = require("supertest");
var cheerio = require("cheerio");
var chai = require("chai");
var should = chai.should();
var router = require("../router");

var testServer = null;
describe("World Minesweeper", function () {
  before(function launchServer() {
    testServer = http.createServer(router.onRequest).listen(5001);
  });

  after(function stopServer() {
    testServer.close();
  });

  describe("Minesweeper board", function () {
    it("should return a successful html response on /minesweeper", function (done) {
      request(testServer)
        .get("/minesweeper")
        .expect(200)
        .expect("Content-Type", "text/html", done);
    });

    it("page should have a title element with 'Minesweeper' in it", function (done) {
      request(testServer)
        .get("/minesweeper")
        .expect(function (response) {
          var $ = cheerio.load(response.text);
          $("#title")[0].children[0].nodeValue.should.contain("Minesweeper");
        })
        .end(done);
    });
  });
});
<|endoftext|>


<commit_before>import { renderLateInfoPopover } from '../../src/components/task-progress';

describe('Task Progress', () => {
    describe('renderLateInfoPopover', () => {
        describe('incomplete task step', () => {
            const step = {
                is_completed: false,
                published_points: null
            }

            it('does not render anything', () => {
                expect(renderLateInfoPopover(step)).toBeNull();
            });
        });

        describe('completed but ungraded task step', () => {
            const step = {
                is_completed: true,
                published_points: null
            }

            it('renders the "Not yet graded" popup', () => {
                expect(renderLateInfoPopover(step)).toMatchSnapshot();
            });
        });
    });
});
<commit_msg>Fixed lint errors<commit_after>import { renderLateInfoPopover } from '../../src/components/task-progress';

describe('Task Progress', () => {
    describe('renderLateInfoPopover', () => {
        describe('incomplete task step', () => {
            const step = {
                is_completed: false,
                published_points: null,
            }

            it('does not render anything', () => {
                expect(renderLateInfoPopover(step)).toBeNull();
            });
        });

        describe('completed but ungraded task step', () => {
            const step = {
                is_completed: true,
                published_points: null,
            }

            it('renders the "Not yet graded" popup', () => {
                expect(renderLateInfoPopover(step)).toMatchSnapshot();
            });
        });
    });
});
<|endoftext|>


<commit_before>import compact from 'lodash/compact'
import every from 'lodash/every'
import map from 'lodash/map'
import some from 'lodash/some'
import takeWhile from 'lodash/takeWhile'
import toPairs from 'lodash/toPairs'

const SUBSTRING_KEYS = new Set([
	'title',
	'name',
	'description',
	'notes',
	'instructors',
	'times',
	'locations',
])

function checkCourseAgainstQueryBit(course, [key, values]) {
	if (!course.hasOwnProperty(key)) {
		return false
	}

	let substring = SUBSTRING_KEYS.has(key)

	// values is either:
	// - a 1-long array
	// - an $AND, $OR, $NOT, $NOR, or $XOR query
	// - one of the above, but substring

	let hasBool = typeof values[0] === 'string' && values[0].startsWith('$')
	let OR = values[0] === '$OR'
	let NOR = values[0] === '$NOR'
	let AND = values[0] === '$AND'
	let NOT = values[0] === '$NOT'
	let XOR = values[0] === '$XOR'

	if (hasBool) {
		// remove the first value from the array
		// by returning all but the first element
		values = values.slice(1)
	}

	let internalMatches = map(values, val => {
		// dept, gereqs, etc.
		if (Array.isArray(course[key]) && !substring) {
			return course[key].includes(val)
		} else if (Array.isArray(course[key]) && substring) {
			return some(
				map(course[key], item =>
					item.toLowerCase().includes(val.toLowerCase()),
				),
			)
		} else if (substring) {
			return course[key].toLowerCase().includes(val.toLowerCase())
		}
		return course[key] === val
	})

	if (!hasBool) {
		return every(internalMatches)
	}

	let result = false

	if (OR) result = some(internalMatches)
	if (NOR) result = !some(internalMatches)
	if (AND) result = every(internalMatches)
	if (NOT) result = !every(internalMatches)
	if (XOR) result = compact(internalMatches).length === 1

	return result
}

// Checks if a course passes a query check.
// query: Object | the query object that comes out of buildQueryFromString
// course: Course | the course to check
// returns: Boolean | did all query bits pass the check?
export function checkCourseAgainstQuery(query, course) {
	let kvPairs = toPairs(query)
	let matches = takeWhile(kvPairs, pair =>
		checkCourseAgainstQueryBit(course, pair),
	)

	return kvPairs.length === matches.length && every(matches)
}
<commit_msg>remove some _.map/_.some uses from checkCourseAgainstQuery<commit_after>import compact from 'lodash/compact'
import every from 'lodash/every'
import map from 'lodash/map'
import some from 'lodash/some'
import takeWhile from 'lodash/takeWhile'
import toPairs from 'lodash/toPairs'

const SUBSTRING_KEYS = new Set([
	'title',
	'name',
	'description',
	'notes',
	'instructors',
	'times',
	'locations',
])

function checkCourseAgainstQueryBit(course, [key, values]) {
	if (!course.hasOwnProperty(key)) {
		return false
	}

	let substring = SUBSTRING_KEYS.has(key)

	// values is either:
	// - a 1-long array
	// - an $AND, $OR, $NOT, $NOR, or $XOR query
	// - one of the above, but substring

	let hasBool = typeof values[0] === 'string' && values[0].startsWith('$')
	let OR = values[0] === '$OR'
	let NOR = values[0] === '$NOR'
	let AND = values[0] === '$AND'
	let NOT = values[0] === '$NOT'
	let XOR = values[0] === '$XOR'

	if (hasBool) {
		// remove the first value from the array
		// by returning all but the first element
		values = values.slice(1)
	}

	let internalMatches = map(values, val => {
		// dept, gereqs, etc.
		if (Array.isArray(course[key]) && !substring) {
			return course[key].includes(val)
		}

		if (Array.isArray(course[key]) && substring) {
			val = val.toLowerCase()
			return course[key]
				.map(item => item.toLowerCase().includes(val))
				.some(v => v === true)
		}

		if (substring) {
			val = val.toLowerCase()
			return course[key].toLowerCase().includes(val)
		}

		return course[key] === val
	})

	if (!hasBool) {
		return every(internalMatches)
	}

	let result = false

	if (OR) result = some(internalMatches)
	if (NOR) result = !some(internalMatches)
	if (AND) result = every(internalMatches)
	if (NOT) result = !every(internalMatches)
	if (XOR) result = compact(internalMatches).length === 1

	return result
}

// Checks if a course passes a query check.
// query: Object | the query object that comes out of buildQueryFromString
// course: Course | the course to check
// returns: Boolean | did all query bits pass the check?
export function checkCourseAgainstQuery(query, course) {
	let kvPairs = toPairs(query)
	let matches = takeWhile(kvPairs, pair =>
		checkCourseAgainstQueryBit(course, pair),
	)

	return kvPairs.length === matches.length && every(matches)
}
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */
/**
 * Defines support rules related to the view.
 */
sap.ui.define(["jquery.sap.global", "sap/ui/support/library"],
	function(jQuery, SupportLib) {
	"use strict";

	// shortcuts
	var Categories = SupportLib.Categories; // Accessibility, Performance, Memory, ...
	var Severity = SupportLib.Severity; // Hint, Warning, Error
	var Audiences = SupportLib.Audiences; // Control, Internal, Application

	return {
		/**
		 *
		 * @param oRuleSet
		 * @param {object} oCfg configuration object with key 'iNumberOfControlsThreshold' containing an the maximum
		 * number of controls.
		 */
		addRulesToRuleSet: function(oRuleSet, oCfg) {
			oCfg = oCfg || {};
			//**********************************************************
			// Rule Definitions
			//**********************************************************

			/**
			 * Checks for wrongly configured view namespace
			 */
			oRuleSet.addRule({
				id: "XMLViewWrongNamespace",
				audiences: [Audiences.Application],
				categories: [Categories.Functionality],
				enabled: true,
				title: "XML View is not configured with namespace 'sap.ui.core.mvc'",
				description: "For consistency and proper resource loading, the root node of an XML view must be configured with the namespace 'mvc'",
				resolution: "Define the XML view as '<core:View ...>' and configure the XML namepspace as 'xmlns:mvc=\"sap.ui.core.mvc\"'",
				resolutionurls: [{
					text: "Documentation: Namespaces in XML Views",
					href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
				}],
				check: function(oIssueManager, oCoreFacade, oScope) {
					var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });
					aXMLViews.forEach(function (oXMLView) {
						if (oXMLView._xContent.namespaceURI !== "sap.ui.core.mvc") {
							var sViewName = oXMLView.getViewName().split("\.").pop();
							oIssueManager.addIssue({
								severity: Severity.Medium,
								details: "The view '" + sViewName + "' (" + oXMLView.getId() + ") is configured with namespace '" + oXMLView._xContent.namespaceURI + "' instead of 'sap.ui.core.mvc'",
								context: {
									id: oXMLView.getId()
								}
							});
						}
					});
				}
			});

			/**
			 * Checks if a default namespaces is set in an XML view
			 */
			oRuleSet.addRule({
				id: "XMLViewDefaultNamespace",
				audiences: [Audiences.Control, Audiences.Application],
				categories: [Categories.Performance],
				enabled: true,
				title: "Default namespace missing in XML view",
				description: "If the default namespace is missing, the code is less readable and parsing performance may be slow",
				resolution: "Set the namespace of the control library that holds most of the controls you use as default namespace (e.g. xmlns=\"sap.m\")",
				resolutionurls: [{
					text: "Documentation: Namespaces in XML Views",
					href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
				}],
				check: function(oIssueManager, oCoreFacade, oScope) {
					var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });

					aXMLViews.forEach(function (oXMLView) {
						if (!oXMLView._xContent.attributes.getNamedItem("xmlns")) {
							var sViewName = oXMLView.getViewName().split("\.").pop();
							oIssueManager.addIssue({
								severity: Severity.Low,
								details: "The view '" + sViewName + "' (" + oXMLView.getId() + ") does not contain a default namespace",
								context: {
									id: oXMLView.getId()
								}
							});
						}
					});
				}
			});

			oRuleSet.addRule({
				id: "XMLViewLowerCaseControl",
				audiences: ["Control","Application"],
				categories: ["Performance"],
				enabled: true,
				title: "Control tag in XMl view starts with lower case",
				description: "Control tags with lower case cannot be loaded in Linux-based systems",
				resolution: "Start the Control tag with upper case",
				resolutionurls: [],
				check: function (oIssueManager, oCoreFacade, oScope) {

					//get all aggregations of each element
					var aAggregationsOfElements = oScope.getElements().map(
							function (oElement) {
								return Object.keys(oElement.mAggregations);
							}
					);
					//flatten array of arrays and filter duplicates
					var aAggregations = aAggregationsOfElements.reduce(
						function(a, b) {
							return a.concat(b);
						}).filter(
							function (x, i, a) {
								return a.indexOf(x) === i;
							});

					var aXMLViews = oScope.getElements().filter(function (oControl) {
						return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView";
					});

					aXMLViews.forEach(function (oXMLView) {
						var aLocalName = [];
						var _getTags = function (oXcontent) {
							aLocalName.push(oXcontent.localName);
							for (var i = 0; i < oXcontent.children.length; i++) {
								_getTags(oXcontent.children[i]);
							}
						};

						_getTags(oXMLView._xContent);
						aLocalName = jQuery.uniqueSort(aLocalName);

						aLocalName.forEach(function (sTag) 	{
							var sFirstLetter = sTag.charAt(0);
							// check for lowercase, aggregations are excluded
							if ((sFirstLetter.toLowerCase() === sFirstLetter) && !aAggregations.includes(sTag)) {
								var sViewName = oXMLView.getViewName().split("\.").pop();
								oIssueManager.addIssue({
									severity: Severity.High,
									details: "View '" + sViewName + "' (" + oXMLView.getId() + ") contains a Control tag that starts with lower case '" + sTag + "'",
									context: {
										id: oXMLView.getId()
									}
								});
							}
						});
					});
				}
			});

			/**
			 * Checks for unused namespaces inside an XML view
			 */
			oRuleSet.addRule({
				id: "XMLViewUnusedNamespaces",
				audiences: [Audiences.Control, Audiences.Application],
				categories: [Categories.Performance],
				enabled: true,
				title: "Unused namespaces in XML view",
				description: "Namespaces that are declared but not used have a negative impact on performance (and may confuse readers of the code)",
				resolution: "Remove the unused namespaces from the view definition",
				resolutionurls: [{
					text: "Documentation: Namespaces in XML Views",
					href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
				}],
				check: function(oIssueManager, oCoreFacade, oScope) {
					var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });

					aXMLViews.forEach(function (oXMLView) {
						for (var i = 0; i < oXMLView._xContent.attributes.length; i++) {
							var sName = oXMLView._xContent.attributes.item(i).name;
							var sLocalName = oXMLView._xContent.attributes.item(i).localName;
							var sFullName = oXMLView._xContent.attributes.item(i).value;

							// check all explicit namespaces except for the injected support namespace
							// and the mvc, because the use of mvc is checked in other rule
							if (sName.match("xmlns:")
								&& sLocalName !== "xmlns:support"
								&& sLocalName !== "mvc") {
								for (var j = 0; j < oXMLView._xContent.children.length; j++) {
									var sContent = oXMLView._xContent.children[j].outerHTML;

									// check if there is a reference of this namespace inside the view
									if (!sContent.match("<" + sLocalName + ":")) {
										var sViewName = oXMLView.getViewName().split("\.").pop();
										oIssueManager.addIssue({
											severity: Severity.Error,
											details: "View '" + sViewName + "' (" + oXMLView.getId() + ") contains an unused XML namespace '" + sLocalName + "' referencing library '" + sFullName + "'",
											context: {
												id: oXMLView.getId()
											}
										});
									}
								}
							}
						}
					});
				}
			});

		}
	};

}, true);
<commit_msg>[FIX] Support assistent XML view rule<commit_after>/*!
 * ${copyright}
 */
/**
 * Defines support rules related to the view.
 */
sap.ui.define(["jquery.sap.global", "sap/ui/support/library"],
	function(jQuery, SupportLib) {
	"use strict";

	// shortcuts
	var Categories = SupportLib.Categories; // Accessibility, Performance, Memory, ...
	var Severity = SupportLib.Severity; // Hint, Warning, Error
	var Audiences = SupportLib.Audiences; // Control, Internal, Application

	return {
		/**
		 *
		 * @param oRuleSet
		 * @param {object} oCfg configuration object with key 'iNumberOfControlsThreshold' containing an the maximum
		 * number of controls.
		 */
		addRulesToRuleSet: function(oRuleSet, oCfg) {
			oCfg = oCfg || {};
			//**********************************************************
			// Rule Definitions
			//**********************************************************

			/**
			 * Checks for wrongly configured view namespace
			 */
			oRuleSet.addRule({
				id: "XMLViewWrongNamespace",
				audiences: [Audiences.Application],
				categories: [Categories.Functionality],
				enabled: true,
				title: "XML View is not configured with namespace 'sap.ui.core.mvc'",
				description: "For consistency and proper resource loading, the root node of an XML view must be configured with the namespace 'mvc'",
				resolution: "Define the XML view as '<core:View ...>' and configure the XML namepspace as 'xmlns:mvc=\"sap.ui.core.mvc\"'",
				resolutionurls: [{
					text: "Documentation: Namespaces in XML Views",
					href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
				}],
				check: function(oIssueManager, oCoreFacade, oScope) {
					var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });
					aXMLViews.forEach(function (oXMLView) {
						if (oXMLView._xContent.namespaceURI !== "sap.ui.core.mvc") {
							var sViewName = oXMLView.getViewName().split("\.").pop();
							oIssueManager.addIssue({
								severity: Severity.Medium,
								details: "The view '" + sViewName + "' (" + oXMLView.getId() + ") is configured with namespace '" + oXMLView._xContent.namespaceURI + "' instead of 'sap.ui.core.mvc'",
								context: {
									id: oXMLView.getId()
								}
							});
						}
					});
				}
			});

			/**
			 * Checks if a default namespaces is set in an XML view
			 */
			oRuleSet.addRule({
				id: "XMLViewDefaultNamespace",
				audiences: [Audiences.Control, Audiences.Application],
				categories: [Categories.Performance],
				enabled: true,
				title: "Default namespace missing in XML view",
				description: "If the default namespace is missing, the code is less readable and parsing performance may be slow",
				resolution: "Set the namespace of the control library that holds most of the controls you use as default namespace (e.g. xmlns=\"sap.m\")",
				resolutionurls: [{
					text: "Documentation: Namespaces in XML Views",
					href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
				}],
				check: function(oIssueManager, oCoreFacade, oScope) {
					var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });

					aXMLViews.forEach(function (oXMLView) {
						if (!oXMLView._xContent.attributes.getNamedItem("xmlns")) {
							var sViewName = oXMLView.getViewName().split("\.").pop();
							oIssueManager.addIssue({
								severity: Severity.Low,
								details: "The view '" + sViewName + "' (" + oXMLView.getId() + ") does not contain a default namespace",
								context: {
									id: oXMLView.getId()
								}
							});
						}
					});
				}
			});

			oRuleSet.addRule({
				id: "XMLViewLowerCaseControl",
				audiences: ["Control","Application"],
				categories: ["Performance"],
				enabled: true,
				title: "Control tag in XML view starts with lower case",
				description: "Control tags with lower case cannot be loaded in Linux-based systems",
				resolution: "Start the Control tag with upper case",
				resolutionurls: [],
				check: function (oIssueManager, oCoreFacade, oScope) {

					//get all aggregations of each element
					var aAggregationsOfElements = oScope.getElements().map(
							function (oElement) {
								return Object.keys(oElement.getMetadata().getAllAggregations());
							}
					);
					//flatten array of arrays and filter duplicates
					var aAggregations = aAggregationsOfElements.reduce(
						function(a, b) {
							return a.concat(b);
						}).filter(
							function (x, i, a) {
								return a.indexOf(x) === i;
							});

					var aXMLViews = oScope.getElements().filter(function (oControl) {
						return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView";
					});

					aXMLViews.forEach(function (oXMLView) {
						var aLocalName = [];
						var _getTags = function (oXcontent) {
							aLocalName.push(oXcontent.localName);
							for (var i = 0; i < oXcontent.children.length; i++) {
								_getTags(oXcontent.children[i]);
							}
						};

						_getTags(oXMLView._xContent);
						aLocalName = jQuery.uniqueSort(aLocalName);

						aLocalName.forEach(function (sTag) 	{
							var sFirstLetter = sTag.charAt(0);
							// check for lowercase, aggregations are excluded
							if ((sFirstLetter.toLowerCase() === sFirstLetter) && !aAggregations.includes(sTag)) {
								var sViewName = oXMLView.getViewName().split("\.").pop();
								oIssueManager.addIssue({
									severity: Severity.High,
									details: "View '" + sViewName + "' (" + oXMLView.getId() + ") contains a Control tag that starts with lower case '" + sTag + "'",
									context: {
										id: oXMLView.getId()
									}
								});
							}
						});
					});
				}
			});

			/**
			 * Checks for unused namespaces inside an XML view
			 */
			oRuleSet.addRule({
				id: "XMLViewUnusedNamespaces",
				audiences: [Audiences.Control, Audiences.Application],
				categories: [Categories.Performance],
				enabled: true,
				title: "Unused namespaces in XML view",
				description: "Namespaces that are declared but not used have a negative impact on performance (and may confuse readers of the code)",
				resolution: "Remove the unused namespaces from the view definition",
				resolutionurls: [{
					text: "Documentation: Namespaces in XML Views",
					href: "https://sapui5.hana.ondemand.com/#docs/guide/2421a2c9fa574b2e937461b5313671f0.html"
				}],
				check: function(oIssueManager, oCoreFacade, oScope) {
					var aXMLViews = oScope.getElements().filter(function (oControl) { return oControl.getMetadata().getName() === "sap.ui.core.mvc.XMLView"; });

					aXMLViews.forEach(function (oXMLView) {
						for (var i = 0; i < oXMLView._xContent.attributes.length; i++) {
							var sName = oXMLView._xContent.attributes.item(i).name;
							var sLocalName = oXMLView._xContent.attributes.item(i).localName;
							var sFullName = oXMLView._xContent.attributes.item(i).value;

							// check all explicit namespaces except for the injected support namespace
							// and the mvc, because the use of mvc is checked in other rule
							if (sName.match("xmlns:")
								&& sLocalName !== "xmlns:support"
								&& sLocalName !== "mvc") {
								for (var j = 0; j < oXMLView._xContent.children.length; j++) {
									var sContent = oXMLView._xContent.children[j].outerHTML;

									// check if there is a reference of this namespace inside the view
									if (!sContent.match("<" + sLocalName + ":")) {
										var sViewName = oXMLView.getViewName().split("\.").pop();
										oIssueManager.addIssue({
											severity: Severity.Error,
											details: "View '" + sViewName + "' (" + oXMLView.getId() + ") contains an unused XML namespace '" + sLocalName + "' referencing library '" + sFullName + "'",
											context: {
												id: oXMLView.getId()
											}
										});
									}
								}
							}
						}
					});
				}
			});

		}
	};

}, true);
<|endoftext|>


<commit_before>
exports.up = function(knex, Promise) {

};

exports.down = function(knex, Promise) {

};
<commit_msg>created reviews migration<commit_after>
exports.up = function(knex, Promise) {
  knex.schema.createTable('reviews', (table) => {
    table.increments();
    table.integer('rest_id').references('restaurants.id');
    table.integer('user_id').references('users.id');
    table.text('review').notNullable();
    table.integer('rating').notNullable();
    table.timestamp('created_at').defaultTo(knex.fn.now());
  });
};

exports.down = function(knex, Promise) {
  knex.schema.dropTable('reviews');
};
<|endoftext|>


<commit_before>define(['marionette',
    'modules/shipment/collections/distinctproteins',
    'utils/sgs',
    'utils/anoms',
    'utils/editable',
    'collections/datacollections',
    'modules/dc/datacollections',

    'modules/imaging/collections/inspectionimages',
    'modules/imaging/views/imagehistory',

    'tpl!templates/samples/sample.html',
    'backbone', 'backbone-validation'
    ], function(Marionette, DistinctProteins, SG, Anom, Editable, DCCol, DCView,
        InspectionImages, ImageHistoryView,
        template, Backbone) {

    return Marionette.LayoutView.extend({
        className: 'content',
        template: template,

        regions: {
            history: '.history',
            imh: '.im_history',
        },

        initialize: function(options) {
            Backbone.Validation.bind(this);

            this.dcs = new DCCol(null, { queryParams: { sid: this.model.get('BLSAMPLEID'), pp: 5 } })
            this.dcs.fetch()

            this.inspectionimages = new InspectionImages()
            this.inspectionimages.queryParams.sid = this.model.get('BLSAMPLEID')
            this.inspectionimages.fetch()
        },

        onRender: function() {
            var edit = new Editable({ model: this.model, el: this.$el })
            edit.create('NAME', 'text')
            //edit.create('ACRONYM', 'select')
            edit.create('SPACEGROUP', 'select', { data: SG.obj() })
            edit.create('ANOMALOUSSCATTERER', 'select', { data: Anom.obj() })
            edit.create('COMMENTS', 'text')
            edit.create('CODE', 'text')

            _.each(['CELL_A', 'CELL_B', 'CELL_C', 'CELL_ALPHA', 'CELL_BETA', 'CELL_GAMMA', 'REQUIREDRESOLUTION'], function(f, i) {
                edit.create(f, 'text')
            })

            this.distinct = new DistinctProteins()
            var self = this
            this.distinct.fetch().done(function() {
                var opts = _.map(self.distinct.kv(), function(v,k) { return { value: v, id: k } })
                edit.create('PROTEINID', 'autocomplete', { autocomplete: { source: opts } })
            })

            this.history.show(new DCView({ model: this.model, collection: this.dcs, params: { visit: null }, noPageUrl: true, noFilterUrl: true, noSearchUrl: true }))

            this.imh.show(new ImageHistoryView({ historyimages: this.inspectionimages, embed: true }))
        },

    })

})
<commit_msg>only show image history if inspections > 0<commit_after>define(['marionette',
    'modules/shipment/collections/distinctproteins',
    'utils/sgs',
    'utils/anoms',
    'utils/editable',
    'collections/datacollections',
    'modules/dc/datacollections',

    'modules/imaging/collections/inspectionimages',
    'modules/imaging/views/imagehistory',

    'tpl!templates/samples/sample.html',
    'backbone', 'backbone-validation'
    ], function(Marionette, DistinctProteins, SG, Anom, Editable, DCCol, DCView,
        InspectionImages, ImageHistoryView,
        template, Backbone) {

    return Marionette.LayoutView.extend({
        className: 'content',
        template: template,

        regions: {
            history: '.history',
            imh: '.im_history',
        },

        initialize: function(options) {
            Backbone.Validation.bind(this);

            this.dcs = new DCCol(null, { queryParams: { sid: this.model.get('BLSAMPLEID'), pp: 5 } })
            this.dcs.fetch()

            this.inspectionimages = new InspectionImages()
            this.inspectionimages.queryParams.sid = this.model.get('BLSAMPLEID')
            this.inspectionimages.fetch()
        },

        onRender: function() {
            var edit = new Editable({ model: this.model, el: this.$el })
            edit.create('NAME', 'text')
            //edit.create('ACRONYM', 'select')
            edit.create('SPACEGROUP', 'select', { data: SG.obj() })
            edit.create('ANOMALOUSSCATTERER', 'select', { data: Anom.obj() })
            edit.create('COMMENTS', 'text')
            edit.create('CODE', 'text')

            _.each(['CELL_A', 'CELL_B', 'CELL_C', 'CELL_ALPHA', 'CELL_BETA', 'CELL_GAMMA', 'REQUIREDRESOLUTION'], function(f, i) {
                edit.create(f, 'text')
            })

            this.distinct = new DistinctProteins()
            var self = this
            this.distinct.fetch().done(function() {
                var opts = _.map(self.distinct.kv(), function(v,k) { return { value: v, id: k } })
                edit.create('PROTEINID', 'autocomplete', { autocomplete: { source: opts } })
            })

            this.history.show(new DCView({ model: this.model, collection: this.dcs, params: { visit: null }, noPageUrl: true, noFilterUrl: true, noSearchUrl: true }))

            if (this.model.get('INSPECTIONS') > 0) this.imh.show(new ImageHistoryView({ historyimages: this.inspectionimages, embed: true }))
        },

    })

})
<|endoftext|>


<commit_before>/*
Copyright 2019 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import SettingController from "./SettingController";
import dis from "../../dispatcher";

export default class CustomStatusController extends SettingController {
    onChange(level, roomId, newValue) {
        // Dispatch setting change so that some components that are still visible when the
        // Settings page is open (such as RoomTiles) can reflect the change.
        dis.dispatch({
            action: "feature_custom_status_changed",
            value: newValue,
        });
    }
}
<commit_msg>Remove usused setting value from CustomStatusController<commit_after>/*
Copyright 2019 New Vector Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import SettingController from "./SettingController";
import dis from "../../dispatcher";

export default class CustomStatusController extends SettingController {
    onChange(level, roomId, newValue) {
        // Dispatch setting change so that some components that are still visible when the
        // Settings page is open (such as RoomTiles) can reflect the change.
        dis.dispatch({
            action: "feature_custom_status_changed",
        });
    }
}
<|endoftext|>


<commit_before>define(['underscore'], function(_) {
    'use strict';

    // Define this.[type]SocketHandler for each of these
    var TYPES = _.indexBy([
        'edgeDeletion',
        'entityImageUpdated',
        'propertiesChange',
        'textUpdated',
        'userStatusChange',
        'verticesDeleted',
        'workspaceChange',
        'workspaceDelete',
    ]);

    return withSocketHandlers;

    function typeToHandlerName(type) {
        return type + 'SocketHandler';
    }

    function withSocketHandlers() {

        this.after('initialize', function() {
            var self = this,
                types = _.partition(TYPES, function(type) {
                    var handler = typeToHandlerName(type);
                    return (handler in self) && _.isFunction(self[handler]);
                });

            if (types[1].length) {
                console.warn(
                    types[1].length + ' undefined socket handler(s): ',
                    types[1].map(typeToHandlerName).join(', ')
                );
            }

            this.on('socketMessage', this.onSocketMessage);
        });

        this.onSocketMessage = function(evt, message) {
            if (message.type in TYPES) {
                var handler = typeToHandlerName(message.type);
                if (handler in this) {
                    this[handler](message);
                }
            } else {
                console.warn('Unhandled socket message', message.type, message.data);
            }
        };

        this.propertiesChangeSocketHandler = function(message) {
            var self = this,
                updated = null;

            if (message.data && message.data.vertex && !message.data.vertex.sourceVertexId) {
                if (self.cachedVertices[message.data.vertex.id]) {
                    updated = self.updateCacheWithVertex(message.data.vertex, { returnNullIfNotChanged: true });
                    if (updated) {
                        self.trigger('verticesUpdated', {
                            vertices: [updated],
                            options: {
                                originalEvent: message.type,
                                originalData: message.data
                            }
                        });
                    }
                }
            } else if (message.data && message.data.edge) {
                var label = message.data.edge.label,
                    vertices = _.compact([
                        self.cachedVertices[message.data.edge.sourceVertexId],
                        self.cachedVertices[message.data.edge.destVertexId]
                    ]);

                vertices.forEach(function(vertex) {
                    if (!vertex.edgeLabels) {
                        vertex.edgeLabels = [];
                    }

                    if (vertex.edgeLabels.indexOf(label) === -1) {
                        vertex.edgeLabels.push(label);
                    }
                });

                if (vertices.length) {
                    self.trigger('verticesUpdated', {
                        vertices: vertices,
                        options: {
                            originalEvent: message.type
                        }
                    });
                    if (vertices.length === 2) {
                        self.trigger('refreshRelationships');
                    }
                }

                self.trigger('edgesUpdated', {
                    edges: [message.data.edge],
                    options: {
                        originalData: message.data
                    }
                })
            }
        };

        this.entityImageUpdatedSocketHandler = function(message) {
            var updated = null;

            if (message.data && message.data.graphVertexId) {
                updated = this.updateCacheWithVertex(message.data.vertex, { returnNullIfNotChanged: true });
                if (updated) {
                    this.trigger('verticesUpdated', { vertices: [updated] });
                    this.trigger('iconUpdated', { src: null });
                }
            } else console.warn('entityImageUpdated event received with no graphVertexId', message);
        };

        this.textUpdatedSocketHandler = function(message) {
            if (message.data && message.data.graphVertexId) {
                this.trigger('textUpdated', { vertexId: message.data.graphVertexId })
            } else console.warn('textUpdated event received with no graphVertexId', message);
        };

        this.edgeDeletionSocketHandler = function(message) {
            if (_.findWhere(this.selectedEdges, { id: message.data.edgeId })) {
                this.trigger('selectObjects');
            }
            this.trigger('edgesDeleted', { edgeId: message.data.edgeId});
        };

        this.verticesDeletedSocketHandler = function(message) {
            if (_.some(this.selectedVertices, function(vertex) {
                    return ~message.data.vertexIds.indexOf(vertex.id);
                })) {
                this.trigger('selectObjects');
            }
            this.trigger('verticesDeleted', {
                vertices: message.data.vertexIds.map(function(vId) {
                    return { id: vId };
                })
            });
        };

        this.workspaceChangeSocketHandler = function(message) {
            var workspace = $.extend({}, message.data),
                user = _.findWhere(message.data.users, { userId: currentUser.id });

            workspace.editable = /WRITE/i.test(user && user.access);
            workspace.isSharedToUser = workspace.createdBy !== currentUser.id;

            this.trigger('workspaceUpdated', {
                workspace: workspace
            });
        };

        this.workspaceDeleteSocketHandler = function(message) {
            this.trigger('workspaceDeleted', {
                workspaceId: message.workspaceId
            });
        };

        this.userStatusChangeSocketHandler = function(message) {
            // FIXME: disable since this will logout a user if they open
            if (message.data &&
                message.data.status &&
                message.data.status === 'OFFLINE' &&
                message.data.id &&
                message.data.id === currentUser.id) {
                $(document).trigger('logout', {  message: i18n('lumify.session.expired') });
            }
        };

    }
});
<commit_msg>Fix warning<commit_after>define(['underscore'], function(_) {
    'use strict';

    // Define this.[type]SocketHandler for each of these
    var TYPES = _.indexBy([
        'edgeDeletion',
        'entityImageUpdated',
        'propertiesChange',
        'textUpdated',
        'userStatusChange',
        'userWorkspaceChange',
        'verticesDeleted',
        'workspaceChange',
        'workspaceDelete',
    ]);

    return withSocketHandlers;

    function typeToHandlerName(type) {
        return type + 'SocketHandler';
    }

    function withSocketHandlers() {

        this.after('initialize', function() {
            var self = this,
                types = _.partition(TYPES, function(type) {
                    var handler = typeToHandlerName(type);
                    return (handler in self) && _.isFunction(self[handler]);
                });

            if (types[1].length) {
                console.warn(
                    types[1].length + ' undefined socket handler(s): ',
                    types[1].map(typeToHandlerName).join(', ')
                );
            }

            this.on('socketMessage', this.onSocketMessage);
        });

        this.onSocketMessage = function(evt, message) {
            if (message.type in TYPES) {
                var handler = typeToHandlerName(message.type);
                if (handler in this) {
                    this[handler](message);
                }
            } else {
                console.warn('Unhandled socket message', message.type, message.data);
            }
        };

        this.propertiesChangeSocketHandler = function(message) {
            var self = this,
                updated = null;

            if (message.data && message.data.vertex && !message.data.vertex.sourceVertexId) {
                if (self.cachedVertices[message.data.vertex.id]) {
                    updated = self.updateCacheWithVertex(message.data.vertex, { returnNullIfNotChanged: true });
                    if (updated) {
                        self.trigger('verticesUpdated', {
                            vertices: [updated],
                            options: {
                                originalEvent: message.type,
                                originalData: message.data
                            }
                        });
                    }
                }
            } else if (message.data && message.data.edge) {
                var label = message.data.edge.label,
                    vertices = _.compact([
                        self.cachedVertices[message.data.edge.sourceVertexId],
                        self.cachedVertices[message.data.edge.destVertexId]
                    ]);

                vertices.forEach(function(vertex) {
                    if (!vertex.edgeLabels) {
                        vertex.edgeLabels = [];
                    }

                    if (vertex.edgeLabels.indexOf(label) === -1) {
                        vertex.edgeLabels.push(label);
                    }
                });

                if (vertices.length) {
                    self.trigger('verticesUpdated', {
                        vertices: vertices,
                        options: {
                            originalEvent: message.type
                        }
                    });
                    if (vertices.length === 2) {
                        self.trigger('refreshRelationships');
                    }
                }

                self.trigger('edgesUpdated', {
                    edges: [message.data.edge],
                    options: {
                        originalData: message.data
                    }
                })
            }
        };

        this.entityImageUpdatedSocketHandler = function(message) {
            var updated = null;

            if (message.data && message.data.graphVertexId) {
                updated = this.updateCacheWithVertex(message.data.vertex, { returnNullIfNotChanged: true });
                if (updated) {
                    this.trigger('verticesUpdated', { vertices: [updated] });
                    this.trigger('iconUpdated', { src: null });
                }
            } else console.warn('entityImageUpdated event received with no graphVertexId', message);
        };

        this.textUpdatedSocketHandler = function(message) {
            if (message.data && message.data.graphVertexId) {
                this.trigger('textUpdated', { vertexId: message.data.graphVertexId })
            } else console.warn('textUpdated event received with no graphVertexId', message);
        };

        this.edgeDeletionSocketHandler = function(message) {
            if (_.findWhere(this.selectedEdges, { id: message.data.edgeId })) {
                this.trigger('selectObjects');
            }
            this.trigger('edgesDeleted', { edgeId: message.data.edgeId});
        };

        this.verticesDeletedSocketHandler = function(message) {
            if (_.some(this.selectedVertices, function(vertex) {
                    return ~message.data.vertexIds.indexOf(vertex.id);
                })) {
                this.trigger('selectObjects');
            }
            this.trigger('verticesDeleted', {
                vertices: message.data.vertexIds.map(function(vId) {
                    return { id: vId };
                })
            });
        };

        this.workspaceChangeSocketHandler = function(message) {
            var workspace = $.extend({}, message.data),
                user = _.findWhere(message.data.users, { userId: currentUser.id });

            workspace.editable = /WRITE/i.test(user && user.access);
            workspace.isSharedToUser = workspace.createdBy !== currentUser.id;

            this.trigger('workspaceUpdated', {
                workspace: workspace
            });
        };

        this.workspaceDeleteSocketHandler = function(message) {
            this.trigger('workspaceDeleted', {
                workspaceId: message.workspaceId
            });
        };

        this.userStatusChangeSocketHandler = function(message) {
            // FIXME: disable since this will logout a user if they open
            if (message.data &&
                message.data.status &&
                message.data.status === 'OFFLINE' &&
                message.data.id &&
                message.data.id === currentUser.id) {
                $(document).trigger('logout', {  message: i18n('lumify.session.expired') });
            }
        };

        this.userWorkspaceChangeSocketHandler = _.identity;
    }
});
<|endoftext|>


<commit_before>Template.reportBreakdown.onCreated(function() {
  var instance = this;
  instance.yearTotal = new ReactiveVar(0);
  instance.monthTotal = new ReactiveVar(0);
  instance.dayTotal = new ReactiveVar(0);

  if(!Session.get("SelectedBreakdown")){
    Session.set("SelectedBreakdown","rtBreakdown");
  }

  Tracker.autorun(function () {
    getYearlyTotal(instance);
    getMonthlyTotal(instance)
    getDailyTotal(instance)
  });
});

Template.reportBreakdown.onRendered(function() {
});

Template.reportBreakdown.helpers({
  breakDownIsChecked: function(breakdown){
    return isSelectedBreakDown(breakdown) ? "checked" : "";
  },
  breakDownIsActive: function(breakdown){
    return isSelectedBreakDown(breakdown) ? "active" : "";
  },
  yearTotal : function() {
    var val = Template.instance().yearTotal.get();
    return Session.equals("SelectedBreakdown", "rtBreakdown")?formatMs(val):formatCount(val);
  },
  yearRange : function() {
    return "Apr 16, 2014 - Apr 16, 2015";
  },
  monthTotal : function() {
    var val = Template.instance().monthTotal.get();
    return Session.equals("SelectedBreakdown", "rtBreakdown")?formatMs(val):formatCount(val);
  },
  monthRange : function() {
    return "Mar 16, 2015 - Apr 16, 2015";
  },
  isMonthTotalOK: function() {
    //FIXME this is not to be devided by 12 but by number of available periods of data !!!
    var availDataPeriods = 12;
    console.log("month/year comp: " + Template.instance().yearTotal.get()/availDataPeriods  + " > " + Template.instance().monthTotal.get());
    return Template.instance().yearTotal.get()/availDataPeriods > Template.instance().monthTotal.get()?"text-success":"text-danger";
  },
  dayTotal : function() {
    var val = Template.instance().dayTotal.get();
    return Session.equals("SelectedBreakdown", "rtBreakdown")?formatMs(val):formatCount(val);
  },
  isDayTotalOK: function() {
    //FIXME this is not to be devided by 30 but by number of available days in month of data !!!
    var availDataPeriods = 30;
    console.log("month/year comp: " + Template.instance().monthTotal.get()/availDataPeriods  + " > " + Template.instance().dayTotal.get());
    return Template.instance().monthTotal.get()/availDataPeriods > Template.instance().dayTotal.get()?"text-success":"text-danger";
  }

});

Template.reportBreakdown.events({
  'click .breakdown .btn': function(e){
    e.preventDefault();
    Session.set("SelectedBreakdown", e.currentTarget.id);

    getYearlyTotal(Template.instance());
    getMonthlyTotal(Template.instance());
    getDailyTotal(Template.instance());
  }
});

var isSelectedBreakDown = function(breakdown) {
  return Session.equals("SelectedBreakdown", breakdown);
}

function getYearlyTotal(template)
{
  //FIXME pass in the period or last-displayed date
  Meteor.call("compileYearTotal", Session.get("SelectedBreakdown"), Session.get("SelectedEventsStats"), new Date(), function(error, result) {
    if (error) {
      console.log("compileYearTotal callback error: " + error);
    }
    else {
      template.yearTotal.set(result);
    }
  });
}

function getMonthlyTotal(template)
{
  //FIXME pass in the period or last-displayed date
  Meteor.call("compileMonthTotal", Session.get("SelectedBreakdown"), Session.get("SelectedEventsStats"), new Date(), function(error, result) {
    if (error) {
      console.log("compileMonthTotal callback error: " + error);
    }
    else {
      template.monthTotal.set(result);
    }
  });
}

function getDailyTotal(template)
{
  //FIXME pass in the period or last-displayed date
  Meteor.call("compileDayTotal", Session.get("SelectedBreakdown"), Session.get("SelectedEventsStats"), new Date(), function(error, result) {
    if (error) {
      console.log("compileDayTotal callback error: " + error);
    }
    else {
      template.dayTotal.set(result);
    }
  });
}
<commit_msg>Fixed responsiveness in period summaries.<commit_after>Template.reportBreakdown.onCreated(function() {
  var instance = this;
  instance.yearTotal = new ReactiveVar(0);
  instance.monthTotal = new ReactiveVar(0);
  instance.dayTotal = new ReactiveVar(0);

  if(!Session.get("SelectedBreakdown")){
    Session.set("SelectedBreakdown","rtBreakdown");
  }

  Tracker.autorun(function () {
    getYearlyTotal(instance);
    getMonthlyTotal(instance)
    getDailyTotal(instance)
  });
});

Template.reportBreakdown.onRendered(function() {
});

Template.reportBreakdown.helpers({
  breakDownIsChecked: function(breakdown){
    return isSelectedBreakDown(breakdown) ? "checked" : "";
  },
  breakDownIsActive: function(breakdown){
    return isSelectedBreakDown(breakdown) ? "active" : "";
  },
  yearTotal : function() {
    return Template.instance().yearTotal.get()
  },
  yearRange : function() {
    return "Apr 16, 2014 - Apr 16, 2015";
  },
  monthTotal : function() {
    return Template.instance().monthTotal.get()
  },
  monthRange : function() {
    return "Mar 16, 2015 - Apr 16, 2015";
  },
  isMonthTotalOK: function() {
    //FIXME this is not to be devided by 12 but by number of available periods of data !!!
    var availDataPeriods = 12;
    console.log("month/year comp: " + Template.instance().yearTotal.get()/availDataPeriods  + " > " + Template.instance().monthTotal.get());
    return Template.instance().yearTotal.get()/availDataPeriods > Template.instance().monthTotal.get()?"text-success":"text-danger";
  },
  dayTotal : function() {
    return Template.instance().dayTotal.get();
  },
  isDayTotalOK: function() {
    //FIXME this is not to be devided by 30 but by number of available days in month of data !!!
    var availDataPeriods = 30;
    console.log("month/year comp: " + Template.instance().monthTotal.get()/availDataPeriods  + " > " + Template.instance().dayTotal.get());
    return Template.instance().monthTotal.get()/availDataPeriods > Template.instance().dayTotal.get()?"text-success":"text-danger";
  },
  subscriptionType: function() {
    return Session.equals("SelectedBreakdown", "rtBreakdown");
  }

});

Template.reportBreakdown.events({
  'click .breakdown .btn': function(e){
    e.preventDefault();
    Session.set("SelectedBreakdown", e.currentTarget.id);

    getYearlyTotal(Template.instance());
    getMonthlyTotal(Template.instance());
    getDailyTotal(Template.instance());
  }
});

var isSelectedBreakDown = function(breakdown) {
  return Session.equals("SelectedBreakdown", breakdown);
}

function getYearlyTotal(template)
{
  //FIXME pass in the period or last-displayed date
  Meteor.call("compileYearTotal", Session.get("SelectedBreakdown"), Session.get("SelectedEventsStats"), new Date(), function(error, result) {
    if (error) {
      console.log("compileYearTotal callback error: " + error);
    }
    else {
      template.yearTotal.set(Session.equals("SelectedBreakdown", "rtBreakdown")?formatMs(result):formatCount(result));
    }
  });
}

function getMonthlyTotal(template)
{
  //FIXME pass in the period or last-displayed date
  Meteor.call("compileMonthTotal", Session.get("SelectedBreakdown"), Session.get("SelectedEventsStats"), new Date(), function(error, result) {
    if (error) {
      console.log("compileMonthTotal callback error: " + error);
    }
    else {
      template.monthTotal.set(Session.equals("SelectedBreakdown", "rtBreakdown")?formatMs(result):formatCount(result));
    }
  });
}

function getDailyTotal(template)
{
  //FIXME pass in the period or last-displayed date
  Meteor.call("compileDayTotal", Session.get("SelectedBreakdown"), Session.get("SelectedEventsStats"), new Date(), function(error, result) {
    if (error) {
      console.log("compileDayTotal callback error: " + error);
    }
    else {
      template.dayTotal.set(Session.equals("SelectedBreakdown", "rtBreakdown")?formatMs(result):formatCount(result));
    }
  });
}
<|endoftext|>