<commit_before>/* eslint-disable */

import React from 'react';
import { keyBy, map } from 'lodash';
import RogueClient from '../../utilities/RogueClient';
import {
  extractPostsFromSignups,
  extractSignupsFromPosts,
} from '../../helpers';

const reviewComponent = (Component, data) => {
  return class extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        loading: true,
      };

      this.api = new RogueClient(window.location.origin, {
        headers: { Authorization: `Bearer ${window.AUTH}` },
      });
      this.updatePost = this.updatePost.bind(this);
      this.updateTag = this.updateTag.bind(this);
      this.updateQuantity = this.updateQuantity.bind(this);
      this.showHistory = this.showHistory.bind(this);
      this.hideHistory = this.hideHistory.bind(this);
      this.deletePost = this.deletePost.bind(this);
      this.setNewPosts = this.setNewPosts.bind(this);
      this.rotate = this.rotate.bind(this);
    }

    // Loads initial posts into state.
    componentDidMount() {
      // Require initial_posts and campaign parameters.
      if (data.initial_posts && data.campaign) {
        this.getPostsByStatus(data.initial_posts, data.campaign.id);
      } else {
        // @TODO - handle error better.
        console.log(
          'Error: need to know the initial posts to load and the campaign.',
        );
      }
    }

    // Make API call to GET api/v3/posts to get posts by filtered status.
    getPostsByStatus(status, campaignId) {
      this.api
        .getPosts({
          filter: {
            status: status,
            campaign_id: campaignId,
          },
          include: ['signup', 'siblings'],
        })
        .then(json =>
          this.setState({
            campaign: data.campaign,
            posts: keyBy(json.data, 'id'),
            postIds: map(json.data, 'id'),
            signups: extractSignupsFromPosts(keyBy(json.data, 'id')),
            filter: status,
            displayHistoryModal: null,
            historyModalId: null,
            loading: false,
            nextPage: json.meta.cursor.next,
            prevPage: json.meta.cursor.prev,
          }),
        );
    }

    setNewPosts(apiResponse) {
      const posts = keyBy(apiResponse.data, 'id');
      this.setState({
        campaign: data.campaign,
        posts: posts,
        postIds: map(apiResponse.data, 'id'),
        signups: extractSignupsFromPosts(posts),
        displayHistoryModal: null,
        historyModalId: null,
        loading: false,
        nextPage: apiResponse.meta.cursor.next,
        prevPage: apiResponse.meta.cursor.prev,
      });
    }

    // Open the history modal of the given post
    showHistory(postId, event, signupId) {
      event.preventDefault();

      this.api
        .getEvents({
          filter: {
            signup_id: signupId,
          },
        })
        .then(result => {
          this.setState(previousState => {
            const newState = { ...previousState };

            newState.displayHistoryModal = true;
            newState.historyModalId = postId;
            newState.signupEvents = Object.values(result.data);
            return newState;
          });
        });
    }

    // Close the open history modal
    hideHistory(event) {
      if (event) {
        event.preventDefault();
      }

      this.setState({
        displayHistoryModal: false,
        historyModalId: null,
      });
    }

    // Updates a post status.
    updatePost(post, fields) {
      fields.post_id = post.id;

      let request = this.api.postReview(fields);

      return request.then(result => {
        this.setState(previousState => {
          const newState = { ...previousState };

          newState.posts[post.id].status = fields.status;

          return newState;
        });
      });
    }

    // Tag a post.
    updateTag(postId, tag) {
      const field = {
        tag_name: tag,
      };

      let response = this.api.post(`api/v3/posts/${postId}/tags`, field);

      return response.then(result => {
        this.setState(previousState => {
          const newState = { ...previousState };
          const user = newState.posts[postId].user;
          const signup = newState.posts[postId].signup.data;

          // Merge existing post with the newly updated values from API.
          newState.posts[postId] = {
            ...newState.posts[postId],
            ...result['data'],
          };

          return newState;
        });
      });
    }

    // Update a post's quantity.
    updateQuantity(post, newQuantity) {
      // Field to send to /api/v3/posts/:post_id
      const field = {
        quantity: parseInt(newQuantity),
      };

      // Make API request to Rogue to update the quantity on the backend
      let request = this.api.patch(`api/v3/posts/${post['id']}`, field);

      request.then(result => {
        // Update the state
        this.setState(previousState => {
          const newState = { ...previousState };
          newState.posts[post['id']].quantity = result.data['quantity'];

          return newState;
        });
      });

      // Close the modal
      this.hideHistory();
    }

    // Delete a post.
    deletePost(postId, event) {
      event.preventDefault();
      const confirmed = confirm(
        '🚨🔥🚨Are you sure you want to delete this?🚨🔥🚨',
      );

      if (confirmed) {
        // Make API request to Rogue to update the quantity on the backend
        let response = this.api.delete(`api/v3/posts/${postId}`);

        response.then((result) => {
          // Update the state
          this.setState(previousState => {
            var newState = { ...previousState };

            // Remove the deleted post from the state
            delete newState.posts[postId];

            // Remove the postId from the state.
            const postIdIndex = newState.postIds.indexOf(postId);

            if (postIdIndex > -1) {
              newState.postIds.splice(postIdIndex, 1);
            }

            // Return the new state
            return newState;
          });
        });
      }
    }

    // Rotate a Post Image.
    rotate(postId) {
      let response = this.api.post(`images/${postId}?rotate=90`);

      return response.then(json => {
        this.setState(prevState => {
          const newState = { ...prevState };
          // Add a cache-busting string to the end of the image url
          // so that it changes and triggers a re-render.
          newState.posts[postId].media.original_image_url =
            json.original_image_url + '?time=' + Date.now();

          return newState;
        });
      });
    }

    render() {
      const methods = {
        updatePost: this.updatePost,
        updateTag: this.updateTag,
        updateQuantity: this.updateQuantity,
        showHistory: this.showHistory,
        hideHistory: this.hideHistory,
        deletePost: this.deletePost,
        setNewPosts: this.setNewPosts,
        rotate: this.rotate,
      };

      // Pass in the state from this HoC to trigger rendering down the DOM
      // Also pass in methods bound to this instance.
      // Also pass in original data pass to the HoC in case other components still need it down the line.
      return <Component {...this.state} {...methods} {...data} />;
    }
  };
};

export default reviewComponent;
<commit_msg>only returns photo and text posts in inbox<commit_after>/* eslint-disable */

import React from 'react';
import { keyBy, map } from 'lodash';
import RogueClient from '../../utilities/RogueClient';
import {
  extractPostsFromSignups,
  extractSignupsFromPosts,
} from '../../helpers';

const reviewComponent = (Component, data) => {
  return class extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        loading: true,
      };

      this.api = new RogueClient(window.location.origin, {
        headers: { Authorization: `Bearer ${window.AUTH}` },
      });
      this.updatePost = this.updatePost.bind(this);
      this.updateTag = this.updateTag.bind(this);
      this.updateQuantity = this.updateQuantity.bind(this);
      this.showHistory = this.showHistory.bind(this);
      this.hideHistory = this.hideHistory.bind(this);
      this.deletePost = this.deletePost.bind(this);
      this.setNewPosts = this.setNewPosts.bind(this);
      this.rotate = this.rotate.bind(this);
    }

    // Loads initial posts into state.
    componentDidMount() {
      // Require initial_posts and campaign parameters.
      if (data.initial_posts && data.campaign) {
        this.getPostsByStatus(data.initial_posts, data.campaign.id);
      } else {
        // @TODO - handle error better.
        console.log(
          'Error: need to know the initial posts to load and the campaign.',
        );
      }
    }

    // Make API call to GET api/v3/posts to get posts by filtered status.
    getPostsByStatus(status, campaignId) {
      this.api
        .getPosts({
          filter: {
            status: status,
            campaign_id: campaignId,
            type: 'photo,text',
          },
          include: ['signup', 'siblings'],
        })
        .then(json =>
          this.setState({
            campaign: data.campaign,
            posts: keyBy(json.data, 'id'),
            postIds: map(json.data, 'id'),
            signups: extractSignupsFromPosts(keyBy(json.data, 'id')),
            filter: status,
            displayHistoryModal: null,
            historyModalId: null,
            loading: false,
            nextPage: json.meta.cursor.next,
            prevPage: json.meta.cursor.prev,
          }),
        );
    }

    setNewPosts(apiResponse) {
      const posts = keyBy(apiResponse.data, 'id');
      this.setState({
        campaign: data.campaign,
        posts: posts,
        postIds: map(apiResponse.data, 'id'),
        signups: extractSignupsFromPosts(posts),
        displayHistoryModal: null,
        historyModalId: null,
        loading: false,
        nextPage: apiResponse.meta.cursor.next,
        prevPage: apiResponse.meta.cursor.prev,
      });
    }

    // Open the history modal of the given post
    showHistory(postId, event, signupId) {
      event.preventDefault();

      this.api
        .getEvents({
          filter: {
            signup_id: signupId,
          },
        })
        .then(result => {
          this.setState(previousState => {
            const newState = { ...previousState };

            newState.displayHistoryModal = true;
            newState.historyModalId = postId;
            newState.signupEvents = Object.values(result.data);
            return newState;
          });
        });
    }

    // Close the open history modal
    hideHistory(event) {
      if (event) {
        event.preventDefault();
      }

      this.setState({
        displayHistoryModal: false,
        historyModalId: null,
      });
    }

    // Updates a post status.
    updatePost(post, fields) {
      fields.post_id = post.id;

      let request = this.api.postReview(fields);

      return request.then(result => {
        this.setState(previousState => {
          const newState = { ...previousState };

          newState.posts[post.id].status = fields.status;

          return newState;
        });
      });
    }

    // Tag a post.
    updateTag(postId, tag) {
      const field = {
        tag_name: tag,
      };

      let response = this.api.post(`api/v3/posts/${postId}/tags`, field);

      return response.then(result => {
        this.setState(previousState => {
          const newState = { ...previousState };
          const user = newState.posts[postId].user;
          const signup = newState.posts[postId].signup.data;

          // Merge existing post with the newly updated values from API.
          newState.posts[postId] = {
            ...newState.posts[postId],
            ...result['data'],
          };

          return newState;
        });
      });
    }

    // Update a post's quantity.
    updateQuantity(post, newQuantity) {
      // Field to send to /api/v3/posts/:post_id
      const field = {
        quantity: parseInt(newQuantity),
      };

      // Make API request to Rogue to update the quantity on the backend
      let request = this.api.patch(`api/v3/posts/${post['id']}`, field);

      request.then(result => {
        // Update the state
        this.setState(previousState => {
          const newState = { ...previousState };
          newState.posts[post['id']].quantity = result.data['quantity'];

          return newState;
        });
      });

      // Close the modal
      this.hideHistory();
    }

    // Delete a post.
    deletePost(postId, event) {
      event.preventDefault();
      const confirmed = confirm(
        '🚨🔥🚨Are you sure you want to delete this?🚨🔥🚨',
      );

      if (confirmed) {
        // Make API request to Rogue to update the quantity on the backend
        let response = this.api.delete(`api/v3/posts/${postId}`);

        response.then((result) => {
          // Update the state
          this.setState(previousState => {
            var newState = { ...previousState };

            // Remove the deleted post from the state
            delete newState.posts[postId];

            // Remove the postId from the state.
            const postIdIndex = newState.postIds.indexOf(postId);

            if (postIdIndex > -1) {
              newState.postIds.splice(postIdIndex, 1);
            }

            // Return the new state
            return newState;
          });
        });
      }
    }

    // Rotate a Post Image.
    rotate(postId) {
      let response = this.api.post(`images/${postId}?rotate=90`);

      return response.then(json => {
        this.setState(prevState => {
          const newState = { ...prevState };
          // Add a cache-busting string to the end of the image url
          // so that it changes and triggers a re-render.
          newState.posts[postId].media.original_image_url =
            json.original_image_url + '?time=' + Date.now();

          return newState;
        });
      });
    }

    render() {
      const methods = {
        updatePost: this.updatePost,
        updateTag: this.updateTag,
        updateQuantity: this.updateQuantity,
        showHistory: this.showHistory,
        hideHistory: this.hideHistory,
        deletePost: this.deletePost,
        setNewPosts: this.setNewPosts,
        rotate: this.rotate,
      };

      // Pass in the state from this HoC to trigger rendering down the DOM
      // Also pass in methods bound to this instance.
      // Also pass in original data pass to the HoC in case other components still need it down the line.
      return <Component {...this.state} {...methods} {...data} />;
    }
  };
};

export default reviewComponent;
<|endoftext|>


<commit_before>/*
 *
 * Assignable 'hot-buttons' Plugin
 *
 * This adds a bar of 9 buttons that can be shift-click assigned whatever is in the textinput buffer, so you can simply
 * click the button again and have it execute those commands, instead of having to type it all out again and again.
 *
 * It stores these commands as server side options.
 *
 * NOTE:  This is a CONTRIB.  To use this in your game:
 *
 *     Stop Evennia
 *
 *     Copy this file to mygame/web/static_overrides/webclient/js/plugins/hotbuttons.js
 *     Copy evennia/web/webclient/templates/webclient/base.html to mygame/web/template_overrides/webclient/base.html
 *
 *     Edit  mygame/web/template_overrides/webclient/base.html to add:
 *
 *     after the other  plugin tags.
 *
 *     Run:  evennia collectstatic (say 'yes' to the overwrite prompt)
 *     Start Evennia
 */
plugin_handler.add('hotbuttons', (function () {
    var dependencies_met = true; // To start, assume either splithandler or goldenlayout plugin is enabled.

    var hotButtonConfig = {
        content: [{
            type: 'column',
            content: [{
                type: 'row',
                content: [{
                    type: 'column',
                    content: [{
                        type: 'component',
                        componentName: 'Main',
                        isClosable: false,
                        tooltip: 'Main - drag to desird position.',
                        componentState: {
                            types: 'untagged',
                            update_method: 'newlines',
                        },
                    }]
                }],
            }, {
                type: 'component',
                componentName: 'hotbuttons',
                id: 'inputComponent',
                height: 12,
                tooltip: 'Input - The last input in the layout is always the default.',
            }, {
                type: 'component',
                componentName: 'input',
                id: 'inputComponent',
                height: 12,
                tooltip: 'Input - The last input in the layout is always the default.',
            }, {
                type: 'component',
                componentName: 'input',
                id: 'inputComponent',
                height: 12,
                isClosable: false,
                tooltip: 'Input - The last input in the layout is always the default.',
            }]
        }]
    };

    var num_buttons = 9;
    var command_cache = new Array(num_buttons);
    var buttons = null;

    //
    // Add Buttons
    var addButtonsUI = function () {
        buttons = $( [
                '
',
                '
',
                '
',
                '   <button class="btn" id="assign_button0" type="button" value="button0">unassigned</button>',
                '   <button class="btn" id="assign_button1" type="button" value="button1">unassigned</button>',
                '   <button class="btn" id="assign_button2" type="button" value="button2">unassigned</button>',
                '   <button class="btn" id="assign_button3" type="button" value="button3">unassigned</button>',
                '   <button class="btn" id="assign_button4" type="button" value="button4">unassigned</button>',
                '   <button class="btn" id="assign_button5" type="button" value="button5">unassigned</button>',
                '   <button class="btn" id="assign_button6" type="button" value="button6">unassigned</button>',
                '   <button class="btn" id="assign_button7" type="button" value="button7">unassigned</button>',
                '   <button class="btn" id="assign_button8" type="button" value="button8">unassigned</button>',
                '
',
                '
',
                '
',
            ].join("\n") );

        // Are we using splithandler?
        if( plugins['splithandler'] ) {
            // Add buttons in front of the existing #inputform
            $('#input').prev().replaceWith(buttons);

            Split(['#main','#buttons','#input'], {
                sizes: [85,5,10],
                direction: 'vertical',
                gutterSize: 4,
                minSize: [150,20,50],
            });

            return true;
        }

        // Are we using GoldenLayout?
        if( plugins['goldenlayout'] ) {
            // update goldenlayout's global config
            plugins['goldenlayout'].setConfig( hotButtonConfig );

            // then wait for postInit() to create the required component
            return true;
        }

        // Neither so fail
        return false;
    }

    //
    // collect command text
    var assignButton = function(n, text) { // n is 1-based
        // make sure text has something in it
        if( text && text.length ) {
            // cache the command text
            command_cache[n] = text;

            // is there a space in the command, indicating "command argument" syntax?
            if( text.indexOf(" ") > 0 ) {
                // use the first word as the text on the button
                $("#assign_button"+n).text( text.slice(0, text.indexOf(" ")) );
            } else {
                // use the single-word-text on the button
                $("#assign_button"+n).text( text );
            }
        }
    }

    //
    // Shift click a button to clear it
    var clearButton = function(n) {
        // change button text to "unassigned"
        $("#assign_button"+n).text( "unassigned" );
        // clear current command
        command_cache[n] = "unassigned";
    }

    //
    // actually send the command associated with the button that is clicked
    var sendImmediate = function(n) {
        var text = command_cache[n];
        if( text.length ) {
            Evennia.msg("text", [text], {});
        }
    }

    //
    // send, assign, or clear the button
    var hotButtonClicked = function(e) {
        var button = $("#assign_button"+e.data);
        console.log("button " + e.data + " clicked");
        if( button.text() == "unassigned" ) {
            // Assign the button and send the full button state to the server using a Webclient_Options event
            assignButton( e.data, $('#inputfield').val() );
            Evennia.msg("webclient_options", [], { "HotButtons": command_cache });
        } else {
            if( e.shiftKey ) {
                // Clear the button and send the full button state to the server using a Webclient_Options event
                clearButton(e.data);
                Evennia.msg("webclient_options", [], { "HotButtons": command_cache });
            } else {
                sendImmediate(e.data);
            }
        }
    }

    // Public

    //
    // Handle the HotButtons part of a Webclient_Options event
    var onGotOptions = function(args, kwargs) {
        if( dependencies_met && kwargs['HotButtons'] ) {
            var button_options = kwargs['HotButtons'];
            $.each( button_options, function( key, value ) {
                assignButton(key, value);
            });
        }
    }

    //
    // Initialize me
    var init = function() {

        // Add buttons to the UI
        if( addButtonsUI() ) {
            // assign button cache
            for( var n=0; n<num_buttons; n++ ) {
                command_cache[n] = "unassigned";
                $("#assign_button"+n).click( n, hotButtonClicked );
            }
        } else {
            console.log("HotButtons Plugin Dependencies Not Met. No splithandler.js or goldenlayout.js plugin found.");
            dependencies_met = false;
        }
    }

    //
    //
    var postInit = function() {
        if( dependencies_met ) {
            var myLayout = plugins['goldenlayout'].getGL();

            myLayout.registerComponent( 'hotbuttons', function (container, componentState) {
                buttons.appendTo( container.getElement() );
            });

            console.log("HotButtons Plugin Initialized.");
        }
    }

    return {
        init: init,
        postInit: postInit,
        onGotOptions: onGotOptions,
    }
})());
<commit_msg>fix assigning commands to hotbuttons for golden-layout<commit_after>/*
 *
 * Assignable 'hot-buttons' Plugin
 *
 * This adds a bar of 9 buttons that can be shift-click assigned whatever is in the textinput buffer, so you can simply
 * click the button again and have it execute those commands, instead of having to type it all out again and again.
 *
 * It stores these commands as server side options.
 *
 * NOTE:  This is a CONTRIB.  To use this in your game:
 *
 *     Stop Evennia
 *
 *     Copy this file to mygame/web/static_overrides/webclient/js/plugins/hotbuttons.js
 *     Copy evennia/web/webclient/templates/webclient/base.html to mygame/web/template_overrides/webclient/base.html
 *
 *     Edit  mygame/web/template_overrides/webclient/base.html to add:
 *
 *     after the other  plugin tags.
 *
 *     Run:  evennia collectstatic (say 'yes' to the overwrite prompt)
 *     Start Evennia
 */
plugin_handler.add('hotbuttons', (function () {
    var dependencies_met = true; // To start, assume either splithandler or goldenlayout plugin is enabled.

    var num_buttons = 9;
    var command_cache = new Array;

    var hotButtonConfig = {
        content: [{
            type: 'column',
            content: [{
                type: 'row',
                content: [{
                    type: 'column',
                    content: [{
                        type: 'component',
                        componentName: 'Main',
                        isClosable: false,
                        tooltip: 'Main - drag to desird position.',
                        componentState: {
                            types: 'untagged',
                            update_method: 'newlines',
                        },
                    }]
                }],
            }, {
                type: 'component',
                componentName: 'hotbuttons',
                id: 'inputComponent',
                height: 12,
                tooltip: 'Input - The last input in the layout is always the default.',
            }, {
                type: 'component',
                componentName: 'input',
                id: 'inputComponent',
                height: 12,
                tooltip: 'Input - The last input in the layout is always the default.',
            }, {
                type: 'component',
                componentName: 'input',
                id: 'inputComponent',
                height: 12,
                isClosable: false,
                tooltip: 'Input - The last input in the layout is always the default.',
            }]
        }]
    };

    //
    // Add Buttons UI for SplitHandler
    var addButtonsUI = function () {
        var buttons = $( [
                '
',
                '
',
                '
',
                '   <button class="btn" id="assign_button0" type="button" value="button0">unassigned</button>',
                '   <button class="btn" id="assign_button1" type="button" value="button1">unassigned</button>',
                '   <button class="btn" id="assign_button2" type="button" value="button2">unassigned</button>',
                '   <button class="btn" id="assign_button3" type="button" value="button3">unassigned</button>',
                '   <button class="btn" id="assign_button4" type="button" value="button4">unassigned</button>',
                '   <button class="btn" id="assign_button5" type="button" value="button5">unassigned</button>',
                '   <button class="btn" id="assign_button6" type="button" value="button6">unassigned</button>',
                '   <button class="btn" id="assign_button7" type="button" value="button7">unassigned</button>',
                '   <button class="btn" id="assign_button8" type="button" value="button8">unassigned</button>',
                '
',
                '
',
                '
',
            ].join("\n") );

        // Add buttons in front of the existing #inputform
        $('#input').prev().replaceWith(buttons);

        Split(['#main','#buttons','#input'], {
            sizes: [85,5,10],
            direction: 'vertical',
            gutterSize: 4,
            minSize: [150,20,50],
        });

        for( var n=0; n<num_buttons; n++ ) {
            command_cache.push("unassigned");
            $("#assign_button"+n).click( n, hotButtonClicked );
        }
    }

    //
    // collect command text
    var assignButton = function(n, text) { // n is 1-based
        // make sure text has something in it
        if( text && text.length ) {
            // cache the command text
            command_cache[n] = text;

            // is there a space in the command, indicating "command argument" syntax?
            if( text.indexOf(" ") > 0 ) {
                // use the first word as the text on the button
                $("#assign_button"+n).text( text.slice(0, text.indexOf(" ")) );
            } else {
                // use the single-word-text on the button
                $("#assign_button"+n).text( text );
            }
        }
    }

    //
    // Shift click a button to clear it
    var clearButton = function(n) {
        // change button text to "unassigned"
        $("#assign_button"+n).text( "unassigned" );
        // clear current command
        command_cache[n] = "unassigned";
    }

    //
    // actually send the command associated with the button that is clicked
    var sendImmediate = function(n) {
        var text = command_cache[n];
        if( text.length ) {
            Evennia.msg("text", [text], {});
        }
    }

    //
    // send, assign, or clear the button
    var hotButtonClicked = function(e) {
        var button = $("#assign_button"+e.data);
        console.log("button " + e.data + " clicked");
        if( button.text() == "unassigned" ) {
            // Assign the button and send the full button state to the server using a Webclient_Options event
            var input = $('.inputfield:last');
            if( input.length < 1 ) {
                input = $('#inputfield');
            }
            assignButton( e.data, input.val() );
            Evennia.msg("webclient_options", [], { "HotButtons": command_cache });
        } else {
            if( e.shiftKey ) {
                // Clear the button and send the full button state to the server using a Webclient_Options event
                clearButton(e.data);
                Evennia.msg("webclient_options", [], { "HotButtons": command_cache });
            } else {
                sendImmediate(e.data);
            }
        }
    }

    //
    // Create and register the hotbuttons golden-layout component
    var buildComponent = function () {
        var myLayout = plugins['goldenlayout'].getGL();

        myLayout.registerComponent( 'hotbuttons', function (container, componentState) {
            console.log('hotbuttons');

            // build the buttons
            var div = $('
');

            var len = command_cache.length;
            for( var x=len; x < len + num_buttons; x++ ) {
                command_cache.push("unassigned");

                // initialize button command cache and onClick handler
                button = $('<button class="btn" id="assign_button'+x+'" type="button" value="button'+x+'">');
                button.html("unassigned");
                button.click( x, hotButtonClicked );

                button.appendTo( div );
            }

            div.appendTo( container.getElement() );
        });
    }

    // Public

    //
    // Handle the HotButtons part of a Webclient_Options event
    var onGotOptions = function(args, kwargs) {
        if( dependencies_met && kwargs['HotButtons'] ) {
            var button_options = kwargs['HotButtons'];
            $.each( button_options, function( key, value ) {
                assignButton(key, value);
            });
        }
    }

    //
    // Initialize me
    var init = function() {
        // Are we using GoldenLayout?
        if( plugins['goldenlayout'] ) {
            // update goldenlayout's global config
            plugins['goldenlayout'].setConfig( hotButtonConfig );
            // wait for postInit() to create the required component
            dependencies_met = true;
        }

        // Are we using splithandler?
        if( plugins['splithandler'] ) {
            addButtonsUI();
            dependencies_met = true;
        }
    }

    //
    //
    var postInit = function() {
        if( dependencies_met ) {
            if( plugins['goldenlayout'] ) {
                buildComponent();
            }

            console.log("HotButtons Plugin Initialized.");
        } else {
            console.log("HotButtons Plugin Dependencies Not Met. No splithandler.js or goldenlayout.js plugin found.");
        }
    }

    return {
        init: init,
        postInit: postInit,
        onGotOptions: onGotOptions,
    }
})());
<|endoftext|>


<commit_before>define(['marionette', 'views/form',
    'collections/visits',
    'collections/labcontacts',
    'modules/shipment/collections/dewarhistory',

    'modules/shipment/models/dispatch',

    'templates/shipment/dispatch.html',
    'jquery',
    'backbone',
    'backbone-validation',

    ], function(Marionette, FormView,
        Visits, LabContacts, DewarHistory,
        DispatchModel,
        template, $_, Backbone) {

    var VVisits = Visits.extend({
        valueAttribute: 'VISIT',
    })

    return FormView.extend({
        template: template,

        events: {
            'change @ui.lc': 'getlcdetails',
            'change @ui.exp': 'updateLC',
            'click @ui.useAnotherCourierAccount': 'toggleCourierAccountEditing'
        },

        ui: {
            lc: 'select[name=LABCONTACTID]',

            exp: 'select[name=VISIT]',
            lco: 'input[name=LOCALCONTACT]',
            loc: 'input[name=LOCATION]',

            gn: 'input[name=GIVENNAME]',
            fn: 'input[name=FAMILYNAME]',
            addr: 'textarea[name=ADDRESS]',
            em: 'input[name=EMAILADDRESS]',
            ph: 'input[name=PHONENUMBER]',
            lab: 'input[name=LABNAME]',

            accountNumber: 'input[NAME=DELIVERYAGENT_AGENTCODE]',
            courier: 'input[name=DELIVERYAGENT_AGENTNAME]',
            useAnotherCourierAccount: 'input[name=USE_ANOTHER_COURIER_ACCOUNT]',
            dispatchState: '.dispatch-state'
        },

        templateHelpers: function() {
            return {
                DEWAR: this.getOption('dewar').toJSON(),
                SHIPPING: this.getOption('shipping').toJSON()
            }
        },

        createModel: function() {
            this.model = new DispatchModel({
                FACILITYCODE: this.getOption('dewar').get('FACILITYCODE'),
                DEWARID: this.getOption('dewar').get('DEWARID'),
                LABCONTACTID: this.getOption('dewar').get('LABCONTACTID'),
                VISIT: this.getOption('dewar').get('FIRSTEXPERIMENT'),
                // If no agent specified on inbound, default to diamond dhl
                DELIVERYAGENT_AGENTNAME: this.getOption('shipping').get('DELIVERYAGENT_AGENTNAME') || 'DHL'
            })
        },

        success: function(model, response, options) {
            console.log('success from dispatch req')
            app.trigger('shipment:show', this.getOption('dewar').get('SHIPPINGID'))
        },

        failure: function(model, response, options) {
            console.log('failure from dispatch req')
            app.alert({ message: 'Something went wrong registering this dispatch request, please try again'})
        },

        onRender: function() {
            this.date('input[name=DELIVERYAGENT_SHIPPINGDATE]')

            var d = new Date()
            var today = (d.getDate() < 10 ? '0'+d.getDate() : d.getDate()) + '-' + (d.getMonth() < 9 ? '0'+(d.getMonth()+1) : d.getMonth()+1) + '-' + d.getFullYear()
            this.$el.find('input[name=DELIVERYAGENT_SHIPPINGDATE]').val(today)

            var self = this
            this.ready.done(function() {
                self.ui.exp.html(self.visits.opts()).val(self.model.get('VISIT'))
                self.updateLC()
            })

            if (this.shipping.get('DELIVERYAGENT_AGENTCODE')) {
                this.ui.courier.val(this.shipping.get('DELIVERYAGENT_AGENTNAME'))
                this.ui.accountNumber.val(this.shipping.get('DELIVERYAGENT_AGENTCODE'))
                this.ui.courier.attr('disabled', true)
                this.ui.accountNumber.attr('disabled', true)
                this.model.shipmentHasAgentCode = true
            }
        },

        initialize: function(options) {
            this.dewar = options.dewar
            this.contacts = new LabContacts(null, { state: { pageSize: 9999 } })
            this.listenTo(this.contacts, 'sync', this.updateContacts)
            this.refreshContacts()

            var self = this
            this.visits = new VVisits(null, { state: { pageSize: 9999 } })
            this.ready = this.visits.fetch()

            this.history = new DewarHistory(null, { queryParams: { did: this.getOption('dewar').get('DEWARID') }})
            this.history.fetch().done(function() {
                const history = self.history.at(0)
                console.log({ history })
                const location = history ? history.get('STORAGELOCATION') : null
                const historyComment = history ? history.get('COMMENTS') : null
                const restrictedLocations = ['i03', 'i04', 'i04-1', 'i024']

                if (location) {
                    self.ui.loc.val(location)
                    if (restrictedLocations.includes(location.toLowerCase())) {
                        self.ui.dispatchState.text("Warning: This dewar is still on the beamline. We recommend waiting until the dewar returns to storage before requesting it's return. Dewars are not topped up with LN2 after a return is requested.")
                    } else if (
                        location.startsWith('tray-') &&
                        (!historyComment || (typeof historyComment === 'object' && !historyComment.checked))
                    ) {
                        self.ui.dispatchState.text("Warning: This dewar has not had it's contents checked. We recommend asking your local contact to check the dewar's contents before requesting it's return. Dewars are not topped up with LN2 after a return is requested.")
                    } else {
                        self.ui.dispatchState.text("Please note, dewars are not topped up with LN2 after a return is requested.")
                    }
                }
            })
            // Shipping option should be a backbone model
            this.shipping = options.shipping
        },

        updateLC: function() {
            var vis = this.visits.findWhere({ VISIT: this.ui.exp.val() })
            if (vis) {
                var lc = vis.get('LC')
                if (lc) {
                    var lcs = lc.split(',')
                    this.ui.lco.val(lcs[0].trim())
                } else this.ui.lco.val('')
            }

        },

        refreshContacts: function() {
            this.contacts.fetch()
        },

        updateContacts: function() {
            this.ui.lc.html(this.contacts.opts()).val(this.getOption('dewar').get('RETURNLABCONTACTID'))
            this.getlcdetails()
        },

        getlcdetails: function() {
            var lc = this.contacts.findWhere({ LABCONTACTID: this.ui.lc.val() })
            if (lc) {
                this.ui.gn.val(lc.get('GIVENNAME'))
                this.ui.fn.val(lc.get('FAMILYNAME'))
                this.ui.em.val(lc.get('EMAILADDRESS'))
                this.ui.ph.val(lc.get('PHONENUMBER'))
                this.ui.addr.val([lc.get('ADDRESS'),lc.get('CITY'),lc.get('POSTCODE'),lc.get('COUNTRY')].join("\n"))
                this.ui.lab.val(lc.get('LABNAME'))
            }
        },

        toggleCourierAccountEditing: function(event) {
            if (event.target.checked) {
                this.ui.courier.attr('disabled', false)
                this.ui.accountNumber.attr('disabled', false)
            } else {
                this.ui.courier.val(this.shipping.get('DELIVERYAGENT_AGENTNAME'))
                this.ui.accountNumber.val(this.shipping.get('DELIVERYAGENT_AGENTCODE'))

                this.ui.courier.attr('disabled', true)
                this.ui.accountNumber.attr('disabled', true)
            }
        }
    })

})
<commit_msg>fix: set default state for dewars with no history<commit_after>define(['marionette', 'views/form',
    'collections/visits',
    'collections/labcontacts',
    'modules/shipment/collections/dewarhistory',

    'modules/shipment/models/dispatch',

    'templates/shipment/dispatch.html',
    'jquery',
    'backbone',
    'backbone-validation',

    ], function(Marionette, FormView,
        Visits, LabContacts, DewarHistory,
        DispatchModel,
        template, $_, Backbone) {

    var VVisits = Visits.extend({
        valueAttribute: 'VISIT',
    })

    return FormView.extend({
        template: template,

        events: {
            'change @ui.lc': 'getlcdetails',
            'change @ui.exp': 'updateLC',
            'click @ui.useAnotherCourierAccount': 'toggleCourierAccountEditing'
        },

        ui: {
            lc: 'select[name=LABCONTACTID]',

            exp: 'select[name=VISIT]',
            lco: 'input[name=LOCALCONTACT]',
            loc: 'input[name=LOCATION]',

            gn: 'input[name=GIVENNAME]',
            fn: 'input[name=FAMILYNAME]',
            addr: 'textarea[name=ADDRESS]',
            em: 'input[name=EMAILADDRESS]',
            ph: 'input[name=PHONENUMBER]',
            lab: 'input[name=LABNAME]',

            accountNumber: 'input[NAME=DELIVERYAGENT_AGENTCODE]',
            courier: 'input[name=DELIVERYAGENT_AGENTNAME]',
            useAnotherCourierAccount: 'input[name=USE_ANOTHER_COURIER_ACCOUNT]',
            dispatchState: '.dispatch-state'
        },

        templateHelpers: function() {
            return {
                DEWAR: this.getOption('dewar').toJSON(),
                SHIPPING: this.getOption('shipping').toJSON()
            }
        },

        createModel: function() {
            this.model = new DispatchModel({
                FACILITYCODE: this.getOption('dewar').get('FACILITYCODE'),
                DEWARID: this.getOption('dewar').get('DEWARID'),
                LABCONTACTID: this.getOption('dewar').get('LABCONTACTID'),
                VISIT: this.getOption('dewar').get('FIRSTEXPERIMENT'),
                // If no agent specified on inbound, default to diamond dhl
                DELIVERYAGENT_AGENTNAME: this.getOption('shipping').get('DELIVERYAGENT_AGENTNAME') || 'DHL'
            })
        },

        success: function(model, response, options) {
            console.log('success from dispatch req')
            app.trigger('shipment:show', this.getOption('dewar').get('SHIPPINGID'))
        },

        failure: function(model, response, options) {
            console.log('failure from dispatch req')
            app.alert({ message: 'Something went wrong registering this dispatch request, please try again'})
        },

        onRender: function() {
            this.date('input[name=DELIVERYAGENT_SHIPPINGDATE]')

            var d = new Date()
            var today = (d.getDate() < 10 ? '0'+d.getDate() : d.getDate()) + '-' + (d.getMonth() < 9 ? '0'+(d.getMonth()+1) : d.getMonth()+1) + '-' + d.getFullYear()
            this.$el.find('input[name=DELIVERYAGENT_SHIPPINGDATE]').val(today)

            var self = this
            this.ready.done(function() {
                self.ui.exp.html(self.visits.opts()).val(self.model.get('VISIT'))
                self.updateLC()
            })

            if (this.shipping.get('DELIVERYAGENT_AGENTCODE')) {
                this.ui.courier.val(this.shipping.get('DELIVERYAGENT_AGENTNAME'))
                this.ui.accountNumber.val(this.shipping.get('DELIVERYAGENT_AGENTCODE'))
                this.ui.courier.attr('disabled', true)
                this.ui.accountNumber.attr('disabled', true)
                this.model.shipmentHasAgentCode = true
            }
        },

        initialize: function(options) {
            this.dewar = options.dewar
            this.contacts = new LabContacts(null, { state: { pageSize: 9999 } })
            this.listenTo(this.contacts, 'sync', this.updateContacts)
            this.refreshContacts()

            var self = this
            this.visits = new VVisits(null, { state: { pageSize: 9999 } })
            this.ready = this.visits.fetch()

            this.history = new DewarHistory(null, { queryParams: { did: this.getOption('dewar').get('DEWARID') }})
            this.history.fetch().done(function() {
                const history = self.history.at(0)
                console.log({ history })
                const location = history ? history.get('STORAGELOCATION') : null
                const historyComment = history ? history.get('COMMENTS') : null
                const restrictedLocations = ['i03', 'i04', 'i04-1', 'i024']

                if (location) {
                    self.ui.loc.val(location)
                    if (restrictedLocations.includes(location.toLowerCase())) {
                        self.ui.dispatchState.text("Warning: This dewar is still on the beamline. We recommend waiting until the dewar returns to storage before requesting it's return. Dewars are not topped up with LN2 after a return is requested.")
                    } else if (
                        location.startsWith('tray-') &&
                        (!historyComment || (typeof historyComment === 'object' && !historyComment.checked))
                    ) {
                        self.ui.dispatchState.text("Warning: This dewar has not had it's contents checked. We recommend asking your local contact to check the dewar's contents before requesting it's return. Dewars are not topped up with LN2 after a return is requested.")
                    } else {
                        self.ui.dispatchState.text("Please note, dewars are not topped up with LN2 after a return is requested.")
                    }
                } else {
                    self.ui.dispatchState.text("Please note, dewars are not topped up with LN2 after a return is requested.")
                }
            })
            // Shipping option should be a backbone model
            this.shipping = options.shipping
        },

        updateLC: function() {
            var vis = this.visits.findWhere({ VISIT: this.ui.exp.val() })
            if (vis) {
                var lc = vis.get('LC')
                if (lc) {
                    var lcs = lc.split(',')
                    this.ui.lco.val(lcs[0].trim())
                } else this.ui.lco.val('')
            }

        },

        refreshContacts: function() {
            this.contacts.fetch()
        },

        updateContacts: function() {
            this.ui.lc.html(this.contacts.opts()).val(this.getOption('dewar').get('RETURNLABCONTACTID'))
            this.getlcdetails()
        },

        getlcdetails: function() {
            var lc = this.contacts.findWhere({ LABCONTACTID: this.ui.lc.val() })
            if (lc) {
                this.ui.gn.val(lc.get('GIVENNAME'))
                this.ui.fn.val(lc.get('FAMILYNAME'))
                this.ui.em.val(lc.get('EMAILADDRESS'))
                this.ui.ph.val(lc.get('PHONENUMBER'))
                this.ui.addr.val([lc.get('ADDRESS'),lc.get('CITY'),lc.get('POSTCODE'),lc.get('COUNTRY')].join("\n"))
                this.ui.lab.val(lc.get('LABNAME'))
            }
        },

        toggleCourierAccountEditing: function(event) {
            if (event.target.checked) {
                this.ui.courier.attr('disabled', false)
                this.ui.accountNumber.attr('disabled', false)
            } else {
                this.ui.courier.val(this.shipping.get('DELIVERYAGENT_AGENTNAME'))
                this.ui.accountNumber.val(this.shipping.get('DELIVERYAGENT_AGENTCODE'))

                this.ui.courier.attr('disabled', true)
                this.ui.accountNumber.attr('disabled', true)
            }
        }
    })

})
<|endoftext|>


<commit_before>var Campfire = Class.create(Widget, {
    initialize: function($super, widget_id, config) {
	this.messages = [];
	return($super(widget_id, config));
    },
    receive: function(payload) {
	console.log("Received some payload: " + payload);
	if(this.messages.length >= this.config.nitems) {
	    this.messages.shift();
	}
	this.messages.push(payload);
	this.update();
    },
    update: function() {
    new Draggable($(this.container));
	this.container.childElements().invoke('remove');
	this.container.appendChild(this.buildWidgetIcon());
	this.container.appendChild(this.buildHeader());
	this.messages.reverse(false).each(function(message) {
					      var cont = new Element('p');
					      cont.appendChild(new Element('img', { src: message.avatar, width: 48, height: 48 }));
					      cont.appendChild(new Element('a', { href: '#', className: 'author' }).update(message.user));
					      cont.appendChild(document.createTextNode(message.body));
					      cont.appendChild(new Element('hr' ));
					      this.container.appendChild(cont);
					  }.bind(this));
    },

    buildHeader: function() {
	return(new Element("h2").update(this.title));
    },

    buildWidgetIcon: function() {
	return(new Element("img", {src: "images/campfire.png", width: 32, height: 32, className: 'campfire icon'}));
    }
});<commit_msg>Don't create a link for the user<commit_after>var Campfire = Class.create(Widget, {
  initialize: function($super, widget_id, config) {
    this.messages = [];
    return($super(widget_id, config));
  },
  receive: function(payload) {
    if(this.messages.length >= this.config.nitems) {
      this.messages.shift();
    }
    this.messages.push(payload);
    this.update();
  },
  update: function() {
    new Draggable($(this.container));
    this.container.childElements().invoke('remove');
    this.container.appendChild(this.buildWidgetIcon());
    this.container.appendChild(this.buildHeader());
    this.messages.reverse(false).each(function(message) {
      var cont = new Element('p');
      cont.appendChild(new Element('img', { src: message.avatar, width: 48, height: 48 }));
      cont.appendChild(new Element('div', { className: 'author' }).update(message.user));
      cont.appendChild(document.createTextNode(message.body));
      cont.appendChild(new Element('hr' ));
      this.container.appendChild(cont);
    }.bind(this));
  },

  buildHeader: function() {
    return(new Element("h2").update(this.title));
  },

  buildWidgetIcon: function() {
    return(new Element("img", {src: "images/campfire.png", width: 32, height: 32, className: 'campfire icon'}));
  }
});
<|endoftext|>


<commit_before>$(document).ready(function() {
    $.ajax({
        url         : '/api/schedule',
        method      : 'GET',
        dataType    : 'json',
        cache       : false,
        data        : {
            limit: Math.round($(document).height() / 173),
            after: "11:00"
        },
        error : function(xhr, options, error) {
            console.log(xhr);
            console.log(options);
            console.log(error);
        },
        success : function(data) {
            displaySchedule(data);
        }
    });
});

/**
 * Generates and displays html for schedule
 * @param  {array} schedule array of games returned from api
 * @return {void}
 * @TODO Change how icon is displayed. For the moment the same icon is displayed for all sports!
 *
 * @author Doran Kayoumi
 */
function displaySchedule(schedule) {

    var container = $('.schedule');

    // loop through schedule
    for (let game of schedule) {

        // generate html and added immediately to container
        container.append(`

${game.time}

A

${game.teams[0]}

${game.teams[1]}

        `);
    }
}
<commit_msg>Reduce by one limit number of matches displayed<commit_after>$(document).ready(function() {
    $.ajax({
        url         : '/api/schedule',
        method      : 'GET',
        dataType    : 'json',
        cache       : false,
        data        : {
            limit: Math.round($(document).height() / 173) - 1,
            after: "11:00"
        },
        error : function(xhr, options, error) {
            console.log(xhr);
            console.log(options);
            console.log(error);
        },
        success : function(data) {
            displaySchedule(data);
        }
    });
});

/**
 * Generates and displays html for schedule
 * @param  {array} schedule array of games returned from api
 * @return {void}
 * @TODO Change how icon is displayed. For the moment the same icon is displayed for all sports!
 *
 * @author Doran Kayoumi
 */
function displaySchedule(schedule) {

    var container = $('.schedule');

    // loop through schedule
    for (let game of schedule) {

        // generate html and added immediately to container
        container.append(`

${game.time}

A

${game.teams[0]}

${game.teams[1]}

        `);
    }
}
<|endoftext|>


<commit_before>$(function () {
    var thisCount = $("#count").text();
    var countsLeft = parseInt($("#countsLeft").text());
    var theFileName = ('athousandcounts' + thisCount).toString();

    $("#webcam").scriptcam({
        width: 520,
        height: 360,
        path: '/ScriptCam/',
        fileReady: fileReady,
        cornerRadius: 20,
        cornerColor: 'e3e5e2',
        onError: onError,
        showMicrophoneErrors: true,
        useMicrophone: true,
        timeLeft: timeLeft,
        fileName: theFileName,
        connected: showRecord,
        maximumTime: 10
    });
    jQuery.fn.extend({
        animateCount: function (from, to, time) {
            var steps = 1,
                self = this,
                counter;

            if (to - from > 0) {
                steps = -1;
            };

            to -= steps;

            function step() {
                self.text(to += steps);

                if (to === 4) {
                    self.text('COUNT ' + thisCount + '!');
                }

                if ((steps < 0 && from >= to) || (steps > 0 && to >= from)) {
                    clearInterval(counter);
                };

                if (to === 0) {
                    self.text('COUNT!');
                }

            };

            counter = setInterval(step, time || 100);
        }
    });

});
function startRecordingWithCounter(callback) {
    $('#popup').show();
    $('#popupText').animateCount(0, 4, 1000);
    setTimeout(callback, 5200);
}
function showRecord() {
    $("#recordStartButton").attr("disabled", false);
}
function startRecording() {
    $('#popup').hide();
    $("#recordStartButton").attr("disabled", true);
    $("#recordStopButton").attr("disabled", false);
    $("#recordPauseResumeButton").attr("disabled", false);
    $.scriptcam.startRecording();
}
function closeCamera() {
    $("#slider").slider("option", "disabled", true);
    $("#recordPauseResumeButton").attr("disabled", true);
    $("#recordStopButton").attr("disabled", true);
    $.scriptcam.closeCamera();
    setMessage();
}
function fileReady(fileName) {
    $('#recorder').hide();
    $('#message').fadeOut();
    $('#finalMessage').html('Thank you for participating at A Thousand Counts. Your clip will be processed into a video once we have received the last ' + countsLeft + ' counts.

If you know other happy counters like you please invite them!');
    var fileNameNoExtension = fileName.replace(".mp4", "");
    completeCount();
}
function onError(errorId, errorMsg) {
    $('#message').html('Please wait for the file conversion to finish...');
}

function timeLeft(value) {
    $('#timeLeft').val(value);
}

function setMessage() {
    $('#message').html('Please wait for the file conversion to finish...');
}

function completeCount() {
    var id = $("#count").text();
    $.post('/Count/CompleteCount/' + id, null);
}
<commit_msg>Possible solution to counts left problem<commit_after>$(function () {
    var thisCount = $("#count").text();
    var countsLeft = $("#countsLeft").text().toString();
    var theFileName = ('athousandcounts' + thisCount).toString();

    $("#webcam").scriptcam({
        width: 520,
        height: 360,
        path: '/ScriptCam/',
        fileReady: fileReady,
        cornerRadius: 20,
        cornerColor: 'e3e5e2',
        onError: onError,
        showMicrophoneErrors: true,
        useMicrophone: true,
        timeLeft: timeLeft,
        fileName: theFileName,
        connected: showRecord,
        maximumTime: 10
    });
    jQuery.fn.extend({
        animateCount: function (from, to, time) {
            var steps = 1,
                self = this,
                counter;

            if (to - from > 0) {
                steps = -1;
            };

            to -= steps;

            function step() {
                self.text(to += steps);

                if (to === 4) {
                    self.text('COUNT ' + thisCount + '!');
                }

                if ((steps < 0 && from >= to) || (steps > 0 && to >= from)) {
                    clearInterval(counter);
                };

                if (to === 0) {
                    self.text('COUNT!');
                }

            };

            counter = setInterval(step, time || 100);
        }
    });

});
function startRecordingWithCounter(callback) {
    $('#popup').show();
    $('#popupText').animateCount(0, 4, 1000);
    setTimeout(callback, 5200);
}
function showRecord() {
    $("#recordStartButton").attr("disabled", false);
}
function startRecording() {
    $('#popup').hide();
    $("#recordStartButton").attr("disabled", true);
    $("#recordStopButton").attr("disabled", false);
    $("#recordPauseResumeButton").attr("disabled", false);
    $.scriptcam.startRecording();
}
function closeCamera() {
    $("#slider").slider("option", "disabled", true);
    $("#recordPauseResumeButton").attr("disabled", true);
    $("#recordStopButton").attr("disabled", true);
    $.scriptcam.closeCamera();
    setMessage();
}
function fileReady(fileName) {
    $('#recorder').hide();
    $('#message').fadeOut();
    var finalMessage = 'Thank you for participating at A Thousand Counts. Your clip will be processed into a video once we have received the last ' + countsLeft + ' counts.

If you know other happy counters like you please invite them!';
    $('#finalMessage').text(finalMessage);
    var fileNameNoExtension = fileName.replace(".mp4", "");
    completeCount();
}
function onError(errorId, errorMsg) {
    $('#message').html('Please wait for the file conversion to finish...');
}

function timeLeft(value) {
    $('#timeLeft').val(value);
}

function setMessage() {
    $('#message').html('Please wait for the file conversion to finish...');
}

function completeCount() {
    var id = $("#count").text();
    $.post('/Count/CompleteCount/' + id, null);
}
<|endoftext|>


<commit_before>angular.module('MyApp', ['ngResource', 'ngMessages', 'ngAnimate', 'toastr',
    'ui.router', 'satellizer', 'ui.select', 'ngSanitize', 'ui.bootstrap', 'ngImageInputWithPreview'])
    .config(function ($stateProvider, $urlRouterProvider, $authProvider, $locationProvider) {

        /**
         * Helper auth functions
         */
        var skipIfLoggedIn = ['$q', '$auth', function ($q, $auth) {
            var deferred = $q.defer();
            if ($auth.isAuthenticated()) {
                deferred.reject();
            } else {
                deferred.resolve();
            }
            return deferred.promise;
        }];

        var loginRequired = ['$q', '$location', '$auth', function ($q, $location, $auth) {
            var deferred = $q.defer();
            if ($auth.isAuthenticated()) {
                deferred.resolve();
            } else {
                $location.path('/login');
            }
            return deferred.promise;
        }];

        /**
         * App routes
         */
        $stateProvider
            .state('home', {
                url: '/',
                controller: 'HomeCtrl',
                templateUrl: 'client/partials/home.html',
                controllerAs: 'vm'
            })
            .state('login', {
                url: '/login',
                templateUrl: '/client/partials/login.html',
                controller: 'LoginCtrl',
                resolve: {
                    skipIfLoggedIn: skipIfLoggedIn
                }
            }).state('setting', {
                url: '/setting',
                templateUrl: '/client/partials/setting.html',
                controller: 'SettingCtrl',
                abstract: true,
            }).state('setting.font', {
                url: '/font',
                templateUrl: '/client/partials/font.html',
            }).state('setting.color', {
                url: '',
                templateUrl: '/client/partials/color.html',
            })
            .state('signup', {
                url: '/signup',
                templateUrl: '/client/partials/signup.html',
                controller: 'SignupCtrl',
                resolve: {
                    skipIfLoggedIn: skipIfLoggedIn
                }
            })
            .state('logout', {
                url: '/logout',
                template: null,
                controller: 'LogoutCtrl'
            })
            .state('profile', {
                url: '/profile',
                templateUrl: '/client/partials/profile.html',
                controller: 'ProfileCtrl',
                resolve: {
                    loginRequired: loginRequired
                }
            });
        $urlRouterProvider.otherwise('/');
        // use the HTML5 History API
        //$locationProvider.html5Mode(true);

        /**
         *  Satellizer config
         */
        $authProvider.facebook({
            /*clientId: '603122136500203'*/
            clientId: '278082065966761',
            url: 'auth/facebook'

        });

        $authProvider.google({
            clientId: 'YOUR_GOOGLE_CLIENT_ID'
        });

        $authProvider.github({
            clientId: 'YOUR_GITHUB_CLIENT_ID'
        });

        $authProvider.linkedin({
            clientId: 'YOUR_LINKEDIN_CLIENT_ID'
        });

        $authProvider.instagram({
            clientId: 'YOUR_INSTAGRAM_CLIENT_ID'
        });

        $authProvider.yahoo({
            clientId: 'YOUR_YAHOO_CLIENT_ID'
        });

        $authProvider.live({
            clientId: 'YOUR_MICROSOFT_CLIENT_ID'
        });

        $authProvider.twitch({
            clientId: 'YOUR_TWITCH_CLIENT_ID'
        });

        $authProvider.bitbucket({
            clientId: 'YOUR_BITBUCKET_CLIENT_ID'
        });

        $authProvider.spotify({
            clientId: 'YOUR_SPOTIFY_CLIENT_ID'
        });

        $authProvider.twitter({
            url: '/auth/twitter'
            //url: 'http://localhost:3000/auth/twitter'
        });
        $authProvider.dribble({
            //url: '/auth/dribble/api/v2/connections',
            clientId: 'cafe9492c5296869dff75f1a89cc452c1dd085712b9a47fb303d6f9305be35c2',
            url: 'http://localhost:3000/auth/dribble/callback',
            redirectUri: 'http://localhost:3000'// window.location.origin || window.location.protocol + '//' + window.location.host,
            //authorizationEndpoint: 'https://dribbble.com/oauth/authorize'
        });

        $authProvider.oauth2({
            name: 'foursquare',
            url: '/auth/foursquare',
            clientId: 'MTCEJ3NGW2PNNB31WOSBFDSAD4MTHYVAZ1UKIULXZ2CVFC2K',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            authorizationEndpoint: 'https://foursquare.com/oauth2/authenticate'
        });
    }).run(function ($rootScope, $window, $auth) {
        if ($auth.isAuthenticated()) {
            $rootScope.currentUser = JSON.parse($window.localStorage.currentUser);
        }
    });
<commit_msg>Commented the run in app.js<commit_after>angular.module('MyApp', ['ngResource', 'ngMessages', 'ngAnimate', 'toastr',
    'ui.router', 'satellizer', 'ui.select', 'ngSanitize', 'ui.bootstrap', 'ngImageInputWithPreview'])
    .config(function ($stateProvider, $urlRouterProvider, $authProvider, $locationProvider) {

        /**
         * Helper auth functions
         */
        var skipIfLoggedIn = ['$q', '$auth', function ($q, $auth) {
            var deferred = $q.defer();
            if ($auth.isAuthenticated()) {
                deferred.reject();
            } else {
                deferred.resolve();
            }
            return deferred.promise;
        }];

        var loginRequired = ['$q', '$location', '$auth', function ($q, $location, $auth) {
            var deferred = $q.defer();
            if ($auth.isAuthenticated()) {
                deferred.resolve();
            } else {
                $location.path('/login');
            }
            return deferred.promise;
        }];

        /**
         * App routes
         */
        $stateProvider
            .state('home', {
                url: '/',
                controller: 'HomeCtrl',
                templateUrl: 'client/partials/home.html',
                controllerAs: 'vm'
            })
            .state('login', {
                url: '/login',
                templateUrl: '/client/partials/login.html',
                controller: 'LoginCtrl',
                resolve: {
                    skipIfLoggedIn: skipIfLoggedIn
                }
            }).state('setting', {
                url: '/setting',
                templateUrl: '/client/partials/setting.html',
                controller: 'SettingCtrl',
                abstract: true,
            }).state('setting.font', {
                url: '/font',
                templateUrl: '/client/partials/font.html',
            }).state('setting.color', {
                url: '',
                templateUrl: '/client/partials/color.html',
            })
            .state('signup', {
                url: '/signup',
                templateUrl: '/client/partials/signup.html',
                controller: 'SignupCtrl',
                resolve: {
                    skipIfLoggedIn: skipIfLoggedIn
                }
            })
            .state('logout', {
                url: '/logout',
                template: null,
                controller: 'LogoutCtrl'
            })
            .state('profile', {
                url: '/profile',
                templateUrl: '/client/partials/profile.html',
                controller: 'ProfileCtrl',
                resolve: {
                    loginRequired: loginRequired
                }
            });
        $urlRouterProvider.otherwise('/');
        // use the HTML5 History API
        //$locationProvider.html5Mode(true);

        /**
         *  Satellizer config
         */
        $authProvider.facebook({
            /*clientId: '603122136500203'*/
            clientId: '278082065966761',
            url: 'auth/facebook'

        });

        $authProvider.google({
            clientId: 'YOUR_GOOGLE_CLIENT_ID'
        });

        $authProvider.github({
            clientId: 'YOUR_GITHUB_CLIENT_ID'
        });

        $authProvider.linkedin({
            clientId: 'YOUR_LINKEDIN_CLIENT_ID'
        });

        $authProvider.instagram({
            clientId: 'YOUR_INSTAGRAM_CLIENT_ID'
        });

        $authProvider.yahoo({
            clientId: 'YOUR_YAHOO_CLIENT_ID'
        });

        $authProvider.live({
            clientId: 'YOUR_MICROSOFT_CLIENT_ID'
        });

        $authProvider.twitch({
            clientId: 'YOUR_TWITCH_CLIENT_ID'
        });

        $authProvider.bitbucket({
            clientId: 'YOUR_BITBUCKET_CLIENT_ID'
        });

        $authProvider.spotify({
            clientId: 'YOUR_SPOTIFY_CLIENT_ID'
        });

        $authProvider.twitter({
            url: '/auth/twitter'
            //url: 'http://localhost:3000/auth/twitter'
        });
        $authProvider.dribble({
            //url: '/auth/dribble/api/v2/connections',
            clientId: 'cafe9492c5296869dff75f1a89cc452c1dd085712b9a47fb303d6f9305be35c2',
            url: 'http://localhost:3000/auth/dribble/callback',
            redirectUri: 'http://localhost:3000'// window.location.origin || window.location.protocol + '//' + window.location.host,
            //authorizationEndpoint: 'https://dribbble.com/oauth/authorize'
        });

        $authProvider.oauth2({
            name: 'foursquare',
            url: '/auth/foursquare',
            clientId: 'MTCEJ3NGW2PNNB31WOSBFDSAD4MTHYVAZ1UKIULXZ2CVFC2K',
            redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
            authorizationEndpoint: 'https://foursquare.com/oauth2/authenticate'
        });
   // }).run(function ($rootScope, $window, $auth) {
      //  if ($auth.isAuthenticated()) {
            $rootScope.currentUser = JSON.parse($window.localStorage.currentUser);
        //}
    });
<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import { getProductsResult } from '@shopgate/pwa-common-commerce/product/selectors/product';
import fetchCategoryProducts from '@shopgate/pwa-common-commerce/category/actions/fetchCategoryProducts';

/**
 * Maps the contents of the state to the component props.
 * @param {Object} state The current application state.
 * @param {Object} props The component props.
 * @return {Object} The extended component props.
 */
const mapStateToProps = (state, props) => ({
  ...getProductsResult(state, props),
});

/**
 * Connects the dispatch function to a callable function in the props.
 * @param {Function} dispatch The redux dispatch function.
 * @return {Object} The extended component props.
 */
const mapDispatchToProps = dispatch => ({
  getProducts: categoryId => dispatch(fetchCategoryProducts(categoryId)),
});

/**
 * Check to see if the categories have arrived.
 * @param {*} next The next state.
 * @param {*} prev the previous state.
 * @returns {boolean}
 */
const areStatePropsEqual = (next, prev) => {
  if (prev.products.length !== next.products.length) return false;
  if (prev.totalProductCount !== next.totalProductCount) return false;
  return true;
};

export default connect(mapStateToProps, mapDispatchToProps, null, { areStatePropsEqual });
<commit_msg>PWA-433 Send offset to action.<commit_after>import { connect } from 'react-redux';
import { getProductsResult } from '@shopgate/pwa-common-commerce/product/selectors/product';
import fetchCategoryProducts from '@shopgate/pwa-common-commerce/category/actions/fetchCategoryProducts';

/**
 * Maps the contents of the state to the component props.
 * @param {Object} state The current application state.
 * @param {Object} props The component props.
 * @return {Object} The extended component props.
 */
const mapStateToProps = (state, props) => ({
  ...getProductsResult(state, props),
});

/**
 * Connects the dispatch function to a callable function in the props.
 * @param {Function} dispatch The redux dispatch function.
 * @return {Object} The extended component props.
 */
const mapDispatchToProps = dispatch => ({
  getProducts: (categoryId, offset) => dispatch(fetchCategoryProducts(categoryId, offset)),
});

/**
 * Check to see if the categories have arrived.
 * @param {*} next The next state.
 * @param {*} prev the previous state.
 * @returns {boolean}
 */
const areStatePropsEqual = (next, prev) => {
  if (prev.products.length !== next.products.length) return false;
  if (prev.totalProductCount !== next.totalProductCount) return false;
  return true;
};

export default connect(mapStateToProps, mapDispatchToProps, null, { areStatePropsEqual });
<|endoftext|>


<commit_before>var SummaryScheduleCard = {
    name: 'SummaryScheduleCard',
    dom_target: undefined,
    term: 'current',

    render_init: function() {
        if (myuwFeatureEnabled('instructor_schedule') && window.user.instructor) {
            if (SummaryScheduleCard.term === 'current') {
                SummaryScheduleCard.term = window.term.year + ',' + window.term.quarter;
            }

            WSData.fetch_instructed_course_data_for_term(SummaryScheduleCard.term,
                                                         SummaryScheduleCard.render_upon_data,
                                                         SummaryScheduleCard.render_error);
        } else {
            $("#SummaryScheduleCard").hide();
        }
    },

    render_upon_data: function() {
        if (!SummaryScheduleCard._has_all_data()) {
            return;
        }

        SummaryScheduleCard._render();
        LogUtils.cardLoaded(SummaryScheduleCard.name, SummaryScheduleCard.dom_target);
    },

    render_error: function() {
        var error_code = WSData.instructed_course_data_error_code(SummaryScheduleCard.term);
        if (error_code === 410) {
            Error410.render();
        } else if (error_code === 404) {
            $("#SummaryScheduleCard").hide();
        } else {
            raw = CardWithError.render("Summary Schedule");
            InstructorCourseCards.dom_target.html(raw);
        }
    },

    _has_all_data: function () {
        return WSData.normalized_instructed_course_data(SummaryScheduleCard.term) !== undefined;
    },

    _render: function () {
        var term = SummaryScheduleCard.term;
        var instructed_course_data = WSData.normalized_instructed_course_data(term);
        var source = $("#instructor_summary_schedule").html();
        var courses_template = Handlebars.compile(source);
        var total_sections = (instructed_course_data.hasOwnProperty('section_references')
                              ? instructed_course_data.section_references.length
                              : instructed_course_data.sections.length);

        var raw = courses_template({
            quarter: instructed_course_data.quarter,
            year: instructed_course_data.year,
            future_term: instructed_course_data.future_term,
            sections: instructed_course_data.sections,
            section_count: instructed_course_data.sections.length,
            is_instructor: (instructed_course_data !== undefined),
            total_sections: total_sections,
            has_section_references: (total_sections > 0)
        });

        SummaryScheduleCard.dom_target.html(raw);
        SummaryScheduleCard.add_events(SummaryScheduleCard.term);
    },

    add_events: function(term) {
        $(".show_map").on("click", function(ev) {
            var course_id = ev.currentTarget.getAttribute("rel");
            course_id = course_id.replace(/[^a-z0-9]/gi, '_');
            var building = ev.currentTarget.getAttribute("rel");
            building = building.replace(/[^a-z0-9]/gi, '_');
            WSData.log_interaction("show_map_from_course_list_"+building, term);
        });

        $(".course_class_list").on("click", function(ev) {
            var width = 800;
            var height = 400;

            var left = window.screenX + 200;
            var top = window.screenY + 200;

            window.open(ev.target.href, '_blank', 'width='+width+',height='+height+',left='+left+',top='+top);

            var course_id = ev.currentTarget.getAttribute("rel");
            course_id = course_id.replace(/[^a-z0-9]/gi, '_');
            WSData.log_interaction("open_course_classlist_"+course_id, term);
            return false;
        });
    }
};

/* node.js exports */
if (typeof exports == "undefined") {
    var exports = {};
}
exports.SummaryScheduleCard = SummaryScheduleCard;
<commit_msg>jshint<commit_after>var SummaryScheduleCard = {
    name: 'SummaryScheduleCard',
    dom_target: undefined,
    term: 'current',

    render_init: function() {
        if (myuwFeatureEnabled('instructor_schedule') && window.user.instructor) {
            if (SummaryScheduleCard.term === 'current') {
                SummaryScheduleCard.term = window.term.year + ',' + window.term.quarter;
            }

            WSData.fetch_instructed_course_data_for_term(SummaryScheduleCard.term,
                                                         SummaryScheduleCard.render_upon_data,
                                                         SummaryScheduleCard.render_error);
        } else {
            $("#SummaryScheduleCard").hide();
        }
    },

    render_upon_data: function() {
        if (!SummaryScheduleCard._has_all_data()) {
            return;
        }

        SummaryScheduleCard._render();
        LogUtils.cardLoaded(SummaryScheduleCard.name, SummaryScheduleCard.dom_target);
    },

    render_error: function() {
        var error_code = WSData.instructed_course_data_error_code(SummaryScheduleCard.term);
        if (error_code === 410) {
            Error410.render();
        } else if (error_code === 404) {
            $("#SummaryScheduleCard").hide();
        } else {
            raw = CardWithError.render("Summary Schedule");
            InstructorCourseCards.dom_target.html(raw);
        }
    },

    _has_all_data: function () {
        return WSData.normalized_instructed_course_data(SummaryScheduleCard.term) !== undefined;
    },

    _render: function () {
        var term = SummaryScheduleCard.term;
        var instructed_course_data = WSData.normalized_instructed_course_data(term);
        var source = $("#instructor_summary_schedule").html();
        var courses_template = Handlebars.compile(source);
        var total_sections = instructed_course_data.hasOwnProperty('section_references') ?
            instructed_course_data.section_references.length : instructed_course_data.sections.length;

        var raw = courses_template({
            quarter: instructed_course_data.quarter,
            year: instructed_course_data.year,
            future_term: instructed_course_data.future_term,
            sections: instructed_course_data.sections,
            section_count: instructed_course_data.sections.length,
            is_instructor: (instructed_course_data !== undefined),
            total_sections: total_sections,
            has_section_references: (total_sections > 0)
        });

        SummaryScheduleCard.dom_target.html(raw);
        SummaryScheduleCard.add_events(SummaryScheduleCard.term);
    },

    add_events: function(term) {
        $(".show_map").on("click", function(ev) {
            var course_id = ev.currentTarget.getAttribute("rel");
            course_id = course_id.replace(/[^a-z0-9]/gi, '_');
            var building = ev.currentTarget.getAttribute("rel");
            building = building.replace(/[^a-z0-9]/gi, '_');
            WSData.log_interaction("show_map_from_course_list_"+building, term);
        });

        $(".course_class_list").on("click", function(ev) {
            var width = 800;
            var height = 400;

            var left = window.screenX + 200;
            var top = window.screenY + 200;

            window.open(ev.target.href, '_blank', 'width='+width+',height='+height+',left='+left+',top='+top);

            var course_id = ev.currentTarget.getAttribute("rel");
            course_id = course_id.replace(/[^a-z0-9]/gi, '_');
            WSData.log_interaction("open_course_classlist_"+course_id, term);
            return false;
        });
    }
};

/* node.js exports */
if (typeof exports == "undefined") {
    var exports = {};
}
exports.SummaryScheduleCard = SummaryScheduleCard;
<|endoftext|>