<commit_before>"use strict";
angular.module('jtt_aping')
    .config(['$provide', function ($provide) {
        $provide.value("apingDefaultSettings", {
            apingApiKeys: {}
        });
    }])
    .value("apingResults", {})
    .directive('aping', ['apingResults', 'apingDefaultSettings', 'apingUtilityHelper', '$templateRequest', '$compile', function (apingResults, apingDefaultSettings, apingUtilityHelper, $templateRequest, $compile) {
        return {
            restrict: 'E',
            transclude: true,
            template: '<ng-transclude></ng-transclude>',
            scope: {
                model: '@',
                getNativeData: '@',
                items: '@',
                maxItems: '@',
                orderBy: '@',
                orderReverse: '@',
                templateUrl: '@',
                payloadJson: '@',
                removeDoubles: '@',
                mergeDoubles: '@',
                idBy: '@',
                resultProperty: '@', // legacy
                resultName: '@',
                valueName: '@',
                protocol: '@'
            },
            link: function (scope, element, attrs, controller, transcludeFn) {

                var templatePath = scope.templateUrl;

                scope.$watch('templateUrl', function () {
                    renderTemplate(scope.templateUrl);
                });

                if (angular.isUndefined(templatePath)) {
                    if (angular.isDefined(apingDefaultSettings.templateUrl)) {
                        templatePath = apingDefaultSettings.templateUrl;
                        renderTemplate(templatePath);
                    }
                }

                function renderTemplate(_templatePath) {
                    if (angular.isDefined(_templatePath) && _templatePath !== "$NONE") {
                        $templateRequest(_templatePath).then(function (html) {
                            var template = angular.element(html);
                            element.empty().append(template);
                            $compile(template)(scope);
                        });
                    } else {
                        transcludeFn(scope, function (clone, innerScope) {
                            element.html("");
                            element.append(clone);
                            $compile(clone)(innerScope);
                        });
                    }
                    scope.$broadcast('apiNG.templateRendered');
                }
            },
            controller: ['$scope', function ($scope) {

                if(angular.isUndefined($scope.resultName)) {
                    if (angular.isUndefined($scope.resultProperty)) {
                        $scope.resultName = "results";
                    } else {
                        $scope.resultName = $scope.resultProperty;
                    }
                }

                $scope[$scope.resultName] = [];
                $scope.payload = $scope.payloadJson ? apingUtilityHelper.replaceSingleQuotesAndParseJson($scope.payloadJson) : {};

                /**
                 * return current appSettings by merging 'apingDefaultSettings' and '$scope params'
                 * @returns {Object}
                 */
                this.getAppSettings = function () {

                    var items;
                    var maxItems;
                    var getNativeData;
                    var orderReverse;
                    var orderBy;
                    var removeDoubles;
                    var mergeDoubles;
                    var valueName;
                    var idBy;
                    var protocol;

                    if (angular.isDefined($scope.valueName)) {
                        valueName = $scope.valueName;
                    } else {
                        valueName = undefined;
                    }

                    if (angular.isDefined($scope.items)) {
                        items = $scope.items;
                    } else if (angular.isDefined(apingDefaultSettings.items)) {
                        items = apingDefaultSettings.items;
                    } else {
                        items = undefined;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.getNativeData)) {
                        getNativeData = $scope.getNativeData;
                    } else if (angular.isDefined(apingDefaultSettings.getNativeData)) {
                        getNativeData = apingDefaultSettings.getNativeData;
                    } else {
                        getNativeData = false;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.orderBy)) {
                        orderBy = $scope.orderBy;
                    } else if (angular.isDefined(apingDefaultSettings.orderBy)) {
                        orderBy = apingDefaultSettings.orderBy;
                    } else {
                        orderBy = undefined;
                    }

                    if (angular.isDefined($scope.orderReverse)) {
                        orderReverse = $scope.orderReverse;
                    } else if (angular.isDefined(apingDefaultSettings.orderReverse)) {
                        orderReverse = apingDefaultSettings.orderReverse;
                    } else {
                        orderReverse = false;
                    }

                    if (angular.isDefined($scope.removeDoubles)) {
                        removeDoubles = $scope.removeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.removeDoubles)) {
                        removeDoubles = apingDefaultSettings.removeDoubles;
                    } else {
                        removeDoubles = false;
                    }

                    if (angular.isDefined($scope.mergeDoubles)) {
                        mergeDoubles = $scope.mergeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.mergeDoubles)) {
                        mergeDoubles = apingDefaultSettings.mergeDoubles;
                    } else {
                        mergeDoubles = false;
                    }

                    if (angular.isDefined($scope.idBy)) {
                        idBy = $scope.idBy;
                    } else if (angular.isDefined(apingDefaultSettings.idBy)) {
                        idBy = apingDefaultSettings.idBy;
                    } else {
                        idBy = undefined;
                    }

                    if (angular.isDefined($scope.protocol)) {
                        protocol = $scope.protocol;
                    } else if (angular.isDefined(apingDefaultSettings.protocol)) {
                        protocol = apingDefaultSettings.protocol;
                    } else {
                        protocol = undefined;
                    }

                    return {
                        model: $scope.model || apingDefaultSettings.model || "native",
                        getNativeData: getNativeData,
                        items: items,
                        maxItems: maxItems,
                        orderBy: orderBy,
                        orderReverse: orderReverse,
                        removeDoubles: removeDoubles,
                        mergeDoubles: mergeDoubles,
                        idBy: idBy,
                        valueName: valueName,
                        protocol: protocol
                    };
                };

                /**
                 * merge current '$scope.results' with '_array' and sorts, limits and filters the data
                 *
                 * @param _array
                 */
                this.concatToResults = function (_array) {
                    if(angular.isUndefined($scope.resultName)) {
                        if (angular.isUndefined($scope.resultProperty)) {
                            $scope.resultName = "results";
                        } else {
                            $scope.resultName = $scope.resultProperty;
                        }
                    }

                    var tempArray = $scope[$scope.resultName].concat(_array);

                    var appSettings = this.getAppSettings();

                    if (angular.isDefined(appSettings.idBy)) {
                        tempArray = apingUtilityHelper.createIdByPropertiesForArray(tempArray, appSettings.idBy);
                        if (appSettings.mergeDoubles === true || appSettings.mergeDoubles === "true") {
                            tempArray = apingUtilityHelper.mergeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === "false" || appSettings.orderBy === "$NONE")
                            );
                        }
                    }

                    //remove doubles
                    if (appSettings.removeDoubles === true || appSettings.removeDoubles === "true") {
                        if (appSettings.mergeDoubles !== true && appSettings.mergeDoubles !== "true") {
                            tempArray = apingUtilityHelper.removeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === "false" || appSettings.orderBy === "$NONE"),
                                angular.isDefined(appSettings.idBy)
                            );
                        }
                    }

                    //order array
                    if (angular.isDefined(appSettings.orderBy) && appSettings.orderBy !== false && appSettings.orderBy !== "false" && appSettings.orderBy !== "$NONE") {
                        //order random
                        if (appSettings.orderBy === "$RANDOM") {
                            tempArray = apingUtilityHelper.shuffleArray(tempArray);
                        }
                        //order by attribute
                        else {
                            tempArray.sort(apingUtilityHelper.sortArrayByProperty(appSettings.orderBy));
                        }
                    }

                    //order reverse
                    if ((appSettings.orderReverse === true || appSettings.orderReverse === "true") && appSettings.orderBy !== "$RANDOM") {
                        tempArray.reverse();
                    }

                    //crop spare
                    if (appSettings.maxItems > -1 && tempArray.length > appSettings.maxItems) {
                        tempArray = tempArray.splice(0, appSettings.maxItems);
                    }

                    if (angular.isDefined(appSettings.valueName)) {
                        apingResults[appSettings.valueName] = tempArray;
                    }

                    $scope[$scope.resultName] = tempArray;

                    $scope.$broadcast('apiNG.resultMerged', {'resultName': $scope.resultName});
                };
                this.apply = function () {
                    $scope.$apply();
                };
            }]
        };
    }]);<commit_msg>impr: on merge result<commit_after>"use strict";
angular.module('jtt_aping')
    .config(['$provide', function ($provide) {
        $provide.value("apingDefaultSettings", {
            apingApiKeys: {}
        });
    }])
    .value("apingResults", {})
    .directive('aping', ['apingResults', 'apingDefaultSettings', 'apingUtilityHelper', '$templateRequest', '$compile', function (apingResults, apingDefaultSettings, apingUtilityHelper, $templateRequest, $compile) {
        return {
            restrict: 'E',
            transclude: true,
            template: '<ng-transclude></ng-transclude>',
            scope: {
                model: '@',
                getNativeData: '@',
                items: '@',
                maxItems: '@',
                orderBy: '@',
                orderReverse: '@',
                templateUrl: '@',
                payloadJson: '@',
                removeDoubles: '@',
                mergeDoubles: '@',
                idBy: '@',
                resultProperty: '@', // legacy
                resultName: '@',
                valueName: '@',
                protocol: '@'
            },
            link: function (scope, element, attrs, controller, transcludeFn) {

                var templatePath = scope.templateUrl;

                scope.$watch('templateUrl', function () {
                    renderTemplate(scope.templateUrl);
                });

                if (angular.isUndefined(templatePath)) {
                    if (angular.isDefined(apingDefaultSettings.templateUrl)) {
                        templatePath = apingDefaultSettings.templateUrl;
                        renderTemplate(templatePath);
                    }
                }

                function renderTemplate(_templatePath) {
                    if (angular.isDefined(_templatePath) && _templatePath !== "$NONE") {
                        $templateRequest(_templatePath).then(function (html) {
                            var template = angular.element(html);
                            element.empty().append(template);
                            $compile(template)(scope);
                        });
                    } else {
                        transcludeFn(scope, function (clone, innerScope) {
                            element.html("");
                            element.append(clone);
                            $compile(clone)(innerScope);
                        });
                    }
                    scope.$broadcast('apiNG.templateRendered');
                }
            },
            controller: ['$scope', function ($scope) {

                if(angular.isUndefined($scope.resultName)) {
                    if (angular.isUndefined($scope.resultProperty)) {
                        $scope.resultName = "results";
                    } else {
                        $scope.resultName = $scope.resultProperty;
                    }
                }

                $scope[$scope.resultName] = [];
                $scope.payload = $scope.payloadJson ? apingUtilityHelper.replaceSingleQuotesAndParseJson($scope.payloadJson) : {};

                /**
                 * return current appSettings by merging 'apingDefaultSettings' and '$scope params'
                 * @returns {Object}
                 */
                this.getAppSettings = function () {

                    var items;
                    var maxItems;
                    var getNativeData;
                    var orderReverse;
                    var orderBy;
                    var removeDoubles;
                    var mergeDoubles;
                    var valueName;
                    var idBy;
                    var protocol;

                    if (angular.isDefined($scope.valueName)) {
                        valueName = $scope.valueName;
                    } else {
                        valueName = undefined;
                    }

                    if (angular.isDefined($scope.items)) {
                        items = $scope.items;
                    } else if (angular.isDefined(apingDefaultSettings.items)) {
                        items = apingDefaultSettings.items;
                    } else {
                        items = undefined;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.getNativeData)) {
                        getNativeData = $scope.getNativeData;
                    } else if (angular.isDefined(apingDefaultSettings.getNativeData)) {
                        getNativeData = apingDefaultSettings.getNativeData;
                    } else {
                        getNativeData = false;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.orderBy)) {
                        orderBy = $scope.orderBy;
                    } else if (angular.isDefined(apingDefaultSettings.orderBy)) {
                        orderBy = apingDefaultSettings.orderBy;
                    } else {
                        orderBy = undefined;
                    }

                    if (angular.isDefined($scope.orderReverse)) {
                        orderReverse = $scope.orderReverse;
                    } else if (angular.isDefined(apingDefaultSettings.orderReverse)) {
                        orderReverse = apingDefaultSettings.orderReverse;
                    } else {
                        orderReverse = false;
                    }

                    if (angular.isDefined($scope.removeDoubles)) {
                        removeDoubles = $scope.removeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.removeDoubles)) {
                        removeDoubles = apingDefaultSettings.removeDoubles;
                    } else {
                        removeDoubles = false;
                    }

                    if (angular.isDefined($scope.mergeDoubles)) {
                        mergeDoubles = $scope.mergeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.mergeDoubles)) {
                        mergeDoubles = apingDefaultSettings.mergeDoubles;
                    } else {
                        mergeDoubles = false;
                    }

                    if (angular.isDefined($scope.idBy)) {
                        idBy = $scope.idBy;
                    } else if (angular.isDefined(apingDefaultSettings.idBy)) {
                        idBy = apingDefaultSettings.idBy;
                    } else {
                        idBy = undefined;
                    }

                    if (angular.isDefined($scope.protocol)) {
                        protocol = $scope.protocol;
                    } else if (angular.isDefined(apingDefaultSettings.protocol)) {
                        protocol = apingDefaultSettings.protocol;
                    } else {
                        protocol = undefined;
                    }

                    return {
                        model: $scope.model || apingDefaultSettings.model || "native",
                        getNativeData: getNativeData,
                        items: items,
                        maxItems: maxItems,
                        orderBy: orderBy,
                        orderReverse: orderReverse,
                        removeDoubles: removeDoubles,
                        mergeDoubles: mergeDoubles,
                        idBy: idBy,
                        valueName: valueName,
                        protocol: protocol
                    };
                };

                /**
                 * merge current '$scope.results' with '_array' and sorts, limits and filters the data
                 *
                 * @param _array
                 */
                this.concatToResults = function (_array) {
                    if(angular.isUndefined($scope.resultName)) {
                        if (angular.isUndefined($scope.resultProperty)) {
                            $scope.resultName = "results";
                        } else {
                            $scope.resultName = $scope.resultProperty;
                        }
                    }

                    var tempArray = $scope[$scope.resultName].concat(_array);

                    var appSettings = this.getAppSettings();

                    if (angular.isDefined(appSettings.idBy)) {
                        tempArray = apingUtilityHelper.createIdByPropertiesForArray(tempArray, appSettings.idBy);
                        if (appSettings.mergeDoubles === true || appSettings.mergeDoubles === "true") {
                            tempArray = apingUtilityHelper.mergeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === "false" || appSettings.orderBy === "$NONE")
                            );
                        }
                    }

                    //remove doubles
                    if (appSettings.removeDoubles === true || appSettings.removeDoubles === "true") {
                        if (appSettings.mergeDoubles !== true && appSettings.mergeDoubles !== "true") {
                            tempArray = apingUtilityHelper.removeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === "false" || appSettings.orderBy === "$NONE"),
                                angular.isDefined(appSettings.idBy)
                            );
                        }
                    }

                    //order array
                    if (angular.isDefined(appSettings.orderBy) && appSettings.orderBy !== false && appSettings.orderBy !== "false" && appSettings.orderBy !== "$NONE") {
                        //order random
                        if (appSettings.orderBy === "$RANDOM") {
                            tempArray = apingUtilityHelper.shuffleArray(tempArray);
                        }
                        //order by attribute
                        else {
                            tempArray.sort(apingUtilityHelper.sortArrayByProperty(appSettings.orderBy));
                        }
                    }

                    //order reverse
                    if ((appSettings.orderReverse === true || appSettings.orderReverse === "true") && appSettings.orderBy !== "$RANDOM") {
                        tempArray.reverse();
                    }

                    //crop spare
                    if (appSettings.maxItems > -1 && tempArray.length > appSettings.maxItems) {
                        tempArray = tempArray.splice(0, appSettings.maxItems);
                    }

                    if (angular.isDefined(appSettings.valueName)) {
                        apingResults[appSettings.valueName] = tempArray;
                    }

                    $scope[$scope.resultName] = tempArray;

                    $scope.$broadcast('apiNG.resultMerged', {resultName: $scope.resultName, valueName: $scope.valueName});
                    $scope.$emit('apiNG.resultMerged', {resultName: $scope.resultName, valueName: $scope.valueName});
                };
                this.apply = function () {
                    $scope.$apply();
                };
            }]
        };
    }]);<|endoftext|>


<commit_before>import React, {Component} from 'react';
import List from 'material-ui/List';
import ListItem from 'material-ui/List/ListItem';
import Checkbox from 'material-ui/Checkbox';
import RaisedButton from 'material-ui/RaisedButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {muiTheme} from './ColorScheme';

const styles = {
    container: {

    },
    logoContainer: {
        textAlign: 'center'
    }
};

class InviteUsers extends Component {
    constructor(props, context) {
        super(props, context);

        let swapId = this.props.params['swapId'];

        this.hasSelectedUsers = this.hasSelectedUsers.bind(this);
        this.handleInviteUsers = this.handleInviteUsers.bind(this);
        this.handleSelectedUserChange = this.handleSelectedUserChange.bind(this);
        this.getAvailableUsers = this.getAvailableUsers.bind(this);

        this.state = {
            selectedUsers: [],
            availableUsers: [],
            swapId: swapId
        };
    }

    componentDidMount() {
        let me = this;
        fetch('http://beerswap.enservio.lan/BeerWS/api/User/V1').then(function (response) {
            return response.json();
        }).then(setUsers);

        function setUsers(users) {
            me.setState({
                availableUsers: users
            });
        }
    }

    getAvailableUsers = () => {
        return this.state.availableUsers;
    }
    hasSelectedUsers = () => {
        return this.state.selectedUsers.length > 0;
    }

    handleInviteUsers = () => {
        let me = this;
        let selectedUsers = this.state.selectedUsers;
        if (selectedUsers.length === 0) {
            alert('No selected users');
        }

        let swapId = this.state.swapId;
        let url = 'http://beerswap.enservio.lan/BeerWS/api/Beer/Swap/Invite/V1/' + swapId;
        fetch(url, {
            headers: new Headers({
                'Content-Type': 'application/json'
            }),
            mode: 'cors',
            method: 'post',
            body: JSON.stringify(selectedUsers)
        }).then(function () {
            me.props.router.push('/swapcreated/' + swapId);
        });
    }

    handleSelectedUserChange = (e, checked) => {
        let userId = e.target.id,
            selectedUsers = this.state.selectedUsers.slice();

        if (checked) {
            selectedUsers.push(userId);
        } else {
            let idx = selectedUsers.indexOf(userId);
            selectedUsers.splice(idx, 1);
        }

        this.setState({
            selectedUsers: selectedUsers
        });
    }

    render() {

        return (
            <MuiThemeProvider muiTheme={muiTheme}>

Invite Users to Beer Swap

                    <InviteList users={this.getAvailableUsers()}
                                handleSelectedUserChange={this.handleSelectedUserChange}/>
                    <InviteUsersButton handleInviteUsers={this.handleInviteUsers}
                                       hasSelectedUsers={this.hasSelectedUsers}/>

            </MuiThemeProvider>
        );
    }
}

class InviteList extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.props = props;
    }

    render() {
        const users = this.props.users.map((user) => {
            return (
                <ListItem key={user.UserId}
                          leftCheckbox={<Checkbox id={user.UserId} onCheck={this.props.handleSelectedUserChange}/>}
                          primaryText={user.FirstName + ' ' + user.LastName}
                />
            );
        });

        return (
            <List>
                {users}
            </List>
        );
    }
}

class InviteUsersButton extends React.Component {
    render() {
        return (
            <RaisedButton label="Invite Selected Users"
                          primary={true}
                          onTouchTap={this.props.handleInviteUsers}
                          disabled={!this.props.hasSelectedUsers()}/>
        );
    }
}

export default InviteUsers;
<commit_msg>Added select all/none<commit_after>import React, {Component} from 'react';
import List from 'material-ui/List';
import ListItem from 'material-ui/List/ListItem';
import Checkbox from 'material-ui/Checkbox';
import RaisedButton from 'material-ui/RaisedButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {muiTheme} from './ColorScheme';

const styles = {
    container: {

    },
    logoContainer: {
        textAlign: 'center'
    },
    selectAllCheck: {
        paddingLeft: 14
    }
};

class InviteUsers extends Component {
    constructor(props, context) {
        super(props, context);

        let swapId = this.props.params['swapId'];

        this.hasSelectedUsers = this.hasSelectedUsers.bind(this);
        this.handleInviteUsers = this.handleInviteUsers.bind(this);
        this.handleSelectedUserChange = this.handleSelectedUserChange.bind(this);
        this.getAvailableUsers = this.getAvailableUsers.bind(this);
        this.isChecked = this.isChecked.bind(this);

        this.state = {
            selectedUsers: [],
            availableUsers: [],
            swapId: swapId,
            select: true
        };
    }

    componentWillMount() {
        let me = this;
        fetch('http://beerswap.enservio.lan/BeerWS/api/User/V1').then(function (response) {
            return response.json();
        }).then(setUsers);

        function setUsers(users) {
            me.setState({
                availableUsers: users,
                selectedUsers: me.state.select ? users : []
            });
        }
    }

    handleToggle = (e, checkedState) => {
        this.setState({select: checkedState});
        if (checkedState) {
            let allUsers = this.state.availableUsers.slice();
            this.setState({
                selectedUsers: allUsers
            });
        } else {
            this.setState({
                selectedUsers: []
            });
        }
    }

    isChecked = (userId) => {
        let selectedUsers = this.state.selectedUsers.slice();
        return selectedUsers.filter(user => user.UserId === userId).length > 0;
    }

    getAvailableUsers = () => {
        return this.state.availableUsers;
    }
    hasSelectedUsers = () => {
        return this.state.selectedUsers.length > 0;
    }

    handleInviteUsers = () => {
        let me = this;
        let selectedUsers = this.state.selectedUsers;
        if (selectedUsers.length === 0) {
            alert('No selected users');
        }

        let swapId = this.state.swapId;
        let url = 'http://beerswap.enservio.lan/BeerWS/api/Beer/Swap/Invite/V1/' + swapId;
        fetch(url, {
            headers: new Headers({
                'Content-Type': 'application/json'
            }),
            mode: 'cors',
            method: 'post',
            body: JSON.stringify(selectedUsers)
        }).then(function () {
            me.props.router.push('/swapcreated/' + swapId);
        });
    }

    handleSelectedUserChange = (e, checked) => {
        let userId = e.target.id,
            selectedUsers = this.state.selectedUsers.slice();

        if (checked) {
            selectedUsers.push(userId);
        } else {
            let idx = selectedUsers.indexOf(userId);
            selectedUsers.splice(idx, 1);
        }

        this.setState({
            selectedUsers: selectedUsers
        });
    }

    render() {

        return (
            <MuiThemeProvider muiTheme={muiTheme}>

Invite Users to Beer Swap

                    <Checkbox onCheck={this.handleToggle} checked={this.state.select} style={styles.selectAllCheck} label="Select all/none"/>

                    <InviteList users={this.getAvailableUsers()}
                                isChecked={this.isChecked}
                                handleSelectedUserChange={this.handleSelectedUserChange}/>
                    <InviteUsersButton handleInviteUsers={this.handleInviteUsers}
                                       hasSelectedUsers={this.hasSelectedUsers}/>

            </MuiThemeProvider>
        );
    }
}

class InviteList extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.props = props;
    }

    render() {
        const users = this.props.users.map((user) => {
            return (
                <ListItem key={user.UserId}
                          leftCheckbox={<Checkbox id={user.UserId} checked={this.props.isChecked(user.UserId)} onCheck={this.props.handleSelectedUserChange}/>}
                          primaryText={user.FirstName + ' ' + user.LastName}
                />
            );
        });

        return (
            <List>
                {users}
            </List>
        );
    }
}

class InviteUsersButton extends React.Component {
    render() {
        return (
            <RaisedButton label="Invite Selected Users"
                          primary={true}
                          onTouchTap={this.props.handleInviteUsers}
                          disabled={!this.props.hasSelectedUsers()}/>
        );
    }
}

export default InviteUsers;
<|endoftext|>


<commit_before>import React from "react";
import { map } from "lodash-es";
import { connect } from "react-redux";
import { Panel, Button } from "react-bootstrap";
import AddReference from "./AddReference";
import ReferenceItem from "./ReferenceItem";
import ReferenceToolbar from "./Toolbar";
import { remoteReference } from "../actions";
import { ViewHeader } from "../../base";

const ReferenceList = (props) => {

    if (props.documents === null) {
        return
;
    }

    let referenceComponents;

    if (props.documents.length) {
        referenceComponents = map(props.documents, document =>
            <ReferenceItem key={document.id} {...document} />
        );
    }

    referenceComponents.push(
        <Panel key="remote" className="card reference-remote">

Official Remote Reference

                <Button bsStyle="primary" onClick={props.onRemote}>
                    Install
                </Button>

        </Panel>
    );

    return (

            <ViewHeader
                title="References"
                page={props.page}
                count={props.documents.length}
                foundCount={props.found_count}
                totalCount={props.total_count}
            />

            <ReferenceToolbar />

                {referenceComponents}

            {props.routerStateExists ? <AddReference /> : null}

    );
};

const mapStateToProps = state => ({
    ...state.references,
    account: state.account,
    routerStateExists: !!state.router.location.state
});

const mapDispatchToProps = dipatch => ({
    onRemote: () => {
        dipatch(remoteReference());
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(ReferenceList);
<commit_msg>Fix empty reference list error<commit_after>import React from "react";
import { map } from "lodash-es";
import { connect } from "react-redux";
import { Panel, Button } from "react-bootstrap";
import AddReference from "./AddReference";
import ReferenceItem from "./ReferenceItem";
import ReferenceToolbar from "./Toolbar";
import { remoteReference } from "../actions";
import { ViewHeader } from "../../base";

const ReferenceList = (props) => {

    if (props.documents === null) {
        return
;
    }

    let referenceComponents = [];

    if (props.documents.length) {
        referenceComponents = map(props.documents, document =>
            <ReferenceItem key={document.id} {...document} />
        );
    }

    referenceComponents.push(
        <Panel key="remote" className="card reference-remote">

Official Remote Reference

                <Button bsStyle="primary" onClick={props.onRemote}>
                    Install
                </Button>

        </Panel>
    );

    return (

            <ViewHeader
                title="References"
                page={props.page}
                count={props.documents.length}
                foundCount={props.found_count}
                totalCount={props.total_count}
            />

            <ReferenceToolbar />

                {referenceComponents}

            {props.routerStateExists ? <AddReference /> : null}

    );
};

const mapStateToProps = state => ({
    ...state.references,
    account: state.account,
    routerStateExists: !!state.router.location.state
});

const mapDispatchToProps = dipatch => ({
    onRemote: () => {
        dipatch(remoteReference());
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(ReferenceList);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';

import './CollageCanvas.css';

const generateStyle = attributes => {
  return Object.keys(attributes).map(key => {
    const value = attributes[key];
    return key + ':' + value + ';';
  }).join('');
};

const addSource = (element, url, type) => {
  const sourceElement = document.createElement('source');
  sourceElement.setAttribute('src', url);
  sourceElement.setAttribute('type', type);
  element.appendChild(sourceElement);
};

const fullscreen = {
  is: () => {
    const fullscreenElement = document.fullscreenElement ||
                              document.webkitFullscreenElement ||
                              document.mozFullScreenElement ||
                              document.msFullscreenElement;
    return !!fullscreenElement;
  },
  request: e => {
    const req = e.requestFullscreen ||
                e.msRequestFullscreen ||
                e.mozRequestFullScreen ||
                e.webkitRequestFullscreen;
    if(req) {
      req.call(e);
    }
  },
  exit: () => {
    if (document.exitFullscreen) {
    	document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
    	document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
    	document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
    	document.msExitFullscreen();
    }
  },
  addListener: listener => {
    document.addEventListener('fullscreenchange', listener);
    document.addEventListener('webkitfullscreenchange', listener);
    document.addEventListener('mozfullscreenchange', listener);
    document.addEventListener('MSFullscreenChange', listener);
  },
  removeListener: listener => {
    document.removeEventListener('fullscreenchange', listener);
    document.removeEventListener('webkitfullscreenchange', listener);
    document.removeEventListener('mozfullscreenchange', listener);
    document.removeEventListener('MSFullscreenChange', listener);
  }
};

// import DogGridSvg from '../svgs/dot-grid.svg';
import PlaySvg from '../svgs/play.svg';
import FullscreenSvg from '../svgs/fullscreen.svg';
import FullscreenOffSvg from '../svgs/fullscreen-off.svg';

class CollageCanvas extends Component {

  resources = {};

  state = {
    controlsVisible: false,
    facebookHref: 'http://www.facebook.com/sharer.php?u='
  };

  constructor() {
    super();
    this.resized = this.resized.bind(this);
    this.play = this.play.bind(this);
    this.fullscreen = this.fullscreen.bind(this);
    this.showControls = this.showControls.bind(this);
    this.hideControls = this.hideControls.bind(this);
    this.redraw = this.redraw.bind(this);
  }

  redraw() {
    const devicePixelRatio = window.devicePixelRatio || 1;
    // Initiate the canvas
    const ctx = this.canvas.getContext('2d');

    if(this.resources.background) {
      const background = this.backgroundPosition();

      ctx.drawImage(this.resources.background,
                    background.x,
                    background.y,
                    background.width,
                    background.height);

      if(this.resources.videos) {
        this.resources.videos.forEach(video => {
          const width = video.width * background.width;
          const height = video.height * background.height;
          const x = background.x + video.x * background.width;
          const y = background.y + video.y * background.height;
          const rotationDeg = video.rotation / (2 * Math.PI) * 360;

          if(video.player.isFullscreen()) {
            // Make sure full-screening is not distroyed by a strange position.
            video.player.setAttribute('style', '');
          } else {
            const style = {
              width: width / devicePixelRatio + 'px',
              height: height / devicePixelRatio + 'px',
              left: x / devicePixelRatio + 'px',
              top: y / devicePixelRatio + 'px',
              transform: 'rotate(' + rotationDeg + 'deg)',
              'transform-origin': '0 0' // Rotate around the upper left corner
            };
            video.player.setAttribute('style', generateStyle(style));
          }
        });
      }
    }
  }

  resized() {
    // Considering the device pixels might be different from "pixels"
    const devicePixelRatio = window.devicePixelRatio || 1;
    // Set the height to the height of the element
    this.canvas.height = this.canvas.offsetHeight * devicePixelRatio;
    this.canvas.width = this.canvas.offsetWidth * devicePixelRatio;
    this.redraw();
  }

  /* Loads the background image and all the videos that makes up the collage */
  loadResources() {
    const collage = this.props.collage;
    // The background image
    const backgroundElement = document.createElement('img');
    backgroundElement.addEventListener('load', () => {
      // When loaded, add this as a resource
      this.resources.background = backgroundElement;
      // Add a class to display the videos
      this.videoContainer.className += ' CollageCanvas__video-container--visible';
      this.redraw();
    });
    backgroundElement.src = collage.image;
    // The videos
    this.resources.videos = [];
    collage.videos.forEach(video => {
      const element = document.createElement('video');
      const classes = 'video-js vjs-default-skin CollageCanvas__video';
      element.setAttribute('class', classes);
      // TODO: Consider putting a thumbnail in the videos poster attribute
      addSource(element, video.videoData.files.hls, 'application/x-mpegURL');
      addSource(element, video.videoData.files.rtmpMpeg4, 'rtmp/mp4');
      addSource(element, video.videoData.files.rtmpFlv, 'rtmp/flv');

      this.videoContainer.appendChild(element);
      const player = window.videojs(element, {
        controls: 'auto',
        loop: true,
        autoplay: true,
        preload: 'auto',
        muted: true,
        bigPlayButton: false,
        inactivityTimeout: 500,
        controlBar: {
          children: {
            fullscreenToggle: true
          }
        },
        poster: video.videoData.files.thumbnail,
        techOrder: ['html5', 'flash']
      });

      this.resources.videos.push({
        element,
        player,
        x: video.xPos,
        y: video.yPos,
        width: video.width,
        height: video.height,
        rotation: video.rotation
      });

      // If the video needs a user gesture to start, we show the controls.
      player.on('suspend', (e) => {
        if(player.paused()) {
          this.showControls();
        }
      });
      // When the video starts playing the large collage control get hidden.
      player.on('play', this.hideControls);
      player.on('useractive', () => {
        // Mute all other players
        this.muteAllPlayers(player);
        // unmute
        player.muted(false);
        // and start playing this
        player.play();
      });
      // TODO: Add a listner on error as well ...
    });
    this.redraw();
  }

  play() {
    // Loop though all the video elements and start playback
    this.resources.videos.forEach(video => {
      if(!video.player.paused()) {
        video.player.pause();
      }
      video.player.play();
    });
  }

  fullscreen() {
    if (!fullscreen.is()) {
      fullscreen.request(this.everything);
    } else {
      fullscreen.exit();
    }
    // Update the state
    this.setState({
      fullscreen: fullscreen.is()
    });
  }

  showControls() {
    this.setState({
      controlsVisible: true
    });
  }

  hideControls() {
    this.setState({
      controlsVisible: false
    });
  }

  muteAllPlayers(exceptPlayer) {
    this.resources.videos.forEach(video => {
      if(video.player !== exceptPlayer) {
        video.player.muted(true);
      }
    });
  }

  backgroundPosition() {
    const background = this.resources.background;
    const canvas = this.canvas;

    const canvasRatio = canvas.width / canvas.height;
    const backgroundRatio = background.width / background.height;

    if(canvasRatio > backgroundRatio) {
      const height = canvas.height;
      const width = canvas.height * backgroundRatio;
      return {
        height,
        width,
        x: (canvas.width - width) / 2,
        y: 0
      }
    } else {
      const height = canvas.width / backgroundRatio;
      const width = canvas.width;
      return {
        height,
        width,
        x: 0,
        y: (canvas.height - height) / 2
      }
    }
  }

  componentDidMount() {
    window.addEventListener('resize', this.resized);
    this.resized();
    this.loadResources();
    // Redraw when fullscreen changes
    fullscreen.addListener(this.redraw);
    // Set the facebook url to share the current URL
    const url = location.href;
    this.setState({
      facebookHref: 'http://www.facebook.com/sharer.php?u=' + url
    });
  }

  componentDidUpdate(prevProps, prevState) {
    if(prevProps.collage.id !== this.props.collage.id) {
      this.loadResources();
    }
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resized);
    this.resources.videos.forEach(video => {
      video.player.off('suspend');
      video.player.off('play');
      video.player.off('volumechange');
    });
    // Redraw when fullscreen changes
    fullscreen.removeListener(this.redraw);
  }

  render() {
    return (

 { this.everything = e; }}>
        <canvas className="CollageCanvas__canvas"
          ref={(e) => { this.canvas = e; }} />

 { this.videoContainer = e; }} />

          Del på Facebook

          {this.state.fullscreen ? (

          ) : (

          )}

    );
  }
}

CollageCanvas.propTypes = {
  collage: PropTypes.object.isRequired
};

export default CollageCanvas;
<commit_msg>Fixing CSS prefixing at runtime and<commit_after>import React, { Component, PropTypes } from 'react';

import './CollageCanvas.css';

const CSS_PREFIXES = {
  'transform': ['-webkit-transform', '-ms-transform']
};

const generatePrefixes = attributes => {
  const result = {};
  // Loop through the attributes
  Object.keys(attributes).forEach(key => {
    const value = attributes[key];
    // Add the original value to the result
    result[key] = value;
    // If prefixes exists
    if(key in CSS_PREFIXES) {
      const prefixes = CSS_PREFIXES[key];
      // Add values for each prefix to the attributes
      prefixes.forEach(prefix => {
        result[prefix] = value;
      });
    }
  });
  return result;
};

const generateStyle = attributes => {
  const prefixedAttributes = generatePrefixes(attributes);
  return Object.keys(prefixedAttributes).map(key => {
    const value = prefixedAttributes[key];
    return key + ':' + value + ';';
  }).join('');
};

const addSource = (element, url, type) => {
  const sourceElement = document.createElement('source');
  sourceElement.setAttribute('src', url);
  sourceElement.setAttribute('type', type);
  element.appendChild(sourceElement);
};

const fullscreen = {
  is: () => {
    const fullscreenElement = document.fullscreenElement ||
                              document.webkitFullscreenElement ||
                              document.mozFullScreenElement ||
                              document.msFullscreenElement;
    return !!fullscreenElement;
  },
  request: e => {
    const req = e.requestFullscreen ||
                e.msRequestFullscreen ||
                e.mozRequestFullScreen ||
                e.webkitRequestFullscreen;
    if(req) {
      req.call(e);
    }
  },
  exit: () => {
    if (document.exitFullscreen) {
    	document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
    	document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
    	document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
    	document.msExitFullscreen();
    }
  },
  addListener: listener => {
    document.addEventListener('fullscreenchange', listener);
    document.addEventListener('webkitfullscreenchange', listener);
    document.addEventListener('mozfullscreenchange', listener);
    document.addEventListener('MSFullscreenChange', listener);
  },
  removeListener: listener => {
    document.removeEventListener('fullscreenchange', listener);
    document.removeEventListener('webkitfullscreenchange', listener);
    document.removeEventListener('mozfullscreenchange', listener);
    document.removeEventListener('MSFullscreenChange', listener);
  }
};

// import DogGridSvg from '../svgs/dot-grid.svg';
// import PlaySvg from '../svgs/play.svg';
import FullscreenSvg from '../svgs/fullscreen.svg';
import FullscreenOffSvg from '../svgs/fullscreen-off.svg';

class CollageCanvas extends Component {

  resources = {};

  state = {
    controlsVisible: false,
    facebookHref: 'http://www.facebook.com/sharer.php?u='
  };

  constructor() {
    super();
    this.resized = this.resized.bind(this);
    this.play = this.play.bind(this);
    this.fullscreen = this.fullscreen.bind(this);
    this.showControls = this.showControls.bind(this);
    this.hideControls = this.hideControls.bind(this);
    this.redraw = this.redraw.bind(this);
  }

  redraw() {
    const devicePixelRatio = window.devicePixelRatio || 1;
    // Initiate the canvas
    const ctx = this.canvas.getContext('2d');

    if(this.resources.background) {
      const background = this.backgroundPosition();

      ctx.drawImage(this.resources.background,
                    background.x,
                    background.y,
                    background.width,
                    background.height);

      if(this.resources.videos) {
        this.resources.videos.forEach(video => {
          const width = video.width * background.width;
          const height = video.height * background.height;
          const x = background.x + video.x * background.width;
          const y = background.y + video.y * background.height;
          const rotationDeg = video.rotation / (2 * Math.PI) * 360;

          if(video.player.isFullscreen()) {
            // Make sure full-screening is not distroyed by a strange position.
            video.player.setAttribute('style', '');
          } else {
            const style = {
              width: width / devicePixelRatio + 'px',
              height: height / devicePixelRatio + 'px',
              left: x / devicePixelRatio + 'px',
              top: y / devicePixelRatio + 'px',
              transform: 'rotate(' + rotationDeg + 'deg)',
              'transform-origin': '0 0' // Rotate around the upper left corner
            };
            video.player.setAttribute('style', generateStyle(style));
          }
        });
      }
    }
  }

  resized() {
    // Considering the device pixels might be different from "pixels"
    const devicePixelRatio = window.devicePixelRatio || 1;
    // Set the height to the height of the element
    this.canvas.height = this.canvas.offsetHeight * devicePixelRatio;
    this.canvas.width = this.canvas.offsetWidth * devicePixelRatio;
    this.redraw();
  }

  /* Loads the background image and all the videos that makes up the collage */
  loadResources() {
    const collage = this.props.collage;
    // The background image
    const backgroundElement = document.createElement('img');
    backgroundElement.addEventListener('load', () => {
      // When loaded, add this as a resource
      this.resources.background = backgroundElement;
      // Add a class to display the videos
      this.videoContainer.className += ' CollageCanvas__video-container--visible';
      this.redraw();
    });
    backgroundElement.src = collage.image;
    // The videos
    this.resources.videos = [];
    collage.videos.forEach(video => {
      const element = document.createElement('video');
      const classes = 'video-js vjs-default-skin CollageCanvas__video';
      element.setAttribute('class', classes);
      // TODO: Consider putting a thumbnail in the videos poster attribute
      addSource(element, video.videoData.files.hls, 'application/x-mpegURL');
      addSource(element, video.videoData.files.rtmpMpeg4, 'rtmp/mp4');
      addSource(element, video.videoData.files.rtmpFlv, 'rtmp/flv');

      this.videoContainer.appendChild(element);
      const player = window.videojs(element, {
        controls: 'auto',
        loop: true,
        autoplay: true,
        preload: 'auto',
        muted: true,
        bigPlayButton: false,
        inactivityTimeout: 500,
        poster: video.videoData.files.thumbnail,
        techOrder: ['html5', 'flash']
      });

      this.resources.videos.push({
        element,
        player,
        x: video.xPos,
        y: video.yPos,
        width: video.width,
        height: video.height,
        rotation: video.rotation
      });

      // If the video needs a user gesture to start, we show the controls.
      player.on('suspend', (e) => {
        if(player.paused()) {
          this.showControls();
        }
      });
      // When the video starts playing the large collage control get hidden.
      player.on('play', this.hideControls);
      player.on('useractive', () => {
        // and start playing this
        player.play();
        // unmute
        player.muted(false);
        // Mute all other players
        this.muteAllPlayers(player);
      });
      // TODO: Add a listner on error as well ...
    });
    this.redraw();
  }

  play() {
    // Loop though all the video elements and start playback
    this.resources.videos.forEach(video => {
      if(!video.player.paused()) {
        video.player.pause();
      }
      video.player.play();
    });
  }

  fullscreen() {
    if (!fullscreen.is()) {
      fullscreen.request(this.everything);
    } else {
      fullscreen.exit();
    }
    // Update the state
    this.setState({
      fullscreen: fullscreen.is()
    });
  }

  showControls() {
    this.setState({
      controlsVisible: true
    });
  }

  hideControls() {
    this.setState({
      controlsVisible: false
    });
  }

  muteAllPlayers(exceptPlayer) {
    this.resources.videos.forEach(video => {
      if(video.player !== exceptPlayer) {
        video.player.muted(true);
      }
    });
  }

  backgroundPosition() {
    const background = this.resources.background;
    const canvas = this.canvas;

    const canvasRatio = canvas.width / canvas.height;
    const backgroundRatio = background.width / background.height;

    if(canvasRatio > backgroundRatio) {
      const height = canvas.height;
      const width = canvas.height * backgroundRatio;
      return {
        height,
        width,
        x: (canvas.width - width) / 2,
        y: 0
      }
    } else {
      const height = canvas.width / backgroundRatio;
      const width = canvas.width;
      return {
        height,
        width,
        x: 0,
        y: (canvas.height - height) / 2
      }
    }
  }

  componentDidMount() {
    window.addEventListener('resize', this.resized);
    this.resized();
    this.loadResources();
    // Redraw when fullscreen changes
    fullscreen.addListener(this.redraw);
    // Set the facebook url to share the current URL
    const url = location.href;
    this.setState({
      facebookHref: 'http://www.facebook.com/sharer.php?u=' + url
    });
  }

  componentDidUpdate(prevProps, prevState) {
    if(prevProps.collage.id !== this.props.collage.id) {
      this.loadResources();
    }
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resized);
    this.resources.videos.forEach(video => {
      video.player.off('suspend');
      video.player.off('play');
      video.player.off('volumechange');
    });
    // Redraw when fullscreen changes
    fullscreen.removeListener(this.redraw);
  }

  render() {
    return (

 { this.everything = e; }}>
        <canvas className="CollageCanvas__canvas"
          ref={(e) => { this.canvas = e; }} />

 { this.videoContainer = e; }} />

          Del på Facebook

          {this.state.fullscreen ? (

          ) : (

          )}

    );
  }
}

CollageCanvas.propTypes = {
  collage: PropTypes.object.isRequired
};

export default CollageCanvas;
<|endoftext|>


<commit_before>// Subscribe to accommodation counts
Meteor.subscribe('campingRegistrantAccommodationCount');
Meteor.subscribe('semiprivateRegistrantAccommodationCount');
Meteor.subscribe('privateRegistrantAccommodationCount');
Meteor.subscribe('yafRegistrantAccommodationCount');
Meteor.subscribe('jymRegistrantAccommodationCount');
<commit_msg>Added dorm subscriptions.<commit_after>// Subscribe to accommodation counts
Meteor.subscribe('campingRegistrantAccommodationCount');
Meteor.subscribe('semiprivateRegistrantAccommodationCount');
Meteor.subscribe('dormDistantRegistrantAccommodationCount');
Meteor.subscribe('dormProximateRegistrantAccommodationCount');
Meteor.subscribe('yafRegistrantAccommodationCount');
Meteor.subscribe('jymRegistrantAccommodationCount');
<|endoftext|>


<commit_before>// See routing.js for the route

TemplateMixins.Expandible(Template.profile);
Template.profile.onCreated(function() {
	this.editing = new ReactiveVar(false);
	this.changingPass = new ReactiveVar(false);
	this.sending = new ReactiveVar(false);
	this.verifyDelete = new ReactiveVar(false);
});

Template.profile.helpers({
	editing: function() {
		return Template.instance().editing.get();
	},
	changingPass: function() {
		return Template.instance().changingPass.get();
	},

	sending: function() {
		return Template.instance().sending.get();
	},

	verifyDelete: function() {
		return Template.instance().verifyDelete.get();
	},

	groupCount: function() {
		return this.user.groups.count();
	},

	notificationsChecked: function() {
		if (this.user.notifications) return 'checked';
	},

	privacyChecked: function() {
		if (this.user.privacy) return 'checked';
	},

	isVenueEditor: function() {
		return this.user.venues.count() > 0;
	},
	roles: function() {
		return _.clone(Roles).reverse();
	},
	coursesByRole: function(role) {
		var templateData = Template.instance().data;
		var involvedIn = templateData.involvedIn;
		var userID = templateData.user._id;
		var coursesForRole = [];

		involvedIn.forEach(function(course) {
			if(!!hasRoleUser(course.members, role, userID)) {
				coursesForRole.push(course);
			}
		});
		return coursesForRole;
	},
	roleMyList: function() {
		return 'roles.'+this.type+'.myList';
	},
	unsubscribeSuccess: function() {
		return Router.current().params.query.unsubscribed === '';
	},
	unsubscribeError: function() {
		return Router.current().params.query['unsubscribe-error'] === '';
	}
});

Template.profile.events({
	'click .js-profile-info-edit': function(event, instance) {
		Tooltips.hide();
		instance.editing.set(true);
		instance.collapse();
	},

	'click .js-profile-info-cancel': function(event, instance) {
		instance.editing.set(false);
		return false;
	},

	'click .js-change-pwd-btn': function(event, instance) {
		Template.instance().changingPass.set(true);
		instance.collapse();
	},

	'click .js-expand': function(event, instance) {
		instance.changingPass.set(false);
	},

	'click .js-profile-delete-confirm-btn': function(event, instance) {
		Meteor.call('delete_profile', function() {
			addMessage(mf('profile.deleted', 'Your account has been deleted'), 'success');
		});
		instance.collapse(); // Wait for server to log us out.
	},

	'submit .profile-info-edit': function(event, instance) {
		event.preventDefault();
		Meteor.call('update_userdata',
			document.getElementById('editform_username').value,
			document.getElementById('editform_email').value,
			instance.$('.js-notifications').prop("checked"),
			function(err) {
				if (err) {
					showServerError('Saving your profile failed', err);
				} else {
					addMessage(mf('profile.updated', 'Updated profile'), 'success');
					instance.editing.set(false);
				}
			}
		);
	},

	'submit #changePwd': function(event, instance) {
		event.preventDefault();
		var old = document.getElementById('oldpassword').value;
		var pass = document.getElementById('newpassword').value;
		if (pass !== "") {
			if (pass !== document.getElementById('newpassword_confirm').value) {
				addMessage(mf('profile.passwordMismatch', "Sorry, Your new passwords don't match"), 'danger');
				return;
			} else {
				var minLength = 5; // We've got _some_ standards
				if (pass.length < minLength) {
					addMessage(mf('profile.passwordShort', 'Are you serious? Your desired password is too short, sorry.'), 'danger');
					return;
				}
				Accounts.changePassword(old, pass, function(err) {
					if (err) {
						showServerError('Failed to change your password', err);
					} else {
						addMessage(mf('profile.passwordChangedSuccess', 'You have changed your password successfully.'), 'success');
						instance.changingPass.set(false);
					}
				});
			}
		}
	},

	'click .js-verify-mail-btn': function(event, instance) {
		instance.sending.set(true);
		Meteor.call('sendVerificationEmail', function(err) {
			if (err) {
				instance.sending.set(false);
				showServerError('Failed to send verification mail', err);
			} else {
				addMessage(mf('profile.sentVerificationMail', 'A verification mail is on its way to your address.'), 'success');
			}
		});
	}
});
<commit_msg>fix cancel button for change pwd<commit_after>// See routing.js for the route

TemplateMixins.Expandible(Template.profile);
Template.profile.onCreated(function() {
	this.editing = new ReactiveVar(false);
	this.changingPass = new ReactiveVar(false);
	this.sending = new ReactiveVar(false);
	this.verifyDelete = new ReactiveVar(false);
});

Template.profile.helpers({
	editing: function() {
		return Template.instance().editing.get();
	},
	changingPass: function() {
		return Template.instance().changingPass.get();
	},

	sending: function() {
		return Template.instance().sending.get();
	},

	verifyDelete: function() {
		return Template.instance().verifyDelete.get();
	},

	groupCount: function() {
		return this.user.groups.count();
	},

	notificationsChecked: function() {
		if (this.user.notifications) return 'checked';
	},

	privacyChecked: function() {
		if (this.user.privacy) return 'checked';
	},

	isVenueEditor: function() {
		return this.user.venues.count() > 0;
	},
	roles: function() {
		return _.clone(Roles).reverse();
	},
	coursesByRole: function(role) {
		var templateData = Template.instance().data;
		var involvedIn = templateData.involvedIn;
		var userID = templateData.user._id;
		var coursesForRole = [];

		involvedIn.forEach(function(course) {
			if(!!hasRoleUser(course.members, role, userID)) {
				coursesForRole.push(course);
			}
		});
		return coursesForRole;
	},
	roleMyList: function() {
		return 'roles.'+this.type+'.myList';
	},
	unsubscribeSuccess: function() {
		return Router.current().params.query.unsubscribed === '';
	},
	unsubscribeError: function() {
		return Router.current().params.query['unsubscribe-error'] === '';
	}
});

Template.profile.events({
	'click .js-profile-info-edit': function(event, instance) {
		Tooltips.hide();
		instance.editing.set(true);
		instance.collapse();
	},

	'click .js-profile-info-cancel': function(event, instance) {
		instance.editing.set(false);
		return false;
	},

	'click .js-change-pwd-btn': function(event, instance) {
		Template.instance().changingPass.set(true);
		instance.collapse();
	},

	'click .js-change-pwd-cancel': function(event, instance) {
		instance.changingPass.set(false);
	},

	'click .js-expand': function(event, instance) {
		instance.changingPass.set(false);
	},

	'click .js-profile-delete-confirm-btn': function(event, instance) {
		Meteor.call('delete_profile', function() {
			addMessage(mf('profile.deleted', 'Your account has been deleted'), 'success');
		});
		instance.collapse(); // Wait for server to log us out.
	},

	'submit .profile-info-edit': function(event, instance) {
		event.preventDefault();
		Meteor.call('update_userdata',
			document.getElementById('editform_username').value,
			document.getElementById('editform_email').value,
			instance.$('.js-notifications').prop("checked"),
			function(err) {
				if (err) {
					showServerError('Saving your profile failed', err);
				} else {
					addMessage(mf('profile.updated', 'Updated profile'), 'success');
					instance.editing.set(false);
				}
			}
		);
	},

	'submit #changePwd': function(event, instance) {
		event.preventDefault();
		var old = document.getElementById('oldpassword').value;
		var pass = document.getElementById('newpassword').value;
		if (pass !== "") {
			if (pass !== document.getElementById('newpassword_confirm').value) {
				addMessage(mf('profile.passwordMismatch', "Sorry, Your new passwords don't match"), 'danger');
				return;
			} else {
				var minLength = 5; // We've got _some_ standards
				if (pass.length < minLength) {
					addMessage(mf('profile.passwordShort', 'Are you serious? Your desired password is too short, sorry.'), 'danger');
					return;
				}
				Accounts.changePassword(old, pass, function(err) {
					if (err) {
						showServerError('Failed to change your password', err);
					} else {
						addMessage(mf('profile.passwordChangedSuccess', 'You have changed your password successfully.'), 'success');
						instance.changingPass.set(false);
					}
				});
			}
		}
	},

	'click .js-verify-mail-btn': function(event, instance) {
		instance.sending.set(true);
		Meteor.call('sendVerificationEmail', function(err) {
			if (err) {
				instance.sending.set(false);
				showServerError('Failed to send verification mail', err);
			} else {
				addMessage(mf('profile.sentVerificationMail', 'A verification mail is on its way to your address.'), 'success');
			}
		});
	}
});
<|endoftext|>


<commit_before>import ImmutableStore from '../lib/immutable-store';

const defaultState = {
    controllers: {}
};

const state = _.merge({}, defaultState);
const store = new ImmutableStore(state);

export default store;
<commit_msg>Bug fixes<commit_after>import ImmutableStore from '../lib/immutable-store';

const defaultState = {
    controllers: {}
};

const store = new ImmutableStore(defaultState);

export default store;
<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var _ = require('lodash');
var moment = require('moment');
var fs = require('fs');
var path = require('path');
var DEFAULT_LANG = 'en_US';

function updateApplication(args, callback) {
  var seneca = this;
  var plugin = args.role;
  var ENTITY_NS = 'cd/applications';
  var ATTENDANCE_ENTITY_NS = 'cd/attendance';
  var applications = seneca.make$(ENTITY_NS);
  var so = seneca.options();
  var application = args.application;
  var emailSubject = application.emailSubject;
  delete application.emailSubject;

  async.waterfall([
    updateApplication,
    sendEmail
  ], callback);

  function updateApplication(done) {
    applications.list$({eventId: application.eventId, userId: application.userId}, function(err, list){
      if(err) return done(err);

      applications.save$(application, done);
    })
  }

  function sendEmail(application, done) {
    if(application.error) return done(null, application);
    if(application.status !== 'approved') return done(null, application);
    //Only send an email if the application is approved.
    async.waterfall([
      loadUser,
      loadEvent,
      saveAttendanceRecord,
      sendEmail
    ], function (err, res) {
      if(err) return done(null, {error: err});
      return done(null, application);
    });

    function loadUser(cb) {
      seneca.act({role:'cd-users', cmd:'load', id:application.userId }, function (err, response) {
        if(err) return cb(err);
        return cb(null, response);
      });
    }

    function loadEvent(user, cb) {
      seneca.act({role:plugin, cmd:'getEvent', id:application.eventId }, function (err, response) {
        if(err) return cb(err);
        return cb(null, user, response);
      });
    }

    function saveAttendanceRecord(user, event, cb) {
      if(event.type === 'recurring') {
        //Save attendance record for each event date
        var eventDates = event.dates;
        async.each(eventDates, function (eventDate, cb) {
          var attendance = {
            userId: user.id,
            eventId: event.id,
            eventDate: eventDate,
            attended: false
          };
          seneca.act({role: plugin, cmd:'saveAttendance', attendance: attendance}, cb);
        }, function (err) {
          if(err) return cb(err);
          return cb(null, user, event);
        });
      } else {
        //One-off event
        var eventDate = _.first(event.dates);
        var attendance = {
          userId: user.id,
          eventId: event.id,
          eventDate: eventDate,
          attended: false
        };
        seneca.act({role: plugin, cmd: 'saveAttendance', attendance: attendance}, function (err, response) {
          if(err) return cb(err);
          return cb(null, user, event);
        });
      }
    }

    function sendEmail(user, event, sendEmailCb) {
      var recipients = [];
      if(!user.email) { //Approving attendee-u13, retrieve parent email addresses.
        seneca.act({role: 'cd-profiles', cmd: 'list', query: {userId:user.id}}, function (err, userProfiles) {
          if(err) return cb(err);
          var youth = userProfiles[0];
          async.each(youth.parents, function (parentUserId, cb) {
            seneca.act({role: 'cd-profiles', cmd: 'list', query: {userId: parentUserId}}, function (err, response) {
              if(err) return cb(err);
              var parentEmail = youth.email;
              recipients.push(parentEmail);
              cb();
            });
          }, prepareEmails)
        });
      } else {
        recipients.push(user.email);
        prepareEmails();
      }

      function prepareEmails() {
        //Send approval email to all recipients
        if(event.type === 'recurring') {
          //Recurring event
          var locality = args.locality || 'en_US';
          var code = 'recurring-event-application-approved-';

          var eventStartDate = moment.utc(_.first(event.dates)).format('MMMM Do YYYY');
          var eventEndDate = moment.utc(_.last(event.dates)).format('MMMM Do YYYY');

          var eventTime = moment(eventStartDate.startTime).format('HH:mm') + ' - ' + moment(eventStartDate.endTime).format('HH:mm');

          //TODO: Translate weekdays.
          var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
          var eventDay = weekdays[moment.utc(_.first(event.dates)).weekday()];
          var content = {
            userName: user.name,
            eventName: event.name,
            eventStartDate: eventStartDate,
            eventEndDate: eventEndDate,
            eventDay: eventDay,
            eventTime: eventTime,
            year: moment(new Date()).format('YYYY')
          };
          send(code, locality, content);
        } else {
          //One-off event
          var locality = args.locality || 'en_US';
          var code = 'one-off-event-application-approved-';

          var eventDate = moment.utc(_.first(event.dates)).format('MMMM Do YYYY, HH:mm');
          var eventTime = moment(eventDate.startTime).format('HH:mm') + ' - ' + moment(eventDate.endTime).format('HH:mm');
          var content = {
            userName: user.name,
            eventName: event.name,
            eventDate: eventDate,
            eventTime: eventTime,
            year: moment(new Date()).format('YYYY')
          };
          send(code, locality, content);
        }

        function send(code, locality, content) {
          async.each(recipients, function (recipient, cb) {
            var payload = {
              to: recipient,
              code: code,
              locality: locality,
              content: content,
              subject: emailSubject
            };
            seneca.act({role:'cd-dojos', cmd:'send_email', payload:payload}, cb);
          }, sendEmailCb);
        }
      }
    }

  }
}

module.exports = updateApplication;
<commit_msg>refactoring&fixes to update application cmd<commit_after>'use strict';

var async = require('async');
var _ = require('lodash');
var moment = require('moment');
var fs = require('fs');
var path = require('path');
var DEFAULT_LANG = 'en_US';

function updateApplication(args, callback) {
  var seneca = this;
  var plugin = args.role;
  var ENTITY_NS = 'cd/applications';
  var ATTENDANCE_ENTITY_NS = 'cd/attendance';
  var applications = seneca.make$(ENTITY_NS);
  var so = seneca.options();
  var application = args.application;
  var emailSubject = application.emailSubject;
  delete application.emailSubject;

  async.waterfall([
    updateApplication,
    sendEmail
  ], callback);

  function updateApplication(done) {
    applications.list$({eventId: application.eventId, userId: application.userId}, function(err, list){
      if(err) return done(err);

      applications.save$(application, done);
    })
  }

  function sendEmail(application, done) {
    if(application.error) return done(null, application);
    if(application.status !== 'approved') return done(null, application);
    //Only send an email if the application is approved.
    async.waterfall([
      loadUser,
      loadEvent,
      saveAttendanceRecord,
      sendEmail
    ], function (err, res) {
      if(err) return done(null, {error: err});
      return done(null, application);
    });

    function loadUser(cb) {
      seneca.act({role:'cd-users', cmd:'load', id:application.userId }, function (err, response) {
        if(err) return cb(err);
        return cb(null, response);
      });
    }

    function loadEvent(user, cb) {
      seneca.act({role:plugin, cmd:'getEvent', id:application.eventId }, function (err, response) {
        if(err) return cb(err);
        return cb(null, user, response);
      });
    }

    function saveAttendanceRecord(user, event, cb) {
      if(event.type === 'recurring') {
        //Save attendance record for each event date
        async.each(event.dates, function (eventDate, cb) {
          var attendance = {
            userId: user.id,
            eventId: event.id,
            eventDate: eventDate.startTime,
            attended: false
          };
          seneca.act({role: plugin, cmd:'saveAttendance', attendance: attendance}, cb);
        }, function (err) {
          if(err) return cb(err);
          return cb(null, user, event);
        });
      } else {
        //One-off event
        var attendance = {
          userId: user.id,
          eventId: event.id,
          eventDate: _.first(event.dates).startTime,
          attended: false
        };
        seneca.act({role: plugin, cmd: 'saveAttendance', attendance: attendance}, function (err, response) {
          if(err) return cb(err);
          return cb(null, user, event);
        });
      }
    }

    function sendEmail(user, event, sendEmailCb) {
      var recipients = [];
      if(!user.email) { //Approving attendee-u13, retrieve parent email addresses.
        seneca.act({role: 'cd-profiles', cmd: 'list', query: {userId:user.id}}, function (err, userProfiles) {
          if(err) return cb(err);
          var youth = userProfiles[0];
          async.each(youth.parents, function (parentUserId, cb) {
            seneca.act({role: 'cd-profiles', cmd: 'list', query: {userId: parentUserId}}, function (err, response) {
              if(err) return cb(err);
              var parentEmail = youth.email;
              recipients.push(parentEmail);
              cb();
            });
          }, prepareEmails)
        });
      } else {
        recipients.push(user.email);
        prepareEmails();
      }

      function prepareEmails() {
        //Send approval email to all recipients

        var locality = args.locality || 'en_US';
        var code = '';
        var eventTime = '';
        var content = {};

        if(event.type === 'recurring') {
          //Recurring event

          code = 'recurring-event-application-approved-';

          var eventStartDate = moment.utc(_.first(event.dates).startTime).format('MMMM Do YYYY');
          var eventEndDate = moment.utc(_.last(event.dates).startTime).format('MMMM Do YYYY');

          eventTime = moment.utc(_.first(event.dates).startTime).format('HH:mm') + ' - ' + moment.utc(_.first(event.dates).endTime).format('HH:mm');

          //TODO: Translate weekdays.
          var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
          var eventDay = weekdays[moment.utc(_.first(event.dates).startTime).weekday()];

          content.userName = user.name;
          content.eventName = event.name;
          content.eventStartDate = eventStartDate;
          content.eventEndDate = eventEndDate;
          content.eventDay = eventDay;
          content.eventTime = eventTime;
          content.year = moment.utc(new Date()).format('YYYY');

          send(code, locality, content);
        } else {
          //One-off event
          code = 'one-off-event-application-approved-';

          var eventDate = moment.utc(_.first(event.dates).startTime).format('MMMM Do YYYY, HH:mm');
          eventTime = moment.utc(_.first(event.dates).startTime).format('HH:mm') + ' - ' + moment.utc(_.first(event.dates).endTime).format('HH:mm');

          content.userName = user.name;
          content.eventName = event.name;
          content.eventDate =  eventDate;
          content.eventTime = eventTime;
          content.year = moment.utc(new Date()).format('YYYY');

          send(code, locality, content);
        }

        function send(code, locality, content) {
          async.each(recipients, function (recipient, cb) {
            var payload = {
              to: recipient,
              code: code,
              locality: locality,
              content: content,
              subject: emailSubject
            };
            seneca.act({role:'cd-dojos', cmd:'send_email', payload:payload}, cb);
          }, sendEmailCb);
        }
      }
    }

  }
}

module.exports = updateApplication;
<|endoftext|>


<commit_before>/*global Office:false */
/*global PureCloud:false */
/*global startup:false */
/*exported traceService */
/*exported getFileSizeString */
/*exported inIframe */
/* jshint -W097 */
'use strict';

var traceService = new traceService();

function getFileSizeString(numOfBytes){
    if(numOfBytes < 1024){
        return numOfBytes + " Bytes";
    }
    var kb = numOfBytes / 1024;
    if(kb < 1000){
        return Math.round(kb) + " KB";
    }

    var mb = numOfBytes / 1048576;
    return Math.round(mb) + " MB";
}

function inIframe () {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}

function authorizeAndStart(){

    try {
        traceService.debug("authorize and start called");
        var clientId = "";
        var callback = "";

        var environment = window.location.hostname.replace(/(apps|com|\.)/g,"");
        traceService.debug("environment " + environment);

        var environments = {
            inindca_forreal: {
                clientId: "80718713-aa6c-4f7d-bf25-69d9c5e9df2a",
                callback: "https://apps.inindca.com/github-outlook365addins/auth.html"
            },
            ininsca: {
                clientId: "c08fd793-f867-4fcc-bf8c-4f92b294f53c",
                callback: "https://localhost:8080/auth.html"
            },
            localhost: {
                clientId: "c08fd793-f867-4fcc-bf8c-4f92b294f53c",
                callback: "https://localhost:8080/auth.html"
            }
        };

        if(environments[environment] !== null){
            clientId = environments[environment].clientId;
            callback = environments[environment].callback;
        }else{
            traceService.log("Unsupported environment " + environment );
            return;
        }

        var purecloudEnvironment = environment + ".com";
        var app = "github-outlook365addins/" + window.location.pathname.match(/[a-zA-Z]*\.html/)[0];

        if(environment === "localhost"){
            purecloudEnvironment = "inindca.com";
            app = "github-outlook365addins/" + window.location.pathname.match(/[a-zA-Z]*\.html/)[0];
        }

    } catch (e) {
        traceService.error(JSON.stringify(e));
    }

    if(!PureCloud.hasAuthorizationToken()){
        PureCloud.authorize(clientId, callback, app, purecloudEnvironment);
        return;
    }else{
        traceService.debug("authorize token present, setting environment");
        PureCloud.setEnvironment(purecloudEnvironment);
    }

    $('#settings').hide();
    $('#settingsButton').click(function(){
        $('#settings').show();
    });

    $(".close").click(function(){
        $(this).parent().hide();
    });

    $('#logoffButton').click(function(){
        PureCloud.logout();
    });

    startup();

    loadHelpDialog();
    $("#useragent").html( navigator.userAgent);

}

Office.initialize = function () {
    authorizeAndStart();
};
<commit_msg>fixing inindca details<commit_after>/*global Office:false */
/*global PureCloud:false */
/*global startup:false */
/*exported traceService */
/*exported getFileSizeString */
/*exported inIframe */
/* jshint -W097 */
'use strict';

var traceService = new traceService();

function getFileSizeString(numOfBytes){
    if(numOfBytes < 1024){
        return numOfBytes + " Bytes";
    }
    var kb = numOfBytes / 1024;
    if(kb < 1000){
        return Math.round(kb) + " KB";
    }

    var mb = numOfBytes / 1048576;
    return Math.round(mb) + " MB";
}

function inIframe () {
    try {
        return window.self !== window.top;
    } catch (e) {
        return true;
    }
}

function authorizeAndStart(){

    try {
        traceService.debug("authorize and start called");
        var clientId = "";
        var callback = "";

        var environment = window.location.hostname.replace(/(apps|com|\.)/g,"");
        traceService.debug("environment " + environment);

        var environments = {
            inindca: {
                clientId: "80718713-aa6c-4f7d-bf25-69d9c5e9df2a",
                callback: "https://apps.inindca.com/github-outlook365addins/auth.html"
            },
            ininsca: {
                clientId: "c08fd793-f867-4fcc-bf8c-4f92b294f53c",
                callback: "https://localhost:8080/auth.html"
            },
            localhost: {
                clientId: "c08fd793-f867-4fcc-bf8c-4f92b294f53c",
                callback: "https://localhost:8080/auth.html"
            }
        };

        if(environments[environment] !== null){
            clientId = environments[environment].clientId;
            callback = environments[environment].callback;
        }else{
            traceService.log("Unsupported environment " + environment );
            return;
        }

        var purecloudEnvironment = environment + ".com";
        var app = "github-outlook365addins/" + window.location.pathname.match(/[a-zA-Z]*\.html/)[0];

        if(environment === "localhost"){
            purecloudEnvironment = "inindca.com";
            app = "github-outlook365addins/" + window.location.pathname.match(/[a-zA-Z]*\.html/)[0];
        }

    } catch (e) {
        traceService.error(JSON.stringify(e));
    }

    if(!PureCloud.hasAuthorizationToken()){
        PureCloud.authorize(clientId, callback, app, purecloudEnvironment);
        return;
    }else{
        traceService.debug("authorize token present, setting environment");
        PureCloud.setEnvironment(purecloudEnvironment);
    }

    $('#settings').hide();
    $('#settingsButton').click(function(){
        $('#settings').show();
    });

    $(".close").click(function(){
        $(this).parent().hide();
    });

    $('#logoffButton').click(function(){
        PureCloud.logout();
    });

    startup();

    loadHelpDialog();
    $("#useragent").html( navigator.userAgent);

}

Office.initialize = function () {
    authorizeAndStart();
};
<|endoftext|>