<commit_before>import React                  from "react"
import { connect }            from "react-redux"
import { bindActionCreators } from 'redux'
import { Link }               from "react-router"
import { Field, reduxForm }   from "redux-form"
import _                      from "lodash"
import Select, { Creatable }  from "react-select"
import Notifications          from 'react-notification-system-redux'
import { notificationOpts }   from '../../utils/NotificationUtils'

import CatalogSearchBar from "./CatalogSearchBar"
import CatalogItem      from "./CatalogItem"
import CatalogItemBoard from "./CatalogItemBoard"

import "./Catalog.css"

export default class Catalog extends React.Component {

  constructor(props) {
    super(props);

    this.handleDissmis = this.handleDissmis.bind(this)
    this.handleAddItemToBoard = this.handleAddItemToBoard.bind(this)
    this.handleCreateService = this.handleCreateService.bind(this)
    this.selectChange = this.selectChange.bind(this)
    this.updateCustomDomain = this.updateCustomDomain.bind(this)
  }

  componentDidMount() {
    this.props.fetchStacks()
    this.props.fetchCatalog()
  }

  handleDissmis(name) {
    const { removeItemFromBoard, dispatchNotification } = this.props
    removeItemFromBoard(name)
    dispatchNotification(
      Notifications.success,
      notificationOpts(
        'Success',
        `Successfully remove ${ name } from board!`
        )
      )
  }

  handleAddItemToBoard(name, category) {
    const { addItemToBoard, info, dispatchNotification } = this.props

    addItemToBoard(name, category)
    dispatchNotification(
      Notifications.success,
      notificationOpts(
        'Success',
        `Successfully added ${ name } to board!`,
        () => document.getElementById('#board').scrollIntoView()
      )
    )
  }

  handleCreateService(domain, newService) {
    this.props.deployService(
      domain,
      newService,
      Notifications.success,
      notificationOpts('Success', `Successfully deploy service!`)
      )
  }

  renderBoardItem(board) {
    const { info } = this.props
    return board.map((b, index) => {
      return (
        <CatalogItemBoard
          index={ index }
          key={ index }
          serviceName={ Object.keys(b.service)[0] }
          img={ b.manifest.logo }
          title={ b.manifest.title }
          name={ Object.keys(b.service)[0] }
          image={ "b.service" }
          dismiss={this.handleDissmis} />
      )
    })
  }

  renderOperatingSystem(data) {
    const arrData = _.map(data)

    return arrData.map((d) => {
      return (
        <CatalogItem
          key={ d.name }
          onAdd={this.handleAddItemToBoard}
          img={ d.logo }
          name={ d.name }
          title={ d.title }
          desc={ d.description }
          category="os" />
      )
    })
  }

  renderApplication(data) {
    const arrData = _.map(data)

    return arrData.map((d) => {
      return (
        <CatalogItem
          key={ d.name }
          onAdd={this.handleAddItemToBoard}
          img={ d.logo }
          name={ d.name }
          title={ d.title }
          desc={ d.description }
          category="applications" />
      )
    })
  }

  renderDatabase(data) {
    const arrData = _.map(data)

    return arrData.map((d) => {
      return (
        <CatalogItem
          key={ d.name }
          onAdd={this.handleAddItemToBoard}
          img={ d.logo }
          name={ d.name }
          title={ d.title }
          desc={ d.description }
          category="databases" />
      )
    })
  }

  renderFramework(data) {
    const arrData = _.map(data)

    return arrData.map((d) => {
      return (
        <CatalogItem
          key={ d.name }
          onAdd={this.handleAddItemToBoard}
          img={ d.logo }
          name={ d.name }
          title={ d.title }
          desc={ d.description }
          category="frameworks" />
      )
    })
  }

  renderLanguage(data) {
    const arrData = _.map(data)

    return arrData.map((d) => {
      return (
        <CatalogItem
          key={ d.name }
          onAdd={this.handleAddItemToBoard}
          img={ d.logo }
          name={ d.name }
          title={ d.title }
          desc={ d.description }
          category="languages" />
      )
    })
  }

  selectChange(val) {
    console.log("Selected: ", val)
    this.props.setStackName(val.value)
  }

  updateCustomDomain(val) {
    console.log(val.target.value)
    this.props.updateCustomDomain(val.target.value)
  }

	render() {
    const {
      fetching, fetched, error, catalog, board, info, user,
      newService, newService_loading, newService_done,
    } = this.props

    window.board = board
    window.newService = newService
    window.stacks = this.props.stacks
    window.SelectOptions = this.props.options

		return (

CATALOG

<Link to="/">HOME</Link>

CATALOG

        {/*

					<CatalogSearchBar />

*/}

                  PROJECT WIZARD

                        PROJECT NAME

                        <Creatable
                          name="groupName"
                          value={this.props.newService.opt ? this.props.newService.opt.stack : ''}
                          options={this.props.options}
                          onChange={this.selectChange}
                          clearable={true}
                          allowCreate={true}
                          disabled={ newService_loading }
                          promptTextCreator ={(label) => `Create New Project "${label}"`}
                          searchable={true}
                          noResultsText="No project found"
                          placeholder="Project Name..." />

                        CUSTOM DOMAIN

                        <input
                          name="domain"
                          className="form-control"
                          placeholder="Type your custom domain here ..."
                          readOnly={ newService_loading }
                          onChange={this.updateCustomDomain}
                          value={ newService &&
                                  newService.opt &&
                                  newService.opt.domain ?
                                  newService.opt.domain : '' } />

                        DOMAIN

                        { board &&
                          board.length > 0 &&
                          newService &&
                          newService.opt &&
                          newService.opt.services ?
                          ( newService &&
                            newService.opt &&
                            newService.opt.domain ?
                            newService.opt.domain :
                            ( fetched &&
                              user && newService &&
                              newService.opt &&
                              newService.opt.services &&
                              newService.opt.services[Object.keys(newService.opt.services)[0]] &&
                              newService.opt.services[Object.keys(newService.opt.services)[0]].endpoint ?
                              `${user.data.id}-${newService.opt.stack}-${Object.keys(newService.opt.services)[0]}-${info.endpoint}` :
                              'no domain provided'
                            )
                          ) : 'select service and project first' }

                    {/* TODO: tambah loading status dan redirect ke halaman stack */}
                      { this.props.newService &&
                        this.props.newService.opt &&
                        this.props.newService.opt.stack &&
                        board &&
                        board.length > 0 ?
                        ( newService_loading ?
                          <button
                              disabled={ newService_loading }
                              style={{ border: "1px solid #209687" }}
                              className="btn btn-success create-button" >

                              Processing
                          </button> :
                          <button
                            style={{ border: "1px solid #209687" }}
                            className="btn btn-success create-button"
                            onClick={ () => this.handleCreateService(newService && newService.opt && newService.opt.domain ? newService.opt.domain :(fetched && user && newService && newService.opt && newService.opt.services ? `${user.data.id}-${newService.opt.stack}-${Object.keys(newService.opt.services)[0]}-${info.endpoint}`: undefined), newService) } >

                            Deploy Service
                        </button>)
                         :
                        <button
                            className="btn btn-default"
                            type="button"
                            disabled={true} >

                            Deploy Service
                        </button>
                      }

                    {
                      board.length > 0 ?
                      this.renderBoardItem(board) :

                        choose services from catalog below

                    }

          {/*
Operating System

          { fetching &&

          }

            { fetched &&
              this.renderOperatingSystem(catalog.categories.os)
            }

*/}

Applications

          { fetching &&

          }

            { fetched &&
              this.renderApplication(catalog.categories.applications)
            }

Database

          { fetching &&

          }

            { fetched &&
              this.renderDatabase(catalog.categories.databases)
            }

          {/*

Framework

          { fetching &&

          }

            { fetched &&
              this.renderFramework(catalog.categories.frameworks)
            }

Language Stack

          { fetching &&

          }

            { fetched &&
              this.renderLanguage(catalog.categories.languages)
            }

*/}

          {/*

                <button className="btn btn-primary btn-block create-button">BUILD NEW IMAGE</button>

          */}

		)
	}
}
<commit_msg>UPDATE: change clearable to false<commit_after>import React                  from "react"
import { connect }            from "react-redux"
import { bindActionCreators } from 'redux'
import { Link }               from "react-router"
import { Field, reduxForm }   from "redux-form"
import _                      from "lodash"
import Select, { Creatable }  from "react-select"
import Notifications          from 'react-notification-system-redux'
import { notificationOpts }   from '../../utils/NotificationUtils'

import CatalogSearchBar from "./CatalogSearchBar"
import CatalogItem      from "./CatalogItem"
import CatalogItemBoard from "./CatalogItemBoard"

import "./Catalog.css"

export default class Catalog extends React.Component {

  constructor(props) {
    super(props);

    this.handleDissmis = this.handleDissmis.bind(this)
    this.handleAddItemToBoard = this.handleAddItemToBoard.bind(this)
    this.handleCreateService = this.handleCreateService.bind(this)
    this.selectChange = this.selectChange.bind(this)
    this.updateCustomDomain = this.updateCustomDomain.bind(this)
  }

  componentDidMount() {
    this.props.fetchStacks()
    this.props.fetchCatalog()
  }

  handleDissmis(name) {
    const { removeItemFromBoard, dispatchNotification } = this.props
    removeItemFromBoard(name)
    dispatchNotification(
      Notifications.success,
      notificationOpts(
        'Success',
        `Successfully remove ${ name } from board!`
        )
      )
  }

  handleAddItemToBoard(name, category) {
    const { addItemToBoard, info, dispatchNotification } = this.props

    addItemToBoard(name, category)
    dispatchNotification(
      Notifications.success,
      notificationOpts(
        'Success',
        `Successfully added ${ name } to board!`,
        () => document.getElementById('#board').scrollIntoView()
      )
    )
  }

  handleCreateService(domain, newService) {
    this.props.deployService(
      domain,
      newService,
      Notifications.success,
      notificationOpts('Success', `Successfully deploy service!`)
      )
  }

  renderBoardItem(board) {
    const { info } = this.props
    return board.map((b, index) => {
      return (
        <CatalogItemBoard
          index={ index }
          key={ index }
          serviceName={ Object.keys(b.service)[0] }
          img={ b.manifest.logo }
          title={ b.manifest.title }
          name={ Object.keys(b.service)[0] }
          image={ "b.service" }
          dismiss={this.handleDissmis} />
      )
    })
  }

  renderOperatingSystem(data) {
    const arrData = _.map(data)

    return arrData.map((d) => {
      return (
        <CatalogItem
          key={ d.name }
          onAdd={this.handleAddItemToBoard}
          img={ d.logo }
          name={ d.name }
          title={ d.title }
          desc={ d.description }
          category="os" />
      )
    })
  }

  renderApplication(data) {
    const arrData = _.map(data)

    return arrData.map((d) => {
      return (
        <CatalogItem
          key={ d.name }
          onAdd={this.handleAddItemToBoard}
          img={ d.logo }
          name={ d.name }
          title={ d.title }
          desc={ d.description }
          category="applications" />
      )
    })
  }

  renderDatabase(data) {
    const arrData = _.map(data)

    return arrData.map((d) => {
      return (
        <CatalogItem
          key={ d.name }
          onAdd={this.handleAddItemToBoard}
          img={ d.logo }
          name={ d.name }
          title={ d.title }
          desc={ d.description }
          category="databases" />
      )
    })
  }

  renderFramework(data) {
    const arrData = _.map(data)

    return arrData.map((d) => {
      return (
        <CatalogItem
          key={ d.name }
          onAdd={this.handleAddItemToBoard}
          img={ d.logo }
          name={ d.name }
          title={ d.title }
          desc={ d.description }
          category="frameworks" />
      )
    })
  }

  renderLanguage(data) {
    const arrData = _.map(data)

    return arrData.map((d) => {
      return (
        <CatalogItem
          key={ d.name }
          onAdd={this.handleAddItemToBoard}
          img={ d.logo }
          name={ d.name }
          title={ d.title }
          desc={ d.description }
          category="languages" />
      )
    })
  }

  selectChange(val) {
    console.log("Selected: ", val)
    this.props.setStackName(val.value)
  }

  updateCustomDomain(val) {
    console.log(val.target.value)
    this.props.updateCustomDomain(val.target.value)
  }

	render() {
    const {
      fetching, fetched, error, catalog, board, info, user,
      newService, newService_loading, newService_done,
    } = this.props

    window.board = board
    window.newService = newService
    window.stacks = this.props.stacks
    window.SelectOptions = this.props.options

		return (

CATALOG

<Link to="/">HOME</Link>

CATALOG

        {/*

					<CatalogSearchBar />

*/}

                  PROJECT WIZARD

                        PROJECT NAME

                        <Creatable
                          name="groupName"
                          value={this.props.newService.opt ? this.props.newService.opt.stack : ''}
                          options={this.props.options}
                          onChange={this.selectChange}
                          clearable={false}
                          allowCreate={true}
                          disabled={ newService_loading }
                          promptTextCreator ={(label) => `Create New Project "${label}"`}
                          searchable={true}
                          noResultsText="No project found"
                          placeholder="Project Name..." />

                        CUSTOM DOMAIN

                        <input
                          name="domain"
                          className="form-control"
                          placeholder="Type your custom domain here ..."
                          readOnly={ newService_loading }
                          onChange={this.updateCustomDomain}
                          value={ newService &&
                                  newService.opt &&
                                  newService.opt.domain ?
                                  newService.opt.domain : '' } />

                        DOMAIN

                        { board &&
                          board.length > 0 &&
                          newService &&
                          newService.opt &&
                          newService.opt.services ?
                          ( newService &&
                            newService.opt &&
                            newService.opt.domain ?
                            newService.opt.domain :
                            ( fetched &&
                              user && newService &&
                              newService.opt &&
                              newService.opt.services &&
                              newService.opt.services[Object.keys(newService.opt.services)[0]] &&
                              newService.opt.services[Object.keys(newService.opt.services)[0]].endpoint ?
                              `${user.data.id}-${newService.opt.stack}-${Object.keys(newService.opt.services)[0]}-${info.endpoint}` :
                              'no domain provided'
                            )
                          ) : 'select service and project first' }

                    {/* TODO: tambah loading status dan redirect ke halaman stack */}
                      { this.props.newService &&
                        this.props.newService.opt &&
                        this.props.newService.opt.stack &&
                        board &&
                        board.length > 0 ?
                        ( newService_loading ?
                          <button
                              disabled={ newService_loading }
                              style={{ border: "1px solid #209687" }}
                              className="btn btn-success create-button" >

                              Processing
                          </button> :
                          <button
                            style={{ border: "1px solid #209687" }}
                            className="btn btn-success create-button"
                            onClick={ () => this.handleCreateService(newService && newService.opt && newService.opt.domain ? newService.opt.domain :(fetched && user && newService && newService.opt && newService.opt.services ? `${user.data.id}-${newService.opt.stack}-${Object.keys(newService.opt.services)[0]}-${info.endpoint}`: undefined), newService) } >

                            Deploy Service
                        </button>)
                         :
                        <button
                            className="btn btn-default"
                            type="button"
                            disabled={true} >

                            Deploy Service
                        </button>
                      }

                    {
                      board.length > 0 ?
                      this.renderBoardItem(board) :

                        choose services from catalog below

                    }

          {/*
Operating System

          { fetching &&

          }

            { fetched &&
              this.renderOperatingSystem(catalog.categories.os)
            }

*/}

Applications

          { fetching &&

          }

            { fetched &&
              this.renderApplication(catalog.categories.applications)
            }

Database

          { fetching &&

          }

            { fetched &&
              this.renderDatabase(catalog.categories.databases)
            }

          {/*

Framework

          { fetching &&

          }

            { fetched &&
              this.renderFramework(catalog.categories.frameworks)
            }

Language Stack

          { fetching &&

          }

            { fetched &&
              this.renderLanguage(catalog.categories.languages)
            }

*/}

          {/*

                <button className="btn btn-primary btn-block create-button">BUILD NEW IMAGE</button>

          */}

		)
	}
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay';
import XRegExp from 'xregexp';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import { Card, CardActions, CardHeader, CardText } from 'material-ui/Card';
import styled from 'styled-components';
import {
  FormattedMessage,
  defineMessages,
  injectIntl,
  intlShape,
} from 'react-intl';
import config from 'config'; // eslint-disable-line require-path-exists/exists
import PageTitle from '../PageTitle';
import CreateTeamMutation from '../../relay/mutations/CreateTeamMutation';
import Message from '../Message';
import CheckContext from '../../CheckContext';
import { safelParseJSON } from '../../helpers';
import {
  ContentColumn,
  caption,
  subheading2,
  checkBlue,
  black38,
} from '../../styles/js/shared';

const TeamUrlRow = styled.div`
  align-items: flex-end;
  display: flex;
  font-size: 12px;
  margin-top: 24px;
  label {
    font: ${caption};
    color: ${checkBlue};
  }
`;

const TeamUrlColumn = styled.div`
  display: flex;
  flex-direction: column;
  padding-bottom: 9px;
`;

const TeamUrlDomain = styled.span`
  font: ${subheading2};
  color: ${black38};
`;

const messages = defineMessages({
  slugChecking: {
    id: 'createTeam.slugChecking',
    defaultMessage: 'Checking availability...',
  },
  slugAvailable: {
    id: 'createTeam.slugAvailable',
    defaultMessage: 'Available!',
  },
  slugUnavailable: {
    id: 'createTeam.slugUnavailable',
    defaultMessage: 'That URL is unavailable.',
  },
  createTeamError: {
    id: 'createTeam.createTeamError',
    defaultMessage: 'Sorry, could not create the team',
  },
  title: {
    id: 'createTeam.title',
    defaultMessage: 'Create a Team',
  },
  teamNameHint: {
    id: 'createTeam.teamNameHint',
    defaultMessage: 'Team Name',
  },
  teamSlugHint: {
    id: 'createTeam.teamSlugHint',
    defaultMessage: 'team-slug',
  },
});

class CreateTeam extends Component {
  constructor(props) {
    super(props);

    this.state = {
      teamName: '',
      slugName: '',
    };
  }

  componentDidMount() {
    this.teamDisplayName.focus();
  }

  getContext() {
    return new CheckContext(this).getContextStore();
  }

  handleDisplayNameBlur(e) {
    function slugify(text) {
      const regex = XRegExp('[^\\p{L}\\p{N}]+', 'g');
      return XRegExp.replace(text.toString().toLowerCase().trim(), regex, '-');
    }

    const slugName = slugify(e.target.value);

    if (!this.state.slugName && slugName.length) {
      this.setState({ teamName: e.target.value, slugName });
    }
  }

  handleSlugChange(e) {
    this.setState({ slugName: e.target.value });
  }

  handleSubmit(e) {
    e.preventDefault();

    const context = this.getContext();

    const onFailure = (transaction) => {
      const error = transaction.getError();
      let message = this.props.intl.formatMessage(messages.createTeamError);
      const json = safelParseJSON(error.source);
      if (json && json.error) {
        message = json.error;
      }
      this.setState({ message });
    };

    const onSuccess = (response) => {
      this.setState({ message: null });
      const { createTeam: { team } } = response;
      const teams = JSON.parse(context.currentUser.teams);
      teams[team.slug] = { status: 'member', role: 'owner' };
      context.currentUser.teams = JSON.stringify(teams);
      context.currentUser.current_team = team;

      const path = `/${team.slug}`;
      context.history.push(path);
    };

    Relay.Store.commitUpdate(
      new CreateTeamMutation({
        name: this.state.teamName,
        slug: this.state.slugName,
        description: '',
        user: context.currentUser,
      }),
      { onSuccess, onFailure },
    );
  }

  render() {
    return (
      <PageTitle
        prefix={this.props.intl.formatMessage(messages.title)}
        skipTeam
      >

          <ContentColumn narrow>
            <Message message={this.state.message} />
            <Card>
              <CardHeader
                titleStyle={{ fontSize: '20px', lineHeight: '32px' }}
                title={
                  <FormattedMessage
                    id="createTeam.mainHeading"
                    defaultMessage="Create a Team"
                  />
                }
                subtitle={
                  <FormattedMessage
                    id="createTeam.blurb"
                    defaultMessage="Create a team for your organization, or just for yourself:"
                  />
                }
              />
              <form className="create-team__form">
                <CardText>

                    <TextField
                      type="text"
                      id="team-name-container"
                      className="create-team__team-display-name-input"
                      onBlur={this.handleDisplayNameBlur.bind(this)}
                      autoComplete="off"
                      ref={(i) => { this.teamDisplayName = i; }}
                      floatingLabelText={
                        <FormattedMessage
                          id="createTeam.displayName"
                          defaultMessage="Team Name"
                        />
                      }
                      fullWidth
                    />

                  <TeamUrlRow>
                    <TeamUrlColumn>

                        <FormattedMessage
                          id="createTeam.url"
                          defaultMessage="Team URL"
                        />

                      <TeamUrlDomain>
                        {config.selfHost}/
                      </TeamUrlDomain>
                    </TeamUrlColumn>
                    <TextField
                      value={this.state.slugName}
                      type="text"
                      id="team-slug-container"
                      className="create-team__team-slug-input"
                      onChange={this.handleSlugChange.bind(this)}
                      hintText={this.props.intl.formatMessage(messages.teamSlugHint)}
                      autoComplete="off"
                      fullWidth
                    />
                  </TeamUrlRow>
                </CardText>
                <CardActions>
                  <RaisedButton
                    type="submit"
                    className="create-team__submit-button"
                    label={
                      <FormattedMessage
                        id="createTeam.submitButton"
                        defaultMessage="Create"
                      />
                    }
                    primary
                    onClick={this.handleSubmit.bind(this)}
                  />
                </CardActions>
              </form>
            </Card>
          </ContentColumn>

      </PageTitle>
    );
  }
}

CreateTeam.propTypes = {
  // https://github.com/yannickcr/eslint-plugin-react/issues/1389
  // eslint-disable-next-line react/no-typos
  intl: intlShape.isRequired,
};

CreateTeam.contextTypes = {
  store: PropTypes.object,
};

export default injectIntl(CreateTeam);
<commit_msg>Fix typo that broke error message #6807<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay';
import XRegExp from 'xregexp';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import { Card, CardActions, CardHeader, CardText } from 'material-ui/Card';
import styled from 'styled-components';
import {
  FormattedMessage,
  defineMessages,
  injectIntl,
  intlShape,
} from 'react-intl';
import config from 'config'; // eslint-disable-line require-path-exists/exists
import PageTitle from '../PageTitle';
import CreateTeamMutation from '../../relay/mutations/CreateTeamMutation';
import Message from '../Message';
import CheckContext from '../../CheckContext';
import { safelyParseJSON } from '../../helpers';
import {
  ContentColumn,
  caption,
  subheading2,
  checkBlue,
  black38,
} from '../../styles/js/shared';

const TeamUrlRow = styled.div`
  align-items: flex-end;
  display: flex;
  font-size: 12px;
  margin-top: 24px;
  label {
    font: ${caption};
    color: ${checkBlue};
  }
`;

const TeamUrlColumn = styled.div`
  display: flex;
  flex-direction: column;
  padding-bottom: 9px;
`;

const TeamUrlDomain = styled.span`
  font: ${subheading2};
  color: ${black38};
`;

const messages = defineMessages({
  slugChecking: {
    id: 'createTeam.slugChecking',
    defaultMessage: 'Checking availability...',
  },
  slugAvailable: {
    id: 'createTeam.slugAvailable',
    defaultMessage: 'Available!',
  },
  slugUnavailable: {
    id: 'createTeam.slugUnavailable',
    defaultMessage: 'That URL is unavailable.',
  },
  createTeamError: {
    id: 'createTeam.createTeamError',
    defaultMessage: 'Sorry, could not create the team',
  },
  title: {
    id: 'createTeam.title',
    defaultMessage: 'Create a Team',
  },
  teamNameHint: {
    id: 'createTeam.teamNameHint',
    defaultMessage: 'Team Name',
  },
  teamSlugHint: {
    id: 'createTeam.teamSlugHint',
    defaultMessage: 'team-slug',
  },
});

class CreateTeam extends Component {
  constructor(props) {
    super(props);

    this.state = {
      teamName: '',
      slugName: '',
    };
  }

  componentDidMount() {
    this.teamDisplayName.focus();
  }

  getContext() {
    return new CheckContext(this).getContextStore();
  }

  handleDisplayNameBlur(e) {
    function slugify(text) {
      const regex = XRegExp('[^\\p{L}\\p{N}]+', 'g');
      return XRegExp.replace(text.toString().toLowerCase().trim(), regex, '-');
    }

    const slugName = slugify(e.target.value);

    if (!this.state.slugName && slugName.length) {
      this.setState({ teamName: e.target.value, slugName });
    }
  }

  handleSlugChange(e) {
    this.setState({ slugName: e.target.value });
  }

  handleSubmit(e) {
    e.preventDefault();

    const context = this.getContext();

    const onFailure = (transaction) => {
      const error = transaction.getError();
      let message = this.props.intl.formatMessage(messages.createTeamError);
      const json = safelyParseJSON(error.source);
      if (json && json.error) {
        message = json.error;
      }
      this.setState({ message });
    };

    const onSuccess = (response) => {
      this.setState({ message: null });
      const { createTeam: { team } } = response;
      const teams = JSON.parse(context.currentUser.teams);
      teams[team.slug] = { status: 'member', role: 'owner' };
      context.currentUser.teams = JSON.stringify(teams);
      context.currentUser.current_team = team;

      const path = `/${team.slug}`;
      context.history.push(path);
    };

    Relay.Store.commitUpdate(
      new CreateTeamMutation({
        name: this.state.teamName,
        slug: this.state.slugName,
        description: '',
        user: context.currentUser,
      }),
      { onSuccess, onFailure },
    );
  }

  render() {
    return (
      <PageTitle
        prefix={this.props.intl.formatMessage(messages.title)}
        skipTeam
      >

          <ContentColumn narrow>
            <Message message={this.state.message} />
            <Card>
              <CardHeader
                titleStyle={{ fontSize: '20px', lineHeight: '32px' }}
                title={
                  <FormattedMessage
                    id="createTeam.mainHeading"
                    defaultMessage="Create a Team"
                  />
                }
                subtitle={
                  <FormattedMessage
                    id="createTeam.blurb"
                    defaultMessage="Create a team for your organization, or just for yourself:"
                  />
                }
              />
              <form className="create-team__form">
                <CardText>

                    <TextField
                      type="text"
                      id="team-name-container"
                      className="create-team__team-display-name-input"
                      onBlur={this.handleDisplayNameBlur.bind(this)}
                      autoComplete="off"
                      ref={(i) => { this.teamDisplayName = i; }}
                      floatingLabelText={
                        <FormattedMessage
                          id="createTeam.displayName"
                          defaultMessage="Team Name"
                        />
                      }
                      fullWidth
                    />

                  <TeamUrlRow>
                    <TeamUrlColumn>

                        <FormattedMessage
                          id="createTeam.url"
                          defaultMessage="Team URL"
                        />

                      <TeamUrlDomain>
                        {config.selfHost}/
                      </TeamUrlDomain>
                    </TeamUrlColumn>
                    <TextField
                      value={this.state.slugName}
                      type="text"
                      id="team-slug-container"
                      className="create-team__team-slug-input"
                      onChange={this.handleSlugChange.bind(this)}
                      hintText={this.props.intl.formatMessage(messages.teamSlugHint)}
                      autoComplete="off"
                      fullWidth
                    />
                  </TeamUrlRow>
                </CardText>
                <CardActions>
                  <RaisedButton
                    type="submit"
                    className="create-team__submit-button"
                    label={
                      <FormattedMessage
                        id="createTeam.submitButton"
                        defaultMessage="Create"
                      />
                    }
                    primary
                    onClick={this.handleSubmit.bind(this)}
                  />
                </CardActions>
              </form>
            </Card>
          </ContentColumn>

      </PageTitle>
    );
  }
}

CreateTeam.propTypes = {
  // https://github.com/yannickcr/eslint-plugin-react/issues/1389
  // eslint-disable-next-line react/no-typos
  intl: intlShape.isRequired,
};

CreateTeam.contextTypes = {
  store: PropTypes.object,
};

export default injectIntl(CreateTeam);
<|endoftext|>


<commit_before>/**
 * @fileOverview Issue all directive
 * @author Chris James
 */
define(['jquery', 'webfontloader'], function ($, WebFont) {
    'use strict';

    /**
     * Issue All directive
     */
    var IssueAllDirective = function () {
        return {
            restrict: 'A',
            scope: true,
            controller: IssueAllCtrl,
            link: IssueAllLinkFn,
            templateUrl: '/app/lorax/directives/issue-all.tpl.html'
        };
    };

    /**
     * Controller for issue all directive
     * @constructor
     */
    var IssueAllCtrl = function (
        $scope,
        $timeout,
        dataService,
        windowService,
        scrollService,
        pubSubService,
        experienceService
    ) {

        this._$scope = $scope;
        this._$timeout = $timeout;
        this._dataService = dataService;
        this._windowService = windowService;
        this._scrollService = scrollService;
        this._pubSubService = pubSubService;
        this._experienceService = experienceService;

        this._$scope.detail = {
            currentIssue : '',
            scrollTo: this.scrollToIssue.bind(this),
            nextIssue: this.nextIssue.bind(this)
        };

        this._issueOffset = {
            'small': 35,
            'medium': 100,
            'large': 125,
            'xlarge': 138
        };

        this._onScrollBind = this.onScroll.bind(this);

        // get model
        this._dataService.getMain().then(this.onModelLoaded.bind(this));

        this._pubSubService.subscribe('detail.scrollToIssue', this.scrollToIssue.bind(this));
        this._pubSubService.subscribe('detail.open', this.open.bind(this));
        this._pubSubService.subscribe('detail.close', this.close.bind(this));
    };

    IssueAllCtrl.$inject = [
        '$scope',
        '$timeout',
        'dataService',
        'windowService',
        'scrollService',
        'pubSubService',
        'experienceService'
    ];

    IssueAllCtrl.prototype.init = function () {
        WebFont.load({
            active: this.onFontsLoaded.bind(this),
            custom: {families: ['Fira Sans:n2,n3,n4,n5,n6,n7,n8,n9']}
        });
    };

    IssueAllCtrl.prototype.open = function () {
        $(window).on('scroll', this._onScrollBind);
    };

    IssueAllCtrl.prototype.close = function () {
        $(window).off('scroll', this._onScrollBind);
    };

    IssueAllCtrl.prototype.onFontsLoaded = function () {
        this.fontsLoaded = true;

        if (this._$scope.detail.model) {
            this.setOffsets();
        }
    };

    IssueAllCtrl.prototype.onModelLoaded = function (model) {
        this._$scope.detail.model = model;

        if (this.fontsLoaded) {
            this.setOffsets();
        }
    };

    IssueAllCtrl.prototype.setOffsets = function () {
        var issues = this._$scope.detail.model.getIssues();
        var issue;
        var issueElm;
        var issueTitle;

        // hack
        var detailIsHidden = $('#detail').hasClass('ng-hide');
        $('#detail').removeClass('ng-hide');

        // set offset property of all issues
        for (var i = 0; i < issues.length; i ++) {
            issue = issues[i];
            issueElm = $('#' + issue.getId());
            issueTitle = $('.detail-header-section', issueElm);
            issue.offset = issueElm.offset();
            issue.titleOffset = issueTitle.offset();
        }

        this._experienceService.setMenuPositions();

        if (detailIsHidden) {
            $('#detail').addClass('ng-hide');
        }

        this.initialized = true;

        if (this.issue || this.topic) {
            this._doScrollToIssue();
        }
    };

    IssueAllCtrl.prototype.scrollToIssue = function (issue, topic) {
        this.issue = issue;
        this.topic = topic;

        if (this.initialized) {
            this._doScrollToIssue();
        }
    };

    IssueAllCtrl.prototype._doScrollToIssue = function () {
        this._currentStatus = null;

        // get first issue from topic
        if (this.topic && !this.issue) {
            this.issue = this._$scope.detail.model.getTopicById(this.topic).getIssues()[0].getId();
        }

        // find issue offset
        var offset = 0;
        if (this.issue) {
            offset = this._$scope.detail.model.getIssueById(this.issue).offset.top - this._issueOffset[this._windowService.breakpoint()];
        }

        offset = Math.max(1, offset);

        // scroll to offset
        if (!this._scrolled) {
            this._scrollService.go('top', {offset: offset, animate: false});
        }
        this._scrolled = false;
        this._$scope.detail.currentIssue = this.issue;
    };

    IssueAllCtrl.prototype.nextIssue = function () {
        this._$scope.detail.currentIssue =
            $('#' + this._$scope.detail.currentIssue).next().attr('id');

        if (this._$scope.detail.currentIssue) {
            this._$scope.detail.scrollTo(this._$scope.detail.currentIssue);
        }
    };

    IssueAllCtrl.prototype.onScroll = function () {
        var scrollTop = $(window).scrollTop();
        this._experienceService.onScroll(scrollTop);

        var currentElm = $('.detail')[0];
        $('.detail').each(function (index, elm) {
            if (elm.offsetTop - 100 >= scrollTop) {
                return false;
            }
            currentElm = elm;
        });

        var data = this._$scope.detail.model.getIssueById(currentElm.id);
        var status = currentElm.attributes['data-issue-status'].value;

        // if issue changed and it's not right after a scrollToIssue
        if (currentElm.id !== this.issue && this._currentStatus !== null) {
            this._scrolled = true;
            this.issue = currentElm.id;
            this._windowService.setIssue(data);
        }

        if (status !== this._currentStatus) {
            this._windowService.setBgMode(status);
            this._currentStatus = status;
        }

        var topic = data.getParentId();
        if (topic !== this._currentTopic) {
            this._windowService.setTopic(topic);
            this._currentTopic = topic;
        }
    };

    /**
     * Link function for Issue All directive
     * @param {object} scope      Angular scope.
     * @param {JQuery} iElem      Detail wrapper jQuery element.
     */
    var IssueAllLinkFn = function (scope, iElem, iAttrs, controller) {

        // wait for everything to be rendered
        // controller._$timeout(function () {
        //     console.log($('.main--detail').children());
        //     controller.init();
        // }, 500);
        var checkRenderedInterval = setInterval(function () {
            controller._$timeout(function () {
                var children = $('.main--detail').children();
                if(children.length && $(children[0]).attr('data-issue-name')) {
                    clearInterval(checkRenderedInterval);
                    controller.init();
                }
            });
        }, 100);
    };

    return IssueAllDirective;
});
<commit_msg>arrow now fades as you scroll<commit_after>/**
 * @fileOverview Issue all directive
 * @author Chris James
 */
define(['jquery', 'webfontloader'], function ($, WebFont) {
    'use strict';

    /**
     * Issue All directive
     */
    var IssueAllDirective = function () {
        return {
            restrict: 'A',
            scope: true,
            controller: IssueAllCtrl,
            link: IssueAllLinkFn,
            templateUrl: '/app/lorax/directives/issue-all.tpl.html'
        };
    };

    /**
     * Controller for issue all directive
     * @constructor
     */
    var IssueAllCtrl = function (
        $scope,
        $timeout,
        dataService,
        windowService,
        scrollService,
        pubSubService,
        experienceService
    ) {

        this._$scope = $scope;
        this._$timeout = $timeout;
        this._dataService = dataService;
        this._windowService = windowService;
        this._scrollService = scrollService;
        this._pubSubService = pubSubService;
        this._experienceService = experienceService;

        this._$scope.detail = {
            currentIssue : '',
            scrollTo: this.scrollToIssue.bind(this),
            nextIssue: this.nextIssue.bind(this)
        };

        this._downArrowOpacity = 1.0;

        this._issueOffset = {
            'small': 35,
            'medium': 100,
            'large': 125,
            'xlarge': 138
        };

        this._onScrollBind = this.onScroll.bind(this);

        // get model
        this._dataService.getMain().then(this.onModelLoaded.bind(this));

        this._pubSubService.subscribe('detail.scrollToIssue', this.scrollToIssue.bind(this));
        this._pubSubService.subscribe('detail.open', this.open.bind(this));
        this._pubSubService.subscribe('detail.close', this.close.bind(this));
    };

    IssueAllCtrl.$inject = [
        '$scope',
        '$timeout',
        'dataService',
        'windowService',
        'scrollService',
        'pubSubService',
        'experienceService'
    ];

    IssueAllCtrl.prototype.init = function () {
        WebFont.load({
            active: this.onFontsLoaded.bind(this),
            custom: {families: ['Fira Sans:n2,n3,n4,n5,n6,n7,n8,n9']}
        });
    };

    IssueAllCtrl.prototype.open = function () {
        $(window).on('scroll', this._onScrollBind);
    };

    IssueAllCtrl.prototype.close = function () {
        $(window).off('scroll', this._onScrollBind);
    };

    IssueAllCtrl.prototype.onFontsLoaded = function () {
        this.fontsLoaded = true;

        if (this._$scope.detail.model) {
            this.setOffsets();
        }
    };

    IssueAllCtrl.prototype.onModelLoaded = function (model) {
        this._$scope.detail.model = model;

        if (this.fontsLoaded) {
            this.setOffsets();
        }
    };

    IssueAllCtrl.prototype.setOffsets = function () {
        var issues = this._$scope.detail.model.getIssues();
        var issue;
        var issueElm;
        var issueTitle;

        // hack
        var detailIsHidden = $('#detail').hasClass('ng-hide');
        $('#detail').removeClass('ng-hide');

        // set offset property of all issues
        for (var i = 0; i < issues.length; i ++) {
            issue = issues[i];
            issueElm = $('#' + issue.getId());
            issueTitle = $('.detail-header-section', issueElm);
            issue.offset = issueElm.offset();
            issue.titleOffset = issueTitle.offset();
        }

        this._experienceService.setMenuPositions();

        if (detailIsHidden) {
            $('#detail').addClass('ng-hide');
        }

        this.initialized = true;

        if (this.issue || this.topic) {
            this._doScrollToIssue();
        }
    };

    IssueAllCtrl.prototype.scrollToIssue = function (issue, topic) {
        this.issue = issue;
        this.topic = topic;

        if (this.initialized) {
            this._doScrollToIssue();
        }
    };

    IssueAllCtrl.prototype._doScrollToIssue = function () {
        this._currentStatus = null;

        // get first issue from topic
        if (this.topic && !this.issue) {
            this.issue = this._$scope.detail.model.getTopicById(this.topic).getIssues()[0].getId();
        }

        // find issue offset
        var offset = 0;
        if (this.issue) {
            offset = this._$scope.detail.model.getIssueById(this.issue).offset.top - this._issueOffset[this._windowService.breakpoint()];
        }

        offset = Math.max(1, offset);

        // scroll to offset
        if (!this._scrolled) {
            this._scrollService.go('top', {offset: offset, animate: false});
        }
        this._scrolled = false;
        this._$scope.detail.currentIssue = this.issue;
    };

    IssueAllCtrl.prototype.nextIssue = function () {
        this._$scope.detail.currentIssue =
            $('#' + this._$scope.detail.currentIssue).next().attr('id');

        if (this._$scope.detail.currentIssue) {
            this._$scope.detail.scrollTo(this._$scope.detail.currentIssue);
        }
    };

    IssueAllCtrl.prototype.onScroll = function () {
        var scrollTop = $(window).scrollTop();
        this._experienceService.onScroll(scrollTop);

        var currentElm = $('.detail')[0];
        $('.detail').each(function (index, elm) {
            if (elm.offsetTop - 100 >= scrollTop) {
                return false;
            }
            currentElm = elm;
        });

        var data = this._$scope.detail.model.getIssueById(currentElm.id);
        var status = currentElm.attributes['data-issue-status'].value;

        // if issue changed and it's not right after a scrollToIssue
        if (currentElm.id !== this.issue && this._currentStatus !== null) {
            this._scrolled = true;
            this.issue = currentElm.id;
            this._windowService.setIssue(data);
        }

        if (status !== this._currentStatus) {
            this._windowService.setBgMode(status);
            this._currentStatus = status;
        }

        var topic = data.getParentId();
        if (topic !== this._currentTopic) {
            this._windowService.setTopic(topic);
            this._currentTopic = topic;
        }

        // Fade out the down arrow as we scroll
        this._downArrowOpacity -= 0.005;
        console.log(this._downArrowOpacity);
        $('.down-arrow-nav').css('opacity', this._downArrowOpacity);
    };

    /**
     * Link function for Issue All directive
     * @param {object} scope      Angular scope.
     * @param {JQuery} iElem      Detail wrapper jQuery element.
     */
    var IssueAllLinkFn = function (scope, iElem, iAttrs, controller) {

        // wait for everything to be rendered
        // controller._$timeout(function () {
        //     console.log($('.main--detail').children());
        //     controller.init();
        // }, 500);
        var checkRenderedInterval = setInterval(function () {
            controller._$timeout(function () {
                var children = $('.main--detail').children();
                if(children.length && $(children[0]).attr('data-issue-name')) {
                    clearInterval(checkRenderedInterval);
                    controller.init();
                }
            });
        }, 100);
    };

    return IssueAllDirective;
});
<|endoftext|>


<commit_before>$(document).on("page:load ready", function() {

	if ($('body').hasClass('moments show') ||
		$('body').hasClass('strategies show') ||
		$('body').hasClass('meetings show')) {

		$(document).on('click', '#add_comment_button', function(event) {
			event.preventDefault();
			$(this).prop('disabled', true);
			$('#comment_comment').prop('disabled', true);
			$(this).val('Posting comment...');

			if ($('.comment').length > 0) {
				$('.actions').removeClass('no_margin_bottom');
			}

			var url;
			if ($('body').hasClass('moments show')) {
				url = '/moments/comment';
			} else if ($('body').hasClass('strategies show')) {
				url = '/strategies/comment';
			} else {
				url = '/meetings/comment';
			}

			var viewers;
			if ($('#comment_viewers').length) {
				viewers = $('#comment_viewers').val();
			}

			data = {
				comment_type: $('#comment_comment_type').val(),
				commented_on:$('#comment_commented_on').val(),
				comment_by: $('#comment_comment_by').val(),
				comment: $('#comment_comment').val(),
				visibility: $('#comment_visibility').val(),
				viewers: viewers
			};

			$.ajax({
			    dataType: 'json',
			    url: url,
			    type: 'POST',
			    data: data,
			    success: function(json) {
			    	if (json !== undefined) {
			    		$('#add_comment_button').prop('disabled', false);
			    		$('#comment_comment').prop('disabled', false);
			    		$('#comment_comment').val('');
						$('#add_comment_button').val('Comment');

			    		if (!json.no_save) {
				    		var commentid = 'comment_' + json.commentid;
				    		var profile_picture = json.profile_picture;
				    		var comment_info = json.comment_info;
				    		var comment_text = json.comment_text;
				    		var visibility = json.visibility;
				    		var delete_comment = json.delete_comment;

				    		// Remove no_margin_top on first comment
				    		if ($('.comment').length > 0) {
				    			$('.comment.no_margin_top').removeClass('no_margin_top');
				    		}

				    		var newComment = '
';
				    		newComment += '
';
				    		newComment += '
';

				    		newComment += '
';

				    		newComment += profile_picture;
				    		newComment += '
';

				    		newComment += '
';
				    		newComment += '
'
				    		newComment += comment_info;
				    		newComment += '
';
				    		newComment += '
';
				    		newComment += comment_text;
				    		newComment += '
';
				    		if (visibility != null && visibility.length > 0) {
				    			newComment += visibility;
				    		}
				    		newComment += '
';

				    		if (delete_comment != null && delete_comment.length > 0) {
				    			newComment += delete_comment;
				    		}

				    		newComment += '
';
				    		newComment += '
';
				    		newComment += '
';

				    		$('#comments').prepend(newComment);

				    		if ($('.comment').length > 0) {
								$('.actions').removeClass('no_margin_bottom');
							}
				    	}
			    	}
			    },
			    error: function() {
			    	$('#add_comment_button').prop('disabled', false);
			    	$('#comment_comment').prop('disabled', false);
					$('#add_comment_button').val('Comment');
			    }
			});
		});
	}
});<commit_msg>Fixed multiple comment post bug<commit_after>$(document).on("page:load ready", function() {

	if ($('body').hasClass('moments show') ||
		$('body').hasClass('strategies show') ||
		$('body').hasClass('meetings show')) {

		$(document).on('click', '#add_comment_button', function(event) {
			event.preventDefault();

			if (!$(this).prop('disabled')) {
				$(this).prop('disabled', true);
				$('#comment_comment').prop('disabled', true);
				$(this).val('Posting comment...');

				if ($('.comment').length > 0) {
					$('.actions').removeClass('no_margin_bottom');
				}

				var url;
				if ($('body').hasClass('moments show')) {
					url = '/moments/comment';
				} else if ($('body').hasClass('strategies show')) {
					url = '/strategies/comment';
				} else {
					url = '/meetings/comment';
				}

				var viewers;
				if ($('#comment_viewers').length) {
					viewers = $('#comment_viewers').val();
				}

				data = {
					comment_type: $('#comment_comment_type').val(),
					commented_on:$('#comment_commented_on').val(),
					comment_by: $('#comment_comment_by').val(),
					comment: $('#comment_comment').val(),
					visibility: $('#comment_visibility').val(),
					viewers: viewers
				};

				$.ajax({
				    dataType: 'json',
				    url: url,
				    type: 'POST',
				    data: data,
				    success: function(json) {
				    	if (json !== undefined) {
				    		$('#add_comment_button').prop('disabled', false);
				    		$('#comment_comment').prop('disabled', false);
				    		$('#comment_comment').val('');
							$('#add_comment_button').val('Comment');

				    		if (!json.no_save) {
					    		var commentid = 'comment_' + json.commentid;
					    		var profile_picture = json.profile_picture;
					    		var comment_info = json.comment_info;
					    		var comment_text = json.comment_text;
					    		var visibility = json.visibility;
					    		var delete_comment = json.delete_comment;

					    		// Remove no_margin_top on first comment
					    		if ($('.comment').length > 0) {
					    			$('.comment.no_margin_top').removeClass('no_margin_top');
					    		}

					    		var newComment = '
';
					    		newComment += '
';
					    		newComment += '
';

					    		newComment += '
';

					    		newComment += profile_picture;
					    		newComment += '
';

					    		newComment += '
';
					    		newComment += '
'
					    		newComment += comment_info;
					    		newComment += '
';
					    		newComment += '
';
					    		newComment += comment_text;
					    		newComment += '
';
					    		if (visibility != null && visibility.length > 0) {
					    			newComment += visibility;
					    		}
					    		newComment += '
';

					    		if (delete_comment != null && delete_comment.length > 0) {
					    			newComment += delete_comment;
					    		}

					    		newComment += '
';
					    		newComment += '
';
					    		newComment += '
';

					    		$('#comments').prepend(newComment);

					    		if ($('.comment').length > 0) {
									$('.actions').removeClass('no_margin_bottom');
								}
					    	}
				    	}
				    },
				    error: function() {
				    	$('#add_comment_button').prop('disabled', false);
				    	$('#comment_comment').prop('disabled', false);
						$('#add_comment_button').val('Comment');
				    }
				});
			}
		});
	}
});<|endoftext|>


<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//
//= require prefix
//= require prototype-legacy/prototype
//= require prototype-legacy/effects
//= require prototype-legacy/dragdrop
//= require prototype-legacy/controls
//= require prototype-legacy/builder
//= require prototype-legacy/browser-img-pool
//= require prototype-legacy/browser-post-loading
//= require prototype-legacy/browser-thumb-view
//= require prototype-legacy/browser-view
//= require prototype-legacy/common
//= require prototype-legacy/cropper
//= require prototype-legacy/debug-window
//= require prototype-legacy/history
//= require prototype-legacy/inline_image
//= require prototype-legacy/main_menu
//= require prototype-legacy/notes
//= require prototype-legacy/pool
//= require prototype-legacy/post-frame-editor
//= require prototype-legacy/post-upload-form
//= require prototype-legacy/post
//= require prototype-legacy/post_mode_menu
//= require prototype-legacy/post_tag_history
//= require prototype-legacy/preload
//= require prototype-legacy/referral
//= require prototype-legacy/related_tags
//= require prototype-legacy/similar-thumbnailing
//= require prototype-legacy/tag_completion
//= require prototype-legacy/touchscreen-web-app-helpers
//= require prototype-legacy/url-hash
//= require prototype-legacy/user
//= require jquery
//= require jquery_ujs
//= require jquery.cookie
//= require jquery.ui.autocomplete
//= require compat.jquery
//= require cookie
//= require dmail
//= require favorite
//= require forum
//= require user_record
//= require_tree .
<commit_msg>Load jquery before prototype.<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//
//= require prefix
//= require jquery
//= require jquery_ujs
//= require jquery.cookie
//= require jquery.ui.autocomplete
//= require compat.jquery
//= require cookie
//= require dmail
//= require favorite
//= require forum
//= require user_record
//= require_tree .
//= require prototype-legacy/prototype
//= require prototype-legacy/effects
//= require prototype-legacy/dragdrop
//= require prototype-legacy/controls
//= require prototype-legacy/builder
//= require prototype-legacy/browser-img-pool
//= require prototype-legacy/browser-post-loading
//= require prototype-legacy/browser-thumb-view
//= require prototype-legacy/browser-view
//= require prototype-legacy/common
//= require prototype-legacy/cropper
//= require prototype-legacy/debug-window
//= require prototype-legacy/history
//= require prototype-legacy/inline_image
//= require prototype-legacy/main_menu
//= require prototype-legacy/notes
//= require prototype-legacy/pool
//= require prototype-legacy/post-frame-editor
//= require prototype-legacy/post-upload-form
//= require prototype-legacy/post
//= require prototype-legacy/post_mode_menu
//= require prototype-legacy/post_tag_history
//= require prototype-legacy/preload
//= require prototype-legacy/referral
//= require prototype-legacy/related_tags
//= require prototype-legacy/similar-thumbnailing
//= require prototype-legacy/tag_completion
//= require prototype-legacy/touchscreen-web-app-helpers
//= require prototype-legacy/url-hash
//= require prototype-legacy/user

<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .

$(function () {
  $('[data-toggle="tooltip"]').tooltip();
});
<commit_msg>Update tooltip on page change<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .

$(document).on('page:change', function () {
  $('[data-toggle="tooltip"]').tooltip();
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require angular/angular
//= require angular-bootstrap
//= require restangular
//= require angular-flash
//= require angular-ui-router/release/angular-ui-router.js
//= require angular-dragdrop
//= require lodash
//= require_tree .
<commit_msg>assets compile test<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require angular/angular
//= require angular-bootstrap
//= require restangular
//= require angular-flash
//= require angular-ui-router/release/angular-ui-router.js
//= require angular-dragdrop
//= require lodash
//= require_tree .
<|endoftext|>


<commit_before>$(document).ready(function() {

    registerOptionListener();

    $('.invite').val(window.location.href.split('://')[1]);

    $('#vote-submit').hide();
    $('#search-input').hide();
    $('#search-submit').hide();
    $('.option .radio').hide();

    $("#search-input").autocomplete({
	source: function(request, response) {
	    $.ajax({
                type: 'GET',
                dataType: "json",
		url: $('#search-form').attr("action"),
		data: $('#search-form').serialize(),
		success: function(search_results) {
		    response($.map(search_results.response.data,function(item){
                        item["label"]=item.name+" - "+item.address;
                        return item;
                    }));
		}
	    });
	},
        delay: 200,
	minLength: 3,
        select: function(event, ui) {
            if($("#"+ui.item.uuid).length > 0) {
                $("#"+ui.item.uuid).effect("highlight", {}, 1000);
                event.stopPropagation(); //dont close the menu
                event.preventDefault();
            }
            else {
                //var newOption = Mustache.to_html($("#option-template").html(),{option: ui.item,option_klass: $('#option-klass').attr('val')});
                //$("#option-bars").append(newOption);
                var payload = {};
                var form = $('#ballot-form').serializeArray();
                for (attr in form) {
                    payload[form[attr].name] = form[attr].value;
                }
                payload["ballot[options_attributes]"] = ui.item;
                $.ajax({
                    type: 'PUT',
                    url: $('#ballot-form').attr('action'),
                    data: payload,
                    success: function(r){
                        $("#search-input").val("");
                        $("#search-input").hide();
                        $('.option-dialog').show();
                        registerOptionListener();
                    }
                });
            }
            return false;
	}
    });

});

function registerOptionListener() {
    $('.option-inner').click(function(e){
        $("input:radio").attr('checked',false);
        $(this).children().find("input:radio").attr('checked',true);

        // $('.option-inner').removeClass('selected');
        // $(this).addClass('selected');

        $.ajax({
            type: 'POST',
            url: $("#vote-form").attr("action"),
            data: $('#vote-form').serialize(),
            success: function(r){}
        });
    });

    $('a.option-details-btn').click(function(e){
        e.preventDefault();
        var option_path = $(this).attr("href");
        $.ajax({
            type: 'GET',
            url: option_path,
            success: function(response){$("#detail").html(response);}
        });
    });

    $('.option-dialog').click(function(e){
        e.preventDefault();
        $(this).hide();
        $('#search-input').show();
        $('#search-input').focus();
    });

}
<commit_msg>set option-dialog to close on blur<commit_after>$(document).ready(function() {

    registerOptionListener();

    $('.invite').val(window.location.href.split('://')[1]);

    $('#vote-submit').hide();
    $('#search-input').hide();
    $('#search-submit').hide();
    $('.option .radio').hide();

    $("#search-input").autocomplete({
	source: function(request, response) {
	    $.ajax({
                type: 'GET',
                dataType: "json",
		url: $('#search-form').attr("action"),
		data: $('#search-form').serialize(),
		success: function(search_results) {
		    response($.map(search_results.response.data,function(item){
                        item["label"]=item.name+" - "+item.address;
                        return item;
                    }));
		}
	    });
	},
        delay: 200,
	minLength: 3,
        select: function(event, ui) {
            if($("#"+ui.item.uuid).length > 0) {
                $("#"+ui.item.uuid).effect("highlight", {}, 1000);
                event.stopPropagation(); //dont close the menu
                event.preventDefault();
            }
            else {
                //var newOption = Mustache.to_html($("#option-template").html(),{option: ui.item,option_klass: $('#option-klass').attr('val')});
                //$("#option-bars").append(newOption);
                var payload = {};
                var form = $('#ballot-form').serializeArray();
                for (attr in form) {
                    payload[form[attr].name] = form[attr].value;
                }
                payload["ballot[options_attributes]"] = ui.item;
                $.ajax({
                    type: 'PUT',
                    url: $('#ballot-form').attr('action'),
                    data: payload,
                    success: function(r){
                        $("#search-input").val("");
                        $("#search-input").hide();
                        $('.option-dialog').show();
                        registerOptionListener();
                    }
                });
            }
            return false;
	}
    });

});

function registerOptionListener() {
    $('.option-inner').click(function(e){
        $("input:radio").attr('checked',false);
        $(this).children().find("input:radio").attr('checked',true);

        // $('.option-inner').removeClass('selected');
        // $(this).addClass('selected');

        $.ajax({
            type: 'POST',
            url: $("#vote-form").attr("action"),
            data: $('#vote-form').serialize(),
            success: function(r){}
        });
    });

    $('a.option-details-btn').click(function(e){
        e.preventDefault();
        var option_path = $(this).attr("href");
        $.ajax({
            type: 'GET',
            url: option_path,
            success: function(response){$("#detail").html(response);}
        });
    });

    $('.option-dialog').click(function(e){
        e.preventDefault();
        $(this).hide();
        $('#search-input').show();
        $('#search-input').focus();
    });

  $('#search-input').blur(function(e){
       $(this).hide();
       $('.option-dialog').show();
  });

}
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

$(document).ready(function() {
  Emotionall.init();
});
<commit_msg>remove default rails comments<commit_after>//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

$(document).ready(function() {
  Emotionall.init();
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require cartodb.core
//= require_tree .

$(document).ready(function() {
  if (!(/dont-show-alpha-notice/.test(document.cookie))) {
    $('.alpha-notice').show();
  }

  $('.alpha-notice .close').on('click', function(event) {
    $('.alpha-notice').remove();
    document.cookie = "dont-show-alpha-notice=true";
  });
});
<commit_msg>added back d3 and modernizr<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require modernizr.custom.30580
//= require d3
//= require cartodb.core
//= require_tree .

$(document).ready(function() {
  if (!(/dont-show-alpha-notice/.test(document.cookie))) {
    $('.alpha-notice').show();
  }

  $('.alpha-notice .close').on('click', function(event) {
    $('.alpha-notice').remove();
    document.cookie = "dont-show-alpha-notice=true";
  });
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require maps
//= require_tree .
<commit_msg>Require react compononents/react-slider in application.js<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require maps
//= require components/react-slider
//= require_tree .
<|endoftext|>


<commit_before> // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//= require gmaps/google
//= require underscore-min
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require moment
//= require bootstrap-datetimepicker
//= require_tree .

<commit_msg>delete gmaps dependency<commit_after> // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require moment
//= require bootstrap-datetimepicker
//= require_tree .

<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require turbolinks
//= require_tree .
<commit_msg>fix(application.js): remove require_tree<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require turbolinks
//= require index
<|endoftext|>


<commit_before>/**
 * The Component Utility
 *
 * @module aui-component
 */

var Lang = A.Lang,

	concat = function(arr, arr2) {
		return (arr || []).concat(arr2 || []);
	},

	getClassName = A.getClassName,

	NAME = 'component',

	CSS_HELPER_HIDDEN = getClassName('helper', 'hidden'),
	CONSTRUCTOR_OBJECT = Object.prototype.constructor;

/**
 * A base class for Component, providing:
 *

 *
Widget Lifecycle (initializer, renderUI, bindUI, syncUI, destructor)

 *

 *

 *
 * Check the list of Configuration Attributes available for
 * Component.
 *
 * @param config {Object} Object literal specifying widget configuration properties.
 *
 * @class Component
 * @constructor
 * @extends Widget
 */
var Component = function(config) {
	var instance = this;

	instance._originalConfig = config;

	instance._setRender(config);

	Component.superclass.constructor.apply(this, arguments);

	INSTANCES[instance.get('id')] = instance;
};

var INSTANCES = Component._INSTANCES = {};

/**
 * Static property provides a string to identify the class.
 *
 * @property Component.NAME
 * @type String
 * @static
 */
Component.NAME = 'component';

/**
 * Static property used to define the default attribute
 * configuration for the Component.
 *
 * @property Component.ATTRS
 * @type Object
 * @static
 */
Component.ATTRS = {
	/**
	* Boolean indicating if use of the WAI-ARIA Roles and States should be
	* enabled for the Widget.
	*
	* @attribute useARIA
	* @readOnly
	* @writeOnce
	* @default true
	* @type boolean
	*/
	useARIA: {
		writeOnce: true,
		value: false,
		validator: Lang.isBoolean
	},

	/**
	 * CSS class to be automatically added to the boundingBox.
	 *
	 * @attribute cssClass
	 * @default null
	 * @type String
	 */
	cssClass: {
		lazyAdd: false,
		value: null
	},

	/**
	 * css class added to hide the boundingBox when
     * visible is set to
     * false.
	 *
	 * @attribute hideClass
	 * @default 'aui-helper-hidden'
	 * @type String
	 */
	hideClass: {
		value: CSS_HELPER_HIDDEN
	},

	/**
	 * If true the render phase will be autimatically invoked
     * preventing the .render() manual call.
	 *
	 * @attribute render
	 * @default false
	 * @type boolean | Node
	 */
	render: {
		value: false,
		writeOnce: true
	}
};

A.extend(
	Component,
	A.Widget,
	{
		/**
		 * Construction logic executed during Component instantiation. Lifecycle.
		 *
		 * @method initializer
		 * @protected
		 */
		initializer: function(config) {
			var instance = this;

			if (config && config.cssClass) {
				instance._uiSetCssClass(config.cssClass);
			}

			instance._setComponentClassNames();

			instance.after('cssClassChange', instance._afterCssClassChange);
			instance.after('visibleChange', instance._afterComponentVisibleChange);
		},

		/**
		 * Clone the current Component.
		 *
		 * @method clone
		 * @param {Object} config
		 * @return {Widget} Cloned instance.
		 */
		clone: function(config) {
			var instance = this;

			config = config || {};

			config.id = config.id || A.guid();

			A.mix(config, instance._originalConfig);

			return new instance.constructor(config);
		},

		/**
		 * Toggle the visibility of the Panel toggling the value of the
	     * visible attribute.
		 *
		 * @method toggle
		 * @param visible Force the visibility of the component to this state.
		 */
		toggle: function(visible) {
			var instance = this;

			if (!Lang.isBoolean(visible)) {
				visible = !instance.get('visible');
			}

			return instance.set('visible', visible);
		},

		/**
		 * Fires after the value of the
		 * visible attribute change.
		 *
		 * @method _afterComponentVisibleChange
		 * @param {EventFacade} event
		 * @protected
		 */
		_afterComponentVisibleChange: function(event) {
			var instance = this;

			var hideClass = instance.get('hideClass');

			if (hideClass !== false) {
				var boundingBox = instance.get('boundingBox');

				var action = 'addClass';

				if (event.newVal) {
					action = 'removeClass';
				}

				boundingBox[action](hideClass || CSS_HELPER_HIDDEN);
			}
		},

		/**
		 * Fires after the value of the
		 * cssClass attribute change.
		 *
		 * @method _afterCssClassChange
		 * @param {EventFacade} event
		 * @protected
		 */
		_afterCssClassChange: function(event) {
			var instance = this;

			instance._uiSetCssClass(event.newVal, event.prevVal);
		},

		/**
		 * Renders the Component based upon a passed in interaction.
		 *
		 * @method _renderInteraction
		 * @protected
		 */
		_renderInteraction: function(event, parentNode) {
			var instance = this;

			instance.render(parentNode);

			var renderHandles = instance._renderHandles;

			for (var i = renderHandles.length - 1; i >= 0; i--) {
				var handle = renderHandles.pop();

				handle.detach();
			}
		},

		/**
		 * Set the class names on the Component contentBox.
		 *
		 * @method _setComponentClassNames
		 * @protected
		 */
		_setComponentClassNames: function() {
			var instance = this;

			var classes = instance._getClasses();
			var name;
			var buffer = [];

			for (var i = classes.length - 4; i >= 0; i--) {
				name = classes[i].NAME.toLowerCase();

				buffer.push(getClassName(name, 'content'));
			}

			instance.get('contentBox').addClass(buffer.join(' '));
		},

		/**
		 * Set the interaction and render behavior based upon an object
		 * (intercepts the default rendering behavior).
		 *
		 * @method _setRender
		 * @protected
		 */
		_setRender: function(config) {
			var instance = this;

			var render = config && config.render;

			if (render && render.constructor == CONSTRUCTOR_OBJECT) {
				var eventType = render.eventType || 'mousemove';
				var parentNode = render.parentNode;
				var selector = render.selector || parentNode;

				if (selector) {
					instance._renderHandles = [];

					var renderHandles = instance._renderHandles;

					if (!Lang.isArray(eventType)) {
						eventType = [eventType];
					}

					var renderInteraction = A.rbind(instance._renderInteraction, instance, parentNode);

					var interactionNode = A.one(selector);

					 for (var i = eventType.length - 1; i >= 0; i--) {
						renderHandles[i] = interactionNode.once(eventType[i], renderInteraction);
					 }

					delete config.render;
				}
			}
		},

		/**
		 * Applies the CSS classes to the boundingBox and
         * contentBox.
		 *
		 * @method _uiSetCssClass
		 * @protected
		 * @param {String} newVal
		 * @param {String} prevVal
		 */
		_uiSetCssClass: function(newVal, prevVal) {
			var instance = this;

			var prevValContent = prevVal + '-content';

			var newValContent = newVal + '-content';

			var boundingBox = instance.get('boundingBox');
			var contentBox = instance.get('contentBox');

			boundingBox.replaceClass(prevVal, newVal);
			contentBox.replaceClass(prevValContent, newValContent);
		}
	}
);

Component.getById = function(id) {
	return INSTANCES[id];
};

var COMP_PROTO = Component.prototype;

var DEFAULT_UI_ATTRS = A.Widget.prototype._UI_ATTRS;

Component.create = function(config) {
	config = config || {};

	var extendsClass = config.EXTENDS || A.Component;

	var component = config.constructor;

	if (!component || component == CONSTRUCTOR_OBJECT){
		component = function(){
			component.superclass.constructor.apply(this, arguments);
		};
	}

	var configProto = config.prototype;

	if (configProto) {
		if (config.UI_ATTRS || config.BIND_UI_ATTRS || config.SYNC_UI_ATTRS) {
			var BIND_UI_ATTRS = concat(config.BIND_UI_ATTRS, config.UI_ATTRS);
			var SYNC_UI_ATTRS = concat(config.SYNC_UI_ATTRS, config.UI_ATTRS);

			var extendsProto = extendsClass.prototype;
			var extendsUIAttrs = (extendsProto && extendsProto._UI_ATTRS) || DEFAULT_UI_ATTRS;

			BIND_UI_ATTRS = concat(extendsUIAttrs.BIND, BIND_UI_ATTRS);
			SYNC_UI_ATTRS = concat(extendsUIAttrs.SYNC, SYNC_UI_ATTRS);

			var configProtoUIAttrs = configProto._UI_ATTRS;

			if (!configProtoUIAttrs) {
				configProtoUIAttrs = configProto._UI_ATTRS = {};
			}

			if (BIND_UI_ATTRS.length) {
				configProtoUIAttrs.BIND = BIND_UI_ATTRS;
			}

			if (SYNC_UI_ATTRS.length) {
				configProtoUIAttrs.SYNC = SYNC_UI_ATTRS;
			}
		}
	}

	var augmentsClasses = config.AUGMENTS;

	if (augmentsClasses && !Lang.isArray(augmentsClasses)) {
		augmentsClasses = [augmentsClasses];
	}

	A.mix(component, config);

	delete component.prototype;

	A.extend(component, extendsClass, configProto);

	if (augmentsClasses) {
		component = A.Base.build(config.NAME, component, augmentsClasses, { dynamic: false });
	}

	if (!('CSS_PREFIX' in component)) {
		component.CSS_PREFIX = A.getClassName(component.NAME);
	}

	return component;
};

Component.CSS_PREFIX = getClassName('component');

A.Component = Component;<commit_msg>AUI-402 - Changing component to autogenerate the CSS_PREFIX<commit_after>/**
 * The Component Utility
 *
 * @module aui-component
 */

var Lang = A.Lang,

	concat = function(arr, arr2) {
		return (arr || []).concat(arr2 || []);
	},

	getClassName = A.getClassName,

	NAME = 'component',

	CSS_HELPER_HIDDEN = getClassName('helper', 'hidden'),
	CONSTRUCTOR_OBJECT = Object.prototype.constructor;

/**
 * A base class for Component, providing:
 *

 *
Widget Lifecycle (initializer, renderUI, bindUI, syncUI, destructor)

 *

 *

 *
 * Check the list of Configuration Attributes available for
 * Component.
 *
 * @param config {Object} Object literal specifying widget configuration properties.
 *
 * @class Component
 * @constructor
 * @extends Widget
 */
var Component = function(config) {
	var instance = this;

	instance._originalConfig = config;

	instance._setRender(config);

	Component.superclass.constructor.apply(this, arguments);

	INSTANCES[instance.get('id')] = instance;
};

var INSTANCES = Component._INSTANCES = {};

/**
 * Static property provides a string to identify the class.
 *
 * @property Component.NAME
 * @type String
 * @static
 */
Component.NAME = 'component';

/**
 * Static property used to define the default attribute
 * configuration for the Component.
 *
 * @property Component.ATTRS
 * @type Object
 * @static
 */
Component.ATTRS = {
	/**
	* Boolean indicating if use of the WAI-ARIA Roles and States should be
	* enabled for the Widget.
	*
	* @attribute useARIA
	* @readOnly
	* @writeOnce
	* @default true
	* @type boolean
	*/
	useARIA: {
		writeOnce: true,
		value: false,
		validator: Lang.isBoolean
	},

	/**
	 * CSS class to be automatically added to the boundingBox.
	 *
	 * @attribute cssClass
	 * @default null
	 * @type String
	 */
	cssClass: {
		lazyAdd: false,
		value: null
	},

	/**
	 * css class added to hide the boundingBox when
     * visible is set to
     * false.
	 *
	 * @attribute hideClass
	 * @default 'aui-helper-hidden'
	 * @type String
	 */
	hideClass: {
		value: CSS_HELPER_HIDDEN
	},

	/**
	 * If true the render phase will be autimatically invoked
     * preventing the .render() manual call.
	 *
	 * @attribute render
	 * @default false
	 * @type boolean | Node
	 */
	render: {
		value: false,
		writeOnce: true
	}
};

A.extend(
	Component,
	A.Widget,
	{
		/**
		 * Construction logic executed during Component instantiation. Lifecycle.
		 *
		 * @method initializer
		 * @protected
		 */
		initializer: function(config) {
			var instance = this;

			if (config && config.cssClass) {
				instance._uiSetCssClass(config.cssClass);
			}

			instance._setComponentClassNames();

			instance.after('cssClassChange', instance._afterCssClassChange);
			instance.after('visibleChange', instance._afterComponentVisibleChange);
		},

		/**
		 * Clone the current Component.
		 *
		 * @method clone
		 * @param {Object} config
		 * @return {Widget} Cloned instance.
		 */
		clone: function(config) {
			var instance = this;

			config = config || {};

			config.id = config.id || A.guid();

			A.mix(config, instance._originalConfig);

			return new instance.constructor(config);
		},

		/**
		 * Toggle the visibility of the Panel toggling the value of the
	     * visible attribute.
		 *
		 * @method toggle
		 * @param visible Force the visibility of the component to this state.
		 */
		toggle: function(visible) {
			var instance = this;

			if (!Lang.isBoolean(visible)) {
				visible = !instance.get('visible');
			}

			return instance.set('visible', visible);
		},

		/**
		 * Fires after the value of the
		 * visible attribute change.
		 *
		 * @method _afterComponentVisibleChange
		 * @param {EventFacade} event
		 * @protected
		 */
		_afterComponentVisibleChange: function(event) {
			var instance = this;

			var hideClass = instance.get('hideClass');

			if (hideClass !== false) {
				var boundingBox = instance.get('boundingBox');

				var action = 'addClass';

				if (event.newVal) {
					action = 'removeClass';
				}

				boundingBox[action](hideClass || CSS_HELPER_HIDDEN);
			}
		},

		/**
		 * Fires after the value of the
		 * cssClass attribute change.
		 *
		 * @method _afterCssClassChange
		 * @param {EventFacade} event
		 * @protected
		 */
		_afterCssClassChange: function(event) {
			var instance = this;

			instance._uiSetCssClass(event.newVal, event.prevVal);
		},

		/**
		 * Renders the Component based upon a passed in interaction.
		 *
		 * @method _renderInteraction
		 * @protected
		 */
		_renderInteraction: function(event, parentNode) {
			var instance = this;

			instance.render(parentNode);

			var renderHandles = instance._renderHandles;

			for (var i = renderHandles.length - 1; i >= 0; i--) {
				var handle = renderHandles.pop();

				handle.detach();
			}
		},

		/**
		 * Set the class names on the Component contentBox.
		 *
		 * @method _setComponentClassNames
		 * @protected
		 */
		_setComponentClassNames: function() {
			var instance = this;

			var classes = instance._getClasses();
			var name;
			var buffer = [];

			for (var i = classes.length - 4; i >= 0; i--) {
				name = classes[i].NAME.toLowerCase();

				buffer.push(getClassName(name, 'content'));
			}

			instance.get('contentBox').addClass(buffer.join(' '));
		},

		/**
		 * Set the interaction and render behavior based upon an object
		 * (intercepts the default rendering behavior).
		 *
		 * @method _setRender
		 * @protected
		 */
		_setRender: function(config) {
			var instance = this;

			var render = config && config.render;

			if (render && render.constructor == CONSTRUCTOR_OBJECT) {
				var eventType = render.eventType || 'mousemove';
				var parentNode = render.parentNode;
				var selector = render.selector || parentNode;

				if (selector) {
					instance._renderHandles = [];

					var renderHandles = instance._renderHandles;

					if (!Lang.isArray(eventType)) {
						eventType = [eventType];
					}

					var renderInteraction = A.rbind(instance._renderInteraction, instance, parentNode);

					var interactionNode = A.one(selector);

					 for (var i = eventType.length - 1; i >= 0; i--) {
						renderHandles[i] = interactionNode.once(eventType[i], renderInteraction);
					 }

					delete config.render;
				}
			}
		},

		/**
		 * Applies the CSS classes to the boundingBox and
         * contentBox.
		 *
		 * @method _uiSetCssClass
		 * @protected
		 * @param {String} newVal
		 * @param {String} prevVal
		 */
		_uiSetCssClass: function(newVal, prevVal) {
			var instance = this;

			var prevValContent = prevVal + '-content';

			var newValContent = newVal + '-content';

			var boundingBox = instance.get('boundingBox');
			var contentBox = instance.get('contentBox');

			boundingBox.replaceClass(prevVal, newVal);
			contentBox.replaceClass(prevValContent, newValContent);
		}
	}
);

Component.getById = function(id) {
	return INSTANCES[id];
};

var COMP_PROTO = Component.prototype;

var DEFAULT_UI_ATTRS = A.Widget.prototype._UI_ATTRS;

Component._applyCssPrefix = function(component) {
	if (component && !('CSS_PREFIX' in component)) {
		component.CSS_PREFIX = A.getClassName(component.NAME);
	}

	return component;
};

Component.create = function(config) {
	config = config || {};

	var extendsClass = config.EXTENDS || A.Component;

	var component = config.constructor;

	if (!component || component == CONSTRUCTOR_OBJECT){
		component = function(){
			component.superclass.constructor.apply(this, arguments);
		};
	}

	var configProto = config.prototype;

	if (configProto) {
		if (config.UI_ATTRS || config.BIND_UI_ATTRS || config.SYNC_UI_ATTRS) {
			var BIND_UI_ATTRS = concat(config.BIND_UI_ATTRS, config.UI_ATTRS);
			var SYNC_UI_ATTRS = concat(config.SYNC_UI_ATTRS, config.UI_ATTRS);

			var extendsProto = extendsClass.prototype;
			var extendsUIAttrs = (extendsProto && extendsProto._UI_ATTRS) || DEFAULT_UI_ATTRS;

			BIND_UI_ATTRS = concat(extendsUIAttrs.BIND, BIND_UI_ATTRS);
			SYNC_UI_ATTRS = concat(extendsUIAttrs.SYNC, SYNC_UI_ATTRS);

			var configProtoUIAttrs = configProto._UI_ATTRS;

			if (!configProtoUIAttrs) {
				configProtoUIAttrs = configProto._UI_ATTRS = {};
			}

			if (BIND_UI_ATTRS.length) {
				configProtoUIAttrs.BIND = BIND_UI_ATTRS;
			}

			if (SYNC_UI_ATTRS.length) {
				configProtoUIAttrs.SYNC = SYNC_UI_ATTRS;
			}
		}
	}

	var augmentsClasses = config.AUGMENTS;

	if (augmentsClasses && !Lang.isArray(augmentsClasses)) {
		augmentsClasses = [augmentsClasses];
	}

	A.mix(component, config);

	delete component.prototype;

	A.extend(component, extendsClass, configProto);

	if (augmentsClasses) {
		component = A.Base.build(config.NAME, component, augmentsClasses, { dynamic: false });
	}

	Component._applyCssPrefix(component);

	return component;
};

Component.CSS_PREFIX = getClassName('component');

var Base = A.Base;

Component.build = function() {
	var component = Base.build.apply(Base, arguments);

	Component._applyCssPrefix(component);

	return component;
};

A.Component = Component;<|endoftext|>


<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//
//= require prefix
//= require prototype-legacy/prototype
//= require prototype-legacy/effects
//= require prototype-legacy/dragdrop
//= require prototype-legacy/controls
//= require prototype-legacy/builder
//= require prototype-legacy/browser-img-pool
//= require prototype-legacy/browser-post-loading
//= require prototype-legacy/browser-thumb-view
//= require prototype-legacy/browser-view
//= require prototype-legacy/comment
//= require prototype-legacy/common
//= require prototype-legacy/cropper
//= require prototype-legacy/debug-window
//= require prototype-legacy/dmail
//= require prototype-legacy/favorite
//= require prototype-legacy/forum
//= require prototype-legacy/history
//= require prototype-legacy/inline_image
//= require prototype-legacy/main_menu
//= require prototype-legacy/notes
//= require prototype-legacy/pool
//= require prototype-legacy/post-frame-editor
//= require prototype-legacy/post-upload-form
//= require prototype-legacy/post
//= require prototype-legacy/post_mode_menu
//= require prototype-legacy/post_tag_history
//= require prototype-legacy/preload
//= require prototype-legacy/referral
//= require prototype-legacy/related_tags
//= require prototype-legacy/similar-thumbnailing
//= require prototype-legacy/tag_completion
//= require prototype-legacy/touchscreen-web-app-helpers
//= require prototype-legacy/url-hash
//= require prototype-legacy/user
//= require prototype-legacy/user_record
//= require prototype-legacy/vote-widget
//= require jquery
//= require jquery_ujs
//= require jquery.cookie
//= require jquery.ui.autocomplete
//= require compat.jquery
//= require cookie
//= require_tree .
<commit_msg>Remove legacy vote-widget<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
//
//= require prefix
//= require prototype-legacy/prototype
//= require prototype-legacy/effects
//= require prototype-legacy/dragdrop
//= require prototype-legacy/controls
//= require prototype-legacy/builder
//= require prototype-legacy/browser-img-pool
//= require prototype-legacy/browser-post-loading
//= require prototype-legacy/browser-thumb-view
//= require prototype-legacy/browser-view
//= require prototype-legacy/comment
//= require prototype-legacy/common
//= require prototype-legacy/cropper
//= require prototype-legacy/debug-window
//= require prototype-legacy/dmail
//= require prototype-legacy/favorite
//= require prototype-legacy/forum
//= require prototype-legacy/history
//= require prototype-legacy/inline_image
//= require prototype-legacy/main_menu
//= require prototype-legacy/notes
//= require prototype-legacy/pool
//= require prototype-legacy/post-frame-editor
//= require prototype-legacy/post-upload-form
//= require prototype-legacy/post
//= require prototype-legacy/post_mode_menu
//= require prototype-legacy/post_tag_history
//= require prototype-legacy/preload
//= require prototype-legacy/referral
//= require prototype-legacy/related_tags
//= require prototype-legacy/similar-thumbnailing
//= require prototype-legacy/tag_completion
//= require prototype-legacy/touchscreen-web-app-helpers
//= require prototype-legacy/url-hash
//= require prototype-legacy/user
//= require prototype-legacy/user_record
//= require jquery
//= require jquery_ujs
//= require jquery.cookie
//= require jquery.ui.autocomplete
//= require compat.jquery
//= require cookie
//= require_tree .
<|endoftext|>