<commit_before>import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import Slider from 'react-slick'
import { NextPaddle, PrevPaddle } from './CarouselParts'
import PostStreamContainer from '../../containers/PostStreamContainer'
import { css, media, select } from '../../styles/jss'
import * as s from '../../styles/jso'

const editorialWrapperStyle = css(
  s.relative,
  s.fullHeight,
  select('& .slick-slider, & .slick-list, & .slick-track', s.fullHeight),
)
const editorialNavStyle = css(
  s.absolute,
  s.zIndex3,
  { top: 0, right: 0 },
  media(s.minBreak2, { top: 5, right: 5 }),
)
const itemBaseStyle = css(
  s.relative,
  s.flex,
  s.flexWrap,
  s.fullWidth,
  s.fullHeight,
  s.px20,
  s.py20,
  s.bgcTransparent,
  media(s.minBreak2, s.px40, s.py40),
)

export class SlickCarousel extends PureComponent {
  static propTypes = {
    postIds: PropTypes.object.isRequired,
    renderProps: PropTypes.object.isRequired,
  }

  next = () => {
    this.slider.slickNext()
  }

  prev = () => {
    this.slider.slickPrev()
  }

  render() {
    const { postIds, renderProps } = this.props
    return (

        <Slider
          autoplay
          arrows={false}
          infinite
          ref={(comp) => {
            this.slider = comp
            return this.slider
          }}
        >
          {postIds.map(id => (
            <div className={itemBaseStyle} key={`curatedEditorial_post_${id}`}>
              <PostStreamContainer
                postId={id}
                {...renderProps}
              />

          ))}
        </Slider>
        {postIds.size > 1 &&

            <PrevPaddle onClick={this.prev} />
            <NextPaddle onClick={this.next} />

        }

    )
  }
}

export default SlickCarousel

<commit_msg>fix carousel CSS<commit_after>import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import Slider from 'react-slick'
import { NextPaddle, PrevPaddle } from './CarouselParts'
import PostStreamContainer from '../../containers/PostStreamContainer'
import { css, media, select } from '../../styles/jss'
import * as s from '../../styles/jso'

const editorialWrapperStyle = css(
  s.relative,
  s.fullHeight,
  select('& .slick-slide > div', s.fullHeight),
  select('& .slick-slider, & .slick-list, & .slick-track', s.fullHeight),
)
const editorialNavStyle = css(
  s.absolute,
  s.zIndex3,
  { top: 0, right: 0 },
  media(s.minBreak2, { top: 5, right: 5 }),
)
const itemBaseStyle = css(
  s.relative,
  s.flex,
  s.flexWrap,
  s.fullWidth,
  s.fullHeight,
  s.px20,
  s.py20,
  s.bgcTransparent,
  media(s.minBreak2, s.p0),
)

export class SlickCarousel extends PureComponent {
  static propTypes = {
    postIds: PropTypes.object.isRequired,
    renderProps: PropTypes.object.isRequired,
  }

  next = () => {
    this.slider.slickNext()
  }

  prev = () => {
    this.slider.slickPrev()
  }

  render() {
    const { postIds, renderProps } = this.props
    return (

        <Slider
          autoplay
          arrows={false}
          infinite
          ref={(comp) => {
            this.slider = comp
            return this.slider
          }}
        >
          {postIds.map(id => (
            <div className={itemBaseStyle} key={`curatedEditorial_post_${id}`}>
              <PostStreamContainer
                postId={id}
                {...renderProps}
              />

          ))}
        </Slider>
        {postIds.size > 1 &&

            <PrevPaddle onClick={this.prev} />
            <NextPaddle onClick={this.next} />

        }

    )
  }
}

export default SlickCarousel

<|endoftext|>


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

    if (module !== 'undefined' && module.exports)
        module.exports = new RaProto();
    else
        global.ra = new RaProto();

    function RaProto() {
        var Events = {};

        function ra(generator) {
            var gen = generator(requirebind, ajaxbind);

            function nextItem(error, result) {
                var item = gen.next(result);

                if (error)
                    emit('error', error);
                else if (!item.done)
                    item.value(nextItem);

                if (item.done)
                    emit('end');
              }

          nextItem();

          return ra;
        }

        ra.on = function(event, callback) {
            var funcs = Events[event];

            if (funcs)
                funcs.push(callback);
            else
                Events[event] = [callback];

            return ra;
        };

        function emit(event, data) {
            var funcs = Events[event];

            if (funcs)
                funcs.forEach(function(fn) {
                    fn(data);
                });
            else if (event === 'error')
                throw data;
        }

        function ajaxbind(url) {
            return ajax.bind(null, url);
        }

        function requirebind(url) {
            return require.bind(null, url);
        }

        function require(url, callback) {
            ajax(url, function(error, data) {
                if (error)
                    callback(error);
                else
                    evaluate(url, data, callback);
            });
        }

        function ajax(url, callback) {
            var request = new XMLHttpRequest();
            request.open('GET', url, true);

            request.addEventListener('load', function() {
                var data    = this.response,
                    status  = this.status;

                if (status >= 200 && status < 400)
                    callback(null, data);
                else
                    callback(this.response);
            });

            request.addEventListener('error', function(error) {
                callback(error);
            });

            request.send();
        }

        function evaluate(url, data, callback) {
            var error,
                result,
                js        = /js$/.test(url),
                begin       = 'var module = { exports:{} };' +
                            '(function(exports, require, module) {',
                end         = '})(module.exports, null, module);' +
                            'return module.exports;';

            if (!js)
                error = tryCatch(function() {
                    result = JSON.parse(data);
                });
            else
                error = tryCatch(function() {
                    result = Function(begin + data + end)();
                });

            callback(error, result);
        }

        function tryCatch(fn) {
            var error;

            try {
                fn();
            } catch(err) {
                error = err;
            }

            return error;
        }

        return ra;
    }
})(this);
<commit_msg>fix(ra) module -> typeof module<commit_after>(function(global) {
    'use strict';

    if (typeof module !== 'undefined' && module.exports)
        module.exports = new RaProto();
    else
        global.ra = new RaProto();

    function RaProto() {
        var Events = {};

        function ra(generator) {
            var gen = generator(requirebind, ajaxbind);

            function nextItem(error, result) {
                var item = gen.next(result);

                if (error)
                    emit('error', error);
                else if (!item.done)
                    item.value(nextItem);

                if (item.done)
                    emit('end');
              }

          nextItem();

          return ra;
        }

        ra.on = function(event, callback) {
            var funcs = Events[event];

            if (funcs)
                funcs.push(callback);
            else
                Events[event] = [callback];

            return ra;
        };

        function emit(event, data) {
            var funcs = Events[event];

            if (funcs)
                funcs.forEach(function(fn) {
                    fn(data);
                });
            else if (event === 'error')
                throw data;
        }

        function ajaxbind(url) {
            return ajax.bind(null, url);
        }

        function requirebind(url) {
            return require.bind(null, url);
        }

        function require(url, callback) {
            ajax(url, function(error, data) {
                if (error)
                    callback(error);
                else
                    evaluate(url, data, callback);
            });
        }

        function ajax(url, callback) {
            var request = new XMLHttpRequest();
            request.open('GET', url, true);

            request.addEventListener('load', function() {
                var data    = this.response,
                    status  = this.status;

                if (status >= 200 && status < 400)
                    callback(null, data);
                else
                    callback(this.response);
            });

            request.addEventListener('error', function(error) {
                callback(error);
            });

            request.send();
        }

        function evaluate(url, data, callback) {
            var error,
                result,
                js        = /js$/.test(url),
                begin       = 'var module = { exports:{} };' +
                            '(function(exports, require, module) {',
                end         = '})(module.exports, null, module);' +
                            'return module.exports;';

            if (!js)
                error = tryCatch(function() {
                    result = JSON.parse(data);
                });
            else
                error = tryCatch(function() {
                    result = Function(begin + data + end)();
                });

            callback(error, result);
        }

        function tryCatch(fn) {
            var error;

            try {
                fn();
            } catch(err) {
                error = err;
            }

            return error;
        }

        return ra;
    }
})(this);
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import './input-password.scss';
const InputPassword = (props) => {
  const {
    id,
    onBlur,
    error
  } = props;

  const hasError = error && error.message && error.message.length > 0;
  const inputClassName = hasError? 'text-password text-password--error' :'text-password';

  return

    <input id={id} type="password" onBlur={onBlur} className={inputClassName} />
    {hasError ? {error.message} :null }

};

InputPassword.propTypes = {
  id: PropTypes.string.isRequired
};

export default InputPassword;
<commit_msg>Testing for push command<commit_after>import React, {PropTypes} from 'react';
import './input-password.scss';
const InputPassword = (props) => {
  const {
    id,
    onBlur,
    error
  } = props;

  const hasError = error && error.message && error.message.length > 0;
  const inputClassName = hasError? 'text-password text-password--error' :'text-password';

  return

    <input id={id} type="password" onBlur={onBlur} className={inputClassName} />
    {hasError ? {error.message} :null }

};

InputPassword.propTypes = {
  id: PropTypes.string.isRequired
};

export default InputPassword;
<|endoftext|>


<commit_before>// import { ProseMirror } from './../../../prosemirror/dist/edit'
import { Step } from './../../../prosemirror/dist/transform'
import { defaultSchema } from './../../../prosemirror/dist/model/defaultschema'

export class ProseMeteorAuthority {
  /**
   * Central authority to track a ProseMirror document, apply steps from clients, and notify clients when changes occur.
   * @param  {String} docId              a unique id for the doc
   * @constructor
   */
  constructor( docId, snapshotCollection, serverStreamer ) {
    console.log('created authority for doc: ' + docId);
    // create a new PM instance to track the doc's' state
    //  = new ProseMirror();
    this.doc = null;
    this.docId = docId;
    this.snapshotCollection = snapshotCollection;
    this.steps = [];
    this.stepClientIds = [];
    this.streamer = serverStreamer;
    // when a client submits new steps, we receieve them
    this.streamer.on('clientSubmitSteps', this.receieveSteps.bind(this));
  }
  /**
   * Receive new steps from a client, applying them to the local doc and
   * storing them.
   * @param  {Number} version    version of the document these steps apply to
   * @param  {[Step]} steps      steps to be applied to the doc
   * @param  {String} clientId   id of the client submitting the steps
   * @return {[type]}          [description]
   */
  receieveSteps({ clientId, steps, version }) {
    // parse the steps from json and convert them into Step instances
    const stepObjects = steps.map((step) => {
      return Step.fromJSON(defaultSchema, step);
    });
    //console.log('Server got step: ' + resp);
    console.log('Authority received steps from client ' + clientId + ' for version ' + version);
    //
    // if the client submitted steps but that client didn't have the latest version
    // of the doc, stop since they must be applied to newest doc version
    if (version !== this.steps.length) {
      return;
    }
    // apply and accumulate new steps
    steps.forEach((step) => {
      this.doc = step.apply(this.doc).doc;
      this.steps.push(step);
      this.stepClientIds.push(clientId);
    });
    console.log('Authority updated doc:', this.doc);
    console.log('Authority steps:', this.steps);
    console.log('Authority step client Ids:', this.stepClientIds);
    // notify listening clients that new steps have arrived
    // this.streamer.emit('authorityNewSteps');
  }
  /**
   * Return all steps since the provided version.
   * @param  {Number} version    version of the document
   * @return {Object} stepsSince  object with "steps" array and "clientIds" array
   */
  stepsSince(version) {
    return {
      steps: this.steps.slice(version),
      clientIds: this.stepClientIds.slice(version)
    };
  }
  // /**
  //  * Store a snapshot of the current document in the snapshotCollection
  //  */
  // storeSnapshot() {
  //   const doc = this.pm.doc;
  //   const newSnapshotJSON = doc.toJSON();
  //   const newSnapshotNumber = ProseMeteorManager.numberOfSnapshots() + 1;
  //   this.snapshotCollection.insert({
  //     docId: this.docId,
  //     docJSON: newSnapshotJSON,
  //     timestamp: Date.now(),
  //     number: newSnapshotNumber
  //   });
  // }
  // /**
  // * Loads the latest snapshot from db and sets it to this authority's PM instance's doc state.
  // */
  // loadLatestSnapshot() {
  //   const snapshotJSON = ProseMeteorManager.getLatestSnapshotJSON(this.docId);
  //   this.pm.setDoc(this.pm.schema.nodeFromJSON(lastSnapshot));
  // }
}
<commit_msg>fix to use step objects from json<commit_after>// import { ProseMirror } from './../../../prosemirror/dist/edit'
import { Step } from './../../../prosemirror/dist/transform'
import { defaultSchema } from './../../../prosemirror/dist/model/defaultschema'

export class ProseMeteorAuthority {
  /**
   * Central authority to track a ProseMirror document, apply steps from clients, and notify clients when changes occur.
   * @param  {String} docId              a unique id for the doc
   * @constructor
   */
  constructor( docId, snapshotCollection, serverStreamer ) {
    console.log('created authority for doc: ' + docId);
    // create a new PM instance to track the doc's' state
    //  = new ProseMirror();
    this.doc = null;
    this.docId = docId;
    this.snapshotCollection = snapshotCollection;
    this.steps = [];
    this.stepClientIds = [];
    this.streamer = serverStreamer;
    // when a client submits new steps, we receieve them
    this.streamer.on('clientSubmitSteps', this.receieveSteps.bind(this));
  }
  /**
   * Receive new steps from a client, applying them to the local doc and
   * storing them.
   * @param  {Number} version    version of the document these steps apply to
   * @param  {[Step]} steps      steps to be applied to the doc
   * @param  {String} clientId   id of the client submitting the steps
   * @return {[type]}          [description]
   */
  receieveSteps({ clientId, steps, version }) {
    // parse the steps from json and convert them into Step instances
    const stepObjects = steps.map((step) => {
      return Step.fromJSON(defaultSchema, step);
    });
    //console.log('Server got step: ' + resp);
    console.log('Authority received steps from client ' + clientId + ' for version ' + version);
    //
    // if the client submitted steps but that client didn't have the latest version
    // of the doc, stop since they must be applied to newest doc version
    if (version !== this.steps.length) {
      return;
    }
    // apply and accumulate new steps
    stepObjects.forEach((step) => {
      this.doc = step.apply(this.doc).doc;
      this.steps.push(step);
      this.stepClientIds.push(clientId);
    });
    console.log('Authority updated doc:', this.doc);
    console.log('Authority steps:', this.steps);
    console.log('Authority step client Ids:', this.stepClientIds);
    // notify listening clients that new steps have arrived
    // this.streamer.emit('authorityNewSteps');
  }
  /**
   * Return all steps since the provided version.
   * @param  {Number} version    version of the document
   * @return {Object} stepsSince  object with "steps" array and "clientIds" array
   */
  stepsSince(version) {
    return {
      steps: this.steps.slice(version),
      clientIds: this.stepClientIds.slice(version)
    };
  }
  // /**
  //  * Store a snapshot of the current document in the snapshotCollection
  //  */
  // storeSnapshot() {
  //   const doc = this.pm.doc;
  //   const newSnapshotJSON = doc.toJSON();
  //   const newSnapshotNumber = ProseMeteorManager.numberOfSnapshots() + 1;
  //   this.snapshotCollection.insert({
  //     docId: this.docId,
  //     docJSON: newSnapshotJSON,
  //     timestamp: Date.now(),
  //     number: newSnapshotNumber
  //   });
  // }
  // /**
  // * Loads the latest snapshot from db and sets it to this authority's PM instance's doc state.
  // */
  // loadLatestSnapshot() {
  //   const snapshotJSON = ProseMeteorManager.getLatestSnapshotJSON(this.docId);
  //   this.pm.setDoc(this.pm.schema.nodeFromJSON(lastSnapshot));
  // }
}
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import TextInput from '../common/text-input';

class PropertyEditPage extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      property: Object.assign({}, props.property),
      errors: {},
      saving: false
    };

    this.updatePropertyState = this.updatePropertyState.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.property.id != nextProps.property.id) {
      // Necessary to populate form when existing property is loaded directly.
      this.setState({property: Object.assign({}, nextProps.property)});
    }
  }

  updatePropertyState(event) {
    const field = event.target.name;
    let property = this.state.property;
    property[field] = event.target.value;
    return this.setState({property});
  }

  render() {
    return (

        <TextInput name="id" label="Id" value={this.state.property.id} onChange={this.updatePropertyState} error={this.state.errors.id}/>
        <TextInput name="price" label="Price" value={this.state.property.price} onChange={this.updatePropertyState} error={this.state.errors.title}/>
        <TextInput name="propertyType" label="Property type" value={this.state.property.propertyType} onChange={this.updatePropertyState} error={this.state.errors.propertyType}/>

    );
  }
}

function getPropertyById(properties, id) {
  const property = properties.filter(course => course.id == id);
  if (property.length) return property[0]; //since filter returns an array, have to grab the first.
  return null;
}

function mapStateToProps(state, ownProps) {
  const id = ownProps.params.id;

  let property = {};

  if (id && state.properties.length > 0) {
    property = getPropertyById(state.properties, id);
  }

  return {
    property
  };
}

export default connect(mapStateToProps)(PropertyEditPage);<commit_msg>Refactoring<commit_after>import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import TextInput from '../common/text-input';

class PropertyEditPage extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      property: Object.assign({}, props.property),
      errors: {},
      saving: false
    };

    this.updatePropertyState = this.updatePropertyState.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.property.id != nextProps.property.id) {
      // Necessary to populate form when existing property is loaded directly.
      this.setState({property: Object.assign({}, nextProps.property)});
    }
  }

  updatePropertyState(event) {
    const field = event.target.name;
    let property = this.state.property;
    property[field] = event.target.value;
    return this.setState({property});
  }

  render() {
    return (

        <TextInput name="id" label="Id" value={this.state.property.id} onChange={this.updatePropertyState} error={this.state.errors.id}/>
        <TextInput name="price" label="Price" value={this.state.property.price} onChange={this.updatePropertyState} error={this.state.errors.title}/>
        <TextInput name="propertyType" label="Property type" value={this.state.property.propertyType} onChange={this.updatePropertyState} error={this.state.errors.propertyType}/>

    );
  }
}

function getPropertyById(properties, id) {
  const property = properties.filter(course => course.id == id);
  if (property.length) return property[0]; //since filter returns an array, have to grab the first.
  return null;
}

function mapStateToProps(state, ownProps) {
  const id = ownProps.params.id;

  const property = id && state.properties.length > 0 ? getPropertyById(state.properties, id) : {};

  return {property};
}

export default connect(mapStateToProps)(PropertyEditPage);<|endoftext|>


<commit_before>import React from 'react'

import { TableRow, TableRowColumn } from 'material-ui/Table'

const DaysWorking = ({ annualLeave, sickLeave, publicHolidays, weekends, days, style }) => {
  delete days.thisYear
  // get total number of days in the year.
  // subtract weekends, sickLeave, annualLeave, publicHolidays from it.
  const total = Object.values(days)

  return (
    <TableRow>
      <TableRowColumn>

Total number of days you are working this year

      </TableRowColumn>
      <TableRowColumn>

{ !isNaN(total) && total }

      </TableRowColumn>
    </TableRow>
  )
}

export default DaysWorking
<commit_msg>add functional logic for total value<commit_after>import React from 'react'

import { TableRow, TableRowColumn } from 'material-ui/Table'

const DaysWorking = ({ annualLeave, sickLeave, publicHolidays, weekends, days, style }) => {
  const total = Object.values(days)
    .filter(value => value < 54) // get rid of the thisYear value
    .reduce((a, b) => a + b) // add up all the remaining values
    - (annualLeave + sickLeave + publicHolidays + weekends)
  return (
    <TableRow>
      <TableRowColumn>

Total number of days you are working this year

      </TableRowColumn>
      <TableRowColumn>

{ !isNaN(total) && annualLeave && sickLeave && total }

      </TableRowColumn>
    </TableRow>
  )
}

export default DaysWorking
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

'use strict';

var getMediaButton = document.querySelector('button#getMedia');
var createPeerConnectionButton =
    document.querySelector('button#createPeerConnection');
var createOfferButton = document.querySelector('button#createOffer');
var setOfferButton = document.querySelector('button#setOffer');
var createAnswerButton = document.querySelector('button#createAnswer');
var setAnswerButton = document.querySelector('button#setAnswer');
var hangupButton = document.querySelector('button#hangup');
var dataChannelSend = document.querySelector('textarea#dataChannelSend');
var dataChannelReceive = document.querySelector('textarea#dataChannelReceive');

getMediaButton.onclick = getMedia;
createPeerConnectionButton.onclick = createPeerConnection;
createOfferButton.onclick = createOffer;
setOfferButton.onclick = setOffer;
createAnswerButton.onclick = createAnswer;
setAnswerButton.onclick = setAnswer;
hangupButton.onclick = hangup;

var offer;
var offerSdpTextarea = document.querySelector('div#local textarea');
var answer;
var answerSdpTextarea = document.querySelector('div#remote textarea');

var audioSelect = document.querySelector('select#audioSrc');
var videoSelect = document.querySelector('select#videoSrc');

audioSelect.onchange = videoSelect.onchange = getMedia;

var localVideo = document.querySelector('div#local video');
var remoteVideo = document.querySelector('div#remote video');

var selectSourceDiv = document.querySelector('div#selectSource');

var localPeerConnection;
var remotePeerConnection;
var localStream;
var sendChannel;
var receiveChannel;
var dataChannelOptions = {
  ordered: true
};
var dataChannelCounter = 0;
var sendDataLoop;
var offerOptions = {
  offerToReceiveAudio: 1,
  offerToReceiveVideo: 1
};

getSources();

function getSources() {
  if (typeof MediaStreamTrack === 'undefined') {
    alert(
      'This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
  } else {
    navigator.mediaDevices.enumerateDevices().then(gotSources);
  }
}

function gotSources(sourceInfos) {
  selectSourceDiv.classList.remove('hidden');
  var audioCount = 0;
  var videoCount = 0;
  for (var i = 0; i < sourceInfos.length; i++) {
    var option = document.createElement('option');
    option.value = sourceInfos[i].id;
    option.text = sourceInfos[i].label;
    if (sourceInfos[i].kind === 'audioinput') {
      audioCount++;
      if (option.text === '') {
        option.text = 'Audio ' + audioCount;
      }
      audioSelect.appendChild(option);
    } else if (sourceInfos[i].kind === 'videoinput') {
      videoCount++;
      if (option.text === '') {
        option.text = 'Video ' + videoCount;
      }
      videoSelect.appendChild(option);
    } else {
      console.log('unknown', JSON.stringify(sourceInfos[i]));
    }
  }
}

function getMedia() {
  getMediaButton.disabled = true;
  createPeerConnectionButton.disabled = false;

  if (localStream) {
    localVideo.src = null;
    localStream.getTracks().forEach(function(track) { track.stop(); });
  }
  var audioSource = audioSelect.value;
  trace('Selected audio source: ' + audioSource);
  var videoSource = videoSelect.value;
  trace('Selected video source: ' + videoSource);

  var constraints = {
    audio: {
      optional: [{
        sourceId: audioSource
      }]
    },
    video: {
      optional: [{
        sourceId: videoSource
      }]
    }
  };
  trace('Requested local stream');
  navigator.mediaDevices.getUserMedia(constraints)
  .then(gotStream)
  .catch(function(e) {
    console.log('navigator.getUserMedia error: ', e);
  });
}

function gotStream(stream) {
  trace('Received local stream');
  // Call the polyfill wrapper to attach the media stream to this element.
  attachMediaStream(localVideo, stream);
  localStream = stream;
}

function createPeerConnection() {
  createPeerConnectionButton.disabled = true;
  createOfferButton.disabled = false;
  createAnswerButton.disabled = false;
  setOfferButton.disabled = false;
  setAnswerButton.disabled = false;
  hangupButton.disabled = false;
  trace('Starting call');
  var videoTracks = localStream.getVideoTracks();
  var audioTracks = localStream.getAudioTracks();
  if (videoTracks.length > 0) {
    trace('Using video device: ' + videoTracks[0].label);
  }
  if (audioTracks.length > 0) {
    trace('Using audio device: ' + audioTracks[0].label);
  }
  var servers = null;

  localPeerConnection = new RTCPeerConnection(servers);
  trace('Created local peer connection object localPeerConnection');
  sendChannel = localPeerConnection.createDataChannel('sendDataChannel',
      dataChannelOptions);
  localPeerConnection.onicecandidate = iceCallback1;
  sendChannel.onopen = onSendChannelStateChange;
  sendChannel.onclose = onSendChannelStateChange;
  sendChannel.onerror = onSendChannelStateChange;

  remotePeerConnection = new RTCPeerConnection(servers);
  trace('Created remote peer connection object remotePeerConnection');
  remotePeerConnection.onicecandidate = iceCallback2;
  remotePeerConnection.onaddstream = gotRemoteStream;
  remotePeerConnection.ondatachannel = receiveChannelCallback;

  localPeerConnection.addStream(localStream);
  trace('Adding Local Stream to peer connection');
}

function onSetSessionDescriptionSuccess() {
  trace('Set session description success.');
}

function onSetSessionDescriptionError(error) {
  trace('Failed to set session description: ' + error.toString());
}

// Workaround for crbug/322756.
function maybeAddLineBreakToEnd(sdp) {
  var endWithLineBreak = new RegExp(/\n$/);
  if (!endWithLineBreak.test(sdp)) {
    return sdp + '\n';
  }
  return sdp;
}

function createOffer() {
  localPeerConnection.createOffer(gotDescription1,
      onCreateSessionDescriptionError, offerOptions);
}

function onCreateSessionDescriptionError(error) {
  trace('Failed to create session description: ' + error.toString());
}

function setOffer() {
  var sdp = offerSdpTextarea.value;
  sdp = maybeAddLineBreakToEnd(sdp);
  sdp = sdp.replace(/\n/g, '\r\n');
  offer.ѕdp = sdp;
  localPeerConnection.setLocalDescription(offer,
      onSetSessionDescriptionSuccess,
      onSetSessionDescriptionError);
  trace('Modified Offer from localPeerConnection \n' + sdp);
  remotePeerConnection.setRemoteDescription(offer,
      onSetSessionDescriptionSuccess,
      onSetSessionDescriptionError);
}

function gotDescription1(description) {
  offer = description;
  offerSdpTextarea.disabled = false;
  offerSdpTextarea.value = description.sdp;
}

function createAnswer() {
  // Since the 'remote' side has no media stream we need
  // to pass in the right constraints in order for it to
  // accept the incoming offer of audio and video.
  remotePeerConnection.createAnswer(gotDescription2,
      onCreateSessionDescriptionError);
}

function setAnswer() {
  var sdp = answerSdpTextarea.value;
  sdp = maybeAddLineBreakToEnd(sdp);
  sdp = sdp.replace(/\n/g, '\r\n');
  answer.sdp = sdp;
  remotePeerConnection.setLocalDescription(answer,
      onSetSessionDescriptionSuccess,
      onSetSessionDescriptionError);
  trace('Modified Answer from remotePeerConnection \n' + sdp);
  localPeerConnection.setRemoteDescription(answer,
      onSetSessionDescriptionSuccess,
      onSetSessionDescriptionError);
}

function gotDescription2(description) {
  answer = description;
  answerSdpTextarea.disabled = false;
  answerSdpTextarea.value = description.sdp;
}

function sendData() {
  var data = dataChannelSend.value + '\nCounter: ' + dataChannelCounter;
  sendChannel.send(data);
  dataChannelCounter++;
  trace('Sent Data: ' + data);
}

function hangup() {
  remoteVideo.src = '';
  trace('Ending call');
  localStream.getTracks().forEach(function(track) { track.stop(); });
  sendChannel.close();
  receiveChannel.close();
  localPeerConnection.close();
  remotePeerConnection.close();
  localPeerConnection = null;
  remotePeerConnection = null;
  offerSdpTextarea.disabled = true;
  answerSdpTextarea.disabled = true;
  getMediaButton.disabled = false;
  createPeerConnectionButton.disabled = true;
  createOfferButton.disabled = true;
  setOfferButton.disabled = true;
  createAnswerButton.disabled = true;
  setAnswerButton.disabled = true;
  hangupButton.disabled = true;
}

function gotRemoteStream(e) {
  // Call the polyfill wrapper to attach the media stream to this element.
  attachMediaStream(remoteVideo, e.stream);
  trace('Received remote stream');
}

function iceCallback1(event) {
  if (event.candidate) {
    remotePeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate),
        onAddIceCandidateSuccess, onAddIceCandidateError);
    trace('Local ICE candidate: \n' + event.candidate.candidate);
  }
}

function iceCallback2(event) {
  if (event.candidate) {
    localPeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate),
        onAddIceCandidateSuccess, onAddIceCandidateError);
    trace('Remote ICE candidate: \n ' + event.candidate.candidate);
  }
}

function onAddIceCandidateSuccess() {
  trace('AddIceCandidate success.');
}

function onAddIceCandidateError(error) {
  trace('Failed to add Ice Candidate: ' + error.toString());
}

function receiveChannelCallback(event) {
  trace('Receive Channel Callback');
  receiveChannel = event.channel;
  receiveChannel.onmessage = onReceiveMessageCallback;
  receiveChannel.onopen = onReceiveChannelStateChange;
  receiveChannel.onclose = onReceiveChannelStateChange;
}

function onReceiveMessageCallback(event) {
  trace('Received Message');
  dataChannelReceive.value = event.data;
}

function onSendChannelStateChange() {
  var readyState = sendChannel.readyState;
  trace('Send channel state is: ' + readyState);
  if (readyState === 'open') {
    dataChannelSend.disabled = false;
    sendDataLoop = setInterval(sendData, 1000);
  } else {
    clearInterval(sendDataLoop);
    dataChannelSend.disabled = true;
  }
}

function onReceiveChannelStateChange() {
  var readyState = receiveChannel.readyState;
  trace('Receive channel state is: ' + readyState);
}
<commit_msg>Fixing typo that breaks setOffer in the sdp munging sample.<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

'use strict';

var getMediaButton = document.querySelector('button#getMedia');
var createPeerConnectionButton =
    document.querySelector('button#createPeerConnection');
var createOfferButton = document.querySelector('button#createOffer');
var setOfferButton = document.querySelector('button#setOffer');
var createAnswerButton = document.querySelector('button#createAnswer');
var setAnswerButton = document.querySelector('button#setAnswer');
var hangupButton = document.querySelector('button#hangup');
var dataChannelSend = document.querySelector('textarea#dataChannelSend');
var dataChannelReceive = document.querySelector('textarea#dataChannelReceive');

getMediaButton.onclick = getMedia;
createPeerConnectionButton.onclick = createPeerConnection;
createOfferButton.onclick = createOffer;
setOfferButton.onclick = setOffer;
createAnswerButton.onclick = createAnswer;
setAnswerButton.onclick = setAnswer;
hangupButton.onclick = hangup;

var offer;
var offerSdpTextarea = document.querySelector('div#local textarea');
var answer;
var answerSdpTextarea = document.querySelector('div#remote textarea');

var audioSelect = document.querySelector('select#audioSrc');
var videoSelect = document.querySelector('select#videoSrc');

audioSelect.onchange = videoSelect.onchange = getMedia;

var localVideo = document.querySelector('div#local video');
var remoteVideo = document.querySelector('div#remote video');

var selectSourceDiv = document.querySelector('div#selectSource');

var localPeerConnection;
var remotePeerConnection;
var localStream;
var sendChannel;
var receiveChannel;
var dataChannelOptions = {
  ordered: true
};
var dataChannelCounter = 0;
var sendDataLoop;
var offerOptions = {
  offerToReceiveAudio: 1,
  offerToReceiveVideo: 1
};

getSources();

function getSources() {
  if (typeof MediaStreamTrack === 'undefined') {
    alert(
      'This browser does not support MediaStreamTrack.\n\nTry Chrome Canary.');
  } else {
    navigator.mediaDevices.enumerateDevices().then(gotSources);
  }
}

function gotSources(sourceInfos) {
  selectSourceDiv.classList.remove('hidden');
  var audioCount = 0;
  var videoCount = 0;
  for (var i = 0; i < sourceInfos.length; i++) {
    var option = document.createElement('option');
    option.value = sourceInfos[i].id;
    option.text = sourceInfos[i].label;
    if (sourceInfos[i].kind === 'audioinput') {
      audioCount++;
      if (option.text === '') {
        option.text = 'Audio ' + audioCount;
      }
      audioSelect.appendChild(option);
    } else if (sourceInfos[i].kind === 'videoinput') {
      videoCount++;
      if (option.text === '') {
        option.text = 'Video ' + videoCount;
      }
      videoSelect.appendChild(option);
    } else {
      console.log('unknown', JSON.stringify(sourceInfos[i]));
    }
  }
}

function getMedia() {
  getMediaButton.disabled = true;
  createPeerConnectionButton.disabled = false;

  if (localStream) {
    localVideo.src = null;
    localStream.getTracks().forEach(function(track) { track.stop(); });
  }
  var audioSource = audioSelect.value;
  trace('Selected audio source: ' + audioSource);
  var videoSource = videoSelect.value;
  trace('Selected video source: ' + videoSource);

  var constraints = {
    audio: {
      optional: [{
        sourceId: audioSource
      }]
    },
    video: {
      optional: [{
        sourceId: videoSource
      }]
    }
  };
  trace('Requested local stream');
  navigator.mediaDevices.getUserMedia(constraints)
  .then(gotStream)
  .catch(function(e) {
    console.log('navigator.getUserMedia error: ', e);
  });
}

function gotStream(stream) {
  trace('Received local stream');
  // Call the polyfill wrapper to attach the media stream to this element.
  attachMediaStream(localVideo, stream);
  localStream = stream;
}

function createPeerConnection() {
  createPeerConnectionButton.disabled = true;
  createOfferButton.disabled = false;
  createAnswerButton.disabled = false;
  setOfferButton.disabled = false;
  setAnswerButton.disabled = false;
  hangupButton.disabled = false;
  trace('Starting call');
  var videoTracks = localStream.getVideoTracks();
  var audioTracks = localStream.getAudioTracks();
  if (videoTracks.length > 0) {
    trace('Using video device: ' + videoTracks[0].label);
  }
  if (audioTracks.length > 0) {
    trace('Using audio device: ' + audioTracks[0].label);
  }
  var servers = null;

  localPeerConnection = new RTCPeerConnection(servers);
  trace('Created local peer connection object localPeerConnection');
  sendChannel = localPeerConnection.createDataChannel('sendDataChannel',
      dataChannelOptions);
  localPeerConnection.onicecandidate = iceCallback1;
  sendChannel.onopen = onSendChannelStateChange;
  sendChannel.onclose = onSendChannelStateChange;
  sendChannel.onerror = onSendChannelStateChange;

  remotePeerConnection = new RTCPeerConnection(servers);
  trace('Created remote peer connection object remotePeerConnection');
  remotePeerConnection.onicecandidate = iceCallback2;
  remotePeerConnection.onaddstream = gotRemoteStream;
  remotePeerConnection.ondatachannel = receiveChannelCallback;

  localPeerConnection.addStream(localStream);
  trace('Adding Local Stream to peer connection');
}

function onSetSessionDescriptionSuccess() {
  trace('Set session description success.');
}

function onSetSessionDescriptionError(error) {
  trace('Failed to set session description: ' + error.toString());
}

// Workaround for crbug/322756.
function maybeAddLineBreakToEnd(sdp) {
  var endWithLineBreak = new RegExp(/\n$/);
  if (!endWithLineBreak.test(sdp)) {
    return sdp + '\n';
  }
  return sdp;
}

function createOffer() {
  localPeerConnection.createOffer(gotDescription1,
      onCreateSessionDescriptionError, offerOptions);
}

function onCreateSessionDescriptionError(error) {
  trace('Failed to create session description: ' + error.toString());
}

function setOffer() {
  var sdp = offerSdpTextarea.value;
  sdp = maybeAddLineBreakToEnd(sdp);
  sdp = sdp.replace(/\n/g, '\r\n');
  offer.sdp = sdp;
  localPeerConnection.setLocalDescription(offer,
      onSetSessionDescriptionSuccess,
      onSetSessionDescriptionError);
  trace('Modified Offer from localPeerConnection \n' + sdp);
  remotePeerConnection.setRemoteDescription(offer,
      onSetSessionDescriptionSuccess,
      onSetSessionDescriptionError);
}

function gotDescription1(description) {
  offer = description;
  offerSdpTextarea.disabled = false;
  offerSdpTextarea.value = description.sdp;
}

function createAnswer() {
  // Since the 'remote' side has no media stream we need
  // to pass in the right constraints in order for it to
  // accept the incoming offer of audio and video.
  remotePeerConnection.createAnswer(gotDescription2,
      onCreateSessionDescriptionError);
}

function setAnswer() {
  var sdp = answerSdpTextarea.value;
  sdp = maybeAddLineBreakToEnd(sdp);
  sdp = sdp.replace(/\n/g, '\r\n');
  answer.sdp = sdp;
  remotePeerConnection.setLocalDescription(answer,
      onSetSessionDescriptionSuccess,
      onSetSessionDescriptionError);
  trace('Modified Answer from remotePeerConnection \n' + sdp);
  localPeerConnection.setRemoteDescription(answer,
      onSetSessionDescriptionSuccess,
      onSetSessionDescriptionError);
}

function gotDescription2(description) {
  answer = description;
  answerSdpTextarea.disabled = false;
  answerSdpTextarea.value = description.sdp;
}

function sendData() {
  var data = dataChannelSend.value + '\nCounter: ' + dataChannelCounter;
  sendChannel.send(data);
  dataChannelCounter++;
  trace('Sent Data: ' + data);
}

function hangup() {
  remoteVideo.src = '';
  trace('Ending call');
  localStream.getTracks().forEach(function(track) { track.stop(); });
  sendChannel.close();
  receiveChannel.close();
  localPeerConnection.close();
  remotePeerConnection.close();
  localPeerConnection = null;
  remotePeerConnection = null;
  offerSdpTextarea.disabled = true;
  answerSdpTextarea.disabled = true;
  getMediaButton.disabled = false;
  createPeerConnectionButton.disabled = true;
  createOfferButton.disabled = true;
  setOfferButton.disabled = true;
  createAnswerButton.disabled = true;
  setAnswerButton.disabled = true;
  hangupButton.disabled = true;
}

function gotRemoteStream(e) {
  // Call the polyfill wrapper to attach the media stream to this element.
  attachMediaStream(remoteVideo, e.stream);
  trace('Received remote stream');
}

function iceCallback1(event) {
  if (event.candidate) {
    remotePeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate),
        onAddIceCandidateSuccess, onAddIceCandidateError);
    trace('Local ICE candidate: \n' + event.candidate.candidate);
  }
}

function iceCallback2(event) {
  if (event.candidate) {
    localPeerConnection.addIceCandidate(new RTCIceCandidate(event.candidate),
        onAddIceCandidateSuccess, onAddIceCandidateError);
    trace('Remote ICE candidate: \n ' + event.candidate.candidate);
  }
}

function onAddIceCandidateSuccess() {
  trace('AddIceCandidate success.');
}

function onAddIceCandidateError(error) {
  trace('Failed to add Ice Candidate: ' + error.toString());
}

function receiveChannelCallback(event) {
  trace('Receive Channel Callback');
  receiveChannel = event.channel;
  receiveChannel.onmessage = onReceiveMessageCallback;
  receiveChannel.onopen = onReceiveChannelStateChange;
  receiveChannel.onclose = onReceiveChannelStateChange;
}

function onReceiveMessageCallback(event) {
  trace('Received Message');
  dataChannelReceive.value = event.data;
}

function onSendChannelStateChange() {
  var readyState = sendChannel.readyState;
  trace('Send channel state is: ' + readyState);
  if (readyState === 'open') {
    dataChannelSend.disabled = false;
    sendDataLoop = setInterval(sendData, 1000);
  } else {
    clearInterval(sendDataLoop);
    dataChannelSend.disabled = true;
  }
}

function onReceiveChannelStateChange() {
  var readyState = receiveChannel.readyState;
  trace('Receive channel state is: ' + readyState);
}
<|endoftext|>


<commit_before>/**
 * A plugin to identify unclear link text such as "more" and "click here,"
 * which can make for a bad experience when using a screen reader
 */

let $ = require("jquery");
let Plugin = require("../base");
let annotate = require("../shared/annotate")("link-text");

class LinkTextPlugin extends Plugin {
    getTitle() {
        return "Link text";
    }

    getDescription() {
        return `
            Identifies links that may be confusing when read by a screen
            reader
        `;
    }

    /**
     * Slightly modified unclear text checking that has been refactored into
     * a single method to be called with arbitrary strings.
     *
     * Original: https://github.com/GoogleChrome/accessibility-developer-tools/blob/9183b21cb0a02f5f04928f5cb7cb339b6bbc9ff8/src/audits/LinkWithUnclearPurpose.js#L55-67
     */
    isDescriptiveText(textContent) {
        textContent = textContent.replace(/[^a-zA-Z ]/g, "");
        let stopWords = [
            "click", "tap", "go", "here", "learn", "more", "this", "page",
            "link", "about"
        ];

        for (let i = 0; i < stopWords.length; i++) {
            let stopwordRE = new RegExp("\\b" + stopWords[i] + "\\b", "ig");
            textContent = textContent.replace(stopwordRE, "");
            if (textContent.trim() === "") {
                return false;
            }
        }

        return true;
    }

    /**
     * Checks whether or not the text content of an element (including things
     * like `aria-label`) is unclear.
     */
    validateTextContent(el) {
        let textContent = $.axs.properties.getTextFromDescendantContent(el);
        return {
            textContent: textContent,
            result: this.isDescriptiveText(textContent),
        };
    }

    /**
     * Checks if an image has descriptive alt text. This is used to determine
     * whether or not image links ( tags with a single  descendant)
     * are unclear.
     */
    validateAltText(el) {
        let altTextContent = el.getAttribute("alt");
        return {
            textContent: altTextContent,
            result: this.isDescriptiveText(altTextContent),
        };
    }

    reportError($el, description, textContent) {
        let entry = this.error("Link text is unclear", description, $el);
        annotate.errorLabel($el, "",
            `Link text "${textContent}" is unclear`, entry);
    }

    run() {
        $("a").each((i, el) => {
            let $el = $(el);

            // Ignore the tota11y UI
            if ($el.parents(".tota11y").length) {
                return;
            }

            // If this anchor contains a single image, we will test the
            // clarity of that image's alt text.
            if ($el.find("> img").length === 1) {
                let report = this.validateAltText($el.find("> img")[0]);

                if (!report.result) {
                    let description = `
                        The alt text for this link's image,
                        "${report.textContent}", is unclear without
                        context and may be confusing to screen readers.
                        Consider providing more detailed alt text.
                    `;

                    this.reportError($el, description, report.textContent);
                }
            } else {
                let report = this.validateTextContent(el);

                if (!report.result) {
                    let description = `
                        The text "${report.textContent}" is unclear
                        without context and may be confusing to screen readers.
                        Consider rearranging the <a></a>
                         tags or including special screen reader text.
                    `;

                    this.reportError($el, description, report.textContent);
                }
            }
        });
    }

    cleanup() {
        annotate.removeAll();
    }
}

module.exports = LinkTextPlugin;
<commit_msg>rework regex<commit_after>/**
 * A plugin to identify unclear link text such as "more" and "click here,"
 * which can make for a bad experience when using a screen reader
 */

let $ = require("jquery");
let Plugin = require("../base");
let annotate = require("../shared/annotate")("link-text");

class LinkTextPlugin extends Plugin {
    getTitle() {
        return "Link text";
    }

    getDescription() {
        return `
            Identifies links that may be confusing when read by a screen
            reader
        `;
    }

    /**
     * Slightly modified unclear text checking that has been refactored into
     * a single method to be called with arbitrary strings.
     *
     * Original: https://github.com/GoogleChrome/accessibility-developer-tools/blob/9183b21cb0a02f5f04928f5cb7cb339b6bbc9ff8/src/audits/LinkWithUnclearPurpose.js#L55-67
     */
    isDescriptiveText(textContent) {
        let stopWords = [
            "click", "tap", "go", "here", "learn", "more", "this", "page",
            "link", "about"
        ];
        // Generate a regex to match each of the stopWords
        let stopWordsRE = new RegExp(`\\b(${stopWords.join("|")})\\b`, "ig");

        textContent = textContent
            // Strip leading non-alphabetical characters
            .replace(/[^a-zA-Z ]/g, "")
            // Remove the stopWords
            .replace(stopWordsRE, "");

        // Return whether or not there is any text left
        return textContent.trim() !== "";
    }

    /**
     * Checks whether or not the text content of an element (including things
     * like `aria-label`) is unclear.
     */
    validateTextContent(el) {
        let textContent = $.axs.properties.getTextFromDescendantContent(el);
        return {
            textContent: textContent,
            result: this.isDescriptiveText(textContent),
        };
    }

    /**
     * Checks if an image has descriptive alt text. This is used to determine
     * whether or not image links ( tags with a single  descendant)
     * are unclear.
     */
    validateAltText(el) {
        let altTextContent = el.getAttribute("alt");
        return {
            textContent: altTextContent,
            result: this.isDescriptiveText(altTextContent),
        };
    }

    reportError($el, description, textContent) {
        let entry = this.error("Link text is unclear", description, $el);
        annotate.errorLabel($el, "",
            `Link text "${textContent}" is unclear`, entry);
    }

    run() {
        $("a").each((i, el) => {
            let $el = $(el);

            // Ignore the tota11y UI
            if ($el.parents(".tota11y").length) {
                return;
            }

            // If this anchor contains a single image, we will test the
            // clarity of that image's alt text.
            if ($el.find("> img").length === 1) {
                let report = this.validateAltText($el.find("> img")[0]);

                if (!report.result) {
                    let description = `
                        The alt text for this link's image,
                        "${report.textContent}", is unclear without
                        context and may be confusing to screen readers.
                        Consider providing more detailed alt text.
                    `;

                    this.reportError($el, description, report.textContent);
                }
            } else {
                let report = this.validateTextContent(el);

                if (!report.result) {
                    let description = `
                        The text "${report.textContent}" is unclear
                        without context and may be confusing to screen readers.
                        Consider rearranging the <a></a>
                         tags or including special screen reader text.
                    `;

                    this.reportError($el, description, report.textContent);
                }
            }
        });
    }

    cleanup() {
        annotate.removeAll();
    }
}

module.exports = LinkTextPlugin;
<|endoftext|>


<commit_before>import { expect } from 'chai';
import Fibonacci from '../../src/math/Fibonacci';

describe('Fibonacci', () => {

  describe('Fibonacci.calculate()', () => {

    it('should return 8 given fib(6)', () => {
      const fib = new Fibonacci();
      const result = fib.calculate(6);
      expect(result).to.be.equal(8);
    });

  });

  describe('Fibonacci.calculate2()', () => {

    it('should return 13 given fib(7)', () => {
      const fib = new Fibonacci();
      const result = fib.calculate(7);
      expect(result).to.be.equal(13);
    });

  });

});
<commit_msg>added another test case<commit_after>import { expect } from 'chai';
import Fibonacci from '../../src/math/Fibonacci';

describe('Fibonacci', () => {

  describe('Fibonacci.calculate()', () => {

    it('should return 8 given fib(6)', () => {
      const fib = new Fibonacci();
      const result = fib.calculate(6);
      expect(result).to.be.equal(8);
    });

  });

  describe('Fibonacci.calculate2()', () => {
    it('should return 13 given fib(7)', () => {
      const fib = new Fibonacci();
      const result = fib.calculate(7);
      expect(result).to.be.equal(13);
    });
  });

});
<|endoftext|>


<commit_before>/*
==================================================================================================
  Jasy - JavaScript Tooling Refined
  Copyright 2010-2011 Sebastian Werner
==================================================================================================
*/

/**
 * @break {Permutation}
 * @require {Assert}
 * @require {fix.ObjectKeys}
 */
(function(global, undef)
{
	var cache = {};

	var genericToString = function() {
		return "[Module " + this.moduleName + "]";
	};

	var isModuleValue = +new Date;

	// Small hack to correctly bootstrap system
	global.Permutation = {
		getValue : function() {},
		isSet : function() {}
	};

	/**
	 * Define a module with static methods/fields.
	 *
	 * As there are new fields added to the member data structure and the module
	 * itself this is not feasible to being used as a structure for looping through
	 * via for-in loops.
	 *
	 * @param name {String} Name of Module
	 * @param members {Map} Data structure containing the members
	 */
	var Module = global.Module = function(name, members)
	{
		if (Permutation.isSet("debug"))
		{
			Assert.assertModuleName(name, "Invalid module name " + name + "!");
			Assert.assertMap(members, "Invalid map as module configuration in " + name + "!");
		}

		var prefix = name + ".";
		var value;

		for (var key in members)
		{
			value = members[key];

			// Performance would better using typeof but instanceof is required to exclude RegExps
			if (value instanceof Function) {
				value.displayName = prefix + key;
			}
		}

		// Add module name, implement toString() and valueOf()
		if(members.moduleName == null) {
			members.moduleName = name;
		}

		if(!members.hasOwnProperty("toString")) {
			members.toString = genericToString;
		}

		if(!members.hasOwnProperty("valueOf")) {
			members.valueOf = genericToString;
		}

		// Mark as module
		members.__isModule = isModuleValue;

		// Attach to name
		Module.declareName(name, members, true);
	};

	/**
	 * Declares the given name and stores the given object onto it.
	 *
	 * @param name {String} Namespace/Package e.g. foo.bar.baz
	 * @param object {Object} Any object
	 * @param duplicate {Boolean?false} Whether an error should be thrown when names are overwritten
	 * @return {Object} Returns the given object
	 */
	Module.declareName = function(name, object, duplicate)
	{
		if (duplicate && name in cache) {
			throw new Error("Namespace " + name + " is already in use by another object!");
		}

		var splits = name.split(".");
		var current = global;
		var length = splits.length-1;
		var segment;
		var i = 0;

		while(i<length)
		{
			segment = splits[i++];
			if (!(segment in current)) {
				current = current[segment] = {};
			} else {
				current = current[segment];
			}
		}

		// Store Object
		return cache[name] = current[splits[i]] = object;
	};

	/**
	 * Returns all registers names (modules, interfaces, classes, etc.)
	 *
	 * @return {Array}
	 */
	Module.getAllNames = function() {
		return Object.keys(cache);
	};

	/**
	 * Clears the object under the given name (incl cache)
	 *
	 * @param name {String} Clears the given name (Only works with stuff attached via {@see #declare})
	 * @return {Boolean} Whether clearing was successful
	 */
	Module.clearName = function(name)
	{
		if (name in cache)
		{
			delete cache[name];

			var current = global;
			var splitted = name.split(".");
			for (var i=0, l=splitted.length-1; i<l; i++) {
				current = current[splitted[i]];
			}

			// Delete might not work when global object is affected
			try{
				delete current[splitted[i]];
			} catch(ex) {
				current[splitted[i]] = undef;
			}

			return true;
		}

		return false;
	};

	/**
	 * Resolves a given name into the already existing object/class.
	 *
	 * @param name {String} Name to resolve
	 * @return {Object} Returns the object stored under the given name
	 */
	Module.resolveName = function(name)
	{
		var current = cache[name];
		if (!current)
		{
			current = global;
			if (name)
			{
				var splitted = name.split(".");
				for (var i=0, l=splitted.length; i<l; i++)
				{
					current = current[splitted[i]];
					if (!current)
					{
						current = null;
						break;
					}
				}
			}
		}

		return current;
	};

	/**
	 * Resolves a given Module name
	 *
	 * @param moduleName {String} Name to resolve
	 * @return {Object} Returns the Module stored under the given name
	 */
	Module.getByName = function(moduleName)
	{
		if (Permutation.isSet("debug")) {
			Assert.assertString(moduleName);
		}

		var obj = Module.resolveName(moduleName);
		return isModule(obj) ? obj : null;
	};

	/**
	 * Whether the given name is a valid module name.
	 *
	 * @param value {String} Any string
	 * @return {Boolean} Whether the given string is a valid module name
	 */
	var isModuleName = Module.isModuleName = function(value) {
		return /^(([a-z][a-z0-9]+\.)*)([A-Z][a-zA-Z0-9]*)$/.test(value);
	};

	/**
	 * Whether the given object is a Model
	 *
	 * @return {Boolean} Whether the given argument is an valid Model.
	 */
	var isModule = Module.isModule = function(module) {
		return !!(module && typeof module == "object" && module.__isModule === isModuleValue);
	}

	// Add assertion for module name
	Assert.add(isModuleName, "isModuleName", "Invalid module name!");

	// Add assertion for module type
	Assert.add(isModule, "isModule", "Invalid module!");

})(this);
<commit_msg>Function.bind() should still be fixed. Even if not used here.<commit_after>/*
==================================================================================================
  Jasy - JavaScript Tooling Refined
  Copyright 2010-2011 Sebastian Werner
==================================================================================================
*/

/**
 * @break {Permutation}
 * @require {Assert}
 * @require {fix.ObjectKeys}
 * @require {fix.FunctionBind}
 */
(function(global, undef)
{
	var cache = {};

	var genericToString = function() {
		return "[Module " + this.moduleName + "]";
	};

	var isModuleValue = +new Date;

	// Small hack to correctly bootstrap system
	global.Permutation = {
		getValue : function() {},
		isSet : function() {}
	};

	/**
	 * Define a module with static methods/fields.
	 *
	 * As there are new fields added to the member data structure and the module
	 * itself this is not feasible to being used as a structure for looping through
	 * via for-in loops.
	 *
	 * @param name {String} Name of Module
	 * @param members {Map} Data structure containing the members
	 */
	var Module = global.Module = function(name, members)
	{
		if (Permutation.isSet("debug"))
		{
			Assert.assertModuleName(name, "Invalid module name " + name + "!");
			Assert.assertMap(members, "Invalid map as module configuration in " + name + "!");
		}

		var prefix = name + ".";
		var value;

		for (var key in members)
		{
			value = members[key];

			// Performance would better using typeof but instanceof is required to exclude RegExps
			if (value instanceof Function) {
				value.displayName = prefix + key;
			}
		}

		// Add module name, implement toString() and valueOf()
		if(members.moduleName == null) {
			members.moduleName = name;
		}

		if(!members.hasOwnProperty("toString")) {
			members.toString = genericToString;
		}

		if(!members.hasOwnProperty("valueOf")) {
			members.valueOf = genericToString;
		}

		// Mark as module
		members.__isModule = isModuleValue;

		// Attach to name
		Module.declareName(name, members, true);
	};

	/**
	 * Declares the given name and stores the given object onto it.
	 *
	 * @param name {String} Namespace/Package e.g. foo.bar.baz
	 * @param object {Object} Any object
	 * @param duplicate {Boolean?false} Whether an error should be thrown when names are overwritten
	 * @return {Object} Returns the given object
	 */
	Module.declareName = function(name, object, duplicate)
	{
		if (duplicate && name in cache) {
			throw new Error("Namespace " + name + " is already in use by another object!");
		}

		var splits = name.split(".");
		var current = global;
		var length = splits.length-1;
		var segment;
		var i = 0;

		while(i<length)
		{
			segment = splits[i++];
			if (!(segment in current)) {
				current = current[segment] = {};
			} else {
				current = current[segment];
			}
		}

		// Store Object
		return cache[name] = current[splits[i]] = object;
	};

	/**
	 * Returns all registers names (modules, interfaces, classes, etc.)
	 *
	 * @return {Array}
	 */
	Module.getAllNames = function() {
		return Object.keys(cache);
	};

	/**
	 * Clears the object under the given name (incl cache)
	 *
	 * @param name {String} Clears the given name (Only works with stuff attached via {@see #declare})
	 * @return {Boolean} Whether clearing was successful
	 */
	Module.clearName = function(name)
	{
		if (name in cache)
		{
			delete cache[name];

			var current = global;
			var splitted = name.split(".");
			for (var i=0, l=splitted.length-1; i<l; i++) {
				current = current[splitted[i]];
			}

			// Delete might not work when global object is affected
			try{
				delete current[splitted[i]];
			} catch(ex) {
				current[splitted[i]] = undef;
			}

			return true;
		}

		return false;
	};

	/**
	 * Resolves a given name into the already existing object/class.
	 *
	 * @param name {String} Name to resolve
	 * @return {Object} Returns the object stored under the given name
	 */
	Module.resolveName = function(name)
	{
		var current = cache[name];
		if (!current)
		{
			current = global;
			if (name)
			{
				var splitted = name.split(".");
				for (var i=0, l=splitted.length; i<l; i++)
				{
					current = current[splitted[i]];
					if (!current)
					{
						current = null;
						break;
					}
				}
			}
		}

		return current;
	};

	/**
	 * Resolves a given Module name
	 *
	 * @param moduleName {String} Name to resolve
	 * @return {Object} Returns the Module stored under the given name
	 */
	Module.getByName = function(moduleName)
	{
		if (Permutation.isSet("debug")) {
			Assert.assertString(moduleName);
		}

		var obj = Module.resolveName(moduleName);
		return isModule(obj) ? obj : null;
	};

	/**
	 * Whether the given name is a valid module name.
	 *
	 * @param value {String} Any string
	 * @return {Boolean} Whether the given string is a valid module name
	 */
	var isModuleName = Module.isModuleName = function(value) {
		return /^(([a-z][a-z0-9]+\.)*)([A-Z][a-zA-Z0-9]*)$/.test(value);
	};

	/**
	 * Whether the given object is a Model
	 *
	 * @return {Boolean} Whether the given argument is an valid Model.
	 */
	var isModule = Module.isModule = function(module) {
		return !!(module && typeof module == "object" && module.__isModule === isModuleValue);
	}

	// Add assertion for module name
	Assert.add(isModuleName, "isModuleName", "Invalid module name!");

	// Add assertion for module type
	Assert.add(isModule, "isModule", "Invalid module!");

})(this);
<|endoftext|>


<commit_before>import EventEmitter from 'events';
import React from 'react';
import Router from 'react-router';
import Modal from 'react-bootstrap';

import './ui/navbar.js';

import Home from './pages/home.js';
import LoginModal from './modals/login.js';

var Route = Router.Route;
var RouteHandler = Router.RouteHandler

window.modal_instances = {}
React.render(<LoginModal/>, document.getElementById('modals'));

class App extends React.Component
{
    render() {
        return (<RouteHandler/>)
    }
}

class NoopRoute extends React.Component { render() { return null }}

var page_routes = (
    <Route handler={App}>
        <Route handler={Home} path="/home" />
        <Route handler={NoopRoute} path="login" />
    </Route>
);
var page_router = Router.create({
    routes: page_routes,
    location: Router.HistoryLocation
});
page_router.run((Root) => {
    if (Object.keys(modal_instances).indexOf(document.location.pathname) !== -1)
        modal_instances[document.location.pathname].setState({ show: true });
    else
        React.render(<Root/>, document.getElementById('app'));
});

document.body.addEventListener('click', (e) => {
    if (e.target.pathname) {
        history.pushState({}, '', e.target.pathname);
        page_router.refresh();
        e.preventDefault();
    }
});
<commit_msg>catch any errors during resolve<commit_after>import EventEmitter from 'events';
import React from 'react';
import Router from 'react-router';
import Modal from 'react-bootstrap';

import './ui/navbar.js';

import Home from './pages/home.js';
import LoginModal from './modals/login.js';

var Route = Router.Route;
var RouteHandler = Router.RouteHandler

window.modal_instances = {}
React.render(<LoginModal/>, document.getElementById('modals'));

class App extends React.Component
{
    render() {
        return (<RouteHandler/>)
    }
}

class NoopRoute extends React.Component { render() { return null }}

var page_routes = (
    <Route handler={App}>
        <Route handler={Home} path="/home" />
        <Route handler={NoopRoute} path="login" />
    </Route>
);
var page_router = Router.create({
    routes: page_routes,
    location: Router.HistoryLocation
});
page_router.run((Root) => {
    if (Object.keys(modal_instances).indexOf(document.location.pathname) !== -1)
        modal_instances[document.location.pathname].setState({ show: true });
    else
        React.render(<Root/>, document.getElementById('app'));
});

document.body.addEventListener('click', (e) => {
    if (e.target.pathname) {
        e.preventDefault();
        history.pushState({}, '', e.target.pathname);
        try {
            page_router.refresh();
        } catch (ex) {
            console.error(ex);
        }
    }
});
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'

import Input from './TextInputComponent'

// `PureComponent` is only available in React >= 15.3.0.
const PureComponent = React.PureComponent || React.Component

export default class TextInput extends PureComponent
{
	static propTypes =
	{
		// Text field label
		label            : PropTypes.string,

		// HTML form input `name` attribute
		name             : PropTypes.string,

		// Text field value
		value            : PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

		// Is called when the `value` is edited
		onChange         : PropTypes.func.isRequired,

		// A custom input component.
		inputComponent   : PropTypes.oneOfType
		([
			PropTypes.func,
			PropTypes.string
		]),

		// Disables the text field
		disabled         : PropTypes.bool,

		// Renders an error message below the `<input/>`
		error            : PropTypes.string,

		// If this flag is `true` then the `error` is shown.
		// If this flag is `false` then the `error` is not shown (even if passed).
		indicateInvalid  : PropTypes.bool,

		// Set to `true` to mark the field as required
		required         : PropTypes.bool,

		// `<input/>` placeholder
		placeholder      : PropTypes.string,

		// `<textarea/>` instead of an `<input type="text"/>`
		multiline        : PropTypes.bool,

		// Deprecated.
		// Use `type="email"` instead.
		// Sets HTML input `type` attribute to `email`
		email            : PropTypes.bool,

		// Deprecated.
		// Use `type="password"` instead.
		// Sets HTML input `type` attribute to `password`
		password         : PropTypes.bool,

		// Autofocuses the input field
		focus            : PropTypes.bool,

		// HTML `tabindex` attribute
		tabIndex         : PropTypes.number,

		// `<textarea/>` `rows` attribute (row count, i.e. height)
		rows             : PropTypes.number,

		// `<textarea/>` `cols` attribute (column count, i.e. width)
		cols             : PropTypes.number,

		// Is called when the input is focused
		onFocus          : PropTypes.func,

		// `onKeyDown` event handler
		onKeyDown        : PropTypes.func,

		// Is called when the input is blurred
		onBlur           : PropTypes.func,

		// Is called when the input is clicked
		onClick           : PropTypes.func,

		// CSS style object
		style            : PropTypes.object,

		// CSS name
		className        : PropTypes.string,

		// CSS style object for `<input/>`
		inputStyle       : PropTypes.object
	}

	static defaultProps =
	{
		// Show `error` (if passed).
		indicateInvalid : true
	}

	storeInputNode = (node) => this.input = node

	focus = () => this.input.focus()

	render()
	{
		const
		{
			indicateInvalid,
			error,
			style,
			className,
			// Deprecated.
			// Use `type="password"` instead.
			password,
			// Deprecated.
			// Use `type="email"` instead.
			email,
			...rest
		}
		= this.props

		// Deprecated.
		// Use `type="password"` instead.
		if (password) {
			rest.type = 'password'
		}

		// Deprecated.
		// Use `type="email"` instead.
		if (email) {
			rest.type = 'email'
		}

		return (

				<Input
					{...rest}
					inputRef={this.storeInputNode}
					error={error}
					indicateInvalid={indicateInvalid} />

				{/* Error message */}
				{ indicateInvalid && error &&

						{ error }

				}

		)
	}

	// render_static()
	// {
	// 	const { label } = this.props
	//
	// 	return (
	//

	// 			<Input {...this.props} placeholder={label} />
	//

	// 	)
	// }
}<commit_msg>`rrui__text-input--focus`<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'

import Input from './TextInputComponent'

// `PureComponent` is only available in React >= 15.3.0.
const PureComponent = React.PureComponent || React.Component

export default class TextInput extends PureComponent
{
	static propTypes =
	{
		// Text field label
		label            : PropTypes.string,

		// HTML form input `name` attribute
		name             : PropTypes.string,

		// Text field value
		value            : PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

		// Is called when the `value` is edited
		onChange         : PropTypes.func.isRequired,

		// A custom input component.
		inputComponent   : PropTypes.oneOfType
		([
			PropTypes.func,
			PropTypes.string
		]),

		// Disables the text field
		disabled         : PropTypes.bool,

		// Renders an error message below the `<input/>`
		error            : PropTypes.string,

		// If this flag is `true` then the `error` is shown.
		// If this flag is `false` then the `error` is not shown (even if passed).
		indicateInvalid  : PropTypes.bool,

		// Set to `true` to mark the field as required
		required         : PropTypes.bool,

		// `<input/>` placeholder
		placeholder      : PropTypes.string,

		// `<textarea/>` instead of an `<input type="text"/>`
		multiline        : PropTypes.bool,

		// Deprecated.
		// Use `type="email"` instead.
		// Sets HTML input `type` attribute to `email`
		email            : PropTypes.bool,

		// Deprecated.
		// Use `type="password"` instead.
		// Sets HTML input `type` attribute to `password`
		password         : PropTypes.bool,

		// Autofocuses the input field
		focus            : PropTypes.bool,

		// HTML `tabindex` attribute
		tabIndex         : PropTypes.number,

		// `<textarea/>` `rows` attribute (row count, i.e. height)
		rows             : PropTypes.number,

		// `<textarea/>` `cols` attribute (column count, i.e. width)
		cols             : PropTypes.number,

		// Is called when the input is focused
		onFocus          : PropTypes.func,

		// `onKeyDown` event handler
		onKeyDown        : PropTypes.func,

		// Is called when the input is blurred
		onBlur           : PropTypes.func,

		// Is called when the input is clicked
		onClick           : PropTypes.func,

		// CSS style object
		style            : PropTypes.object,

		// CSS name
		className        : PropTypes.string,

		// CSS style object for `<input/>`
		inputStyle       : PropTypes.object
	}

	static defaultProps =
	{
		// Show `error` (if passed).
		indicateInvalid : true
	}

	state = {}

	storeInputNode = (node) => this.input = node

	focus = () => this.input.focus()

	onFocus = () => this.setState({ isFocused: true })
	onBlur  = () => this.setState({ isFocused: false })

	render()
	{
		const
		{
			indicateInvalid,
			error,
			style,
			className,
			// Deprecated.
			// Use `type="password"` instead.
			password,
			// Deprecated.
			// Use `type="email"` instead.
			email,
			...rest
		}
		= this.props

		const { isFocused } = this.state

		// Deprecated.
		// Use `type="password"` instead.
		if (password) {
			rest.type = 'password'
		}

		// Deprecated.
		// Use `type="email"` instead.
		if (email) {
			rest.type = 'email'
		}

		return (

				<Input
					{...rest}
					inputRef={this.storeInputNode}
					error={error}
					indicateInvalid={indicateInvalid}
					onFocus={this.onFocus}
					onBlur={this.onBlur} />

				{/* Error message */}
				{ indicateInvalid && error &&

						{ error }

				}

		)
	}

	// render_static()
	// {
	// 	const { label } = this.props
	//
	// 	return (
	//

	// 			<Input {...this.props} placeholder={label} />
	//

	// 	)
	// }
}<|endoftext|>


<commit_before>/* globals jQuery */
/*!
 * TOGGLE elements with the same parent + add "open"-class
 */
; (function ($, undefined) {
    $(function () {
        $('.js-toggle').click(function () {
            var self = $(this);
            if (self.hasClass('open')) {
                self.parent().find('.js-hide').slideUp(300);
                self.removeClass('open');
            } else {
                self.addClass('open');
                self.parent().find('.js-hide').slideDown(300);
            }
            return false;
        })
    });
}(jQuery));

// Add dim class to panels

; (function ($, undefined) {
    $(function () {

        $('.index-heading').click(function () {
           if ($(this).hasClass('expanded')) {
               $(this).removeClass('expanded');
               if ($('.panel-heading.expanded').length === 0) {
                   $('.panel-heading').removeClass('dim');
               }
               else {
                   $(this).addClass('dim')
               }
           } else {
               $('.panel-heading').removeClass('expanded');
               $(this).addClass('expanded');
               $('.panel-heading').addClass('dim');
               $('.panel-heading.expanded').removeClass('dim');
           }
       });
    });
}(jQuery));

// Hide second level column menu when clicking on the active upper level item:
// (function ($) {
//   $(function () {
//     var upperLvlClicked = false; var stopPropagationNextClick = false
//     function handleClick (event) {
//       if (upperLvlClicked && !stopPropagationNextClick) {
//         stopPropagationNextClick = true
//         console.log($('.a-colnav.dropdown').children('li').eq(4).find('a'))
//         $('.a-colnav.dropdown').children('li').eq(4).find('a').click()
//       } else {
//         upperLvlClicked = true; stopPropagationNextClick = false
//       }
//     }
//     $('li.a-colnav').on('click', handleClick)
//     $('a.a-colnav-item').on('click', handleClick)
//   })
// }(jQuery))

// Adjust position of second level menu upon click:
(function ($) {
  $(function () {
    $('#colnav').on('mouseup', function (event) {
      var target = $(event.target); var second = $('.a-colnav-secondLevel')
      second.css('margin-left', '-1px')
      var getThird = function (el) {
        if (el.attr('class') === '.a-colnav-thirdLevel') return el
        else return el.find('.a-colnav-thirdLevel')
      }
      var findOpenThird = function (el) {
        var bool = false
        el.find('.a-colnav-thirdLevel').each(function () {
          if ($(this).attr('data-ignore') === 'false') bool = true
        })
        return bool
      }
      var isOpen = function (el) {
        var x = 'expanded'
        return (el.closest('a').hasClass(x) || el.find('a').hasClass(x) ||
          el.hasClass(x))
      }
      var ul = target.closest('ul')
      if (ul.hasClass('a-colnav-secondLevel' || 'a-colnav-thirdLevel')) {
        if (!findOpenThird(ul)) second.animate({ 'margin-left': '-78px' }, 125)
        else { second.css('margin-left', '-78px') }
        getThird(ul).css('margin-left', '-1px').css('left', '100%')
          .attr('data-ignore', 'false')
        if (ul.hasClass('a-colnav-secondLevel')) {
          ul.children('li').children('a').addClass('dim-second')
          target.closest('a').removeClass('dim-second')
          target.children('a').removeClass('dim-second')
          target.removeClass('dim-second')
        }
      } else if (ul.hasClass('a-colnav') && isOpen(target)) {
        $('.dim').removeClass('dim'); second.css('margin-left', '-10000px')
        getThird(ul).css('margin-left', '-10000px')
          .attr('data-ignore', 'true')
        $('.col-md-3').removeClass('col-md-3').addClass('col-md-6')
          .removeClass('col-md-offset-4').addClass('col-md-offset-1')
      } else {
        second.each(function () {
          getThird($(this)).attr('data-ignore', 'true')
        })
        $('.dim-second').removeClass('dim-second')
        $('.col-md-6').removeClass('col-md-6').addClass('col-md-3')
          .removeClass('col-md-offset-1').addClass('col-md-offset-4')
      }
    })
  })
}(jQuery))

// INPUT Focus style
// If state on input is "focus", add class to a-input : "a-input-focus"

; (function ($, undefined) {
    $(function () {

        $("input.form-control").focus(function(){
        $(this).parent().addClass("a-input-focus");

        }).blur(function(){
               $(this).parent().removeClass("a-input-focus");
        })
    });
}(jQuery));

// TOOLTIP AND POPOVERS

; (function ($, undefined) {
    $(function () {

      $('[data-toggle="tooltip"]').tooltip();

      $('[data-toggle="popover"]').popover();

      $('#example').popover(options);

    })
}(jQuery));

/*!
 * COLAPSE "Mobile navigation" + add "open"-class
 */
; (function ($, undefined) {

    $(function () {

        $('.ap-sideNav-mobilebar').click(function () {
            var self = $(this);
            var searchButton = $('.a-toggle-search').hasClass('open');

            if (self.hasClass('open')) {
                $('.ap-sideNav-collapse').slideUp(300);
                self.removeClass('open');
            } else {
                if (searchButton === true) {
                    $('.a-search').slideUp(300);
                    $('.a-toggle-search').removeClass('open');

                }
                self.addClass('open');
                $('.ap-sideNav-collapse').slideDown(300);
            }

            return false;
        })
    });

}(jQuery));

// Add dim class to colnav FIRST LEVEL (The panels that is not active)
// TODO: Combine first and second level javascript. On second level, make the items not DIM when menu is closed and another 2-level is opened (Reset)

; (function ($, undefined) {
    $(function () {

        $('.a-colnav-item').click(function () {
           if ($(this).hasClass('expanded')) {
               $(this).removeClass('expanded');
               if ($('.a-colnav-item.expanded').length === 0) {
                   $('.a-colnav-item').removeClass('dim-second-no');
               }
               else {
                   $(this).addClass('dim')
               }
           } else {
               $('.a-colnav-item').removeClass('expanded');
               $(this).addClass('expanded');
               $('.a-colnav-item').addClass('dim');
               $('.a-colnav-item.expanded').removeClass('dim');
           }
       });
    });
}(jQuery));

// Add dim class to colnav SECOND LEVEL

; (function ($, undefined) {
    $(function () {

        $('.a-colnav-item-second').click(function () {
           if ($(this).hasClass('expanded-second')) {
               $(this).removeClass('expanded-second');
               if ($('.a-colnav-item-second.expanded-second').length === 0) {
                   $('.a-colnav-item-second').removeClass('dim-second-no');
               }
               else {
                   $(this).addClass('dim-second')
               }
           } else {
               $('.a-colnav-item-second').removeClass('expanded-second');
               $(this).addClass('expanded-second');
               $('.a-colnav-item-second').addClass('dim-second');
               $('.a-colnav-item-second.expanded-second').removeClass('dim-second');
           }
       });
    });
}(jQuery));

/**
 * SmoothState
 */
$(function() {
  $('#main').smoothState();
});

/**
 * Anchor js
 * Add anchors to all h1s, h2s, h3s and h4s inside of .ap-content.
 */
anchors.options.placement = 'left';
anchors.options.class = 'a-anchor';
anchors.add('.ap-content h1, .ap-content h2, .ap-content h3, .ap-content h4');
<commit_msg>Separately hide/show filters on toggle.<commit_after>/* globals jQuery */
/*!
 * TOGGLE elements with the same parent + add "open"-class
 */
; (function ($, undefined) {
    $(function () {
        $('.js-toggle').click(function () {
            var self = $(this);
            if (self.hasClass('open')) {
                self.parent().find('.js-hide').slideUp(300);
                self.removeClass('open');
            } else {
                self.addClass('open');
                self.parent().find('.js-hide').slideDown(300);
            }
            return false;
        })
    });
}(jQuery));

// Add dim class to panels

; (function ($, undefined) {
    $(function () {

        $('.index-heading').click(function () {
           if ($(this).hasClass('expanded')) {
               $(this).removeClass('expanded');
               if ($('.panel-heading.expanded').length === 0) {
                   $('.panel-heading').removeClass('dim');
               }
               else {
                   $(this).addClass('dim')
               }
           } else {
               $('.panel-heading').removeClass('expanded');
               $(this).addClass('expanded');
               $('.panel-heading').addClass('dim');
               $('.panel-heading.expanded').removeClass('dim');
           }
       });
    });
}(jQuery));

// Hide second level column menu when clicking on the active upper level item:
// (function ($) {
//   $(function () {
//     var upperLvlClicked = false; var stopPropagationNextClick = false
//     function handleClick (event) {
//       if (upperLvlClicked && !stopPropagationNextClick) {
//         stopPropagationNextClick = true
//         console.log($('.a-colnav.dropdown').children('li').eq(4).find('a'))
//         $('.a-colnav.dropdown').children('li').eq(4).find('a').click()
//       } else {
//         upperLvlClicked = true; stopPropagationNextClick = false
//       }
//     }
//     $('li.a-colnav').on('click', handleClick)
//     $('a.a-colnav-item').on('click', handleClick)
//   })
// }(jQuery))

(function ($) {
  // Hide other filters upon filter toggle:
  $(function () {
    $('.a-collapseFilter').on('mouseup', function () {
      $('.a-collapseContent').removeClass('in')
      $('.a-collapseFilter').addClass('collapsed')
      $(this).removeClass('collapsed')
    })
  })
  // Adjust position of second level menu upon click:
  $(function () {
    $('#colnav').on('mouseup', function (event) {
      var target = $(event.target); var second = $('.a-colnav-secondLevel')
      second.css('margin-left', '-1px')
      var getThird = function (el) {
        if (el.attr('class') === '.a-colnav-thirdLevel') return el
        else return el.find('.a-colnav-thirdLevel')
      }
      var findOpenThird = function (el) {
        var bool = false
        el.find('.a-colnav-thirdLevel').each(function () {
          if ($(this).attr('data-ignore') === 'false') bool = true
        })
        return bool
      }
      var isOpen = function (el) {
        var x = 'expanded'
        return (el.closest('a').hasClass(x) || el.find('a').hasClass(x) ||
          el.hasClass(x))
      }
      var ul = target.closest('ul')
      if (ul.hasClass('a-colnav-secondLevel' || 'a-colnav-thirdLevel')) {
        if (!findOpenThird(ul)) second.animate({ 'margin-left': '-78px' }, 125)
        else { second.css('margin-left', '-78px') }
        getThird(ul).css('margin-left', '-1px').css('left', '100%')
          .attr('data-ignore', 'false')
        if (ul.hasClass('a-colnav-secondLevel')) {
          ul.children('li').children('a').addClass('dim-second')
          target.closest('a').removeClass('dim-second')
          target.children('a').removeClass('dim-second')
          target.removeClass('dim-second')
        }
      } else if (ul.hasClass('a-colnav') && isOpen(target)) {
        $('.dim').removeClass('dim'); second.css('margin-left', '-10000px')
        getThird(ul).css('margin-left', '-10000px')
          .attr('data-ignore', 'true')
        $('.col-md-3').removeClass('col-md-3').addClass('col-md-6')
          .removeClass('col-md-offset-4').addClass('col-md-offset-1')
      } else {
        second.each(function () {
          getThird($(this)).attr('data-ignore', 'true')
        })
        $('.dim-second').removeClass('dim-second')
        $('.col-md-6').removeClass('col-md-6').addClass('col-md-3')
          .removeClass('col-md-offset-1').addClass('col-md-offset-4')
      }
    })
  })
}(jQuery))

// INPUT Focus style
// If state on input is "focus", add class to a-input : "a-input-focus"

; (function ($, undefined) {
    $(function () {

        $("input.form-control").focus(function(){
        $(this).parent().addClass("a-input-focus");

        }).blur(function(){
               $(this).parent().removeClass("a-input-focus");
        })
    });
}(jQuery));

// TOOLTIP AND POPOVERS

; (function ($, undefined) {
    $(function () {

      $('[data-toggle="tooltip"]').tooltip();

      $('[data-toggle="popover"]').popover();

      $('#example').popover(options);

    })
}(jQuery));

/*!
 * COLAPSE "Mobile navigation" + add "open"-class
 */
; (function ($, undefined) {

    $(function () {

        $('.ap-sideNav-mobilebar').click(function () {
            var self = $(this);
            var searchButton = $('.a-toggle-search').hasClass('open');

            if (self.hasClass('open')) {
                $('.ap-sideNav-collapse').slideUp(300);
                self.removeClass('open');
            } else {
                if (searchButton === true) {
                    $('.a-search').slideUp(300);
                    $('.a-toggle-search').removeClass('open');

                }
                self.addClass('open');
                $('.ap-sideNav-collapse').slideDown(300);
            }

            return false;
        })
    });

}(jQuery));

// Add dim class to colnav FIRST LEVEL (The panels that is not active)
// TODO: Combine first and second level javascript. On second level, make the items not DIM when menu is closed and another 2-level is opened (Reset)

; (function ($, undefined) {
    $(function () {

        $('.a-colnav-item').click(function () {
           if ($(this).hasClass('expanded')) {
               $(this).removeClass('expanded');
               if ($('.a-colnav-item.expanded').length === 0) {
                   $('.a-colnav-item').removeClass('dim-second-no');
               }
               else {
                   $(this).addClass('dim')
               }
           } else {
               $('.a-colnav-item').removeClass('expanded');
               $(this).addClass('expanded');
               $('.a-colnav-item').addClass('dim');
               $('.a-colnav-item.expanded').removeClass('dim');
           }
       });
    });
}(jQuery));

// Add dim class to colnav SECOND LEVEL

; (function ($, undefined) {
    $(function () {

        $('.a-colnav-item-second').click(function () {
           if ($(this).hasClass('expanded-second')) {
               $(this).removeClass('expanded-second');
               if ($('.a-colnav-item-second.expanded-second').length === 0) {
                   $('.a-colnav-item-second').removeClass('dim-second-no');
               }
               else {
                   $(this).addClass('dim-second')
               }
           } else {
               $('.a-colnav-item-second').removeClass('expanded-second');
               $(this).addClass('expanded-second');
               $('.a-colnav-item-second').addClass('dim-second');
               $('.a-colnav-item-second.expanded-second').removeClass('dim-second');
           }
       });
    });
}(jQuery));

/**
 * SmoothState
 */
$(function() {
  $('#main').smoothState();
});

/**
 * Anchor js
 * Add anchors to all h1s, h2s, h3s and h4s inside of .ap-content.
 */
anchors.options.placement = 'left';
anchors.options.class = 'a-anchor';
anchors.add('.ap-content h1, .ap-content h2, .ap-content h3, .ap-content h4');
<|endoftext|>