<commit_before>// @flow
import React from "react"
import _ from "lodash"
import TextField from "@material-ui/core/TextField"
import Radio from "@material-ui/core/Radio"
import Checkbox from "@material-ui/core/Checkbox"
import R from "ramda"
import ReactTelInput from "react-telephone-input"

import DateField from "../components/inputs/DateField"
import { validationErrorSelector, classify } from "./util"
import { sendFormFieldEvent } from "../lib/google_analytics"
import type { Validator, UIValidator } from "../lib/validation/profile"
import type { Profile } from "../flow/profileTypes"
import { CP1252_REGEX } from "../constants"
import FormControlLabel from "@material-ui/core/FormControlLabel"

// utility functions for pushing changes to profile forms back to the
// redux store.
// this expects that the `updateProfile` and `profile` props are passed
// in to whatever component it is used in.

const radioButtonLabelSelector = label => `radio-label-${classify(label)}`

const radioButtonLabel = label => (

    {label}

)

export const radioButtons = R.map(option => (
  <FormControlLabel
    classes={{ root: "profile-radio-button" }}
    value={option.value}
    control={<Radio />}
    label={radioButtonLabel(option.label)}
    key={option.label}
  />
))

/**
 * bind to this.boundTextField in the constructor of a form component
 * to update text fields when editing the profile
 * we pass in a keyset looking like this:
 *
 * ["top-level-key", index, "nested_object_key"] or just ["top_level_key"]
 */
export function boundTextField(
  keySet: string[],
  label: string,
  {
    multiLine = false,
    maxLength = 0
    }: { multiLine: boolean, maxLength: number } = {}
): React$Element<*> {
  const {
    profile,
    errors,
    updateProfile,
    validator,
    updateValidationVisibility,
    updateProfileValidation
  } = this.props

  const onChange = e => {
    const clone = _.cloneDeep(profile)
    _.set(clone, keySet, e.target.value)
    updateValidationVisibility(keySet)
    updateProfile(clone, validator)
  }

  const onBlur = () => {
    updateValidationVisibility(keySet)
    updateProfileValidation(profile, validator)
    sendFormFieldEvent(keySet)
  }

  const getValue = () => {
    const value = _.get(profile, keySet, "")
    return _.isNull(value) || _.isUndefined(value) ? "" : value
  }

  // fullWidth means set width to 100% instead of 256px. This lets us use the
  // Grid and Cell to manage its size
  const options = {}
  if (maxLength) {
    options.maxLength = maxLength
  }
  const error = _.get(errors, keySet, undefined) !== undefined
  return (
    <TextField
      onBlur={onBlur}
      name={label}
      multiline={multiLine}
      classes={{
        root: `input-text ${validationErrorSelector(errors, keySet)}`
      }}
      label={label}
      value={getValue()}
      fullWidth={true}
      error={error}
      onChange={onChange}
      {...options}
    />
  )
}

/**
 * bind this to this.boundDateField in the constructor of a form component
 * to update date fields
 * pass in the name (used as placeholder), key for profile.
 */
export function boundDateField(
  keySet: string[],
  label: string,
  omitDay: boolean,
  allowFutureYear: boolean = false
): React$Element<*> {
  // eslint-disable-line max-len
  const {
    profile,
    errors,
    updateProfile,
    validator,
    updateValidationVisibility,
    updateProfileValidation
  } = this.props

  const onBlur = () => {
    updateValidationVisibility(keySet)
    updateProfileValidation(profile, validator)
    sendFormFieldEvent(keySet)
  }

  return (
    <DateField
      data={profile}
      errors={errors}
      updateHandler={updateProfile}
      onBlur={onBlur}
      validator={validator}
      keySet={keySet}
      label={label}
      omitDay={omitDay}
      allowFutureYear={allowFutureYear}
    />
  )
}

export function boundCheckbox(
  keySet: string[],
  label: string | React$Element<*>
): React$Element<*> {
  const {
    profile,
    errors,
    updateProfile,
    validator,
    updateValidationVisibility
  } = this.props

  const onChange = e => {
    const clone = _.cloneDeep(profile)
    _.set(clone, keySet, e.target.checked)
    updateValidationVisibility(keySet)
    updateProfile(clone, validator)
    sendFormFieldEvent(keySet)
  }

  const style = {
    backgroundColor: "#a31f34"
  }

  return (
    <div
      className={`bound-check-box ${validationErrorSelector(errors, keySet)}`}
    >

        <Checkbox
          checked={_.get(profile, keySet)}
          onCheck={onChange}
          inputStyle={style}
        />
        {label}

      {_.get(errors, keySet)}

  )
}

const onTelChange = R.curry(
  (keySet, profile, updateProfile, validator, newPhoneNumber) => {
    const currentPhoneNumber = _.get(profile, keySet)
    if (currentPhoneNumber !== newPhoneNumber) {
      const clone = _.cloneDeep(profile)
      _.set(clone, keySet, newPhoneNumber)
      updateProfile(clone, validator)
    }
  }
)

export function boundTelephoneInput(keySet: string[]): React$Element<*> {
  const {
    profile,
    errors,
    updateProfile,
    validator,
    updateProfileValidation,
    updateValidationVisibility
  } = this.props

  const onBlur = () => {
    updateValidationVisibility(keySet)
    updateProfileValidation(profile, validator)
    sendFormFieldEvent(keySet)
  }

  const currentCountry = R.toLower(R.pathOr("", ["country"], profile))
  return (
    <div
      className={`bound-telephone ${validationErrorSelector(errors, keySet)}`}
    >
      <ReactTelInput
        defaultCountry={currentCountry}
        flagsImagePath="/static/images/flags.png"
        onChange={onTelChange(keySet, profile, updateProfile, validator)}
        onBlur={onBlur}
        value={R.pathOr("", keySet, profile)}
      />
      {_.get(errors, keySet)}

  )
}

/**
 * Validates the profile then PATCHes the profile if validation succeeded.
 * Returns a promise which resolves with the new profile if validation and PATCH succeeded,
 * or rejects if either failed
 */
export function saveProfileStep(
  validator: Validator | UIValidator,
  isLastStep: boolean = false
): Promise<Profile> {
  const { saveProfile, profile, ui } = this.props
  const clone = {
    ...profile,
    filled_out: profile.filled_out || isLastStep
  }

  if (isLastStep && !profile.filled_out) {
    clone.email_optin = true
  }
  return saveProfile(validator, clone, ui)
}

/**
 * Returns true when first name or last name has non CP-1252 string(s).
 */
export function shouldRenderRomanizedFields(profile: Profile): boolean {
  const firstName = _.get(profile, ["first_name"], "")
  const lastName = _.get(profile, ["last_name"], "")
  return !CP1252_REGEX.test(firstName) || !CP1252_REGEX.test(lastName)
}
<commit_msg>Limit the address field to 100 characters<commit_after>// @flow
import React from "react"
import _ from "lodash"
import TextField from "@material-ui/core/TextField"
import Radio from "@material-ui/core/Radio"
import Checkbox from "@material-ui/core/Checkbox"
import R from "ramda"
import ReactTelInput from "react-telephone-input"

import DateField from "../components/inputs/DateField"
import { validationErrorSelector, classify } from "./util"
import { sendFormFieldEvent } from "../lib/google_analytics"
import type { Validator, UIValidator } from "../lib/validation/profile"
import type { Profile } from "../flow/profileTypes"
import { CP1252_REGEX } from "../constants"
import FormControlLabel from "@material-ui/core/FormControlLabel"

// utility functions for pushing changes to profile forms back to the
// redux store.
// this expects that the `updateProfile` and `profile` props are passed
// in to whatever component it is used in.

const radioButtonLabelSelector = label => `radio-label-${classify(label)}`

const radioButtonLabel = label => (

    {label}

)

export const radioButtons = R.map(option => (
  <FormControlLabel
    classes={{ root: "profile-radio-button" }}
    value={option.value}
    control={<Radio />}
    label={radioButtonLabel(option.label)}
    key={option.label}
  />
))

/**
 * bind to this.boundTextField in the constructor of a form component
 * to update text fields when editing the profile
 * we pass in a keyset looking like this:
 *
 * ["top-level-key", index, "nested_object_key"] or just ["top_level_key"]
 */
export function boundTextField(
  keySet: string[],
  label: string,
  {
    multiLine = false,
    maxLength = 0
    }: { multiLine: boolean, maxLength: number } = {}
): React$Element<*> {
  const {
    profile,
    errors,
    updateProfile,
    validator,
    updateValidationVisibility,
    updateProfileValidation
  } = this.props

  const onChange = e => {
    const clone = _.cloneDeep(profile)
    _.set(clone, keySet, e.target.value)
    updateValidationVisibility(keySet)
    updateProfile(clone, validator)
  }

  const onBlur = () => {
    updateValidationVisibility(keySet)
    updateProfileValidation(profile, validator)
    sendFormFieldEvent(keySet)
  }

  const getValue = () => {
    const value = _.get(profile, keySet, "")
    return _.isNull(value) || _.isUndefined(value) ? "" : value
  }

  // fullWidth means set width to 100% instead of 256px. This lets us use the
  // Grid and Cell to manage its size
  const options = {}
  if (maxLength) {
    options.maxLength = maxLength
  }
  const error = _.get(errors, keySet, undefined) !== undefined
  return (
    <TextField
      onBlur={onBlur}
      name={label}
      multiline={multiLine}
      classes={{
        root: `input-text ${validationErrorSelector(errors, keySet)}`
      }}
      label={label}
      value={getValue()}
      fullWidth={true}
      error={error}
      onChange={onChange}
      inputProps={{ ...options }}
    />
  )
}

/**
 * bind this to this.boundDateField in the constructor of a form component
 * to update date fields
 * pass in the name (used as placeholder), key for profile.
 */
export function boundDateField(
  keySet: string[],
  label: string,
  omitDay: boolean,
  allowFutureYear: boolean = false
): React$Element<*> {
  // eslint-disable-line max-len
  const {
    profile,
    errors,
    updateProfile,
    validator,
    updateValidationVisibility,
    updateProfileValidation
  } = this.props

  const onBlur = () => {
    updateValidationVisibility(keySet)
    updateProfileValidation(profile, validator)
    sendFormFieldEvent(keySet)
  }

  return (
    <DateField
      data={profile}
      errors={errors}
      updateHandler={updateProfile}
      onBlur={onBlur}
      validator={validator}
      keySet={keySet}
      label={label}
      omitDay={omitDay}
      allowFutureYear={allowFutureYear}
    />
  )
}

export function boundCheckbox(
  keySet: string[],
  label: string | React$Element<*>
): React$Element<*> {
  const {
    profile,
    errors,
    updateProfile,
    validator,
    updateValidationVisibility
  } = this.props

  const onChange = e => {
    const clone = _.cloneDeep(profile)
    _.set(clone, keySet, e.target.checked)
    updateValidationVisibility(keySet)
    updateProfile(clone, validator)
    sendFormFieldEvent(keySet)
  }

  const style = {
    backgroundColor: "#a31f34"
  }

  return (
    <div
      className={`bound-check-box ${validationErrorSelector(errors, keySet)}`}
    >

        <Checkbox
          checked={_.get(profile, keySet)}
          onCheck={onChange}
          inputStyle={style}
        />
        {label}

      {_.get(errors, keySet)}

  )
}

const onTelChange = R.curry(
  (keySet, profile, updateProfile, validator, newPhoneNumber) => {
    const currentPhoneNumber = _.get(profile, keySet)
    if (currentPhoneNumber !== newPhoneNumber) {
      const clone = _.cloneDeep(profile)
      _.set(clone, keySet, newPhoneNumber)
      updateProfile(clone, validator)
    }
  }
)

export function boundTelephoneInput(keySet: string[]): React$Element<*> {
  const {
    profile,
    errors,
    updateProfile,
    validator,
    updateProfileValidation,
    updateValidationVisibility
  } = this.props

  const onBlur = () => {
    updateValidationVisibility(keySet)
    updateProfileValidation(profile, validator)
    sendFormFieldEvent(keySet)
  }

  const currentCountry = R.toLower(R.pathOr("", ["country"], profile))
  return (
    <div
      className={`bound-telephone ${validationErrorSelector(errors, keySet)}`}
    >
      <ReactTelInput
        defaultCountry={currentCountry}
        flagsImagePath="/static/images/flags.png"
        onChange={onTelChange(keySet, profile, updateProfile, validator)}
        onBlur={onBlur}
        value={R.pathOr("", keySet, profile)}
      />
      {_.get(errors, keySet)}

  )
}

/**
 * Validates the profile then PATCHes the profile if validation succeeded.
 * Returns a promise which resolves with the new profile if validation and PATCH succeeded,
 * or rejects if either failed
 */
export function saveProfileStep(
  validator: Validator | UIValidator,
  isLastStep: boolean = false
): Promise<Profile> {
  const { saveProfile, profile, ui } = this.props
  const clone = {
    ...profile,
    filled_out: profile.filled_out || isLastStep
  }

  if (isLastStep && !profile.filled_out) {
    clone.email_optin = true
  }
  return saveProfile(validator, clone, ui)
}

/**
 * Returns true when first name or last name has non CP-1252 string(s).
 */
export function shouldRenderRomanizedFields(profile: Profile): boolean {
  const firstName = _.get(profile, ["first_name"], "")
  const lastName = _.get(profile, ["last_name"], "")
  return !CP1252_REGEX.test(firstName) || !CP1252_REGEX.test(lastName)
}
<|endoftext|>


<commit_before>import { importHtml, importOnCall, Q, ajax } from '/utils/msa-utils.js'

const addInputPopup = importOnCall("/utils/msa-utils-popup.js", "addInputPopup")
const makeSuggestions = importOnCall("/utils/msa-utils-suggest.js", "makeSuggestions")

const isArr = Array.isArray

// template

const template = `

Users	Permission

		<input type="image" class="icon add" src="/utils/img/add">

`

const permTrTemplate = `

		<input type="image" class="icon rm" src="/utils/img/remove">

`

// style

importHtml(``)

// msa-user-perm-editor

export class HTMLMsaUserPermEditorElement extends HTMLElement {

	connectedCallback() {
		this.Q = Q
		this.innerHTML = this.getTemplate()
		this.classList.add("msa-user-perm-editor")
		this.sync()
		this.initActions()
	}

	getTemplate() {
		return template
	}

	initActions() {
		this.Q("input.add").onclick = () => this.addPermUnit()
	}

	setValue(val) {
		this.value = val
		this.syncValue()
	}

	sync(name, oldVal, newVal) {
		this.syncValue()
	}
	syncValue() {
		this.Q("table.value tbody").innerHTML = ""
		let expr = this.value && this.value.expr
		if (!expr) return
		if (!isArr(expr)) expr = [expr]
		expr.forEach(val => this.addPermUnit(val))
	}

	async addPermUnit(expr) {
		const tbody = this.Q("table.value tbody")
		const tr = (await importHtml(permTrTemplate, tbody))[0]
		this.setPermUnitExpr(tr, expr)
		this.initPermUnitActions(tr)
	}

	getDefaultPermUnitExpr() {
		return { group: "all", value: false }
	}

	setPermUnitExpr(tr, expr) {
		if (!expr) expr = this.getDefaultPermUnitExpr()
		this.setPermUnitUser(tr, expr)
		this.setPermUnitValue(tr, expr.value)
	}

	setPermUnitUser(tr, expr) {
		if (!tr.expr) tr.expr = {}
		tr.expr.user = expr.user
		tr.expr.group = expr.group
		this.syncPermUnitUser(tr)
	}
	syncPermUnitUser(tr) {
		tr.querySelector(".user").textContent = tr.expr.user || tr.expr.group
	}

	setPermUnitValue(tr, val) {
		if (!tr.expr) tr.expr = {}
		tr.expr.value = val
		this.syncPermUnitValue(tr)
	}
	syncPermUnitValue(tr) {
		tr.querySelector(".perm").textContent = tr.expr.value
	}

	initPermUnitActions(tr) {

		tr.querySelector(".user").addEventListener("click", async () => {
			addInputPopup(this, { wel: "/user/msa-user-selector.js" })
				.then(val => this.setPermUnitUser(tr, val))
		})

		this.initPermUnitPermActions(tr, tr.querySelector(".perm"))

		tr.querySelector("input.rm").onclick = () => tr.remove()
	}

	initPermUnitPermActions(tr, permEl) {
		// TODO
	}

	getValue() {
		const expr = []
		this.querySelectorAll("table.value tbody tr").forEach(tr =>
			expr.push(tr.expr))
		const defVal = this.value && this.value.defVal
		return { expr, defVal }
	}
}

customElements.define("msa-user-perm-editor", HTMLMsaUserPermEditorElement)

export class HTMLMsaUserPermNumEditorElement extends HTMLMsaUserPermEditorElement {

	connectedCallback() {
		if (this.hasAttribute("labels"))
			this.labels = this.getAttribute("labels").split(",")
		super.connectedCallback()
	}
	getDefaultPermUnitExpr() {
		return { group: "all", value: 0 }
	}
	initPermUnitPermActions(tr, permEl) {
		makeSuggestions(permEl, async el => this.labels, {
			waitTime: 0,
			fillTarget: (el, suggest) =>
				this.setPermUnitValue(tr, this.labels.indexOf(suggest))
		})
	}
	syncPermUnitValue(tr) {
		const val = tr.expr.value, labels = this.labels
		const prettyVal = labels ? labels[val] : val
		tr.querySelector(".perm").textContent = prettyVal
	}
	formatPerm(expr) {
		if (!isArr && typeof expr === "object") {
			if (expr.or) return "( " + expr.or.map(or => this.formatPerm(or)).join(" OR ") + " )"
			if (expr.and) return "( " + expr.and.map(and => this.formatPerm(and)).join(" AND ") + " )"
		}
		if (this.labels && typeof expr === "number") {
			return this.labels[expr]
		}
		return super.formatPerm(expr)
	}
	formatPermValue(val) {
		if (this.labels)
			return this.labels[val]
		return val
	}
}

customElements.define("msa-user-perm-num-editor", HTMLMsaUserPermNumEditorElement)<commit_msg>msa-user-perm-editor: Fix<commit_after>import { importHtml, importOnCall, Q, ajax } from '/utils/msa-utils.js'

const importAsInputPopup = importOnCall("/utils/msa-utils-popup.js", "importAsInputPopup")
const makeSuggestions = importOnCall("/utils/msa-utils-suggest.js", "makeSuggestions")

const isArr = Array.isArray

// template

const template = `

Users	Permission

		<input type="image" class="icon add" src="/utils/img/add">

`

const permTrTemplate = `

		<input type="image" class="icon rm" src="/utils/img/remove">

`

// style

importHtml(``)

// msa-user-perm-editor

export class HTMLMsaUserPermEditorElement extends HTMLElement {

	connectedCallback() {
		this.Q = Q
		this.innerHTML = this.getTemplate()
		this.classList.add("msa-user-perm-editor")
		this.sync()
		this.initActions()
	}

	getTemplate() {
		return template
	}

	initActions() {
		this.Q("input.add").onclick = () => this.addPermUnit()
	}

	setValue(val) {
		this.value = val
		this.syncValue()
	}

	sync(name, oldVal, newVal) {
		this.syncValue()
	}
	syncValue() {
		this.Q("table.value tbody").innerHTML = ""
		let expr = this.value && this.value.expr
		if (!expr) return
		if (!isArr(expr)) expr = [expr]
		expr.forEach(val => this.addPermUnit(val))
	}

	async addPermUnit(expr) {
		const tbody = this.Q("table.value tbody")
		const tr = (await importHtml(permTrTemplate, tbody))[0]
		this.setPermUnitExpr(tr, expr)
		this.initPermUnitActions(tr)
	}

	getDefaultPermUnitExpr() {
		return { group: "all", value: false }
	}

	setPermUnitExpr(tr, expr) {
		if (!expr) expr = this.getDefaultPermUnitExpr()
		this.setPermUnitUser(tr, expr)
		this.setPermUnitValue(tr, expr.value)
	}

	setPermUnitUser(tr, expr) {
		if (!tr.expr) tr.expr = {}
		tr.expr.user = expr.user
		tr.expr.group = expr.group
		this.syncPermUnitUser(tr)
	}
	syncPermUnitUser(tr) {
		tr.querySelector(".user").textContent = tr.expr.user || tr.expr.group
	}

	setPermUnitValue(tr, val) {
		if (!tr.expr) tr.expr = {}
		tr.expr.value = val
		this.syncPermUnitValue(tr)
	}
	syncPermUnitValue(tr) {
		tr.querySelector(".perm").textContent = tr.expr.value
	}

	initPermUnitActions(tr) {

		tr.querySelector(".user").addEventListener("click", async () => {
			importAsInputPopup(this, { wel: "/user/msa-user-selector.js" })
				.then(val => this.setPermUnitUser(tr, val))
		})

		this.initPermUnitPermActions(tr, tr.querySelector(".perm"))

		tr.querySelector("input.rm").onclick = () => tr.remove()
	}

	initPermUnitPermActions(tr, permEl) {
		// TODO
	}

	getValue() {
		const expr = []
		this.querySelectorAll("table.value tbody tr").forEach(tr =>
			expr.push(tr.expr))
		const defVal = this.value && this.value.defVal
		return { expr, defVal }
	}
}

customElements.define("msa-user-perm-editor", HTMLMsaUserPermEditorElement)

export class HTMLMsaUserPermNumEditorElement extends HTMLMsaUserPermEditorElement {

	connectedCallback() {
		if (this.hasAttribute("labels"))
			this.labels = this.getAttribute("labels").split(",")
		super.connectedCallback()
	}
	getDefaultPermUnitExpr() {
		return { group: "all", value: 0 }
	}
	initPermUnitPermActions(tr, permEl) {
		makeSuggestions(permEl, async el => this.labels, {
			waitTime: 0,
			fillTarget: (el, suggest) =>
				this.setPermUnitValue(tr, this.labels.indexOf(suggest))
		})
	}
	syncPermUnitValue(tr) {
		const val = tr.expr.value, labels = this.labels
		const prettyVal = labels ? labels[val] : val
		tr.querySelector(".perm").textContent = prettyVal
	}
	formatPerm(expr) {
		if (!isArr && typeof expr === "object") {
			if (expr.or) return "( " + expr.or.map(or => this.formatPerm(or)).join(" OR ") + " )"
			if (expr.and) return "( " + expr.and.map(and => this.formatPerm(and)).join(" AND ") + " )"
		}
		if (this.labels && typeof expr === "number") {
			return this.labels[expr]
		}
		return super.formatPerm(expr)
	}
	formatPermValue(val) {
		if (this.labels)
			return this.labels[val]
		return val
	}
}

customElements.define("msa-user-perm-num-editor", HTMLMsaUserPermNumEditorElement)<|endoftext|>


<commit_before>(function(){

    xtag.register('widget-Filter', {
        extends: 'div',
        lifecycle: {
            created: function() {
                var spawnCondition, filterTitle, currentFilter,
                    controlWrap = document.createElement('form'),
                    controlRows = [],
                    encodedFilter = document.createElement('input'),
                    applyFilter = document.createElement('input'),
                    filterNameLabel = document.createElement('label'),
                    filterName = document.createElement('input'),
                    saveFilter = document.createElement('button'),
                    chooseFilterLabel = document.createElement('label'),
                    chooseFilter = document.createElement('select'),
                    loadFilter = document.createElement('button'),
                    deleteFilter = document.createElement('button'),
                    loadTarget = document.createElement('input'),
                    deleteTarget = document.createElement('input'),
                    saveLoadFilter = document.createElement('button');

                this.filterConditions = [];
                this.nRows = [];
                this.detectors = ['DANTE', 'DESCANT', 'GRIFFIN', 'PACES', 'SCEPTAR', 'ZDS'];
                this.detectorCodes = ['DA', 'DS', 'GR', 'PA', 'SE', 'ZD'],
                this.filterOptions = ['Singles', 'Coincidences', 'Prescale'];
                this.filterCodes = ['S', 'C', 'P'];

                filterTitle = document.createElement('h1');
                filterTitle.innerHTML = 'Filter Control';
                this.appendChild(filterTitle);
                currentFilter = document.createElement('h3');
                currentFilter.setAttribute('id', 'currentFilter');
                this.appendChild(currentFilter);

                this.conditionWrap = document.createElement('form');
                this.conditionWrap.setAttribute('id', 'conditionWrap');
                this.conditionWrap.onchange = function(){
                    document.getElementById('filterName').value = '';
                }
                this.appendChild(this.conditionWrap);

                this.spawnFilterCondition();

                spawnCondition = document.createElement('button');
                spawnCondition.innerHTML = 'OR new condition';
                spawnCondition.setAttribute('class', 'stdin');
                spawnCondition.setAttribute('id', 'spawnCondition')
                spawnCondition.onclick = this.spawnFilterCondition.bind(this);
                this.appendChild(spawnCondition);

                controlWrap.setAttribute('class', 'filterControl summary');
                controlWrap.setAttribute('id', 'filterDefinitionForm');
                controlWrap.setAttribute('method', 'POST');
                controlWrap.setAttribute('action', 'registerFilter');
                this.appendChild(controlWrap);

                controlRows[0] = document.createElement('span')
                controlWrap.appendChild(controlRows[0]);

                encodedFilter.setAttribute('type', 'text');
                encodedFilter.setAttribute('id', 'encodedFilter');
                encodedFilter.setAttribute('style', 'display:none');
                encodedFilter.setAttribute('name', 'filterString');
                controlRows[0].appendChild(encodedFilter);

                applyFilter.setAttribute('type', 'checkbox');
                applyFilter.setAttribute('id', 'applyFilter');
                applyFilter.setAttribute('style', 'display:none');
                applyFilter.setAttribute('name', 'applyFilter');
                controlRows[0].appendChild(applyFilter);

                filterNameLabel.innerHTML = 'Filter Name:';
                filterName.setAttribute('class', 'stdin');
                filterName.setAttribute('type', 'text');
                filterName.setAttribute('id', 'filterName');
                filterName.setAttribute('name', 'filterName');
                filterName.setAttribute('pattern', '^[\\S]*$');
                filterName.setAttribute('required', true);
                controlRows[0].appendChild(filterNameLabel);
                controlRows[0].appendChild(filterName);

                saveFilter.setAttribute('class', 'stdin');
                saveFilter.innerHTML = 'Save Filter Definition';
                saveFilter.onclick = this.registerNewFilter.bind(this);
                controlRows[0].appendChild(saveFilter);

                saveLoadFilter.setAttribute('class', 'stdin');
                saveLoadFilter.innerHTML = 'Save & Apply Filter Definition';
                saveLoadFilter.onclick = function(){
                    this.registerNewFilter();
                    document.getElementById('applyFilter').checked = true;
                }.bind(this);
                controlRows[0].appendChild(saveLoadFilter);

                controlRows[1] = document.createElement('span');
                controlWrap.appendChild(controlRows[1]);

                chooseFilterLabel.innerHTML = 'Load / Delete Filter:'
                controlRows[1].appendChild(chooseFilterLabel);
                chooseFilter.setAttribute('class', 'stdin');
                chooseFilter.setAttribute('id', 'filterList');
                controlRows[1].appendChild(chooseFilter);

                loadTarget.setAttribute('type', 'text');
                loadTarget.setAttribute('name', 'loadTarget');
                loadTarget.setAttribute('id', 'loadTarget');
                loadTarget.setAttribute('value', 'null');
                loadTarget.setAttribute('style', 'display:none');
                controlRows[1].appendChild(loadTarget);
                loadFilter.setAttribute('class', 'stdin');
                loadFilter.innerHTML = 'Load'
                loadFilter.onclick = function(){
                    document.getElementById('loadTarget').value = selected('filterList')
                }
                controlRows[1].appendChild(loadFilter);

                deleteTarget.setAttribute('type', 'text');
                deleteTarget.setAttribute('name', 'deleteTarget');
                deleteTarget.setAttribute('id', 'deleteTarget');
                deleteTarget.setAttribute('value', 'null');
                deleteTarget.setAttribute('style', 'display:none');
                controlRows[1].appendChild(deleteTarget);
                deleteFilter.setAttribute('class', 'stdin');
                deleteFilter.innerHTML = 'Delete'
                deleteFilter.onclick = function(){
                    document.getElementById('deleteTarget').value = selected('filterList')
                }
                controlRows[1].appendChild(deleteFilter);

                XHR('http://'+this.MIDAS+'/?cmd=jcopy&odb=/Filter&encoding=json-nokeys', this.registerFilterODB.bind(this));
            },
            inserted: function() {},
            removed: function() {},
            attributeChanged: function() {}
        },
        events: {

        },
        accessors: {
            'MIDAS':{
                attribute: {} //this just needs to be declared
            }
        },
        methods: {
            'spawnFilterCondition' : function(){
                var newCondition = document.createElement('div'),
                    leftTab = document.createElement('div'),
                    filterContent = document.createElement('div'),
                    conditionTable = document.createElement('table'),
                    addNewRow = document.createElement('button'),
                    deleteCondition = document.createElement('button'),
                    index = this.filterConditions.length;

                newCondition.setAttribute('id', 'filterCondition' + index);
                newCondition.setAttribute('class', 'filterCondition');
                this.conditionWrap.appendChild(newCondition);

                leftTab.setAttribute('id', 'leftTab' + index);
                leftTab.setAttribute('class', 'leftTab');
                leftTab.innerHTML = 'OR';
                newCondition.appendChild(leftTab);

                filterContent.setAttribute('id', 'filterContent' + index);
                filterContent.setAttribute('class', 'filterContent');
                newCondition.appendChild(filterContent)

                conditionTable.setAttribute('id', 'filterTable'+index);
                conditionTable.setAttribute('class', 'filterTable');
                filterContent.appendChild(conditionTable);

                addNewRow.setAttribute('id', 'addNewRow' + index);
                addNewRow.setAttribute('class', 'stdin lightButton');
                addNewRow.setAttribute('return', false);
                addNewRow.innerHTML = 'AND new condition';
                addNewRow.onclick = this.addNewRow.bind(this, index);
                filterContent.appendChild(addNewRow);

                deleteCondition.setAttribute('id', 'deleteCondition' + index);
                deleteCondition.setAttribute('class', 'stdin lightButton');
                //deleteCondition.setAttribute('return', false);
                deleteCondition.innerHTML = 'Delete This Block';
                deleteCondition.onclick = this.deleteOrBlock.bind(this, index);
                filterContent.appendChild(deleteCondition);

                this.nRows[index] = 0;
                addNewRow.onclick();

                this.filterConditions.push(newCondition);
            },

            'addNewRow' : function(index){
                var row, cell,
                    detectorSelect, detectorOption,
                    filterSelect, filterOption,
                    optionConfigWrap, optionConfigLabel, optionConfigInput,
                    deleteRow,
                    i,
                    rowIndex = this.nRows[index]

                row = document.createElement('tr');
                row.setAttribute('id', 'filterRow' + index + rowIndex);
                document.getElementById('filterTable' + index).appendChild(row);

                cell = document.createElement('td');
                cell.innerHTML = 'AND';
                row.appendChild(cell);

                cell = document.createElement('td');
                row.appendChild(cell);
                detectorSelect = document.createElement('select');
                detectorSelect.setAttribute('id', 'detectorSelect'+index+rowIndex);
                detectorSelect.setAttribute('class', 'stdin');
                for(i=0; i<this.detectors.length; i++){
                    detectorOption = document.createElement('option');
                    detectorOption.value = this.detectorCodes[i];
                    detectorOption.innerHTML = this.detectors[i];
                    detectorSelect.appendChild(detectorOption);
                }
                cell.appendChild(detectorSelect);

                cell = document.createElement('td');
                row.appendChild(cell);
                filterSelect = document.createElement('select');
                filterSelect.setAttribute('id', 'filterType'+index+rowIndex)
                filterSelect.setAttribute('class', 'stdin');
                filterSelect.onchange = function(idCode){
                    var filterType = selected('filterType'+idCode);

                    this.manageInputCell(filterType, idCode);

                }.bind(this, ''+index+rowIndex);
                for(i=0; i<this.filterOptions.length; i++){
                    filterOption = document.createElement('option');
                    filterOption.value = this.filterCodes[i];
                    filterOption.innerHTML = this.filterOptions[i];
                    filterSelect.appendChild(filterOption);
                }
                cell.appendChild(filterSelect);

                cell = document.createElement('td');
                row.appendChild(cell);
                optionConfigWrap = document.createElement('div');
                optionConfigWrap.setAttribute('id', 'optionConfigWrap'+index+rowIndex);
                optionConfigWrap.setAttribute('class', 'optionConfigWrap hiddenConfig');
                cell.appendChild(optionConfigWrap);
                optionConfigLabel = document.createElement('label');
                optionConfigLabel.setAttribute('id', 'optionConfigLabel'+index+rowIndex);
                optionConfigWrap.appendChild(optionConfigLabel);
                optionConfigInput = document.createElement('input');
                optionConfigInput.setAttribute('id', 'optionConfigInput'+index+rowIndex);
                optionConfigInput.setAttribute('class', 'stdin');
                optionConfigInput.setAttribute('type', 'number');
                optionConfigInput.setAttribute('step', 1);
                optionConfigInput.setAttribute('min', 0);
                optionConfigWrap.appendChild(optionConfigInput);

                cell = document.createElement('td');
                row.appendChild(cell);
                deleteRow = document.createElement('button');
                deleteRow.setAttribute('return', false);
                deleteRow.innerHTML = 'Remove';
                deleteRow.setAttribute('class', 'stdin');
                deleteRow.onclick = this.deleteRow.bind(this, index, ''+index+rowIndex);
                cell.appendChild(deleteRow);

                this.nRows[index]++;

            },

            'manageInputCell' : function(filterType, idCode){

                if(filterType == 'S'){
                    document.getElementById('optionConfigWrap'+idCode).setAttribute('class', 'optionConfigWrap hiddenConfig');
                } else if(filterType == 'C'){
                    document.getElementById('optionConfigWrap'+idCode).setAttribute('class', 'optionConfigWrap');
                    document.getElementById('optionConfigLabel'+idCode).innerHTML = 'Multiplicity: ';
                    document.getElementById('optionConfigInput'+idCode).setAttribute('value', 2);
                } else if(filterType == 'P'){
                    document.getElementById('optionConfigWrap'+idCode).setAttribute('class', 'optionConfigWrap');
                    document.getElementById('optionConfigLabel'+idCode).innerHTML = 'Factor: ';
                    document.getElementById('optionConfigInput'+idCode).setAttribute('value', 10);
                }
            },

            'deleteOrBlock' : function(index){
                var block = document.getElementById('filterCondition' + index);
                this.conditionWrap.removeChild(block);
            },

            'deleteRow' : function(index, idCode){
                var row = document.getElementById('filterRow'+idCode);
                document.getElementById('filterTable'+index).removeChild(row);

            },

            'registerNewFilter' : function(){
                var filterConditions = this.querySelectorAll('div.filterCondition'),
                    tableRows,
                    selects,
                    detector, filter, scale, condition,
                    encoded = [],
                    i,j;

                for(i=0; i<filterConditions.length; i++){
                    tableRows = filterConditions[i].querySelectorAll('tr');
                    if(!tableRows || tableRows.length == 0) continue;
                    encoded[i] = [];

                    for(j=0; j<tableRows.length; j++){
                        selects = tableRows[j].querySelectorAll('select');

                        detector = selected(selects[0].id);
                        filter = selected(selects[1].id);
                        scale = parseInt(tableRows[j].querySelectorAll('input')[0].value, 10);
                        if(!scale) scale = 1;

                        condition = detector + '-' + filter + '-' + scale;

                        encoded[i][j] = condition;

                    }
                }

                document.getElementById('encodedFilter').value = JSON.stringify(encoded);
            },

            'registerFilterODB' : function(responseText){
                var data = JSON.parse(responseText),
                    currentName = data.Current,
                    currentFilter = data.Filters[currentName],
                    filterSelect = document.getElementById('filterList'),
                    filterOptions, key;

                this.filterRecord = data;

                this.loadFilter(currentFilter);
                document.getElementById('filterName').value = currentName;
                document.getElementById('currentFilter').innerHTML = 'Current Active Filter: ' + currentName;

                for(key in data.Filters){
                    filterOptions = document.createElement('option');
                    filterOptions.innerHTML = key;
                    filterOptions.value = key;
                    filterSelect.appendChild(filterOptions);

                }

                filterSelect.value = currentName;
            },

            'loadFilter' : function(currentFilter){
                var orCells = this.querySelectorAll('div.filterCondition'),
                    cellDelete,
                    createOr = document.getElementById('spawnCondition'),
                    currentOr,
                    i, key;

                for(i=0; i<orCells.length; i++){
                    cellDelete = orCells[i].querySelectorAll('button.lightButton')[1]; //TODO fragile - don't ever change that class or loading breaks!
                    cellDelete.onclick();
                }

                for(key in currentFilter){
                    if(key.indexOf('last_written') != -1 ) continue;

                    createOr.onclick();

                    currentOr = this.querySelectorAll('div.filterCondition');
                    currentOr = currentOr[currentOr.length - 1];
                    if(currentFilter[key] instanceof Array){
                        for(i=0; i<currentFilter[key].length; i++){
                            currentOr.querySelectorAll('select')[i*2].value = currentFilter[key][i].slice(0,2);
                            currentOr.querySelectorAll('select')[i*2+1].value = currentFilter[key][i].slice(3,4);
                            currentOr.querySelectorAll('select')[i*2+1].onchange();
                            currentOr.querySelectorAll('input')[i].value = parseInt(currentFilter[key][i].slice(5),10);

                            if(i<currentFilter[key].length-1)
                                currentOr.querySelectorAll('button.lightButton')[0].onclick();
                        }
                    } else {
                        currentOr.querySelectorAll('select')[0].value = currentFilter[key].slice(0,2);
                        currentOr.querySelectorAll('select')[1].value = currentFilter[key].slice(3,4);
                        currentOr.querySelectorAll('select')[1].onchange();
                        currentOr.querySelectorAll('input')[0].value = parseInt(currentFilter[key].slice(5),10);
                    }

                }
            }

        }
    });

})();<commit_msg>remove filter name on edit<commit_after>(function(){

    xtag.register('widget-Filter', {
        extends: 'div',
        lifecycle: {
            created: function() {
                var spawnCondition, filterTitle, currentFilter,
                    controlWrap = document.createElement('form'),
                    controlRows = [],
                    encodedFilter = document.createElement('input'),
                    applyFilter = document.createElement('input'),
                    filterNameLabel = document.createElement('label'),
                    filterName = document.createElement('input'),
                    saveFilter = document.createElement('button'),
                    chooseFilterLabel = document.createElement('label'),
                    chooseFilter = document.createElement('select'),
                    loadFilter = document.createElement('button'),
                    deleteFilter = document.createElement('button'),
                    loadTarget = document.createElement('input'),
                    deleteTarget = document.createElement('input'),
                    saveLoadFilter = document.createElement('button');

                this.filterConditions = [];
                this.nRows = [];
                this.detectors = ['DANTE', 'DESCANT', 'GRIFFIN', 'PACES', 'SCEPTAR', 'ZDS'];
                this.detectorCodes = ['DA', 'DS', 'GR', 'PA', 'SE', 'ZD'],
                this.filterOptions = ['Singles', 'Coincidences', 'Prescale'];
                this.filterCodes = ['S', 'C', 'P'];

                filterTitle = document.createElement('h1');
                filterTitle.innerHTML = 'Filter Control';
                this.appendChild(filterTitle);
                currentFilter = document.createElement('h3');
                currentFilter.setAttribute('id', 'currentFilter');
                this.appendChild(currentFilter);

                this.conditionWrap = document.createElement('form');
                this.conditionWrap.setAttribute('id', 'conditionWrap');
                this.conditionWrap.onchange = function(){
                    document.getElementById('filterName').value = '';
                }
                this.appendChild(this.conditionWrap);

                this.spawnFilterCondition();

                spawnCondition = document.createElement('button');
                spawnCondition.innerHTML = 'OR new condition';
                spawnCondition.setAttribute('class', 'stdin');
                spawnCondition.setAttribute('id', 'spawnCondition')
                spawnCondition.onclick = this.spawnFilterCondition.bind(this);
                this.appendChild(spawnCondition);

                controlWrap.setAttribute('class', 'filterControl summary');
                controlWrap.setAttribute('id', 'filterDefinitionForm');
                controlWrap.setAttribute('method', 'POST');
                controlWrap.setAttribute('action', 'registerFilter');
                this.appendChild(controlWrap);

                controlRows[0] = document.createElement('span')
                controlWrap.appendChild(controlRows[0]);

                encodedFilter.setAttribute('type', 'text');
                encodedFilter.setAttribute('id', 'encodedFilter');
                encodedFilter.setAttribute('style', 'display:none');
                encodedFilter.setAttribute('name', 'filterString');
                controlRows[0].appendChild(encodedFilter);

                applyFilter.setAttribute('type', 'checkbox');
                applyFilter.setAttribute('id', 'applyFilter');
                applyFilter.setAttribute('style', 'display:none');
                applyFilter.setAttribute('name', 'applyFilter');
                controlRows[0].appendChild(applyFilter);

                filterNameLabel.innerHTML = 'Filter Name:';
                filterName.setAttribute('class', 'stdin');
                filterName.setAttribute('type', 'text');
                filterName.setAttribute('id', 'filterName');
                filterName.setAttribute('name', 'filterName');
                filterName.setAttribute('pattern', '^[\\S]*$');
                filterName.setAttribute('required', true);
                controlRows[0].appendChild(filterNameLabel);
                controlRows[0].appendChild(filterName);

                saveFilter.setAttribute('class', 'stdin');
                saveFilter.innerHTML = 'Save Filter Definition';
                saveFilter.onclick = this.registerNewFilter.bind(this);
                controlRows[0].appendChild(saveFilter);

                saveLoadFilter.setAttribute('class', 'stdin');
                saveLoadFilter.innerHTML = 'Save & Apply Filter Definition';
                saveLoadFilter.onclick = function(){
                    this.registerNewFilter();
                    document.getElementById('applyFilter').checked = true;
                }.bind(this);
                controlRows[0].appendChild(saveLoadFilter);

                controlRows[1] = document.createElement('span');
                controlWrap.appendChild(controlRows[1]);

                chooseFilterLabel.innerHTML = 'Load / Delete Filter:'
                controlRows[1].appendChild(chooseFilterLabel);
                chooseFilter.setAttribute('class', 'stdin');
                chooseFilter.setAttribute('id', 'filterList');
                controlRows[1].appendChild(chooseFilter);

                loadTarget.setAttribute('type', 'text');
                loadTarget.setAttribute('name', 'loadTarget');
                loadTarget.setAttribute('id', 'loadTarget');
                loadTarget.setAttribute('value', 'null');
                loadTarget.setAttribute('style', 'display:none');
                controlRows[1].appendChild(loadTarget);
                loadFilter.setAttribute('class', 'stdin');
                loadFilter.innerHTML = 'Load'
                loadFilter.onclick = function(){
                    document.getElementById('loadTarget').value = selected('filterList')
                }
                controlRows[1].appendChild(loadFilter);

                deleteTarget.setAttribute('type', 'text');
                deleteTarget.setAttribute('name', 'deleteTarget');
                deleteTarget.setAttribute('id', 'deleteTarget');
                deleteTarget.setAttribute('value', 'null');
                deleteTarget.setAttribute('style', 'display:none');
                controlRows[1].appendChild(deleteTarget);
                deleteFilter.setAttribute('class', 'stdin');
                deleteFilter.innerHTML = 'Delete'
                deleteFilter.onclick = function(){
                    document.getElementById('deleteTarget').value = selected('filterList')
                }
                controlRows[1].appendChild(deleteFilter);

                XHR('http://'+this.MIDAS+'/?cmd=jcopy&odb=/Filter&encoding=json-nokeys', this.registerFilterODB.bind(this));
            },
            inserted: function() {},
            removed: function() {},
            attributeChanged: function() {}
        },
        events: {

        },
        accessors: {
            'MIDAS':{
                attribute: {} //this just needs to be declared
            }
        },
        methods: {
            'spawnFilterCondition' : function(){
                var newCondition = document.createElement('div'),
                    leftTab = document.createElement('div'),
                    filterContent = document.createElement('div'),
                    conditionTable = document.createElement('table'),
                    addNewRow = document.createElement('button'),
                    deleteCondition = document.createElement('button'),
                    index = this.filterConditions.length;

                newCondition.setAttribute('id', 'filterCondition' + index);
                newCondition.setAttribute('class', 'filterCondition');
                this.conditionWrap.appendChild(newCondition);

                leftTab.setAttribute('id', 'leftTab' + index);
                leftTab.setAttribute('class', 'leftTab');
                leftTab.innerHTML = 'OR';
                newCondition.appendChild(leftTab);

                filterContent.setAttribute('id', 'filterContent' + index);
                filterContent.setAttribute('class', 'filterContent');
                newCondition.appendChild(filterContent)

                conditionTable.setAttribute('id', 'filterTable'+index);
                conditionTable.setAttribute('class', 'filterTable');
                filterContent.appendChild(conditionTable);

                addNewRow.setAttribute('id', 'addNewRow' + index);
                addNewRow.setAttribute('class', 'stdin lightButton');
                addNewRow.innerHTML = 'AND new condition';
                addNewRow.onclick = this.addNewRow.bind(this, index);
                filterContent.appendChild(addNewRow);

                deleteCondition.setAttribute('id', 'deleteCondition' + index);
                deleteCondition.setAttribute('class', 'stdin lightButton');
                deleteCondition.innerHTML = 'Delete This Block';
                deleteCondition.onclick = this.deleteOrBlock.bind(this, index);
                filterContent.appendChild(deleteCondition);

                this.nRows[index] = 0;
                addNewRow.onclick();

                this.filterConditions.push(newCondition);
            },

            'addNewRow' : function(index){
                var row, cell,
                    detectorSelect, detectorOption,
                    filterSelect, filterOption,
                    optionConfigWrap, optionConfigLabel, optionConfigInput,
                    deleteRow,
                    i,
                    rowIndex = this.nRows[index]

                row = document.createElement('tr');
                row.setAttribute('id', 'filterRow' + index + rowIndex);
                document.getElementById('filterTable' + index).appendChild(row);

                cell = document.createElement('td');
                cell.innerHTML = 'AND';
                row.appendChild(cell);

                cell = document.createElement('td');
                row.appendChild(cell);
                detectorSelect = document.createElement('select');
                detectorSelect.setAttribute('id', 'detectorSelect'+index+rowIndex);
                detectorSelect.setAttribute('class', 'stdin');
                for(i=0; i<this.detectors.length; i++){
                    detectorOption = document.createElement('option');
                    detectorOption.value = this.detectorCodes[i];
                    detectorOption.innerHTML = this.detectors[i];
                    detectorSelect.appendChild(detectorOption);
                }
                cell.appendChild(detectorSelect);

                cell = document.createElement('td');
                row.appendChild(cell);
                filterSelect = document.createElement('select');
                filterSelect.setAttribute('id', 'filterType'+index+rowIndex)
                filterSelect.setAttribute('class', 'stdin');
                filterSelect.onchange = function(idCode){
                    var filterType = selected('filterType'+idCode);

                    this.manageInputCell(filterType, idCode);

                }.bind(this, ''+index+rowIndex);
                for(i=0; i<this.filterOptions.length; i++){
                    filterOption = document.createElement('option');
                    filterOption.value = this.filterCodes[i];
                    filterOption.innerHTML = this.filterOptions[i];
                    filterSelect.appendChild(filterOption);
                }
                cell.appendChild(filterSelect);

                cell = document.createElement('td');
                row.appendChild(cell);
                optionConfigWrap = document.createElement('div');
                optionConfigWrap.setAttribute('id', 'optionConfigWrap'+index+rowIndex);
                optionConfigWrap.setAttribute('class', 'optionConfigWrap hiddenConfig');
                cell.appendChild(optionConfigWrap);
                optionConfigLabel = document.createElement('label');
                optionConfigLabel.setAttribute('id', 'optionConfigLabel'+index+rowIndex);
                optionConfigWrap.appendChild(optionConfigLabel);
                optionConfigInput = document.createElement('input');
                optionConfigInput.setAttribute('id', 'optionConfigInput'+index+rowIndex);
                optionConfigInput.setAttribute('class', 'stdin');
                optionConfigInput.setAttribute('type', 'number');
                optionConfigInput.setAttribute('step', 1);
                optionConfigInput.setAttribute('min', 0);
                optionConfigWrap.appendChild(optionConfigInput);

                cell = document.createElement('td');
                row.appendChild(cell);
                deleteRow = document.createElement('button');
                deleteRow.innerHTML = 'Remove';
                deleteRow.setAttribute('class', 'stdin');
                deleteRow.onclick = this.deleteRow.bind(this, index, ''+index+rowIndex);
                cell.appendChild(deleteRow);

                this.nRows[index]++;

                return false;

            },

            'manageInputCell' : function(filterType, idCode){

                if(filterType == 'S'){
                    document.getElementById('optionConfigWrap'+idCode).setAttribute('class', 'optionConfigWrap hiddenConfig');
                } else if(filterType == 'C'){
                    document.getElementById('optionConfigWrap'+idCode).setAttribute('class', 'optionConfigWrap');
                    document.getElementById('optionConfigLabel'+idCode).innerHTML = 'Multiplicity: ';
                    document.getElementById('optionConfigInput'+idCode).setAttribute('value', 2);
                } else if(filterType == 'P'){
                    document.getElementById('optionConfigWrap'+idCode).setAttribute('class', 'optionConfigWrap');
                    document.getElementById('optionConfigLabel'+idCode).innerHTML = 'Factor: ';
                    document.getElementById('optionConfigInput'+idCode).setAttribute('value', 10);
                }
            },

            'deleteOrBlock' : function(index){
                var block = document.getElementById('filterCondition' + index);
                this.conditionWrap.removeChild(block);

                return false;
            },

            'deleteRow' : function(index, idCode){
                var row = document.getElementById('filterRow'+idCode);
                document.getElementById('filterTable'+index).removeChild(row);

                return false;
            },

            'registerNewFilter' : function(){
                var filterConditions = this.querySelectorAll('div.filterCondition'),
                    tableRows,
                    selects,
                    detector, filter, scale, condition,
                    encoded = [],
                    i,j;

                for(i=0; i<filterConditions.length; i++){
                    tableRows = filterConditions[i].querySelectorAll('tr');
                    if(!tableRows || tableRows.length == 0) continue;
                    encoded[i] = [];

                    for(j=0; j<tableRows.length; j++){
                        selects = tableRows[j].querySelectorAll('select');

                        detector = selected(selects[0].id);
                        filter = selected(selects[1].id);
                        scale = parseInt(tableRows[j].querySelectorAll('input')[0].value, 10);
                        if(!scale) scale = 1;

                        condition = detector + '-' + filter + '-' + scale;

                        encoded[i][j] = condition;

                    }
                }

                document.getElementById('encodedFilter').value = JSON.stringify(encoded);
            },

            'registerFilterODB' : function(responseText){
                var data = JSON.parse(responseText),
                    currentName = data.Current,
                    currentFilter = data.Filters[currentName],
                    filterSelect = document.getElementById('filterList'),
                    filterOptions, key;

                this.filterRecord = data;

                this.loadFilter(currentFilter);
                document.getElementById('filterName').value = currentName;
                document.getElementById('currentFilter').innerHTML = 'Current Active Filter: ' + currentName;

                for(key in data.Filters){
                    filterOptions = document.createElement('option');
                    filterOptions.innerHTML = key;
                    filterOptions.value = key;
                    filterSelect.appendChild(filterOptions);

                }

                filterSelect.value = currentName;
            },

            'loadFilter' : function(currentFilter){
                var orCells = this.querySelectorAll('div.filterCondition'),
                    cellDelete,
                    createOr = document.getElementById('spawnCondition'),
                    currentOr,
                    i, key;

                for(i=0; i<orCells.length; i++){
                    cellDelete = orCells[i].querySelectorAll('button.lightButton')[1]; //TODO fragile - don't ever change that class or loading breaks!
                    cellDelete.onclick();
                }

                for(key in currentFilter){
                    if(key.indexOf('last_written') != -1 ) continue;

                    createOr.onclick();

                    currentOr = this.querySelectorAll('div.filterCondition');
                    currentOr = currentOr[currentOr.length - 1];
                    if(currentFilter[key] instanceof Array){
                        for(i=0; i<currentFilter[key].length; i++){
                            currentOr.querySelectorAll('select')[i*2].value = currentFilter[key][i].slice(0,2);
                            currentOr.querySelectorAll('select')[i*2+1].value = currentFilter[key][i].slice(3,4);
                            currentOr.querySelectorAll('select')[i*2+1].onchange();
                            currentOr.querySelectorAll('input')[i].value = parseInt(currentFilter[key][i].slice(5),10);

                            if(i<currentFilter[key].length-1)
                                currentOr.querySelectorAll('button.lightButton')[0].onclick();
                        }
                    } else {
                        currentOr.querySelectorAll('select')[0].value = currentFilter[key].slice(0,2);
                        currentOr.querySelectorAll('select')[1].value = currentFilter[key].slice(3,4);
                        currentOr.querySelectorAll('select')[1].onchange();
                        currentOr.querySelectorAll('input')[0].value = parseInt(currentFilter[key].slice(5),10);
                    }

                }
            }

        }
    });

})();<|endoftext|>


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

    var StyleGuideGenerator = require('emo-gen');
    var objectAssign = require('object-assign');

    var StyleGuide = function(grunt, gruntFilesArray, gruntOptions) {
        this.grunt = grunt;

        this.gruntOptions = gruntOptions;

        this.filesToCopy = this.expandGruntFilesArray(gruntFilesArray);

        this.generator = new StyleGuideGenerator(
            this.gruntOptions.components,
            this.gruntOptions
        );
    };

    StyleGuide.createGruntFileMappingOptions = function(gruntFilesObject) {
        var gruntFileMappingOptions = objectAssign({}, gruntFilesObject);

        // delete those properties we don't need
        delete gruntFileMappingOptions.src;
        delete gruntFileMappingOptions.dest;

        return gruntFileMappingOptions;
    };

    var proto = StyleGuide.prototype;

    proto.build = function() {
        return this.generator.place().then(function() {
            return this.generator.copyFiles(this.filesToCopy);
        }.bind(this)).then(function() {
            return this.generator.build();
        }.bind(this));
    };

    proto.expandGruntFilesArray = function(gruntFilesArray) {
        var gruntFilesMappingList = [];

        if (!gruntFilesArray) {
            return gruntFilesMappingList;
        }

        gruntFilesArray.forEach(function(gruntFilesObject) {
            this.grunt.file.expandMapping(
                gruntFilesObject.src,
                gruntFilesObject.dest,
                StyleGuide.createGruntFileMappingOptions(gruntFilesObject)
            ).forEach(function(srcDestFileMapping) {
                var flattenedArray = [];
                var dest = srcDestFileMapping.dest;

                srcDestFileMapping.src.forEach(function(src) {
                    flattenedArray.push({
                        src: src,
                        dest: dest
                    });
                });

                gruntFilesMappingList = gruntFilesMappingList.concat(flattenedArray);
            });
        }.bind(this));

        return gruntFilesMappingList;
    };

    module.exports = StyleGuide;

} ());<commit_msg>Moved the filesToCopy definition aftegenerator place<commit_after>(function() {
    'use strict';

    var StyleGuideGenerator = require('emo-gen');
    var objectAssign = require('object-assign');

    var StyleGuide = function(grunt, gruntFilesArray, gruntOptions) {
        this.grunt = grunt;

        this.gruntFilesArray = gruntFilesArray;

        this.gruntOptions = gruntOptions;

        this.generator = new StyleGuideGenerator(
            this.gruntOptions.components,
            this.gruntOptions
        );
    };

    StyleGuide.createGruntFileMappingOptions = function(gruntFilesObject) {
        var gruntFileMappingOptions = objectAssign({}, gruntFilesObject);

        // delete those properties we don't need
        delete gruntFileMappingOptions.src;
        delete gruntFileMappingOptions.dest;

        return gruntFileMappingOptions;
    };

    var proto = StyleGuide.prototype;

    proto.build = function() {
        return this.generator.place().then(function() {
            var filesToCopy = this.expandGruntFilesArray(this.gruntFilesArray);

            return this.generator.copyFiles(filesToCopy);
        }.bind(this)).then(function() {
            return this.generator.build();
        }.bind(this));
    };

    proto.expandGruntFilesArray = function(gruntFilesArray) {
        var gruntFilesMappingList = [];

        if (!gruntFilesArray) {
            return gruntFilesMappingList;
        }

        gruntFilesArray.forEach(function(gruntFilesObject) {
            this.grunt.file.expandMapping(
                gruntFilesObject.src,
                gruntFilesObject.dest,
                StyleGuide.createGruntFileMappingOptions(gruntFilesObject)
            ).forEach(function(srcDestFileMapping) {
                var flattenedArray = [];
                var dest = srcDestFileMapping.dest;

                srcDestFileMapping.src.forEach(function(src) {
                    flattenedArray.push({
                        src: src,
                        dest: dest
                    });
                });

                gruntFilesMappingList = gruntFilesMappingList.concat(flattenedArray);
            });
        }.bind(this));

        return gruntFilesMappingList;
    };

    module.exports = StyleGuide;

} ());<|endoftext|>


<commit_before>var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  // Where to start
  entry: {
    Select: path.resolve(__dirname, '../../src/Select.jsx')
  },

  // Where to output
  output: {
    path: path.resolve(__dirname, '../../dist'),
    filename: '[name].js',
    libraryTarget: 'umd'
  },

  externals: {
    'classnames': true,
    'lodash': true,
    'react': 'React',
    'react-dom': true,
    'ship-components-outsideclick': true,
    'ship-components-highlight-click': true,
    'react-addons-css-transition-group': true
  },

  module: {
    preLoaders: [{
      test: /\.(jsx?|es6)$/,
      exclude: /(node_modules|dist)/,
      include: /src\/.*/,
      loader: 'eslint'
    }],
    loaders: [
      // ES6/JSX for App
      {
        test: /\.(jsx?|es6)$/,
        exclude: /node_modules/,
        loader: 'babel'
      },
      // CSS Modules
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract(
          'style-loader',
          'css-loader?modules&importLoaders=1&localIdentName=[name]--[local]!postcss-loader'
        )
      }
    ]
  },

  eslint: {
    // Strict linting enforcing
    failOnWarning: true
  },

  // CSS Modules
  postcss: [
    require('postcss-nested'),
    require('postcss-simple-vars')({
      /**
       * Default variables. Should be overridden in mail build system
       * @type {Object}
       */
      variables: {
        'primary-color' : '#38b889',
        'opacity-disabled': '0.58',
        'base-grid-size' : '4px'
      }
    }),
    require('postcss-color-hex-alpha'),
    require('postcss-color-function'),
    require('postcss-calc'),
    require('autoprefixer')
  ],

  stats: {
    children: false,
    colors: true,
    modules: false,
    reasons: true
  },

  resolve: {
    extensions: ['', '.js', '.jsx', '.es6'],
    fallback: path.resolve(__dirname, '../../node_modules')
  },

  resolveLoader: {
    fallback: path.resolve(__dirname, '../../node_modules')
  },

  plugins: [
    new ExtractTextPlugin('[name].css', {
      allChunks: true
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true)
  ],

  devtool: 'source-map'
};
<commit_msg>added support for ship-components to web pack<commit_after>var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  // Where to start
  entry: {
    Select: path.resolve(__dirname, '../../src/Select.jsx')
  },

  // Where to output
  output: {
    path: path.resolve(__dirname, '../../dist'),
    filename: '[name].js',
    libraryTarget: 'umd'
  },

  externals: {
    classnames: true,
    react: 'React',
    'react-dom': true,
    'ship-components-outsideclick': true,
    'ship-components-highlight-click': true,
    'react-addons-css-transition-group': true
  },

  module: {
    preLoaders: [{
      test: /\.(jsx?|es6)$/,
      exclude: /(node_modules|dist)/,
      include: /src\/.*/,
      loader: 'eslint'
    }],
    loaders: [
      // ES6/JSX for App
      {
        test: /\.(jsx?|es6)$/,
        exclude: /node_modules/,
        loader: 'babel'
      },
      // ES6/JSX for App
      {
        test: /\.(jsx?|es6)$/,
        include: [
          /ship-components-.*\/src/
        ],
        loader: 'babel'
      },
      // CSS Modules
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract(
          'style-loader',
          'css-loader?modules&importLoaders=1&localIdentName=[name]--[local]!postcss-loader'
        )
      }
    ]
  },

  eslint: {
    // Strict linting enforcing
    failOnWarning: true
  },

  // CSS Modules
  postcss: [
    require('postcss-nested'),
    require('postcss-simple-vars')({
      /**
       * Default variables. Should be overridden in mail build system
       * @type {Object}
       */
      variables: {
        'primary-color' : '#38b889',
        'opacity-disabled': '0.58',
        'base-grid-size' : '4px'
      }
    }),
    require('postcss-color-hex-alpha'),
    require('postcss-color-function'),
    require('postcss-calc'),
    require('autoprefixer')
  ],

  stats: {
    children: false,
    colors: true,
    modules: false,
    reasons: true
  },

  resolve: {
    extensions: ['', '.js', '.jsx', '.es6'],
    fallback: path.resolve(__dirname, '../../node_modules')
  },

  resolveLoader: {
    fallback: path.resolve(__dirname, '../../node_modules')
  },

  plugins: [
    new ExtractTextPlugin('[name].css', {
      allChunks: true
    }),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(true)
  ],

  devtool: 'source-map'
};
<|endoftext|>


<commit_before>/* eslint no-invalid-this: 0 */
'use strict';

var browsers = {
	phantomjs: new LocalBrowserFactory({
		browser: 'chrome'
	}),
	chromeWindows: new SauceBrowserFactory({
		browser: 'Chrome',
		platform: 'WIN10'
	}),
	/*firefoxWindows: new SauceBrowserFactory({
		browser: 'Firefox',
		platform: 'WIN10'
	}),*/
	ie11Windows: new SauceBrowserFactory({
		browser: 'internet explorer',
		version: '11',
		platform: 'WIN10'
	}),
	edgeWindows: new SauceBrowserFactory({
		browser: 'microsoftedge',
		platform: 'WIN10',
		tags: ['no-d2l-shadow']
	}),
	chromeMac: new SauceBrowserFactory({
		browser: 'Chrome',
		platform: 'SIERRA',
		/* crashes during screenshot command on > 2.24
			https://bugs.chromium.org/p/chromedriver/issues/detail?id=1770# */
		desiredCapabilities: {
			chromedriverVersion: '2.24'
		}
	}),
	safariMac: new SauceBrowserFactory({
		browser: 'Safari',
		platform: 'SIERRA',
		tags: ['no-d2l-shadow']
	}),
	firefoxMac: new SauceBrowserFactory({
		browser: 'Firefox',
		platform: 'SIERRA'
	})
};

var mainlineEndpoint = 'http://localhost:8081/components/d2l-button';
var xEndpoint = 'http://localhost:8000/components/d2l-button';
var buttonEndpoint = '/test/acceptance/button.html';
var buttonSpec = 'test/acceptance/button.gspec';
var floatingButtonsEndpoint = '/test/acceptance/floating-buttons.html';
var floatingButtonsSpec = 'test/acceptance/floating-buttons.gspec';

polymerTests(browsers, function(test) {

	function runTests(name, baseEndpoint) {
		test(name + '-button', {
			endpoint: baseEndpoint + buttonEndpoint + '?wc-shadydom',
			spec: buttonSpec,
			size: '1024x768',
			tags: ['desktop']
		});

		test.shadow(name + '-button-shadow', {
			endpoint: baseEndpoint + buttonEndpoint + '?dom=shadow',
			spec: buttonSpec,
			size: '1024x768',
			tags: ['desktop']
		});

		test(name + '-floating-buttons-desktop', {
			endpoint: baseEndpoint + floatingButtonsEndpoint + '?wc-shadydom',
			spec: floatingButtonsSpec,
			size: '1024x768',
			tags: ['desktop']
		});

		test.shadow(name + '-floating-buttons-desktop-shadow', {
			endpoint: baseEndpoint + floatingButtonsEndpoint + '?dom=shadow',
			spec: floatingButtonsSpec,
			size: '1024x768',
			tags: ['desktop']
		});

		test(name + '-floating-buttons-mobile', {
			endpoint: baseEndpoint + floatingButtonsEndpoint,
			spec: floatingButtonsSpec,
			size: '320x490',
			tags: ['mobile']
		});
	}

	runTests('mainline', mainlineEndpoint);
	runTests('1.x', xEndpoint);
});
<commit_msg>Disable d2l-shadow on Firefox as well<commit_after>/* eslint no-invalid-this: 0 */
'use strict';

var browsers = {
	phantomjs: new LocalBrowserFactory({
		browser: 'chrome'
	}),
	chromeWindows: new SauceBrowserFactory({
		browser: 'Chrome',
		platform: 'WIN10'
	}),
	/*firefoxWindows: new SauceBrowserFactory({
		browser: 'Firefox',
		platform: 'WIN10'
	}),*/
	ie11Windows: new SauceBrowserFactory({
		browser: 'internet explorer',
		version: '11',
		platform: 'WIN10'
	}),
	edgeWindows: new SauceBrowserFactory({
		browser: 'microsoftedge',
		platform: 'WIN10',
		tags: ['no-d2l-shadow']
	}),
	chromeMac: new SauceBrowserFactory({
		browser: 'Chrome',
		platform: 'SIERRA',
		/* crashes during screenshot command on > 2.24
			https://bugs.chromium.org/p/chromedriver/issues/detail?id=1770# */
		desiredCapabilities: {
			chromedriverVersion: '2.24'
		}
	}),
	safariMac: new SauceBrowserFactory({
		browser: 'Safari',
		platform: 'SIERRA',
		tags: ['no-d2l-shadow']
	}),
	firefoxMac: new SauceBrowserFactory({
		browser: 'Firefox',
		platform: 'SIERRA',
		tags: ['no-d2l-shadow']
	})
};

var mainlineEndpoint = 'http://localhost:8081/components/d2l-button';
var xEndpoint = 'http://localhost:8000/components/d2l-button';
var buttonEndpoint = '/test/acceptance/button.html';
var buttonSpec = 'test/acceptance/button.gspec';
var floatingButtonsEndpoint = '/test/acceptance/floating-buttons.html';
var floatingButtonsSpec = 'test/acceptance/floating-buttons.gspec';

polymerTests(browsers, function(test) {

	function runTests(name, baseEndpoint) {
		test(name + '-button', {
			endpoint: baseEndpoint + buttonEndpoint + '?wc-shadydom',
			spec: buttonSpec,
			size: '1024x768',
			tags: ['desktop']
		});

		test.shadow(name + '-button-shadow', {
			endpoint: baseEndpoint + buttonEndpoint + '?dom=shadow',
			spec: buttonSpec,
			size: '1024x768',
			tags: ['desktop']
		});

		test(name + '-floating-buttons-desktop', {
			endpoint: baseEndpoint + floatingButtonsEndpoint + '?wc-shadydom',
			spec: floatingButtonsSpec,
			size: '1024x768',
			tags: ['desktop']
		});

		test.shadow(name + '-floating-buttons-desktop-shadow', {
			endpoint: baseEndpoint + floatingButtonsEndpoint + '?dom=shadow',
			spec: floatingButtonsSpec,
			size: '1024x768',
			tags: ['desktop']
		});

		test(name + '-floating-buttons-mobile', {
			endpoint: baseEndpoint + floatingButtonsEndpoint,
			spec: floatingButtonsSpec,
			size: '320x490',
			tags: ['mobile']
		});
	}

	runTests('mainline', mainlineEndpoint);
	runTests('1.x', xEndpoint);
});
<|endoftext|>


<commit_before>'use strict';

var spi = require('bindings')('spi'),
  assert = require('assert'),
  count = 0,
  totalCount = 0;

function createMessage() {
  var message = [],
    channelByte,
    channel;

  for (channel = 0; channel <= 7; channel += 1) {
    channelByte = 0x80 + (channel << 4);

    message.push({
      sendBuffer: new Buffer([0x01, channelByte, 0x00]),
      receiveBuffer: new Buffer(3),
      byteLength: 3,
      speed: 1350000,
      chipSelectChange: true
    });
  }

  return message;
}

function sync() {
  var mcp3008 = spi.openSync(0, 0);

  mcp3008.setOptionsSync(mcp3008.getOptionsSync());
  mcp3008.transferSync(createMessage());
  mcp3008.closeSync();

  count += 1;
  totalCount += 1;

  async();
}

function transfer(mcp3008, cb) {
  mcp3008.transfer(createMessage(), function (err, message) {
    assert(!err, 'can\'t transfer with mcp3008');
    cb();
  })
}

function accessOptions(mcp3008, cb) {
  mcp3008.getOptions(function (err, options) {
    assert(!err, 'can\'t get options from mcp3008');
    mcp3008.setOptions(options, function (err) {
      assert(!err, 'can\'t set mcp3008 options');
      transfer(mcp3008, cb);
    });
  });
}

function async() {
  var mcp3008 = spi.open(0, 0, function (err) {
    assert(!err, 'can\'t open mcp3008');

    accessOptions(mcp3008, function () {
      mcp3008.close(function (err) {
        assert(!err, 'can\'t close mcp3008');
        sync();
      });
    });
  });
}

setInterval(function () {
  console.log(totalCount + ' ' + count);
  count = 0;
}, 1000);

async();

<commit_msg>display data for four adc channels<commit_after>'use strict';

var spi = require('bindings')('spi'),
  assert = require('assert'),
  count = 0,
  totalCount = 0,
  result;

function createMessage() {
  var message = [],
    channelByte;

  [0, 1, 4, 5].forEach(function (channel) {
    channelByte = 0x80 + (channel << 4);

    message.push({
      sendBuffer: new Buffer([0x01, channelByte, 0x00]),
      receiveBuffer: new Buffer(3),
      byteLength: 3,
      speed: 1350000,
      chipSelectChange: true
    });
  });

  return message;
}

function saveResult(message) {
  result = '';

  message.forEach(function (transfer) {
    result += ((transfer.receiveBuffer[1] << 8) +
      transfer.receiveBuffer[2]) + ' ';
  });
}

function sync() {
  var mcp3008 = spi.openSync(0, 0),
    message = createMessage();

  mcp3008.setOptionsSync(mcp3008.getOptionsSync());
  mcp3008.transferSync(message);
  saveResult(message);
  mcp3008.closeSync();

  count += 1;
  totalCount += 1;

  async();
}

function transfer(mcp3008, cb) {
  mcp3008.transfer(createMessage(), function (err, message) {
    assert(!err, 'can\'t transfer with mcp3008');
    saveResult(message);
    cb();
  })
}

function accessOptions(mcp3008, cb) {
  mcp3008.getOptions(function (err, options) {
    assert(!err, 'can\'t get options from mcp3008');
    mcp3008.setOptions(options, function (err) {
      assert(!err, 'can\'t set mcp3008 options');
      transfer(mcp3008, cb);
    });
  });
}

function async() {
  var mcp3008 = spi.open(0, 0, function (err) {
    assert(!err, 'can\'t open mcp3008');

    accessOptions(mcp3008, function () {
      mcp3008.close(function (err) {
        assert(!err, 'can\'t close mcp3008');
        sync();
      });
    });
  });
}

setInterval(function () {
  console.log(totalCount + ' ' + count + ' - ' + result);
  count = 0;
}, 1000);

async();

<|endoftext|>


<commit_before>/**
 * Created by dleppik on 11/8/13.
 */

"use strict";

describe("Generic bitmap methods", function() {

    // Many of these were generated randomly.  We need to test boundaries around 32 for packed bitmaps
    var arrays = [
        [],
        [0],
        [0, 1],
        [31],
        [33],
        [100],
        [100, 111],
        [ 2, 5, 8, 11, 15, 16, 18, 19, 21, 25, 29, 33, 37, 38, 39, 40, 43, 45, 48, 52 ],
        [ 0, 2, 5, 12, 18, 26, 36, 45, 51, 55, 64, 73, 74, 76, 84, 92, 98, 108, 118, 123 ],
        [ 2, 3, 4, 6, 7, 9, 10, 11, 12, 13, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 27, 29, 31, 33, 35, 36, 38, 40, 42, 44, 46, 47 ],
        [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ]
    ];

    var bitmapClasses = [ ozone.columnStore.ArrayIndexBitmap ];

    var forEachArray = function(beforeElements, onEachElement, afterElements) {
        for (var i=0; i< arrays.length; i++) {
            var array = arrays[i];
            if (typeof beforeElements === "function") {
                beforeElements(array);
            }
            if (typeof(onEachElement) === "function") {
                for (var j=0; j<array.length; j++) {
                    onEachElement(array, array[j]);
                }
            }
            if (typeof afterElements === "function") {
                afterElements(array);
            }
        }
    };

    var bitmapForEachArray = function(withArrayAndBitmap) {
        var builder;
        forEachArray(
            function(array)          { builder = bitmapClass.builder(); },
            function(array, element) { builder.onItem(element); },
            function(array)          { withArrayAndBitmap(array, builder.onEnd()); }
        );
    };

    describe("Binary search", function() {
        it("Finds each element, and only those elements", function() {
            forEachArray(function(array) {
                var element = 0;
                for (var arrayIndex=0; arrayIndex<array.length; arrayIndex++) {
                    var nextInArray = array[arrayIndex];
                    for (; element < nextInArray; element++) {
                        expect(ozone.columnStore.search(element, array, 0, array.length-1)).toEqual(~arrayIndex);
                    }
                    expect(ozone.columnStore.search(element, array, 0, array.length-1)).toEqual(arrayIndex);
                    element++;
                }
            });
        });
    });

    for (var bitmapClassIndex = 0; bitmapClassIndex < bitmapClasses.length; bitmapClassIndex++) {
        var bitmapClass = bitmapClasses[bitmapClassIndex];
        describe("Implementation "+bitmapClassIndex+": "+bitmapClass, function() {
            it("Has a builder that produces something of the right size", function() {
                var builder;
                forEachArray(
                    function() {
                        builder = bitmapClass.builder();
                        expect(typeof(builder)).toBe("object");
                    },
                    function(a, element) { builder.onItem(element); },
                    function(array)      { expect(builder.onEnd().size).toEqual(array.length); }
                );
            });
            it("Reports min accurately", function() {
                bitmapForEachArray(function(array, bitmap) {
                    var expected = (array.length == 0) ?  -1  : array[0];
                    expect(bitmap.min()).toEqual(expected);
                });
            });
            it("Reports max accurately", function() {
                bitmapForEachArray(function(array, bitmap) {
                    var expected = (array.length == 0) ?  -1  : array[array.length-1];
                    expect(bitmap.max()).toEqual(expected);
                });
            });
            it("Reports 'get' accurately", function() {
                bitmapForEachArray(function(array, bitmap) {
                    var element = 0;
                    for (var arrayIndex=0; arrayIndex<array.length; arrayIndex++) {
                        var nextInArray = array[arrayIndex];
                        for (; element < nextInArray; element++) {
                            expect(bitmap.get(element)).toEqual(false);
                        }
                        expect(bitmap.get(element)).toEqual(true);
                        element++;
                    }
                    for (; element < nextInArray+33; element++) {  // Check past next packed bits
                        expect(bitmap.get(element)).toEqual(false);
                    }
                });
            });
            describe("Iterator", function() {
                it("Increases monotonically", function() {
                    bitmapForEachArray(function(array, bitmap) {
                        var it = bitmap.iterator();
                        var previous = -1;
                        while (it.hasNext()) {
                            var element = it.next();
                            expect(element).toBeGreaterThan(previous);
                            previous = element;
                        }
                    });
                });
                it("Matches get", function() {
                    bitmapForEachArray(function(array, bitmap) {
                        var it = bitmap.iterator();
                        while (it.hasNext()) {
                            var element = it.next();
                            expect(bitmap.get(element)).toBe(true);
                        }
                    });
                });
                it("Matches size", function() {
                    bitmapForEachArray(function(array, bitmap) {
                        var it = bitmap.iterator();
                        var count = 0;
                        while (it.hasNext()) {
                            it.next();
                            count++;
                        }
                        expect(count).toBe(bitmap.size);
                    });
                });
                it("Skips properly", function() {
                    bitmapForEachArray(function(array, bitmap) {
                        if (array.length > 0) {
                            var it = bitmap.iterator();
                            it.skipTo(bitmap.min()-1);
                            expect(it.next()).toBe(bitmap.min());

                            it = bitmap.iterator();
                            it.skipTo(bitmap.min());
                            it.skipTo(bitmap.min());
                            it.skipTo(bitmap.min());
                            expect(it.next()).toBe(bitmap.min());
                            if (array.length > 1) {
                                it.skipTo(bitmap.max());
                                expect(it.next()).toBe(bitmap.max());
                            }

                            it = bitmap.iterator();
                            it.skipTo(bitmap.max()+1);
                            expect(it.hasNext()).toBe(false);

                            if (array.length > 1) {
                                it = bitmap.iterator();
                                var skipTo = bitmap.max()-1;
                                it.skipTo(skipTo);
                                var expectedNext = (bitmap.get(skipTo)) ?  skipTo  :  bitmap.max();
                                console.log("skip to "+skipTo+", expectedNext = "+expectedNext+" on "+array);
                                expect(it.next()).toBe(expectedNext);
                            }
                        }
                    });
                });
            });

            it("Fails", function() {
                expect("true").toBeFalsy();
            });

            it("Has 'each' which matches the iterator", function() {
                bitmapForEachArray(function(array, bitmap) {
                    var it = bitmap.iterator();
                    bitmap.each(function(element) {
                        expect(element).toBe(it.next());
                    });
                    expect(it.hasNext()).toBe(false);
                });
            });
        });
    }
});<commit_msg>Removed failing unit test I created to test Jasmine CSS.<commit_after>/**
 * Created by dleppik on 11/8/13.
 */

"use strict";

describe("Generic bitmap methods", function() {

    // Many of these were generated randomly.  We need to test boundaries around 32 for packed bitmaps
    var arrays = [
        [],
        [0],
        [0, 1],
        [31],
        [33],
        [100],
        [100, 111],
        [ 2, 5, 8, 11, 15, 16, 18, 19, 21, 25, 29, 33, 37, 38, 39, 40, 43, 45, 48, 52 ],
        [ 0, 2, 5, 12, 18, 26, 36, 45, 51, 55, 64, 73, 74, 76, 84, 92, 98, 108, 118, 123 ],
        [ 2, 3, 4, 6, 7, 9, 10, 11, 12, 13, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 27, 29, 31, 33, 35, 36, 38, 40, 42, 44, 46, 47 ],
        [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ]
    ];

    var bitmapClasses = [ ozone.columnStore.ArrayIndexBitmap ];

    var forEachArray = function(beforeElements, onEachElement, afterElements) {
        for (var i=0; i< arrays.length; i++) {
            var array = arrays[i];
            if (typeof beforeElements === "function") {
                beforeElements(array);
            }
            if (typeof(onEachElement) === "function") {
                for (var j=0; j<array.length; j++) {
                    onEachElement(array, array[j]);
                }
            }
            if (typeof afterElements === "function") {
                afterElements(array);
            }
        }
    };

    var bitmapForEachArray = function(withArrayAndBitmap) {
        var builder;
        forEachArray(
            function(array)          { builder = bitmapClass.builder(); },
            function(array, element) { builder.onItem(element); },
            function(array)          { withArrayAndBitmap(array, builder.onEnd()); }
        );
    };

    describe("Binary search", function() {
        it("Finds each element, and only those elements", function() {
            forEachArray(function(array) {
                var element = 0;
                for (var arrayIndex=0; arrayIndex<array.length; arrayIndex++) {
                    var nextInArray = array[arrayIndex];
                    for (; element < nextInArray; element++) {
                        expect(ozone.columnStore.search(element, array, 0, array.length-1)).toEqual(~arrayIndex);
                    }
                    expect(ozone.columnStore.search(element, array, 0, array.length-1)).toEqual(arrayIndex);
                    element++;
                }
            });
        });
    });

    for (var bitmapClassIndex = 0; bitmapClassIndex < bitmapClasses.length; bitmapClassIndex++) {
        var bitmapClass = bitmapClasses[bitmapClassIndex];
        describe("Implementation "+bitmapClassIndex+": "+bitmapClass, function() {
            it("Has a builder that produces something of the right size", function() {
                var builder;
                forEachArray(
                    function() {
                        builder = bitmapClass.builder();
                        expect(typeof(builder)).toBe("object");
                    },
                    function(a, element) { builder.onItem(element); },
                    function(array)      { expect(builder.onEnd().size).toEqual(array.length); }
                );
            });
            it("Reports min accurately", function() {
                bitmapForEachArray(function(array, bitmap) {
                    var expected = (array.length == 0) ?  -1  : array[0];
                    expect(bitmap.min()).toEqual(expected);
                });
            });
            it("Reports max accurately", function() {
                bitmapForEachArray(function(array, bitmap) {
                    var expected = (array.length == 0) ?  -1  : array[array.length-1];
                    expect(bitmap.max()).toEqual(expected);
                });
            });
            it("Reports 'get' accurately", function() {
                bitmapForEachArray(function(array, bitmap) {
                    var element = 0;
                    for (var arrayIndex=0; arrayIndex<array.length; arrayIndex++) {
                        var nextInArray = array[arrayIndex];
                        for (; element < nextInArray; element++) {
                            expect(bitmap.get(element)).toEqual(false);
                        }
                        expect(bitmap.get(element)).toEqual(true);
                        element++;
                    }
                    for (; element < nextInArray+33; element++) {  // Check past next packed bits
                        expect(bitmap.get(element)).toEqual(false);
                    }
                });
            });
            describe("Iterator", function() {
                it("Increases monotonically", function() {
                    bitmapForEachArray(function(array, bitmap) {
                        var it = bitmap.iterator();
                        var previous = -1;
                        while (it.hasNext()) {
                            var element = it.next();
                            expect(element).toBeGreaterThan(previous);
                            previous = element;
                        }
                    });
                });
                it("Matches get", function() {
                    bitmapForEachArray(function(array, bitmap) {
                        var it = bitmap.iterator();
                        while (it.hasNext()) {
                            var element = it.next();
                            expect(bitmap.get(element)).toBe(true);
                        }
                    });
                });
                it("Matches size", function() {
                    bitmapForEachArray(function(array, bitmap) {
                        var it = bitmap.iterator();
                        var count = 0;
                        while (it.hasNext()) {
                            it.next();
                            count++;
                        }
                        expect(count).toBe(bitmap.size);
                    });
                });
                it("Skips properly", function() {
                    bitmapForEachArray(function(array, bitmap) {
                        if (array.length > 0) {
                            var it = bitmap.iterator();
                            it.skipTo(bitmap.min()-1);
                            expect(it.next()).toBe(bitmap.min());

                            it = bitmap.iterator();
                            it.skipTo(bitmap.min());
                            it.skipTo(bitmap.min());
                            it.skipTo(bitmap.min());
                            expect(it.next()).toBe(bitmap.min());
                            if (array.length > 1) {
                                it.skipTo(bitmap.max());
                                expect(it.next()).toBe(bitmap.max());
                            }

                            it = bitmap.iterator();
                            it.skipTo(bitmap.max()+1);
                            expect(it.hasNext()).toBe(false);

                            if (array.length > 1) {
                                it = bitmap.iterator();
                                var skipTo = bitmap.max()-1;
                                it.skipTo(skipTo);
                                var expectedNext = (bitmap.get(skipTo)) ?  skipTo  :  bitmap.max();
                                console.log("skip to "+skipTo+", expectedNext = "+expectedNext+" on "+array);
                                expect(it.next()).toBe(expectedNext);
                            }
                        }
                    });
                });
            });

            it("Has 'each' which matches the iterator", function() {
                bitmapForEachArray(function(array, bitmap) {
                    var it = bitmap.iterator();
                    bitmap.each(function(element) {
                        expect(element).toBe(it.next());
                    });
                    expect(it.hasNext()).toBe(false);
                });
            });
        });
    }
});<|endoftext|>