<commit_before>import React, { Component } from 'react'
import { Route } from 'react-router'
import {
  contentFeedLike,
  fetchFeed,
  fetchUserFeeds,
  fetchMoreUserFeeds,
  clearFeeds,
  uploadFeedComment
} from 'redux/actions/FeedActions'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import Loading from 'components/Loading'
import ContentPanel from '../../ContentPanel'
import LoadMoreButton from 'components/LoadMoreButton'
import { addEvent, removeEvent } from 'helpers/listenerHelpers'

class Body extends Component {
  static propTypes = {
    chatMode: PropTypes.bool,
    clearFeeds: PropTypes.func.isRequired,
    contentFeedLike: PropTypes.func.isRequired,
    feeds: PropTypes.array,
    fetchFeed: PropTypes.func.isRequired,
    fetchMoreUserFeeds: PropTypes.func.isRequired,
    fetchUserFeeds: PropTypes.func.isRequired,
    history: PropTypes.object.isRequired,
    loaded: PropTypes.bool.isRequired,
    loadMoreButton: PropTypes.bool.isRequired,
    location: PropTypes.object.isRequired,
    match: PropTypes.object.isRequired,
    uploadFeedComment: PropTypes.func.isRequired,
    myId: PropTypes.number
  }

  constructor() {
    super()
    this.state = {
      currentTab: 'all',
      loading: false
    }
    this.changeTab = this.changeTab.bind(this)
    this.onNoFeed = this.onNoFeed.bind(this)
    this.onScroll = this.onScroll.bind(this)
    this.loadMoreFeeds = this.loadMoreFeeds.bind(this)
  }

  componentDidMount() {
    const { match, location, clearFeeds } = this.props
    this.mounted = true
    addEvent(window, 'scroll', this.onScroll)
    return clearFeeds().then(() => {
      switch (location.pathname) {
        case match.url:
          return this.changeTab('all')
        case `${match.url}/questions`:
          return this.changeTab('question')
        case `${match.url}/comments`:
          return this.changeTab('comment')
        case `${match.url}/videos`:
          return this.changeTab('video')
        case `${match.url}/links`:
          return this.changeTab('url')
        case `${match.url}/discussions`:
          return this.changeTab('discussion')
        default:
          break
      }
    })
  }

  componentDidUpdate(prevProps) {
    const { match, location, clearFeeds } = this.props

    if (prevProps.location !== this.props.location) {
      return clearFeeds().then(() => {
        switch (location.pathname) {
          case match.url:
            return this.changeTab('all')
          case `${match.url}/questions`:
            return this.changeTab('question')
          case `${match.url}/comments`:
            return this.changeTab('comment')
          case `${match.url}/videos`:
            return this.changeTab('video')
          case `${match.url}/links`:
            return this.changeTab('url')
          case `${match.url}/discussions`:
            return this.changeTab('discussion')
          default:
            break
        }
      })
    }
  }

  componentWillUnmount() {
    this.mounted = false
    removeEvent(window, 'scroll', this.onScroll)
  }

  render() {
    const {
      contentFeedLike,
      match: route,
      match: { params: { username } },
      history,
      feeds,
      fetchFeed,
      myId,
      loaded,
      loadMoreButton,
      clearFeeds,
      uploadFeedComment
    } = this.props
    const { loading } = this.state

    return (

            <Route
              exact
              path={route.url}
              children={({ match }) => (

                    clearFeeds().then(() => history.push(route.url))
                  }
                >
                  All

              )}
            />
            <Route
              exact
              path={`${route.url}/questions`}
              children={({ match }) => (

                    clearFeeds().then(() =>
                      history.push(`${route.url}/questions`)
                    )
                  }
                >
                  Questions

              )}
            />
            <Route
              exact
              path={`${route.url}/comments`}
              children={({ match }) => (

                    clearFeeds().then(() =>
                      history.push(`${route.url}/comments`)
                    )
                  }
                >
                  Comments

              )}
            />
            <Route
              exact
              path={`${route.url}/videos`}
              children={({ match }) => (

                    clearFeeds().then(() => history.push(`${route.url}/videos`))
                  }
                >
                  Videos

              )}
            />
            <Route
              exact
              path={`${route.url}/links`}
              children={({ match }) => (

                    clearFeeds().then(() => history.push(`${route.url}/links`))
                  }
                >
                  Links

              )}
            />
            <Route
              exact
              path={`${route.url}/discussions`}
              children={({ match }) => (

                    clearFeeds().then(() =>
                      history.push(`${route.url}/discussions`)
                    )
                  }
                >
                  Discussions

              )}
            />

          {!loaded && <Loading />}
          {loaded &&
            feeds.length > 0 && (

                {feeds.map(feed => {
                  return (
                    <ContentPanel
                      key={`${feed.type}${feed.id}`}
                      onLikeClick={contentFeedLike}
                      feed={feed}
                      userId={myId}
                      fetchFeed={fetchFeed}
                      uploadFeedComment={uploadFeedComment}
                    />
                  )
                })}

            )}
          {loaded &&
            feeds.length === 0 && (

                {this.onNoFeed(username)}

            )}

        {loadMoreButton && (
          <LoadMoreButton onClick={this.loadMoreFeeds} loading={loading} />
        )}

    )
  }

  changeTab(tabName) {
    const { match: { params: { username } }, fetchUserFeeds } = this.props
    if (this.mounted) {
      this.setState({ currentTab: tabName })
    }
    fetchUserFeeds(username, tabName)
  }

  loadMoreFeeds() {
    const {
      match: { params: { username } },
      fetchMoreUserFeeds,
      feeds
    } = this.props
    const { currentTab, loading } = this.state

    if (!loading) {
      this.setState({ loading: true })
      return fetchMoreUserFeeds(
        username,
        currentTab,
        feeds[feeds.length - 1].id
      ).then(() => this.setState({ loading: false }))
    }
  }

  onNoFeed(username) {
    const { currentTab } = this.state
    switch (currentTab) {
      case 'all':
        return `${username} has not posted a anything yet`
      case 'question':
        return `${username} has not posted a question yet`
      case 'comment':
        return `${username} has not posted a comment yet`
      case 'url':
        return `${username} has not posted a link yet`
      case 'video':
        return `${username} has not posted a video yet`
      case 'discussion':
        return `${username} has not posted a discussion yet`
    }
  }

  onScroll() {
    let { chatMode, feeds } = this.props
    const scrollPosition =
      document.documentElement.scrollTop || document.body.scrollTop
    if (!chatMode && feeds.length > 0) {
      this.setState({ scrollPosition })
      if (
        this.state.scrollPosition >=
        (document.body.scrollHeight - window.innerHeight) * 0.7
      ) {
        this.loadMoreFeeds()
      }
    }
  }
}

export default connect(
  state => ({
    chatMode: state.ChatReducer.chatMode,
    feeds: state.FeedReducer.feeds,
    loaded: state.FeedReducer.loaded,
    myId: state.UserReducer.userId,
    loadMoreButton: state.FeedReducer.loadMoreButton,
    homeComponentConnected: state.FeedReducer.homeComponentConnected
  }),
  {
    contentFeedLike,
    fetchFeed,
    fetchUserFeeds,
    fetchMoreUserFeeds,
    uploadFeedComment,
    clearFeeds
  }
)(Body)
<commit_msg>profile panel refactored as well<commit_after>import React, { Component } from 'react'
import { Route } from 'react-router'
import {
  commentFeedLike,
  contentFeedLike,
  feedCommentDelete,
  feedCommentEdit,
  feedContentDelete,
  feedVideoStar,
  fetchFeed,
  fetchUserFeeds,
  fetchMoreUserFeeds,
  likeTargetComment,
  clearFeeds,
  loadMoreFeedCommentsAsync,
  loadMoreFeedReplies,
  questionFeedLike,
  showFeedCommentsAsync,
  uploadFeedComment,
  uploadFeedReply,
  uploadTargetContentComment
} from 'redux/actions/FeedActions'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import Loading from 'components/Loading'
import ContentPanel from '../../ContentPanel'
import LoadMoreButton from 'components/LoadMoreButton'
import { addEvent, removeEvent } from 'helpers/listenerHelpers'

class Body extends Component {
  static propTypes = {
    chatMode: PropTypes.bool,
    clearFeeds: PropTypes.func.isRequired,
    commentFeedLike: PropTypes.func.isRequired,
    contentFeedLike: PropTypes.func.isRequired,
    feeds: PropTypes.array,
    feedCommentDelete: PropTypes.func.isRequired,
    feedCommentEdit: PropTypes.func.isRequired,
    feedContentDelete: PropTypes.func.isRequired,
    feedVideoStar: PropTypes.func.isRequired,
    fetchFeed: PropTypes.func.isRequired,
    fetchMoreUserFeeds: PropTypes.func.isRequired,
    fetchUserFeeds: PropTypes.func.isRequired,
    history: PropTypes.object.isRequired,
    likeTargetComment: PropTypes.func.isRequired,
    loaded: PropTypes.bool.isRequired,
    loadMoreFeedCommentsAsync: PropTypes.func.isRequired,
    loadMoreButton: PropTypes.bool.isRequired,
    loadMoreFeedReplies: PropTypes.func.isRequired,
    location: PropTypes.object.isRequired,
    match: PropTypes.object.isRequired,
    questionFeedLike: PropTypes.func.isRequired,
    showFeedCommentsAsync: PropTypes.func.isRequired,
    uploadFeedComment: PropTypes.func.isRequired,
    uploadFeedReply: PropTypes.func.isRequired,
    uploadTargetContentComment: PropTypes.func.isRequired,
    myId: PropTypes.number
  }

  constructor() {
    super()
    this.state = {
      currentTab: 'all',
      loading: false
    }
    this.changeTab = this.changeTab.bind(this)
    this.onNoFeed = this.onNoFeed.bind(this)
    this.onScroll = this.onScroll.bind(this)
    this.loadMoreFeeds = this.loadMoreFeeds.bind(this)
  }

  componentDidMount() {
    const { match, location, clearFeeds } = this.props
    this.mounted = true
    addEvent(window, 'scroll', this.onScroll)
    return clearFeeds().then(() => {
      switch (location.pathname) {
        case match.url:
          return this.changeTab('all')
        case `${match.url}/questions`:
          return this.changeTab('question')
        case `${match.url}/comments`:
          return this.changeTab('comment')
        case `${match.url}/videos`:
          return this.changeTab('video')
        case `${match.url}/links`:
          return this.changeTab('url')
        case `${match.url}/discussions`:
          return this.changeTab('discussion')
        default:
          break
      }
    })
  }

  componentDidUpdate(prevProps) {
    const { match, location, clearFeeds } = this.props

    if (prevProps.location !== this.props.location) {
      return clearFeeds().then(() => {
        switch (location.pathname) {
          case match.url:
            return this.changeTab('all')
          case `${match.url}/questions`:
            return this.changeTab('question')
          case `${match.url}/comments`:
            return this.changeTab('comment')
          case `${match.url}/videos`:
            return this.changeTab('video')
          case `${match.url}/links`:
            return this.changeTab('url')
          case `${match.url}/discussions`:
            return this.changeTab('discussion')
          default:
            break
        }
      })
    }
  }

  componentWillUnmount() {
    this.mounted = false
    removeEvent(window, 'scroll', this.onScroll)
  }

  render() {
    const {
      commentFeedLike,
      contentFeedLike,
      match: route,
      match: { params: { username } },
      history,
      likeTargetComment,
      loadMoreFeedReplies,
      feeds,
      feedCommentDelete,
      feedCommentEdit,
      feedContentDelete,
      feedVideoStar,
      fetchFeed,
      loadMoreFeedCommentsAsync,
      myId,
      loaded,
      loadMoreButton,
      clearFeeds,
      questionFeedLike,
      showFeedCommentsAsync,
      uploadFeedComment,
      uploadFeedReply,
      uploadTargetContentComment
    } = this.props
    const { loading } = this.state

    return (

            <Route
              exact
              path={route.url}
              children={({ match }) => (

                    clearFeeds().then(() => history.push(route.url))
                  }
                >
                  All

              )}
            />
            <Route
              exact
              path={`${route.url}/questions`}
              children={({ match }) => (

                    clearFeeds().then(() =>
                      history.push(`${route.url}/questions`)
                    )
                  }
                >
                  Questions

              )}
            />
            <Route
              exact
              path={`${route.url}/comments`}
              children={({ match }) => (

                    clearFeeds().then(() =>
                      history.push(`${route.url}/comments`)
                    )
                  }
                >
                  Comments

              )}
            />
            <Route
              exact
              path={`${route.url}/videos`}
              children={({ match }) => (

                    clearFeeds().then(() => history.push(`${route.url}/videos`))
                  }
                >
                  Videos

              )}
            />
            <Route
              exact
              path={`${route.url}/links`}
              children={({ match }) => (

                    clearFeeds().then(() => history.push(`${route.url}/links`))
                  }
                >
                  Links

              )}
            />
            <Route
              exact
              path={`${route.url}/discussions`}
              children={({ match }) => (

                    clearFeeds().then(() =>
                      history.push(`${route.url}/discussions`)
                    )
                  }
                >
                  Discussions

              )}
            />

          {!loaded && <Loading />}
          {loaded &&
            feeds.length > 0 && (

                {feeds.map(feed => {
                  return (
                    <ContentPanel
                      key={`${feed.type}${feed.id}`}
                      feed={feed}
                      userId={myId}
                      methods={{
                        ContentPanel: {
                          fetchContent: fetchFeed
                        },
                        Heading: {
                          onUploadAnswer: uploadFeedComment,
                          onLikeClick: contentFeedLike
                        },
                        Contents: {
                          commentActions: {
                            onDelete: feedCommentDelete,
                            onLikeClick: commentFeedLike,
                            onEditDone: feedCommentEdit,
                            onReplySubmit: uploadFeedReply,
                            onLoadMoreReplies: loadMoreFeedReplies
                          },
                          feedVideoStar,
                          loadMoreComments: loadMoreFeedCommentsAsync,
                          onCommentSubmit: uploadFeedComment,
                          onContentDelete: feedContentDelete,
                          onLikeCommentClick: commentFeedLike,
                          onLikeQuestionClick: questionFeedLike,
                          onLikeContentClick: contentFeedLike,
                          showFeedComments: showFeedCommentsAsync,
                          TargetContent: {
                            onDeleteComment: feedCommentDelete,
                            onEditComment: feedCommentEdit,
                            onLikeClick: likeTargetComment,
                            uploadComment: uploadTargetContentComment
                          }
                        }
                      }}
                    />
                  )
                })}

            )}
          {loaded &&
            feeds.length === 0 && (

                {this.onNoFeed(username)}

            )}

        {loadMoreButton && (
          <LoadMoreButton onClick={this.loadMoreFeeds} loading={loading} />
        )}

    )
  }

  changeTab(tabName) {
    const { match: { params: { username } }, fetchUserFeeds } = this.props
    if (this.mounted) {
      this.setState({ currentTab: tabName })
    }
    fetchUserFeeds(username, tabName)
  }

  loadMoreFeeds() {
    const {
      match: { params: { username } },
      fetchMoreUserFeeds,
      feeds
    } = this.props
    const { currentTab, loading } = this.state

    if (!loading) {
      this.setState({ loading: true })
      return fetchMoreUserFeeds(
        username,
        currentTab,
        feeds[feeds.length - 1].id
      ).then(() => this.setState({ loading: false }))
    }
  }

  onNoFeed(username) {
    const { currentTab } = this.state
    switch (currentTab) {
      case 'all':
        return `${username} has not posted a anything yet`
      case 'question':
        return `${username} has not posted a question yet`
      case 'comment':
        return `${username} has not posted a comment yet`
      case 'url':
        return `${username} has not posted a link yet`
      case 'video':
        return `${username} has not posted a video yet`
      case 'discussion':
        return `${username} has not posted a discussion yet`
    }
  }

  onScroll() {
    let { chatMode, feeds } = this.props
    const scrollPosition =
      document.documentElement.scrollTop || document.body.scrollTop
    if (!chatMode && feeds.length > 0) {
      this.setState({ scrollPosition })
      if (
        this.state.scrollPosition >=
        (document.body.scrollHeight - window.innerHeight) * 0.7
      ) {
        this.loadMoreFeeds()
      }
    }
  }
}

export default connect(
  state => ({
    chatMode: state.ChatReducer.chatMode,
    feeds: state.FeedReducer.feeds,
    loaded: state.FeedReducer.loaded,
    myId: state.UserReducer.userId,
    loadMoreButton: state.FeedReducer.loadMoreButton,
    homeComponentConnected: state.FeedReducer.homeComponentConnected
  }),
  {
    contentFeedLike,
    fetchFeed,
    fetchUserFeeds,
    fetchMoreUserFeeds,
    clearFeeds,
    commentFeedLike,
    feedCommentDelete,
    feedContentDelete,
    feedCommentEdit,
    feedVideoStar,
    likeTargetComment,
    loadMoreFeedCommentsAsync,
    loadMoreFeedReplies,
    questionFeedLike,
    showFeedCommentsAsync,
    uploadFeedComment,
    uploadFeedReply,
    uploadTargetContentComment
  }
)(Body)
<|endoftext|>


<commit_before>import _ from 'lodash'
import invariant from 'invariant'

import { awaitHash } from './utils'

const rules = {
  // async validator(fieldValue, param, fieldName, fields, schema)
  required: (fieldValue, required, fieldName) => (
    !fieldValue
      && required
      && `field "${fieldName}" is required`
  ),
  minLength: (fieldValue, minValue, fieldName) => (
    (fieldValue.length < minValue)
      && `field "${fieldName}" must have at least ${minValue} characters`
  ),
  maxLength: (fieldValue, maxValue, fieldName) => (
    (fieldValue.length > maxValue)
      && `field "${fieldName}" must have at most ${minValue} characters`
  ),
  match: (fieldValue, pattern, fieldName) => (
    !`${fieldValue}`.match(pattern)
      && `field "${fieldName}" does not match`
  )
}

const typeValidators = {
  number: _.isNumber,
  string: _.isString
}

const validateField = async (fieldSchema, fieldName, schema, data) => {
  const value = data[fieldName]

  // Validate type.
  /*
  const isValid = typeValidators[fieldSchema.type](value)
  if (!isValid) {
    return 'invalid type'
  }
  */

  // Validate rules.
  let error
  _.some(fieldSchema.rules, (param, ruleName) => {
    const rule = rules[ruleName]
    invariant(
      !!rule,
      `rule "${ruleName}" is not defined`
    )

    error = rules[ruleName](
      value, param, fieldName, data, schema
    )
    return error
  })

  return error
}

export const validate = async (schema, data, options) => {
  // `pickBy` removes the valid fields from the errors hash.
  const errors = _.pickBy(
    await awaitHash(_.mapValues(
      schema, _.partialRight(validateField, data)
    ))
  )

  return _.isEmpty(errors) ? null : errors
}
<commit_msg>Custom messages<commit_after>import _ from 'lodash'
import invariant from 'invariant'

import { awaitHash } from './utils'

const rules = {
  // async validator(fieldValue, param, fieldName, fields, schema)
  required: (fieldValue, required, fieldName) => (
    !fieldValue
      && required
      && `field "${fieldName}" is required`
  ),
  min: (fieldValue, minValue, fieldName) => (
    (fieldValue < minValue)
      && `field "${fieldName}" must not be less than ${minValue}`
  ),
  max: (fieldValue, maxValue, fieldName) => (
    (fieldValue > maxValue)
      && `field "${fieldName}" must not be greater than ${maxValue}`
  ),
  minLength: (fieldValue, minValue, fieldName) => (
    (fieldValue.length < minValue)
      && `field "${fieldName}" must have at least ${minValue} characters`
  ),
  maxLength: (fieldValue, maxValue, fieldName) => (
    (fieldValue.length > maxValue)
      && `field "${fieldName}" must have at most ${maxValue} characters`
  ),
  match: (fieldValue, pattern, fieldName) => (
    !`${fieldValue}`.match(pattern)
      && `field "${fieldName}" does not match`
  )
}

const typeValidators = {
  number: _.isNumber,
  string: _.isString
}

const validateField = async (fieldSchema, fieldName, schema, data) => {
  const value = data[fieldName]

  // Validate type.
  /*
  const isValid = typeValidators[fieldSchema.type](value)
  if (!isValid) {
    return 'invalid type'
  }
  */

  // Validate rules.
  let error
  _.some(fieldSchema.rules, (param, ruleName) => {
    const rule = rules[ruleName]
    invariant(
      !!rule,
      `no rule named "${ruleName}"`
    )

    if (_.isObject(param) && !_.isUndefined(param.param)) {
      const error = rules[ruleName](
        value, param.param, fieldName, data, schema
      )
      return error && (param.error || error)
    } else {
      return rules[ruleName](
        value, param, fieldName, data, schema
      )
    }
  })

  return error
}

export const validate = async (schema, data, options) => {
  // `pickBy` removes the valid fields from the errors hash.
  const errors = _.pickBy(
    await awaitHash(_.mapValues(
      schema, _.partialRight(validateField, data)
    ))
  )

  return _.isEmpty(errors) ? null : errors
}
<|endoftext|>


<commit_before>;(function ($, window, document, undefined) {

  // create the defaults once
  var pluginName = 'dateRangePicker';

  var defaults = {
    container: null,
    numberOfMonths: 3,
    datepickerShowing: true,
    defaultDate: '-1D',
    defaultDateRange: 'LAST_7_DAYS',
    maxDate: '-1D',
    minDate: new Date(2011, 0, 1),
    test: false,
    today: null
  };

  // the actual plugin constructor
  function DateRangePicker (element, options) {
    this.element = element;
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  // avoid Plugin.prototype conflicts
  $.extend(DateRangePicker.prototype, {

    init: function () {
      this.setupContainer();
      this.initializeDateRange();
      this.initializeDatePicker();
    },

    setupContainer: function () {

      var dates = 'Dates:' +
        '<input type="text" id="drp-input-startdate" size="10" readonly> -' +
        ' <input type="text" id="drp-input-enddate" size="10" readonly>';

      var select = '<select id="drp-select-daterange">' +
        '<option value="CUSTOM" selected>Custom</option>' +
        '<option value="MONTH_TO_DATE">Month To Date</option>' +
        '<option value="YEAR_TO_DATE">Year To Date</option>' +
        '<option value="LAST_WEEK">Last Week</option>' +
        '<option value="LAST_MONTH">Last Month</option>' +
        '<option value="LAST_7_DAYS">Last 7 Days</option>' +
        '<option value="LAST_30_DAYS">Last 30 Days</option>' +
        '</select>';

      var controls = 'cancel' +
        '<button id="drp-btn-apply">Apply</button>';

      var datepickerContainer = '

';

      var $container = $(this.settings.container);
      $container.html(dates + select + controls + datepickerContainer);

      this._$startDate = $('#drp-input-startdate');
      this._$endDate = $('#drp-input-enddate');
      this._$selectedDateRange = $('#drp-select-daterange');
      this._$cancel = $('#drp-btn-cancel');
      this._$apply = $('#drp-btn-apply');
      this._$datepicker = $('#drp-container-datepicker');
      this._$element = $('#'+ this.element.id + '');
      this._$container = $(this.settings.container);

    },

    getDateRange: function (option) {

      var settings = this.settings;

      var dateRange = {
        start: '',
        end: ''
      };

      var today = function () {
        return settings.test ? moment(settings.today) : moment();
      };

      var daysToSubtract;
      var dayOfTheWeek;

      switch (option) {

        case 'MONTH_TO_DATE':
          var dayOfTheMonth = today().date() - 1;
          dateRange.start = today().subtract(dayOfTheMonth, 'days').format('ll');
          dateRange.end = today().subtract(1, 'days').format('ll');
          break;

        case 'YEAR_TO_DATE':
          var dayOfTheYear = today().dayOfYear() - 1;
          dateRange.start = today().subtract(dayOfTheYear, 'days').format('ll');
          dateRange.end = today().subtract(1, 'days').format('ll');
          break;

        case 'LAST_WEEK':
          var lastWeek = today().subtract(1, 'weeks');
          daysToSubtract = lastWeek.day();
          dayOfTheWeek = today().day() + 1;
          dateRange.start = moment(lastWeek).subtract(daysToSubtract, 'days').format('ll');
          dateRange.end = today().subtract(dayOfTheWeek, 'days').format('ll');
          break;

        case 'LAST_MONTH':
          var lastMonth = today().subtract(1, 'months');
          daysToSubtract = lastMonth.date() - 1;
          dayOfTheMonth = today().date();
          dateRange.start = moment(lastMonth).subtract(daysToSubtract, 'days').format('ll');
          dateRange.end = today().subtract(dayOfTheMonth, 'days').format('ll');
          break;

        case 'LAST_7_DAYS':
          dateRange.start = today().subtract(7, 'days').format('ll');
          dateRange.end = today().subtract(1, 'days').format('ll');
          break;

        case 'LAST_30_DAYS':
          dateRange.start = today().subtract(30, 'days').format('ll');
          dateRange.end = today().subtract(1, 'days').format('ll');
          break;

        case 'CUSTOM':
          dateRange.start = this._$startDate.val();
          dateRange.end = this._$endDate.val();
          break;

        default:
          dateRange.start = today().subtract(30, 'days').format('ll');
          dateRange.end = today().subtract(1, 'days').format('ll');

      }

      return dateRange;

    },

    initializeDateRange: function () {

      var dateRange = this.getDateRange(this.settings.defaultDateRange);

      this._$element.val(dateRange.start + ' - ' + dateRange.end);
      this._$startDate.val(dateRange.start);
      this._$endDate.val(dateRange.end);

    },

    initializeDatePicker: function () {

      var self = this;

      $('#drp-container-datepicker').datepicker({
        numberOfMonths: 3,
        datepickerShowing: true,
        dateFormat: 'M dd, yy', // ex. Aug 30, 2014
        defaultDate: '-1D',
        maxDate: '-1D',
        minDate: this.settings.minDate,

        beforeShowDay: function (date) {

          var start = self._$startDate.val();
          var end = self._$endDate.val();

          var startDate = $.datepicker.parseDate('M dd, yy', self._$startDate.val());
          var endDate = $.datepicker.parseDate('M dd, yy', self._$endDate.val());

          var startDateFocus = self._$startDate.is(':focus');

          // startDate is not set
          if (!startDate) {
            return [true, ''];
          }
          // date is startDate
          else if (date.getTime() === startDate.getTime()) {
            return [true, 'date-range-item'];
          }
          // date is before startDate
          else if (!startDateFocus && date < startDate) {
            return [false, ''];
          }
          // date is within the date range
          else if (endDate && date >= startDate && date <= endDate) {
            return [true, 'date-range-item'];
          }
          else {
            return [true, ''];
          }

        },

        onSelect: function(dateText, inst) {

          var date1 = $.datepicker.parseDate('M dd, yy', self._$startDate.val());
          var date2 = $.datepicker.parseDate('M dd, yy', self._$endDate.val());

          self._$selectedDateRange.val('CUSTOM');
          self._$startDate.focus();

          if (!date1 || date2) {

            self._$startDate.val(dateText);
            self._$endDate.val('');
            self._$endDate.focus();

          }
          else {
            self._$endDate.val(dateText);
          }

        }

      });

      // disable input when a predefined date range is selected
      self._$selectedDateRange.on('change', function () {

        var $this = $(this);
        var selectedDateRangeValue = $this.val();
        var dateRange;

        var setDateRange = function (start, end) {

          self._$startDate.val(start);
          self._$endDate.val(end);

          $('#drp-container-datepicker').datepicker('refresh');

        };

        if (selectedDateRangeValue === 'CUSTOM') {

          self._$startDate.focus();
          $('#drp-container-datepicker').datepicker('refresh');

        }
        else {
          dateRange = self.getDateRange(selectedDateRangeValue);
          setDateRange(dateRange.start, dateRange.end);
        }

      });

      self._$cancel.on('click', function (e) {
        e.preventDefault();
        self._$startDate.val('');
        self._$endDate.val('');

        self._$startDate.focus();
        self._$selectedDateRange.val('CUSTOM');
        $('#drp-container-datepicker').datepicker('refresh');

      });

      self._$apply.on('click', function () {

        // disable button if date range input fields are empty
        if (self._$startDate.val() === '' || self._$endDate.val() === '') {
          self._$startDate.focus();
          return;
        }
        else {

          self.settings.defaultDateRange =  self._$selectedDateRange.val();

          self.initializeDateRange();

          self._$container.toggle();
          $(this).blur();
          self._$startDate.focus();
          $('#drp-container-datepicker').datepicker('refresh');
        }

      });

      this._$element.on('click', function () {

        self._$container.toggle();
        $(this).blur();
        self._$startDate.focus();
        $('#drp-container-datepicker').datepicker('refresh');

      });

      // close date picker if clicked elsewhere
      $(document).click(function (event) {
        var $target = $(event.target);
        if (!($target.attr('id') === self._$element.attr('id') ||
          $target.closest('#daterange-picker-container, .ui-datepicker-header').length)) {
          self._$container.hide();
        }
      });

    }

  });

  // a really lightweight plugin wrapper around the constructor,
  // preventing against multiple instantiations
  $.fn[ pluginName ] = function ( options ) {
    this.each(function() {
      if ( !$.data( this, 'plugin_' + pluginName ) ) {
        $.data( this, 'plugin_' + pluginName, new DateRangePicker( this, options ) );
      }
    });

    // chain jQuery functions
    return this;
  };

})(jQuery, window, document);
<commit_msg>Enable custom date selection after selecting a pre-defined date range option<commit_after>;(function ($, window, document, undefined) {

  // create the defaults once
  var pluginName = 'dateRangePicker';

  var defaults = {
    container: null,
    numberOfMonths: 3,
    datepickerShowing: true,
    defaultDate: '-1D',
    defaultDateRange: 'LAST_7_DAYS',
    maxDate: '-1D',
    minDate: new Date(2011, 0, 1),
    test: false,
    today: null
  };

  // the actual plugin constructor
  function DateRangePicker (element, options) {
    this.element = element;
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  // avoid Plugin.prototype conflicts
  $.extend(DateRangePicker.prototype, {

    init: function () {
      this.setupContainer();
      this.initializeDateRange();
      this.initializeDatePicker();
    },

    setupContainer: function () {

      var dates = 'Dates:' +
        '<input type="text" id="drp-input-startdate" size="10" readonly> -' +
        ' <input type="text" id="drp-input-enddate" size="10" readonly>';

      var select = '<select id="drp-select-daterange">' +
        '<option value="CUSTOM" selected>Custom</option>' +
        '<option value="MONTH_TO_DATE">Month To Date</option>' +
        '<option value="YEAR_TO_DATE">Year To Date</option>' +
        '<option value="LAST_WEEK">Last Week</option>' +
        '<option value="LAST_MONTH">Last Month</option>' +
        '<option value="LAST_7_DAYS">Last 7 Days</option>' +
        '<option value="LAST_30_DAYS">Last 30 Days</option>' +
        '</select>';

      var controls = 'cancel' +
        '<button id="drp-btn-apply">Apply</button>';

      var datepickerContainer = '

';

      var $container = $(this.settings.container);
      $container.html(dates + select + controls + datepickerContainer);

      this._$startDate = $('#drp-input-startdate');
      this._$endDate = $('#drp-input-enddate');
      this._$selectedDateRange = $('#drp-select-daterange');
      this._$cancel = $('#drp-btn-cancel');
      this._$apply = $('#drp-btn-apply');
      this._$datepicker = $('#drp-container-datepicker');
      this._$element = $('#'+ this.element.id + '');
      this._$container = $(this.settings.container);

    },

    getDateRange: function (option) {

      var settings = this.settings;

      var dateRange = {
        start: '',
        end: ''
      };

      var today = function () {
        return settings.test ? moment(settings.today) : moment();
      };

      var daysToSubtract;
      var dayOfTheWeek;

      switch (option) {

        case 'MONTH_TO_DATE':
          var dayOfTheMonth = today().date() - 1;
          dateRange.start = today().subtract(dayOfTheMonth, 'days').format('ll');
          dateRange.end = today().subtract(1, 'days').format('ll');
          break;

        case 'YEAR_TO_DATE':
          var dayOfTheYear = today().dayOfYear() - 1;
          dateRange.start = today().subtract(dayOfTheYear, 'days').format('ll');
          dateRange.end = today().subtract(1, 'days').format('ll');
          break;

        case 'LAST_WEEK':
          var lastWeek = today().subtract(1, 'weeks');
          daysToSubtract = lastWeek.day();
          dayOfTheWeek = today().day() + 1;
          dateRange.start = moment(lastWeek).subtract(daysToSubtract, 'days').format('ll');
          dateRange.end = today().subtract(dayOfTheWeek, 'days').format('ll');
          break;

        case 'LAST_MONTH':
          var lastMonth = today().subtract(1, 'months');
          daysToSubtract = lastMonth.date() - 1;
          dayOfTheMonth = today().date();
          dateRange.start = moment(lastMonth).subtract(daysToSubtract, 'days').format('ll');
          dateRange.end = today().subtract(dayOfTheMonth, 'days').format('ll');
          break;

        case 'LAST_7_DAYS':
          dateRange.start = today().subtract(7, 'days').format('ll');
          dateRange.end = today().subtract(1, 'days').format('ll');
          break;

        case 'LAST_30_DAYS':
          dateRange.start = today().subtract(30, 'days').format('ll');
          dateRange.end = today().subtract(1, 'days').format('ll');
          break;

        case 'CUSTOM':
          dateRange.start = this._$startDate.val();
          dateRange.end = this._$endDate.val();
          break;

        default:
          dateRange.start = today().subtract(30, 'days').format('ll');
          dateRange.end = today().subtract(1, 'days').format('ll');

      }

      return dateRange;

    },

    setDefaultSelectOption: function () {
      var self = this;
      $('#drp-select-daterange option').each(function(i, option) {
        if (option.value === self.settings.defaultDateRange) {
          $(option).attr('selected', 'selected');
        }
      });
    },

    initializeDateRange: function () {

      var dateRange = this.getDateRange(this.settings.defaultDateRange);

      this.setDefaultSelectOption();
      this._$element.val(dateRange.start + ' - ' + dateRange.end);
      this._$startDate.val(dateRange.start);
      this._$endDate.val(dateRange.end);

    },

    initializeDatePicker: function () {

      var self = this;

      $('#drp-container-datepicker').datepicker({
        numberOfMonths: 3,
        datepickerShowing: true,
        dateFormat: 'M dd, yy', // ex. Aug 30, 2014
        defaultDate: '-1D',
        maxDate: '-1D',
        minDate: this.settings.minDate,

        beforeShowDay: function (date) {

          var start = self._$startDate.val();
          var end = self._$endDate.val();

          var startDate = $.datepicker.parseDate('M dd, yy', self._$startDate.val());
          var endDate = $.datepicker.parseDate('M dd, yy', self._$endDate.val());

          var startDateFocus = self._$startDate.is(':focus');

          // startDate is not set
          if (!startDate) {
            return [true, ''];
          }
          // date is startDate
          else if (date.getTime() === startDate.getTime()) {
            return [true, 'date-range-item'];
          }
          // date is before startDate
          else if (!startDateFocus && date < startDate) {
            return [false, ''];
          }
          // date is within the date range
          else if (endDate && date >= startDate && date <= endDate) {
            return [true, 'date-range-item'];
          }
          else {
            return [true, ''];
          }

        },

        onSelect: function(dateText, inst) {

          var date1 = $.datepicker.parseDate('M dd, yy', self._$startDate.val());
          var date2 = $.datepicker.parseDate('M dd, yy', self._$endDate.val());

          self._$selectedDateRange.val('CUSTOM');
          self._$startDate.focus();

          if (!date1 || date2) {

            self._$startDate.val(dateText);
            self._$endDate.val('');
            self._$endDate.focus();

          }
          else {
            self._$endDate.val(dateText);
          }

        }

      });

      // disable input when a predefined date range is selected
      self._$selectedDateRange.on('change', function () {

        var $this = $(this);
        var selectedDateRangeValue = $this.val();
        var dateRange;

        var setDateRange = function (start, end) {

          self._$startDate.val(start);
          self._$endDate.val(end);
          self._$startDate.focus();

          $('#drp-container-datepicker').datepicker('refresh');

        };

        if (selectedDateRangeValue === 'CUSTOM') {

          self._$startDate.focus();
          $('#drp-container-datepicker').datepicker('refresh');

        }
        else {
          dateRange = self.getDateRange(selectedDateRangeValue);
          setDateRange(dateRange.start, dateRange.end);
        }

      });

      self._$cancel.on('click', function (e) {
        e.preventDefault();
        self._$startDate.val('');
        self._$endDate.val('');

        self._$startDate.focus();
        self._$selectedDateRange.val('CUSTOM');
        $('#drp-container-datepicker').datepicker('refresh');

      });

      self._$apply.on('click', function () {

        // disable button if date range input fields are empty
        if (self._$startDate.val() === '' || self._$endDate.val() === '') {
          self._$startDate.focus();
          return;
        }
        else {

          self.settings.defaultDateRange =  self._$selectedDateRange.val();

          self.initializeDateRange();

          self._$container.toggle();
          $(this).blur();
          self._$startDate.focus();
          $('#drp-container-datepicker').datepicker('refresh');
        }

      });

      this._$element.on('click', function () {

        self._$container.toggle();
        $(this).blur();
        self._$startDate.focus();
        $('#drp-container-datepicker').datepicker('refresh');

      });

      // close date picker if clicked elsewhere
      $(document).click(function (event) {
        var $target = $(event.target);
        if (!($target.attr('id') === self._$element.attr('id') ||
          $target.closest('#daterange-picker-container, .ui-datepicker-header').length)) {
          self._$container.hide();
        }
      });

    }

  });

  // a really lightweight plugin wrapper around the constructor,
  // preventing against multiple instantiations
  $.fn[ pluginName ] = function ( options ) {
    this.each(function() {
      if ( !$.data( this, 'plugin_' + pluginName ) ) {
        $.data( this, 'plugin_' + pluginName, new DateRangePicker( this, options ) );
      }
    });

    // chain jQuery functions
    return this;
  };

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


<commit_before>// -----------------------------------------------------------------------------
// Name: /public/js/game/editor/engine.js
// Author: Adam Barreiro
// Description:
// Updated: 28-10-2013
// -----------------------------------------------------------------------------

/**
 * Main file - RequireJS
 */
define (["./constants", "./audio" ,"./components", "./multi"], function(Constants, Audio, Components, Multi) {

// -----------------------------------------------------------------------------
// Private
// -----------------------------------------------------------------------------

var CHARACTER;
var LEVEL;
var STUDENT;
var SIZE = Constants.getViewportSize('px');

function setCharacter(entity) {
    CHARACTER = entity;
}

function getCharacter() {
    return CHARACTER;
}

function setLevel(level) {
    LEVEL = level;
}

function getLevel() {
    return LEVEL;
}

function setStudent(student) {
    STUDENT = student;
}

function getStudent() {
    return STUDENT;
}

/**
 * Makes an AJAX petition in order to load a level of the game.
 * @param number - Number of the level to load
 * @param callback(data) - Callback when the query finishes.
 */
function loadLevel(callback) {
    $.ajax({
        url: '/levelLoad',
        type: 'POST',
        dataType: 'json',
        data: {number: getLevel()},
        success: function(data) {
            callback(data);
        }
    });
}

/**
 * Makes an AJAX petition in order to save a level of the game.
 * @param callback(data) - Callback when the query finishes.
 */
function saveGame(callback) {
    $.ajax({
        url: '/saveGame',
        type: 'POST',
        dataType: 'json',
        data: {student: getStudent(), level: getLevel()},
        success: function(data) {
            callback(data);
        }
    });
}

function drawTile(x,y,type) {
    switch (type) {
        default: break;
        case 1: setCharacter(Crafty.e("Character").at(x,y)); break;
        case 2: Crafty.e("Floor1").at(x,y);  break;
        case 3: Crafty.e("Floor2").at(x,y);  break;
        case 4: Crafty.e("Floor3").at(x,y);  break;
        case 5: Crafty.e("Floor4").at(x,y);  break;
        case 6: Crafty.e("Floor5").at(x,y);  break;
        case 7: Crafty.e("Abyss").at(x,y); break;
        case 8: Crafty.e("Hide").at(x,y);  break;
        case 9: Crafty.e("Chest").at(x,y); break;
        case 10: Crafty.e("Enemy1").at(x,y); break;
        case 11: Crafty.e("Enemy2").at(x,y); break;
        case 12: Crafty.e("Enemy3").at(x,y); break;
        case 13: Crafty.e("Enemy4").at(x,y); break;
        case 14: Crafty.e("Enemy5").at(x,y); break;
        case 15: Crafty.e("Exit").at(x,y); break;
    }

}

function clean(background) {
    Crafty('obj').each(function() { this.destroy(); });
    Crafty.background(background || "url('/assets/img/backgrounds/wall" + (Math.floor(Math.random()*5)+1) + ".jpg') no-repeat");
}

function drawLevel(data) {
    Multi.setEnemyTotal(0);
    var multi = Multi.getMultiplayer();
    for (var i in data.map) {
        x = Math.floor(parseInt(i,10) % Constants.getLevelSize('tiles').width);
        y = Math.floor(parseInt(i,10) / Constants.getLevelSize('tiles').width);
        type = data.map[i];
        drawTile(x,y,data.map[i]);
    }
    var pos;
    if (multi === "connector") {
        Crafty("Character").addComponent("Mimic").connectorMode();
        pos = Crafty("Character").getMultiPosition();
        Crafty.e("Multiplayer").at(pos[0],pos[1]);
    } else if (multi === "creator"){
        Crafty("Character").addComponent("Mimic").creatorMode();
        pos = Crafty("Character").getMultiPosition();
        Crafty.e("Multiplayer").at(pos[0],pos[1]);
    }
    Crafty.viewport.centerOn(getCharacter(),0);
    Crafty.viewport.follow(getCharacter(), 0, 0);
    resizeController();
    if (Crafty("Multiplayer").length > 0) {
        Crafty("Character").multiplayerUpdateHealth();
    }
}

function resize() {
    SIZE = Constants.getViewportSize('px');
    Crafty.viewport.init(SIZE.width,SIZE.height);
    $('.bottom').css({'width': Constants.getViewportSize('px').width});
    $('canvas').remove();
    Crafty.canvas.init();
    Crafty.trigger("InvalidateViewport");
}

function resizeController() {
    var resizeTimeOut = null;
    window.onresize = function() {
        if(resizeTimeOut !== null) clearTimeout(resizeTimeOut);
            resizeTimeOut = setTimeout(function() {
                resize();
        },10);
    };
}

function initCrafty() {
    Crafty.init(Constants.getLevelSize('px').width, Constants.getLevelSize('px').height);
    Crafty.viewport.init(SIZE.width,SIZE.height);
    Crafty.canvas.init();
}

function drawElements() {
    var html = ['
Salir
',
                '
Sonido: SÍ
',
                '
',
                    '
',
                        'Vida

',
                        'Enemigo

',
                    '
',
                    '
',
                        'RADAR
OK
',
                    '
',
                    '
',
                        'Bonus
',
                    '
',
                '
'].join('\n');
    $('body').append(html);
    $('#back').on("click", function() {
        if (confirm("¿Quieres salir del juego?")) {
            clean();
            window.location = "/game";
        }
    });
    $('#music').on("click", function() {
        if ($('#music').attr("name") === "si") {
            $("#music").text("Sonido: NO");
            $('#music').attr("name", "no");
            Crafty.audio.mute();
        } else {
            $("#music").text("Sonido: SÍ");
            $('#music').attr("name", "si");
            Crafty.audio.unmute();
        }
    });
    $('.bottom').css({'width': Constants.getViewportSize('px').width});
}

function gameScene() {
    Crafty.scene("Game", function(data){
        drawLevel(data);
        drawElements();
        Audio.playLevel();
    });
}

function nextScene() {
    Crafty.scene("Next", function(data) {
            var html = ['
',
                '
¡NIVEL SUPERADO!
',
                '
Pulsa Siguiente para ir al siguiente nivel
',
                '<input class="button" type="button" value="Siguiente"/>',
            '
'].join('\n');
        Audio.stopLevel();
        $('.bottom').remove();
        $('#back').remove();
        $('#music').remove();
        $('#cr-stage').fadeOut(1000, function() {
            $('body').append(html);
            $('.button').on("click", function() {
                $('.popup').remove();
                clean();
                $('#cr-stage').show();
                Crafty.scene("Game",data);
            });
        });
    });
}

function endScene() {
    Crafty.scene("End", function() {
        var html = ['
',
                '
¡Enhorabuena, destruiste a tus enemigos y saliste con vida!
',
                '
Ahora eres un experto resolviendo polinomios :)
',
                '<input class="button" type="button" value="Volver al menu"/>
',
                ].join('\n');
        $('body').append(html);
        $('h1').css({
            "text-align" : "center",
            "color" : "white",
            "border-bottom" : "solid 1px #999999",
            "line-height" : "150%",
            "padding" : "10px"
        });
        $('.button').css({
            "clear" : "both",
            "float" : "left",
            "margin-top": "50px",
            "margin-left" : "45%"});
        $('.button').on('click', function() {
            $('#exp').remove();
            Crafty.stop();
            $('#cr-stage').remove();
            window.location="/";
        });
    });
}

function deathScene() {
    Crafty.scene("Death", function(data) {
        var html = ['
',
            '
¡HAS MUERTO!
',
            '
¡Vuelve a intentarlo!
',
            '<input class="button" type="button" value="¡Venganza!"/>',
        '
'].join('\n');
        $('.bottom').remove();
        $('#back').remove();
        $('#music').remove();
        $('#cr-stage').fadeOut(1000, function() {
            $('body').append(html);
            $('.button').on("click", function() {
                $('.popup').remove();
                clean();
                $('#cr-stage').show();
                Crafty.scene("Game", data);
            });
        });
    });
}

function loadingScene() {
    Crafty.scene("Loading", function(data){
        var html = ['
',
                '
Cargando...
',
                '

',
                '

',
                '	',
                '

',
                '	',
                '

',
                '	',
                '

'].join('\n');
        $('#cr-stage').hide();
        $('body').append(html);
        $('h1').css({"text-align":"center", "color":"white"});
        $('table').css({"width":"80%", "margin":"0px auto"});
        $('.ltuto').css({"margin-top":"30px","float":"left","box-shadow":"10px 10px 10px #111111"});
        $('.rtuto').css({"margin-top":"30px","float":"right","box-shadow":"10px 10px 10px #111111"});
        $('#loading').css({"margin":"0 auto","border":"1px solid #FFF","background-color":"#000","width":"500px","height":"10px","box-shadow":"10px 10px 10px #111111"});
        $('#progress').css({"border":"0px","background-color":"#999","width":"100px","height":"10px"});
        var assets = ['/assets/img/backgrounds/wall1.jpg',
                      '/assets/img/backgrounds/wall2.jpg',
                      '/assets/img/backgrounds/wall3.jpg',
                      '/assets/img/backgrounds/wall4.jpg',
                      '/assets/img/backgrounds/wall5.jpg'];
        var loaded = false;
        var i = 444;
        var interval = setInterval(function() {
            if (!loaded) {
                if (i === 999) i = 444;
                i=i+111;
                $('#progress').css({"background-color":"#"+i});

            } else {
                clearInterval(interval);
            }
        },100);
        var gi = Components.getGameGraphics();
        Audio.addAudio();
        assets.join(Audio.loadAudio());
        assets.join(gi);
        Crafty.load(assets,
        function() {
            loaded=true;
            Components.setGameGraphics(gi);
            $('#loading').remove();
            $("h1").text("¡Todo listo!");
            $('table').before('
<input class="button" type="button" value="¡Empezar!"/>
');
            $('#cont').css({"margin": "0 auto", "text-align": "center"});
            $('.button').on("click", function() {
                $('#exp').remove();
                clean();
                $('#cr-stage').show();
                Crafty.scene('Game', data);
            });
        },
        function(e) {
            $("#progress").width(e.percent*5);
        });
    });
}

function initScenes() {
    gameScene();
    loadingScene();
    deathScene();
    endScene();
    nextScene();
}

// -----------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------

return {

    newGame: function(student, level, multi) {
        setStudent(student);
        setLevel(level);
        Multi.setMultiplayer(multi);
        loadLevel(function(data) {
            initScenes();
            if (data.map) {
                initCrafty();
                if (multi === "connector") { // In multiplayer the connector doesn't save the game
                    Crafty.scene('Loading',data);
                } else {
                    saveGame(function(ok) {
                        Crafty.scene('Loading',data);
                    });
                }
            } else {
                Crafty.scene("End");
            }
        });
    },
    nextLevel: function(mode) {
        setLevel(getLevel()+1);
        loadLevel(function(data) {
            if (data.map) {
                if (Multi.getMultiplayer() === "connector") { // In multiplayer the connector doesn't save the game
                    Crafty.scene('Next',data);
                } else {
                    saveGame(function(ok) {
                        Crafty.scene('Next',data);
                    });
                }
            } else {
                Crafty.scene("End");
            }
        });
    },
    restartLevel: function() {
        loadLevel(function(data) {
            if (data.map) {
                Crafty.scene("Death",data);
            }
        });
    }
};

});<commit_msg>Bug fixes<commit_after>// -----------------------------------------------------------------------------
// Name: /public/js/game/editor/engine.js
// Author: Adam Barreiro
// Description:
// Updated: 28-10-2013
// -----------------------------------------------------------------------------

/**
 * Main file - RequireJS
 */
define (["./constants", "./audio" ,"./components", "./multi"], function(Constants, Audio, Components, Multi) {

// -----------------------------------------------------------------------------
// Private
// -----------------------------------------------------------------------------

var CHARACTER;
var LEVEL;
var STUDENT;
var SIZE = Constants.getViewportSize('px');

function setCharacter(entity) {
    CHARACTER = entity;
}

function getCharacter() {
    return CHARACTER;
}

function setLevel(level) {
    LEVEL = level;
}

function getLevel() {
    return LEVEL;
}

function setStudent(student) {
    STUDENT = student;
}

function getStudent() {
    return STUDENT;
}

/**
 * Makes an AJAX petition in order to load a level of the game.
 * @param number - Number of the level to load
 * @param callback(data) - Callback when the query finishes.
 */
function loadLevel(callback) {
    $.ajax({
        url: '/levelLoad',
        type: 'POST',
        dataType: 'json',
        data: {number: getLevel()},
        success: function(data) {
            callback(data);
        }
    });
}

/**
 * Makes an AJAX petition in order to save a level of the game.
 * @param callback(data) - Callback when the query finishes.
 */
function saveGame(callback) {
    $.ajax({
        url: '/saveGame',
        type: 'POST',
        dataType: 'json',
        data: {student: getStudent(), level: getLevel()},
        success: function(data) {
            callback(data);
        }
    });
}

function drawTile(x,y,type) {
    switch (type) {
        default: break;
        case 1: setCharacter(Crafty.e("Character").at(x,y)); break;
        case 2: Crafty.e("Floor1").at(x,y);  break;
        case 3: Crafty.e("Floor2").at(x,y);  break;
        case 4: Crafty.e("Floor3").at(x,y);  break;
        case 5: Crafty.e("Floor4").at(x,y);  break;
        case 6: Crafty.e("Floor5").at(x,y);  break;
        case 7: Crafty.e("Abyss").at(x,y); break;
        case 8: Crafty.e("Hide").at(x,y);  break;
        case 9: Crafty.e("Chest").at(x,y); break;
        case 10: Crafty.e("Enemy1").at(x,y); break;
        case 11: Crafty.e("Enemy2").at(x,y); break;
        case 12: Crafty.e("Enemy3").at(x,y); break;
        case 13: Crafty.e("Enemy4").at(x,y); break;
        case 14: Crafty.e("Enemy5").at(x,y); break;
        case 15: Crafty.e("Exit").at(x,y); break;
    }

}

function clean(background) {
    Crafty('obj').each(function() { this.destroy(); });
    Crafty.background(background || "url('/assets/img/backgrounds/wall" + (Math.floor(Math.random()*5)+1) + ".jpg') no-repeat");
}

function drawLevel(data) {
    Multi.setEnemyTotal(0);
    var multi = Multi.getMultiplayer();
    for (var i in data.map) {
        x = Math.floor(parseInt(i,10) % Constants.getLevelSize('tiles').width);
        y = Math.floor(parseInt(i,10) / Constants.getLevelSize('tiles').width);
        type = data.map[i];
        drawTile(x,y,data.map[i]);
    }
    var pos;
    if (multi === "connector") {
        Crafty("Character").addComponent("Mimic").connectorMode();
        pos = Crafty("Character").getMultiPosition();
        Crafty.e("Multiplayer").at(pos[0],pos[1]);
    } else if (multi === "creator"){
        Crafty("Character").addComponent("Mimic").creatorMode();
        pos = Crafty("Character").getMultiPosition();
        Crafty.e("Multiplayer").at(pos[0],pos[1]);
    }
    Crafty.viewport.centerOn(getCharacter(),0);
    Crafty.viewport.follow(getCharacter(), 0, 0);
    resizeController();
}

function resize() {
    SIZE = Constants.getViewportSize('px');
    Crafty.viewport.init(SIZE.width,SIZE.height);
    $('.bottom').css({'width': Constants.getViewportSize('px').width});
    $('canvas').remove();
    Crafty.canvas.init();
    Crafty.trigger("InvalidateViewport");
}

function resizeController() {
    var resizeTimeOut = null;
    window.onresize = function() {
        if(resizeTimeOut !== null) clearTimeout(resizeTimeOut);
            resizeTimeOut = setTimeout(function() {
                resize();
        },10);
    };
}

function initCrafty() {
    Crafty.init(Constants.getLevelSize('px').width, Constants.getLevelSize('px').height);
    Crafty.viewport.init(SIZE.width,SIZE.height);
    Crafty.canvas.init();
}

function drawElements() {
    var html = ['
Salir
',
                '
Sonido: SÍ
',
                '
',
                    '
',
                        'Vida

',
                        'Enemigo

',
                    '
',
                    '
',
                        'RADAR
OK
',
                    '
',
                    '
',
                        'Bonus
',
                    '
',
                '
'].join('\n');
    $('body').append(html);
    $('#back').on("click", function() {
        if (confirm("¿Quieres salir del juego?")) {
            clean();
            window.location = "/game";
        }
    });
    $('#music').on("click", function() {
        if ($('#music').attr("name") === "si") {
            $("#music").text("Sonido: NO");
            $('#music').attr("name", "no");
            Crafty.audio.mute();
        } else {
            $("#music").text("Sonido: SÍ");
            $('#music').attr("name", "si");
            Crafty.audio.unmute();
        }
    });
    $('.bottom').css({'width': Constants.getViewportSize('px').width});
}

function gameScene() {
    Crafty.scene("Game", function(data){
        drawLevel(data);
        drawElements();
        Audio.playLevel();
    });
}

function nextScene() {
    Crafty.scene("Next", function(data) {
            var html = ['
',
                '
¡NIVEL SUPERADO!
',
                '
Pulsa Siguiente para ir al siguiente nivel
',
                '<input class="button" type="button" value="Siguiente"/>',
            '
'].join('\n');
        Audio.stopLevel();
        $('.bottom').remove();
        $('#back').remove();
        $('#music').remove();
        $('#cr-stage').fadeOut(1000, function() {
            $('body').append(html);
            $('.button').on("click", function() {
                $('.popup').remove();
                clean();
                $('#cr-stage').show();
                Crafty.scene("Game",data);
            });
        });
    });
}

function endScene() {
    Crafty.scene("End", function() {
        var html = ['
',
                '
¡Enhorabuena, destruiste a tus enemigos y saliste con vida!
',
                '
Ahora eres un experto resolviendo polinomios :)
',
                '<input class="button" type="button" value="Volver al menu"/>
',
                ].join('\n');
        $('body').append(html);
        $('h1').css({
            "text-align" : "center",
            "color" : "white",
            "border-bottom" : "solid 1px #999999",
            "line-height" : "150%",
            "padding" : "10px"
        });
        $('.button').css({
            "clear" : "both",
            "float" : "left",
            "margin-top": "50px",
            "margin-left" : "45%"});
        $('.button').on('click', function() {
            $('#exp').remove();
            Crafty.stop();
            $('#cr-stage').remove();
            window.location="/";
        });
    });
}

function deathScene() {
    Crafty.scene("Death", function(data) {
        var html = ['
',
            '
¡HAS MUERTO!
',
            '
¡Vuelve a intentarlo!
',
            '<input class="button" type="button" value="¡Venganza!"/>',
        '
'].join('\n');
        $('.bottom').remove();
        $('#back').remove();
        $('#music').remove();
        $('#cr-stage').fadeOut(1000, function() {
            $('body').append(html);
            $('.button').on("click", function() {
                $('.popup').remove();
                clean();
                $('#cr-stage').show();
                Crafty.scene("Game", data);
            });
        });
    });
}

function loadingScene() {
    Crafty.scene("Loading", function(data){
        var html = ['
',
                '
Cargando...
',
                '

',
                '

',
                '	',
                '

',
                '	',
                '

',
                '	',
                '

'].join('\n');
        $('#cr-stage').hide();
        $('body').append(html);
        $('h1').css({"text-align":"center", "color":"white"});
        $('table').css({"width":"80%", "margin":"0px auto"});
        $('.ltuto').css({"margin-top":"30px","float":"left","box-shadow":"10px 10px 10px #111111"});
        $('.rtuto').css({"margin-top":"30px","float":"right","box-shadow":"10px 10px 10px #111111"});
        $('#loading').css({"margin":"0 auto","border":"1px solid #FFF","background-color":"#000","width":"500px","height":"10px","box-shadow":"10px 10px 10px #111111"});
        $('#progress').css({"border":"0px","background-color":"#999","width":"100px","height":"10px"});
        var assets = ['/assets/img/backgrounds/wall1.jpg',
                      '/assets/img/backgrounds/wall2.jpg',
                      '/assets/img/backgrounds/wall3.jpg',
                      '/assets/img/backgrounds/wall4.jpg',
                      '/assets/img/backgrounds/wall5.jpg'];
        var loaded = false;
        var i = 444;
        var interval = setInterval(function() {
            if (!loaded) {
                if (i === 999) i = 444;
                i=i+111;
                $('#progress').css({"background-color":"#"+i});

            } else {
                clearInterval(interval);
            }
        },100);
        var gi = Components.getGameGraphics();
        Audio.addAudio();
        assets.join(Audio.loadAudio());
        assets.join(gi);
        Crafty.load(assets,
        function() {
            loaded=true;
            Components.setGameGraphics(gi);
            $('#loading').remove();
            $("h1").text("¡Todo listo!");
            $('table').before('
<input class="button" type="button" value="¡Empezar!"/>
');
            $('#cont').css({"margin": "0 auto", "text-align": "center"});
            $('.button').on("click", function() {
                $('#exp').remove();
                clean();
                $('#cr-stage').show();
                Crafty.scene('Game', data);
            });
        },
        function(e) {
            $("#progress").width(e.percent*5);
        });
    });
}

function initScenes() {
    gameScene();
    loadingScene();
    deathScene();
    endScene();
    nextScene();
}

// -----------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------

return {

    newGame: function(student, level, multi) {
        setStudent(student);
        setLevel(level);
        Multi.setMultiplayer(multi);
        loadLevel(function(data) {
            initScenes();
            if (data.map) {
                initCrafty();
                if (multi === "connector") { // In multiplayer the connector doesn't save the game
                    Crafty.scene('Loading',data);
                } else {
                    saveGame(function(ok) {
                        Crafty.scene('Loading',data);
                    });
                }
            } else {
                Crafty.scene("End");
            }
        });
    },
    nextLevel: function(mode) {
        setLevel(getLevel()+1);
        loadLevel(function(data) {
            if (data.map) {
                if (Multi.getMultiplayer() === "connector") { // In multiplayer the connector doesn't save the game
                    Crafty.scene('Next',data);
                } else {
                    saveGame(function(ok) {
                        Crafty.scene('Next',data);
                    });
                }
            } else {
                Crafty.scene("End");
            }
        });
    },
    restartLevel: function() {
        loadLevel(function(data) {
            if (data.map) {
                Crafty.scene("Death",data);
            }
        });
    }
};

});<|endoftext|>


<commit_before>function foreach(array, callback) {
	for (var i = 0; i < array.length; i++) {
		callback(array[i]);
	}
}

function sum() {
	var total = 0;
	foreach(arguments, function (value) {
		total += value;
	});
	return total;
}

console.log(sum(1, 2, 3));
<commit_msg>Simplified the first.js script.<commit_after>function sum(values) {
	var total = 0;
	values.map(function (value) {
		total += value;
	});
	return total;
}

var numbersToSum = [1, 2, 3];
console.log(sum(numbersToSum));
<|endoftext|>


<commit_before>"use strict";

var
  View = require('space-pen').View,
  inherits = require('./utils').inherits;

var MessagePanelView = function (params) {
  this.title = params.title;
  this.rawTitle = params.rawTitle || false;
  this.speed = params.speed || 'fast';
  this.panel = undefined;
  this.autoScroll = params.autoScroll || false;
  this.closeMethod = params.closeMethod || 'hide';
  this.messages = [];

  View.apply(this, arguments);
};

inherits(MessagePanelView, View);

MessagePanelView.content = function () {
  this.div({
    class: 'am-panel tool-panel panel-bottom native-key-bindings',
    tabindex: '-1'
  }, function () {
    this.div({
      class: 'panel-heading'
    }, function () {
      this.div({
        class: 'heading-title inline-block',
        style: 'cursor: pointer',
        outlet: 'heading',
        click: 'toggle'
      });
      this.div({
        class: 'heading-summary inline-block',
        outlet: 'summary'
      });
      this.div({
        class: 'heading-buttoms inline-block pull-right'
      }, function () {
        this.div({
          class: 'heading-autoScroll inline-block icon-move-down',
          style: 'cursor: pointer',
          outlet: 'btnAutoScroll',
          click: 'toggleAutoScroll'
        });
        this.div({
          class: 'heading-fold inline-block icon-fold',
          style: 'cursor: pointer',
          outlet: 'btnFold',
          click: 'toggle'
        });
        this.div({
          class: 'heading-close inline-block icon-x',
          style: 'cursor: pointer;',
          outlet: 'btnClose',
          click: 'close'
        });
      }.bind(this));
    }.bind(this));
    this.div({
      class: 'panel-body padded',
      outlet: 'body',
      style: 'max-height: 170px; overflow-y: scroll;'
    });
  }.bind(this));
};

MessagePanelView.prototype.attach = function () {
  if (this.panel === undefined) {
    this.panel = atom.workspace.addBottomPanel({item: this});
  } else {
    this.panel.show();
  }
};

MessagePanelView.prototype.close = function () {
  if (this.panel !== undefined) {
    this.panel[this.closeMethod].call(this.panel);
    if (this.closeMethod === 'destroy') {
      this.panel = undefined;
    }
  }
};

MessagePanelView.prototype.initialize = function () {
  this.setTitle(this.title, this.rawTitle);
  if (this.autoScroll) {
    this.toggleAutoScroll();
  }
  this.summary.hide();
};

MessagePanelView.prototype.setTitle = function (title, raw) {
  if (raw) {
    this.heading.html(title);
  } else {
    this.heading.text(title);
  }
};

MessagePanelView.prototype.setSummary = function (summary) {
  var
    message = summary.summary,
    className = summary.className,
    raw = summary.rawSummary || false,
    handler = summary.handler || undefined;
  // Reset the class-attributes on the old summary
  this.summary.attr('class', 'heading-summary inline-block');
  // Set the new summary
  if (raw) {
    this.summary.html(message);
  } else {
    this.summary.text(message);
  }
  if (className) {
    this.summary.addClass(className);
  }
  if (handler) {
    handler(this.summary);
  }
};

MessagePanelView.prototype.toggle = function () {
  this.btnFold.toggleClass('icon-fold, icon-unfold');
  this.body.toggle(this.speed);
  // Because we want to toggle between display:
  // 'none' and 'inline-block' for the summary,
  // we can't use .toggle().
  if (this.summary.css('display') === 'none') {
    this.summary.css('display', 'inline-block');
  } else {
    this.summary.hide();
  }
};

MessagePanelView.prototype.clear = function () {
  this.messages = [];
  this.body.empty();
};

MessagePanelView.prototype.add = function (view) {
  if (this.messages.length === 0 && view.getSummary) {
    // This is the first message, so use it to
    // set the summary
    this.setSummary(view.getSummary());
  }
  this.messages.push(view);
  this.body.append(view);
  this.updateScroll();
};

MessagePanelView.prototype.updateScroll = function () {
  if (this.btnAutoScroll.hasClass('icon-move-up')) {
    this.body.scrollTop(1E10);
  } else {
    this.body.scrollTop(0);
  }
};

MessagePanelView.prototype.toggleAutoScroll = function () {
  this.btnAutoScroll.toggleClass('icon-move-up');
  this.updateScroll();
};

module.exports = MessagePanelView;
<commit_msg>making sure that autoscroll will autoscroll on attach<commit_after>"use strict";

var
  View = require('space-pen').View,
  inherits = require('./utils').inherits;

var MessagePanelView = function (params) {
  this.title = params.title;
  this.rawTitle = params.rawTitle || false;
  this.speed = params.speed || 'fast';
  this.panel = undefined;
  this.autoScroll = params.autoScroll || false;
  this.closeMethod = params.closeMethod || 'hide';
  this.messages = [];

  View.apply(this, arguments);
};

inherits(MessagePanelView, View);

MessagePanelView.content = function () {
  this.div({
    class: 'am-panel tool-panel panel-bottom native-key-bindings',
    tabindex: '-1'
  }, function () {
    this.div({
      class: 'panel-heading'
    }, function () {
      this.div({
        class: 'heading-title inline-block',
        style: 'cursor: pointer',
        outlet: 'heading',
        click: 'toggle'
      });
      this.div({
        class: 'heading-summary inline-block',
        outlet: 'summary'
      });
      this.div({
        class: 'heading-buttoms inline-block pull-right'
      }, function () {
        this.div({
          class: 'heading-autoScroll inline-block icon-move-down',
          style: 'cursor: pointer',
          outlet: 'btnAutoScroll',
          click: 'toggleAutoScroll'
        });
        this.div({
          class: 'heading-fold inline-block icon-fold',
          style: 'cursor: pointer',
          outlet: 'btnFold',
          click: 'toggle'
        });
        this.div({
          class: 'heading-close inline-block icon-x',
          style: 'cursor: pointer;',
          outlet: 'btnClose',
          click: 'close'
        });
      }.bind(this));
    }.bind(this));
    this.div({
      class: 'panel-body padded',
      outlet: 'body',
      style: 'max-height: 170px; overflow-y: scroll;'
    });
  }.bind(this));
};

MessagePanelView.prototype.attach = function () {
  if (this.panel === undefined) {
    this.panel = atom.workspace.addBottomPanel({item: this});

    if (this.btnAutoScroll.hasClass('icon-move-up')) {
      this.body.scrollTop(1E10);
    }
  } else {
    this.panel.show();
  }
};

MessagePanelView.prototype.close = function () {
  if (this.panel !== undefined) {
    this.panel[this.closeMethod].call(this.panel);
    if (this.closeMethod === 'destroy') {
      this.panel = undefined;
    }
  }
};

MessagePanelView.prototype.initialize = function () {
  this.setTitle(this.title, this.rawTitle);
  if (this.autoScroll) {
    this.toggleAutoScroll();
  }
  this.summary.hide();
};

MessagePanelView.prototype.setTitle = function (title, raw) {
  if (raw) {
    this.heading.html(title);
  } else {
    this.heading.text(title);
  }
};

MessagePanelView.prototype.setSummary = function (summary) {
  var
    message = summary.summary,
    className = summary.className,
    raw = summary.rawSummary || false,
    handler = summary.handler || undefined;
  // Reset the class-attributes on the old summary
  this.summary.attr('class', 'heading-summary inline-block');
  // Set the new summary
  if (raw) {
    this.summary.html(message);
  } else {
    this.summary.text(message);
  }
  if (className) {
    this.summary.addClass(className);
  }
  if (handler) {
    handler(this.summary);
  }
};

MessagePanelView.prototype.toggle = function () {
  this.btnFold.toggleClass('icon-fold, icon-unfold');
  this.body.toggle(this.speed);
  // Because we want to toggle between display:
  // 'none' and 'inline-block' for the summary,
  // we can't use .toggle().
  if (this.summary.css('display') === 'none') {
    this.summary.css('display', 'inline-block');
  } else {
    this.summary.hide();
  }
};

MessagePanelView.prototype.clear = function () {
  this.messages = [];
  this.body.empty();
};

MessagePanelView.prototype.add = function (view) {
  if (this.messages.length === 0 && view.getSummary) {
    // This is the first message, so use it to
    // set the summary
    this.setSummary(view.getSummary());
  }
  this.messages.push(view);
  this.body.append(view);
  this.updateScroll();
};

MessagePanelView.prototype.updateScroll = function () {
  if (this.btnAutoScroll.hasClass('icon-move-up')) {
    this.body.scrollTop(1E10);
  } else {
    this.body.scrollTop(0);
  }
};

MessagePanelView.prototype.toggleAutoScroll = function () {
  this.btnAutoScroll.toggleClass('icon-move-up');
  this.updateScroll();
};

module.exports = MessagePanelView;
<|endoftext|>


<commit_before>'use strict'

var renderer_api  = new RendererAPI()
if (renderer_api.is_webgl_enabled() === false) {
    console.log('WebGL is not enabled!')
    throw new Error('WebGL is not enabled!')
}
var stats_api = new StatsAPI()
var scene = new THREE.Scene()
var camera   = new THREE.PerspectiveCamera(renderer_api.field_of_view, renderer_api.aspect_ratio, renderer_api.near_clipping, renderer_api.far_clipping)
renderer_api.set_camera(camera)
var fps_controls = new FPSControls(camera)
scene.add(fps_controls.get_object())

var pointer_lock_api = new PointerLockAPI(fps_controls)

var geometry = new THREE.BoxGeometry(5,5, 5)
//var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
var material = new THREE.MeshLambertMaterial({ color: 0x00ff00 })
var cube 	 = new THREE.Mesh(geometry, material)
scene.add(cube)

// Going to try to create a plane here.
var plane_geometry = new THREE.PlaneGeometry(2000, 2000, 100, 100)
plane_geometry.applyMatrix(new THREE.Matrix4().makeRotationX(- Math.PI / 2))
//var plane_material = new THREE.MeshBasicMaterial({color: 0x0000ff})
var plane_material = new THREE.MeshLambertMaterial({color: 0xccffcc, side: THREE.FrontSide, wireframe: true})
var plane_mesh     = new THREE.Mesh(plane_geometry, plane_material)
scene.add(plane_mesh)

var log_geometry = new THREE.PlaneGeometry(50, 50, 100, 100)
log_geometry.applyMatrix(new THREE.Matrix4().makeRotationY(- Math.PI / 2))
var log_material = new THREE.MeshBasicMaterial({color: 0xccffcc, wireframe: true})
log_material.color.set('black')
log_material.opacity   = 0
log_material.blending  = THREE.NoBlending
var log_mesh = new THREE.Mesh(log_geometry, log_material)
scene.add(log_mesh)

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

var css_renderer_api = new CSSRendererAPI()

var cssScene = new THREE.Scene()

var math_formulas = document.getElementById('math_formulas')

var element = document.createElement('div')
element.innerHTML = 'Plain text inside a div.'
element.className = 'three-div'

//var css_object = new THREE.CSS3DObject(math_formulas)
var css_object = new THREE.CSS3DObject(element)
css_object.position.x = log_mesh.position.x
css_object.position.y = log_mesh.position.y + 10
css_object.position.z = log_mesh.position.z

css_object.rotation.x = log_mesh.rotation.x
css_object.rotation.y = log_mesh.rotation.y
css_object.rotation.z = log_mesh.rotation.z

var light4 = new THREE.HemisphereLight(0xffbf67, 0x15c6ff, .3)
scene.add(light4)

//scene.add(css_object)
cssScene.add(css_object)

// @@@@
css_renderer_api.renderer.domElement.appendChild(renderer_api.renderer.domElement)
document.body.appendChild(css_renderer_api.renderer.domElement)
// @@@@

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

camera.position.z = 10

/*
// Line test.
var line_material = new THREE.LineBasicMaterial({color: LIGHT_GREEN, opacity: 1, linewidth: 50})
var line_geometry = new THREE.Geometry()
line_geometry.vertices.push(new THREE.Vector3(-100, 0, 0))
line_geometry.vertices.push(new THREE.Vector3(0, 100, 0))
line_geometry.vertices.push(new THREE.Vector3(0, 0, 0))
line_geometry.vertices.push(new THREE.Vector3(50, 50, 50))
var line = new THREE.Line(line_geometry, line_material)
scene.add(line)
*/

// Add lights.
var ambiColor = '#cbe7ff'
var ambientLight = new THREE.AmbientLight(ambiColor, .4)
scene.add(ambientLight)
/*
var light = new THREE.DirectionalLight( 0xffffff, 1.5 )
light.position.set(1, 1, 1 )
scene.add(light)s

var light2 = new THREE.DirectionalLight( 0xffffff, 0.75 )
light2.position.set(-1, - 0.5, -1)
scene.add(light2)
*/

var data_display = new DataDisplay(fps_controls)

var light3 = new THREE.PointLight(0xccffcc, 1, 1000)
light3.position.set(5, 15, 5)
scene.add(light3)

//var shader_api = new ShaderAPI(renderer_api, scene, camera)

var previous_time = performance.now()

var animate = function () {

    //shader_api.render()

    requestAnimationFrame(animate)

    stats_api.pre_render()

    cube.rotation.x += 0.01
    cube.rotation.y += 0.01

    var time = performance.now()
    var delta = (time - previous_time) / 1000

    fps_controls.physics(delta)
    data_display.update()

    //css_renderer_api.renderer.render(cssScene, camera)
    //renderer_api.render(scene, camera)
    renderer_api.renderer.render(scene, camera)
    css_renderer_api.renderer.render(cssScene, camera)

    stats_api.post_render()

    previous_time = time
}

animate()

<commit_msg>Log rule display testing 46<commit_after>'use strict'

var renderer_api  = new RendererAPI()
if (renderer_api.is_webgl_enabled() === false) {
    console.log('WebGL is not enabled!')
    throw new Error('WebGL is not enabled!')
}
var stats_api = new StatsAPI()
var scene = new THREE.Scene()
var camera   = new THREE.PerspectiveCamera(renderer_api.field_of_view, renderer_api.aspect_ratio, renderer_api.near_clipping, renderer_api.far_clipping)
renderer_api.set_camera(camera)
var fps_controls = new FPSControls(camera)
scene.add(fps_controls.get_object())

var pointer_lock_api = new PointerLockAPI(fps_controls)

var geometry = new THREE.BoxGeometry(5,5, 5)
//var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
var material = new THREE.MeshLambertMaterial({ color: 0x00ff00 })
var cube 	 = new THREE.Mesh(geometry, material)
scene.add(cube)

// Going to try to create a plane here.
var plane_geometry = new THREE.PlaneGeometry(2000, 2000, 100, 100)
plane_geometry.applyMatrix(new THREE.Matrix4().makeRotationX(- Math.PI / 2))
//var plane_material = new THREE.MeshBasicMaterial({color: 0x0000ff})
var plane_material = new THREE.MeshLambertMaterial({color: 0xccffcc, side: THREE.FrontSide, wireframe: false})
var plane_mesh     = new THREE.Mesh(plane_geometry, plane_material)
scene.add(plane_mesh)

var log_geometry = new THREE.PlaneGeometry(50, 50, 100, 100)
log_geometry.applyMatrix(new THREE.Matrix4().makeRotationY(- Math.PI / 2))
var log_material = new THREE.MeshBasicMaterial({color: 0xccffcc, wireframe: true})
log_material.color.set('black')
log_material.opacity   = 0
log_material.blending  = THREE.NoBlending
var log_mesh = new THREE.Mesh(log_geometry, log_material)
scene.add(log_mesh)

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

var css_renderer_api = new CSSRendererAPI()

var cssScene = new THREE.Scene()

var math_formulas = document.getElementById('math_formulas')

var element = document.createElement('div')
element.innerHTML = 'Plain text inside a div.'
element.className = 'three-div'

//var css_object = new THREE.CSS3DObject(math_formulas)
var css_object = new THREE.CSS3DObject(element)
css_object.position.x = log_mesh.position.x
css_object.position.y = log_mesh.position.y + 10
css_object.position.z = log_mesh.position.z

css_object.rotation.x = log_mesh.rotation.x
css_object.rotation.y = log_mesh.rotation.y
css_object.rotation.z = log_mesh.rotation.z

//var light4 = new THREE.HemisphereLight(0xffbf67, 0x15c6ff, .3)
//scene.add(light4)

//scene.add(css_object)
cssScene.add(css_object)

// @@@@
css_renderer_api.renderer.domElement.appendChild(renderer_api.renderer.domElement)
document.body.appendChild(css_renderer_api.renderer.domElement)
// @@@@

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

camera.position.z = 10

/*
// Line test.
var line_material = new THREE.LineBasicMaterial({color: LIGHT_GREEN, opacity: 1, linewidth: 50})
var line_geometry = new THREE.Geometry()
line_geometry.vertices.push(new THREE.Vector3(-100, 0, 0))
line_geometry.vertices.push(new THREE.Vector3(0, 100, 0))
line_geometry.vertices.push(new THREE.Vector3(0, 0, 0))
line_geometry.vertices.push(new THREE.Vector3(50, 50, 50))
var line = new THREE.Line(line_geometry, line_material)
scene.add(line)
*/

// Add lights.
var ambiColor = '#cbe7ff'
var ambientLight = new THREE.AmbientLight(ambiColor, .4)
scene.add(ambientLight)
/*
var light = new THREE.DirectionalLight( 0xffffff, 1.5 )
light.position.set(1, 1, 1 )
scene.add(light)s

var light2 = new THREE.DirectionalLight( 0xffffff, 0.75 )
light2.position.set(-1, - 0.5, -1)
scene.add(light2)
*/

var data_display = new DataDisplay(fps_controls)

var light3 = new THREE.PointLight(0xccffcc, 1, 1000)
light3.position.set(5, 15, 5)
scene.add(light3)

//var shader_api = new ShaderAPI(renderer_api, scene, camera)

var previous_time = performance.now()

var animate = function () {

    //shader_api.render()

    requestAnimationFrame(animate)

    stats_api.pre_render()

    cube.rotation.x += 0.01
    cube.rotation.y += 0.01

    var time = performance.now()
    var delta = (time - previous_time) / 1000

    fps_controls.physics(delta)
    data_display.update()

    //css_renderer_api.renderer.render(cssScene, camera)
    //renderer_api.render(scene, camera)
    renderer_api.renderer.render(scene, camera)
    css_renderer_api.renderer.render(cssScene, camera)

    stats_api.post_render()

    previous_time = time
}

animate()

<|endoftext|>


<commit_before>'use strict';

const BbPromise = require('bluebird');
const path = require('path');
const fse = require('fs-extra');

module.exports = {
  validate() {
    this.webpackConfig = (
      this.serverless.service.custom &&
      this.serverless.service.custom.webpack ||
      'webpack.config.js'
    );

    if (typeof this.webpackConfig === 'string') {
      const webpackConfigFilePath = path.join(this.serverless.config.servicePath, this.webpackConfig);
      if (!this.serverless.utils.fileExistsSync(webpackConfigFilePath)) {
        throw new this.serverless.classes
          .Error('The webpack plugin could not find the configuration file at: ' + webpackConfigFilePath);
      }
      this.webpackConfig = require(webpackConfigFilePath);
    }

    // Default context
    if (!this.webpackConfig.context) {
      this.webpackConfig.context = this.serverless.config.servicePath;
    }

    // Default output
    if (!this.webpackConfig.output) {
      const outputPath = path.join(this.serverless.config.servicePath, '.webpack');
      const outputFilename = path.basename(
        Array.isArray(this.webpackConfig.entry)
        ? this.webpackConfig.entry[this.webpackConfig.entry.length - 1]
        : this.webpackConfig.entry
      ) || 'handler.js';
      this.webpackConfig.output = {
        libraryTarget: 'commonjs',
        path: outputPath,
        filename: outputFilename,
      };
    }

    // Custom output path
    if (this.options.out) {
      this.webpackConfig.output.path = path.join(this.serverless.config.servicePath, this.options.out);
    }

    fse.removeSync(this.webpackConfig.output.path);

    return BbPromise.resolve();
  },
};
<commit_msg>Fix broken test<commit_after>'use strict';

const BbPromise = require('bluebird');
const path = require('path');
const fse = require('fs-extra');

module.exports = {
  validate() {
    this.webpackConfig = (
      this.serverless.service.custom &&
      this.serverless.service.custom.webpack ||
      'webpack.config.js'
    );

    if (typeof this.webpackConfig === 'string') {
      const webpackConfigFilePath = path.join(this.serverless.config.servicePath, this.webpackConfig);
      if (!this.serverless.utils.fileExistsSync(webpackConfigFilePath)) {
        throw new this.serverless.classes
          .Error('The webpack plugin could not find the configuration file at: ' + webpackConfigFilePath);
      }
      this.webpackConfig = require(webpackConfigFilePath);
    }

    // Default context
    if (!this.webpackConfig.context) {
      this.webpackConfig.context = this.serverless.config.servicePath;
    }

    // Default output
    if (!this.webpackConfig.output) {
      const outputPath = path.join(this.serverless.config.servicePath, '.webpack');
      const outputFilename = path.basename(
        Array.isArray(this.webpackConfig.entry)
        && this.webpackConfig.entry[this.webpackConfig.entry.length - 1]
        || this.webpackConfig.entry
        || 'handler.js'
      );
      this.webpackConfig.output = {
        libraryTarget: 'commonjs',
        path: outputPath,
        filename: outputFilename,
      };
    }

    // Custom output path
    if (this.options.out) {
      this.webpackConfig.output.path = path.join(this.serverless.config.servicePath, this.options.out);
    }

    fse.removeSync(this.webpackConfig.output.path);

    return BbPromise.resolve();
  },
};
<|endoftext|>


<commit_before>const VARIANT_INTERPRETER_BROWSER_REARRANGEMENT_SETTINGS = {
    menu: {
        // add all filters and let variant-interpreter-browser-cancer handle the visibility based on callers
        // filters: []

        sections: [ // sections and subsections, structure and order is respected
            {
                title: "Sample And File",
                filters: ["sample-genotype", "variant-file", "variant-file-info-filter"],
            },
            {
                title: "Genomic",
                filters: ["region", "feature", "biotype", "type"]
            },
            {
                title: "Clinical",
                filters: ["diseasePanels", "clinical-annotation"]
            },
            {
                title: "Consequence Type",
                filters: ["consequence-type"]
            },
            {
                title: "Population Frequency",
                filters: ["populationFrequency"]
            },
            {
                title: "Phenotype",
                filters: ["go", "hpo"]
            },
            {
                title: "Deleteriousness",
                filters: ["proteinSubstitutionScore", "cadd"]
            },
            {
                title: "Conservation",
                filters: ["conservation"]
            }
        ]
    },
    table: {
        // merge criterium: spread operator
        toolbar: {
            showColumns: true,
            showExport: true,
            showDownload: false
            // columns list for the dropdown will be added in grid components based on settings.table.columns
        }
        // merge criterium: uses this array as filter for internal 1D/2D array. It handles row/col span
        // It is supported either columns[] or hiddenColumns[].
        // columns: ["id"]
    }
    // merge criterium: uses this array as filter for internal 1D array.
    // details: []

};
<commit_msg>wc: clean-up rearregentment settings<commit_after>const VARIANT_INTERPRETER_BROWSER_REARRANGEMENT_SETTINGS = {
    menu: {
        // add all filters and let variant-interpreter-browser-cancer handle the visibility based on callers
        // filters: []

        sections: [ // sections and subsections, structure and order is respected
            // {
            //     title: "Sample And File",
            //     filters: ["variant-file-info-filter"],
            // },
            {
                title: "Genomic",
                filters: ["region", "feature", "biotype", "variant-file-info-filter", "diseasePanels"]
            },
            // {
            //     title: "Clinical",
            //     filters: ["diseasePanels", "clinical-annotation"]
            // },
            // {
            //     title: "Phenotype",
            //     filters: ["go", "hpo"]
            // },
        ]
    },
    table: {
        // merge criterium: spread operator
        toolbar: {
            showColumns: true,
            showExport: true,
            showDownload: false
            // columns list for the dropdown will be added in grid components based on settings.table.columns
        }
        // merge criterium: uses this array as filter for internal 1D/2D array. It handles row/col span
        // It is supported either columns[] or hiddenColumns[].
        // columns: ["id"]
    }
    // merge criterium: uses this array as filter for internal 1D array.
    // details: []

};
<|endoftext|>