<commit_before>/*
  Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*jslint node:true browser:true */
/*global esmorph:true,esprima:true */

(function (exports) {
    'use strict';

    var Syntax = {
        AssignmentExpression: 'AssignmentExpression',
        ArrayExpression: 'ArrayExpression',
        BlockStatement: 'BlockStatement',
        BinaryExpression: 'BinaryExpression',
        BreakStatement: 'BreakStatement',
        CallExpression: 'CallExpression',
        CatchClause: 'CatchClause',
        ConditionalExpression: 'ConditionalExpression',
        ContinueStatement: 'ContinueStatement',
        DoWhileStatement: 'DoWhileStatement',
        DebuggerStatement: 'DebuggerStatement',
        EmptyStatement: 'EmptyStatement',
        ExpressionStatement: 'ExpressionStatement',
        ForStatement: 'ForStatement',
        ForInStatement: 'ForInStatement',
        FunctionDeclaration: 'FunctionDeclaration',
        FunctionExpression: 'FunctionExpression',
        Identifier: 'Identifier',
        IfStatement: 'IfStatement',
        Literal: 'Literal',
        LabeledStatement: 'LabeledStatement',
        LogicalExpression: 'LogicalExpression',
        MemberExpression: 'MemberExpression',
        NewExpression: 'NewExpression',
        ObjectExpression: 'ObjectExpression',
        Program: 'Program',
        Property: 'Property',
        ReturnStatement: 'ReturnStatement',
        SequenceExpression: 'SequenceExpression',
        SwitchStatement: 'SwitchStatement',
        SwitchCase: 'SwitchCase',
        ThisExpression: 'ThisExpression',
        ThrowStatement: 'ThrowStatement',
        TryStatement: 'TryStatement',
        UnaryExpression: 'UnaryExpression',
        UpdateExpression: 'UpdateExpression',
        VariableDeclaration: 'VariableDeclaration',
        VariableDeclarator: 'VariableDeclarator',
        WhileStatement: 'WhileStatement',
        WithStatement: 'WithStatement'
    };

    // Executes visitor on the object and its children (recursively).

    function traverse(object, visitor, master) {
        var key, child, parent, path;

        parent = (typeof master === 'undefined') ? [] : master;

        if (visitor.call(null, object, parent) === false) {
            return;
        }
        for (key in object) {
            if (object.hasOwnProperty(key)) {
                child = object[key];
                path = [ object ];
                path.push(parent);
                if (typeof child === 'object' && child !== null) {
                    traverse(child, visitor, path);
                }
            }
        }
    }

    // Insert a prolog in the body of every function.
    // It will be in the form of a function call:
    //
    //     traceName(object);
    //
    // where the object contains the following properties:
    //
    //    'name' holds the name of the function
    //    'lineNumber' holds the starting line number of the function block
    //    'range' contains the index-based range of the function
    //
    // The name of the function represents the associated reference for
    // the function (deduced on a best-effort basis if it is not
    // a function declaration).
    //
    // If traceName is a function instead of a string, it will be invoked and
    // the result will be used as the entire prolog. The arguments for the
    // invocation are the function name, range, and location info.

    function traceFunctionEntrance(traceName) {

        return function (code) {
            var tree,
                functionList,
                param,
                signature,
                pos,
                i;

            tree = esprima.parse(code, { range: true, loc: true });

            functionList = [];
            traverse(tree, function (node, path) {
                var parent;
                if (node.type === Syntax.FunctionDeclaration) {
                    functionList.push({
                        name: node.id.name,
                        range: node.range,
                        loc: node.loc,
                        blockStart: node.body.range[0]
                    });
                } else if (node.type === Syntax.FunctionExpression) {
                    parent = path[0];
                    if (parent.type === Syntax.AssignmentExpression) {
                        if (typeof parent.left.range !== 'undefined') {
                            functionList.push({
                                name: code.slice(parent.left.range[0],
                                          parent.left.range[1] + 1),
                                range: node.range,
                                loc: node.loc,
                                blockStart: node.body.range[0]
                            });
                        }
                    } else if (parent.type === Syntax.VariableDeclarator) {
                        functionList.push({
                            name: parent.id.name,
                            range: node.range,
                            loc: node.loc,
                            blockStart: node.body.range[0]
                        });
                    } else if (parent.type === Syntax.CallExpression) {
                        functionList.push({
                            name: parent.id ? parent.id.name : '[Anonymous]',
                            range: node.range,
                            loc: node.loc,
                            blockStart: node.body.range[0]
                        });
                    } else if (typeof parent.length === 'number') {
                        functionList.push({
                            name: parent.id ? parent.id.name : '[Anonymous]',
                            range: node.range,
                            loc: node.loc,
                            blockStart: node.body.range[0]
                        });
                    } else if (typeof parent.key !== 'undefined') {
                        if (parent.key.type === 'Identifier') {
                            if (parent.value === node && parent.key.name) {
                                functionList.push({
                                    name: parent.key.name,
                                    range: node.range,
                                    loc: node.loc,
                                    blockStart: node.body.range[0]
                                });
                            }
                        }
                    }
                }
            });

            // Insert the instrumentation code from the last entry.
            // This is to ensure that the range for each entry remains valid)
            // (it won't shift due to some new inserting string before the range).
            for (i = functionList.length - 1; i >= 0; i -= 1) {
                param = {
                    name: functionList[i].name,
                    range: functionList[i].range,
                    loc: functionList[i].loc
                };
                if (typeof traceName === 'function') {
                    signature = traceName.call(null, param);
                } else {
                    signature = traceName + '({ ';
                    signature += 'name: \'' + functionList[i].name + '\', ';
                    if (typeof functionList[i].loc !== 'undefined') {
                        signature += 'lineNumber: ' + functionList[i].loc.start.line + ', ';
                    }
                    signature += 'range: [' + functionList[i].range[0] + ', ' +
                        functionList[i].range[1] + '] ';
                    signature += '});';
                }
                pos = functionList[i].blockStart + 1;
                code = code.slice(0, pos) + '\n' + signature + code.slice(pos, code.length);
            }

            return code;
        };
    }

    function modify(code, modifiers) {
        var i;

        if (Object.prototype.toString.call(modifiers) === '[object Array]') {
            for (i = 0; i < modifiers.length; i += 1) {
                code = modifiers[i].call(null, code);
            }
        } else if (typeof modifiers === 'function') {
            code = modifiers.call(null, code);
        } else {
            throw new Error('Wrong use of esmorph.modify() function');
        }

        return code;
    }

    // Sync with package.json.
    exports.version = '0.0.0-dev';

    exports.modify = modify;

    exports.Tracer = {
        FunctionEntrance: traceFunctionEntrance
    };

}(typeof exports === 'undefined' ? (esmorph = {}) : exports));
<commit_msg>Update esmorph.<commit_after>/*
  Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*jslint node:true browser:true */
/*global esmorph:true,esprima:true */

(function (exports) {
    'use strict';

    var Syntax = {
        AssignmentExpression: 'AssignmentExpression',
        ArrayExpression: 'ArrayExpression',
        BlockStatement: 'BlockStatement',
        BinaryExpression: 'BinaryExpression',
        BreakStatement: 'BreakStatement',
        CallExpression: 'CallExpression',
        CatchClause: 'CatchClause',
        ConditionalExpression: 'ConditionalExpression',
        ContinueStatement: 'ContinueStatement',
        DoWhileStatement: 'DoWhileStatement',
        DebuggerStatement: 'DebuggerStatement',
        EmptyStatement: 'EmptyStatement',
        ExpressionStatement: 'ExpressionStatement',
        ForStatement: 'ForStatement',
        ForInStatement: 'ForInStatement',
        FunctionDeclaration: 'FunctionDeclaration',
        FunctionExpression: 'FunctionExpression',
        Identifier: 'Identifier',
        IfStatement: 'IfStatement',
        Literal: 'Literal',
        LabeledStatement: 'LabeledStatement',
        LogicalExpression: 'LogicalExpression',
        MemberExpression: 'MemberExpression',
        NewExpression: 'NewExpression',
        ObjectExpression: 'ObjectExpression',
        Program: 'Program',
        Property: 'Property',
        ReturnStatement: 'ReturnStatement',
        SequenceExpression: 'SequenceExpression',
        SwitchStatement: 'SwitchStatement',
        SwitchCase: 'SwitchCase',
        ThisExpression: 'ThisExpression',
        ThrowStatement: 'ThrowStatement',
        TryStatement: 'TryStatement',
        UnaryExpression: 'UnaryExpression',
        UpdateExpression: 'UpdateExpression',
        VariableDeclaration: 'VariableDeclaration',
        VariableDeclarator: 'VariableDeclarator',
        WhileStatement: 'WhileStatement',
        WithStatement: 'WithStatement'
    };

    // Executes visitor on the object and its children (recursively).

    function traverse(object, visitor, master) {
        var key, child, parent, path;

        parent = (typeof master === 'undefined') ? [] : master;

        if (visitor.call(null, object, parent) === false) {
            return;
        }
        for (key in object) {
            if (object.hasOwnProperty(key)) {
                child = object[key];
                path = [ object ];
                path.push(parent);
                if (typeof child === 'object' && child !== null) {
                    traverse(child, visitor, path);
                }
            }
        }
    }

    // Insert a prolog in the body of every function.
    // It will be in the form of a function call:
    //
    //     traceName(object);
    //
    // where the object contains the following properties:
    //
    //    'name' holds the name of the function
    //    'lineNumber' holds the starting line number of the function block
    //    'range' contains the index-based range of the function
    //
    // The name of the function represents the associated reference for
    // the function (deduced on a best-effort basis if it is not
    // a function declaration).
    //
    // If traceName is a function instead of a string, it will be invoked and
    // the result will be used as the entire prolog. The arguments for the
    // invocation are the function name, range, and location info.

    function traceFunctionEntrance(traceName) {

        return function (code) {
            var tree,
                functionList,
                param,
                signature,
                pos,
                i;

            tree = esprima.parse(code, { range: true, loc: true });

            functionList = [];
            traverse(tree, function (node, path) {
                var parent;
                if (node.type === Syntax.FunctionDeclaration) {
                    functionList.push({
                        name: node.id.name,
                        range: node.range,
                        loc: node.loc,
                        blockStart: node.body.range[0]
                    });
                } else if (node.type === Syntax.FunctionExpression) {
                    parent = path[0];
                    if (parent.type === Syntax.AssignmentExpression) {
                        if (typeof parent.left.range !== 'undefined') {
                            functionList.push({
                                name: code.slice(parent.left.range[0],
                                          parent.left.range[1]).replace('"','\\"'),
                                range: node.range,
                                loc: node.loc,
                                blockStart: node.body.range[0]
                            });
                        }
                    } else if (parent.type === Syntax.VariableDeclarator) {
                        functionList.push({
                            name: parent.id.name,
                            range: node.range,
                            loc: node.loc,
                            blockStart: node.body.range[0]
                        });
                    } else if (parent.type === Syntax.CallExpression) {
                        functionList.push({
                            name: parent.id ? parent.id.name : '[Anonymous]',
                            range: node.range,
                            loc: node.loc,
                            blockStart: node.body.range[0]
                        });
                    } else if (typeof parent.length === 'number') {
                        functionList.push({
                            name: parent.id ? parent.id.name : '[Anonymous]',
                            range: node.range,
                            loc: node.loc,
                            blockStart: node.body.range[0]
                        });
                    } else if (typeof parent.key !== 'undefined') {
                        if (parent.key.type === 'Identifier') {
                            if (parent.value === node && parent.key.name) {
                                functionList.push({
                                    name: parent.key.name,
                                    range: node.range,
                                    loc: node.loc,
                                    blockStart: node.body.range[0]
                                });
                            }
                        }
                    }
                }
            });

            // Insert the instrumentation code from the last entry.
            // This is to ensure that the range for each entry remains valid)
            // (it won't shift due to some new inserting string before the range).
            for (i = functionList.length - 1; i >= 0; i -= 1) {
                param = {
                    name: functionList[i].name,
                    range: functionList[i].range,
                    loc: functionList[i].loc
                };
                if (typeof traceName === 'function') {
                    signature = traceName.call(null, param);
                } else {
                    signature = traceName + '({ ';
                    signature += 'name: \'' + functionList[i].name + '\', ';
                    if (typeof functionList[i].loc !== 'undefined') {
                        signature += 'lineNumber: ' + functionList[i].loc.start.line + ', ';
                    }
                    signature += 'range: [' + functionList[i].range[0] + ', ' +
                        functionList[i].range[1] + '] ';
                    signature += '});';
                }
                pos = functionList[i].blockStart + 1;
                code = code.slice(0, pos) + '\n' + signature + code.slice(pos, code.length);
            }

            return code;
        };
    }

    function modify(code, modifiers) {
        var i;

        if (Object.prototype.toString.call(modifiers) === '[object Array]') {
            for (i = 0; i < modifiers.length; i += 1) {
                code = modifiers[i].call(null, code);
            }
        } else if (typeof modifiers === 'function') {
            code = modifiers.call(null, code);
        } else {
            throw new Error('Wrong use of esmorph.modify() function');
        }

        return code;
    }

    // Sync with package.json.
    exports.version = '0.0.0-dev';

    exports.modify = modify;

    exports.Tracer = {
        FunctionEntrance: traceFunctionEntrance
    };

}(typeof exports === 'undefined' ? (esmorph = {}) : exports));
<|endoftext|>


<commit_before>function rsAuthRun(AUTH_EVENTS,$rootScope,$rsAuth) {

    checkRemember();

    //TODO: Native Angular support, not UI.Router
    $rootScope.$on('$stateChangeStart', function(event, args) {
        checkAuthorization(event, args);
    });

    ////////////////////////

    //Check to see if the session is remembered, and then check to see if the login should be remembered globally.
    function checkRemember() {
        var authToken;
        if (!!$rsAuth.isAuthenticated()) {
            authToken = $rsAuth.isAuthenticated();
            $rsAuth.validateToken(authToken).then(function() {
                $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
            });

        } else if (!!$rsAuth.isRemembered()) { //If the session is remembered globally, validate the token make sure it's clean.
            authToken = $rsAuth.isRemembered();
            $rsAuth.validateToken(authToken).then(function() {
                $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
            });
        }
    }

    //Listen for when the state changes then check the user-role and see if
    //the user is authorized to see the content
    function checkForAll(authorizedRoles) {
        for (var prop in authorizedRoles) {
            if (authorizedRoles[prop] === "*") {
                return true;
            }
        }
        return false;
    }

    function checkAuthorization(event, argus) {
        var args = argus;

        //This is the default is nothing was set in the config data object for $stateProvider
        var authorizedRoles = {
            all: "*"
        };

        //Get the authorized roles from the $stateProvider
        if(args.data && args.data.authorizedRoles) {
            authorizedRoles = args.data.authorizedRoles;
        }

        if(!checkForAll(authorizedRoles)) {
            if (!$rsAuth.isAuthenticated()) {
                //If they are not logged in at all.
                event.preventDefault();
                $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
            } else if (!!$rsAuth.isAuthenticated() && !$rsAuth.isAuthorized) {
                //If you're logged in but you're not authenticated to see the content.
                event.preventDefault();
                $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
            }
        }
    }
}
<commit_msg>That was a gamebreaking bug.<commit_after>function rsAuthRun(AUTH_EVENTS,$rootScope,$rsAuth) {

    checkRemember();

    //TODO: Native Angular support, not UI.Router
    $rootScope.$on('$stateChangeStart', function(event, args) {
        checkAuthorization(event, args);
    });

    ////////////////////////

    //Check to see if the session is remembered, and then check to see if the login should be remembered globally.
    function checkRemember() {
        var authToken;
        if (!!$rsAuth.isAuthenticated()) {
            authToken = $rsAuth.isAuthenticated();
            $rsAuth.validateToken(authToken).then(function() {
                $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
            });

        } else if (!!$rsAuth.isRemembered()) { //If the session is remembered globally, validate the token make sure it's clean.
            authToken = $rsAuth.isRemembered();
            $rsAuth.validateToken(authToken).then(function() {
                $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
            });
        }
    }

    //Listen for when the state changes then check the user-role and see if
    //the user is authorized to see the content
    function checkForAll(authorizedRoles) {
        for (var prop in authorizedRoles) {
            if (authorizedRoles[prop] === "*") {
                return true;
            }
        }
        return false;
    }

    function checkAuthorization(event, argus) {
        var args = argus;

        //This is the default is nothing was set in the config data object for $stateProvider
        var authorizedRoles = {
            all: "*"
        };

        //Get the authorized roles from the $stateProvider
        if(args.data && args.data.authorizedRoles) {
            authorizedRoles = args.data.authorizedRoles;
        }

        if(!checkForAll(authorizedRoles)) {
            if (!$rsAuth.isAuthenticated()) {
                //If they are not logged in at all.
                event.preventDefault();
                $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
            } else if (!!$rsAuth.isAuthenticated() && !$rsAuth.isAuthorized()) {
                //If you're logged in but you're not authenticated to see the content.
                event.preventDefault();
                $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
            }
        }
    }
}
<|endoftext|>


<commit_before>const { ensureDirAsync } = require("fs-extra-promise");
const { resolve, sep } = require("path");

const loadMessageMonitors = (client, baseDir) => new Promise(async (res, rej) => {
  const dir = resolve(`${baseDir}./monitors/`);
  await ensureDirAsync(dir).catch(err => client.emit("error", client.funcs.newError(err)));
  let files = await client.funcs.getFileListing(client, baseDir, "monitors").catch(err => client.emit("error", client.funcs.newError(err)));
  files = files.filter(file => !client.messageMonitors.get(file.name));
  try {
    const fn = files.map(f => new Promise((res) => {
      const props = require(`${f.path}${sep}${f.base}`);
      if (props.init) props.init(client);
      client.messageMonitors.set(f.name, props);
      res(delete require.cache[require.resolve(`${f.path}${sep}${f.base}`)]);
    }));
    await Promise.all(fn).catch(e => client.funcs.log(e, "error"));
    res();
  } catch (e) {
    if (e.code === "MODULE_NOT_FOUND") {
      const module = /'[^']+'/g.exec(e.toString());
      await client.funcs.installNPM(module[0].slice(1, -1))
        .catch((err) => {
          console.error(err);
          process.exit();
        });
      loadMessageMonitors(client, baseDir);
    } else { rej(e); }
  }
});

module.exports = async (client) => {
  client.messageMonitors.clear();
  await loadMessageMonitors(client, client.clientBaseDir).catch(err => client.emit("error", client.funcs.newError(err)));
  if (client.coreBaseDir !== client.clientBaseDir) {
    await loadMessageMonitors(client, client.coreBaseDir).catch(err => client.emit("error", client.funcs.newError(err)));
  }
  client.funcs.log(`Loaded ${client.messageMonitors.size} command monitors.`);
};
<commit_msg>Delete loadMessageMonitors.js<commit_after><|endoftext|>


<commit_before>/**
 * jspsych-iat
 * Kristin Diep
 *
 * plugin for displaying a stimulus and getting a keyboard response
 *
 * documentation: docs.jspsych.org
 *
 **/

 jsPsych.plugins["iat"] = (function() {

  var plugin = {};

  jsPsych.pluginAPI.registerPreload('iat', 'stimulus', 'image', function(t){return !t.is_html || t.is_html == 'undefined'});

  plugin.trial = function(display_element, trial) {

    var plugin_id_name = "jspsych-iat";
    var plugin_id_selector = '#' + plugin_id_name;
    var _join = function( /*args*/ ) {
      var arr = Array.prototype.slice.call(arguments, _join.length);
      return arr.join(separator = '-');
    }

    // if any trial variables are functions
    // this evaluates the function and replaces
    // it with the output of the function
    trial = jsPsych.pluginAPI.evaluateFunctionParameters(trial);

    // set default values for the parameters
    trial.display_feedback = trial.display_feedback || false;
    trial.image_when_wrong = trial.image_when_wrong || 'undefined';
    trial.wrong_image_name = trial.wrong_image_name || 'wrong image';
    trial.left_category_key = trial.left_category_key || 'E';
    trial.right_category_key = trial.right_category_key || 'I';
    trial.left_category_label = trial.left_category_label || ['left'];
    trial.right_category_label = trial.right_category_label || ['right'];
    trial.stim_key_association = trial.stim_key_association || 'undefined';
    trial.response_ends_trial = (typeof trial.response_ends_trial == 'undefined') ? true : trial.response_ends_trial;
    trial.timing_response = trial.timing_response || -1;
    trial.key_to_move_forward = trial.key_to_move_forward || [jsPsych.ALL_KEYS];
    trial.prompt = trial.prompt || "";

    //Get keys to continue and put them in a string
    var i;
    var keysToContinue = "";
    var lastKey = trial.key_to_move_forward.length - 1;
    for(i = 0; i < lastKey; i++) {
      keysToContinue += trial.key_to_move_forward[i] + ", ";
    }

    var html_str = " ";
    //html_str += "
";

    if (!trial.is_html) {
      html_str += "

";
    } else {
      html_str += "

" + trial.stimulus + "

";
    }

    html_str += "
";

    if(trial.left_category_label.length == 1) {
      html_str += "
Press " + trial.left_category_key + " for:
 " +
      trial.left_category_label[0].bold() + "

";
    } else {
      html_str += "
Press " + trial.left_category_key + " for:
 " +
      trial.left_category_label[0].bold() + "
" + "or
" +
      trial.left_category_label[1].bold() + "

";
    }

    html_str += "
";

    if(trial.right_category_label.length == 1) {
      html_str += "
Press " + trial.right_category_key + " for:
 " +
      trial.right_category_label[0].bold() + '

';
    } else {
      html_str += "
Press " + trial.right_category_key + " for:
 " +
      trial.right_category_label[0].bold() + "
" + "or
" +
      trial.right_category_label[1].bold() + "

";
    }

    html_str += "
";

    if(!trial.response_ends_trial && trial.display_feedback == true) {
      html_str += "

";
      var wImg = document.getElementById("wrongImgContainer");
      html_str += "
Trial will continue automatically.
";
    }

    if(!trial.response_ends_trial && !trial.display_feedback) {
      html_str += "
Trial will continue automatically.
";
    }

    if(trial.response_ends_trial && trial.display_feedback == true) {
      html_str += "

";
      var wImg = document.getElementById("wrongImgContainer");
      //wImg.style.visibility = "hidden";

      if(trial.key_to_move_forward.length == 1) {
        if(trial.key_to_move_forward[0] == "other key") {
          html_str += "
If you press the wrong key, a " + trial.wrong_image_name + " will appear. Press the other key to continue.
"
        } else if(trial.key_to_move_forward[0] == jsPsych.ALL_KEYS) {
          html_str += "
If you press the wrong key, a " + trial.wrong_image_name + " will appear. Press any key to continue.
"
        } else {
        html_str += "
If you press the wrong key, a " + trial.wrong_image_name + " will appear. Press " + trial.key_to_move_forward[0] + " to continue.
";
      }
      } else {
        html_str += "
If you press the wrong key, a " + trial.wrong_image_name + " will appear. Press " +
        keysToContinue + " " + trial.key_to_move_forward[lastKey] + " to continue.
";
      }
    } else if (trial.response_ends_trial && trial.display_feedback != true) {
      html_str += "

";
      if(trial.key_to_move_forward.length == 1) {
        if(trial.key_to_move_forward[0] == "other key") {
          html_str += "
If you press the wrong key, press the other key to continue.
"
        } else if(trial.key_to_move_forward[0] == jsPsych.ALL_KEYS) {
          html_str += "
If you press the wrong key, press any key to continue.
"
        } else {
        html_str += "
If you press the wrong key, press " + trial.key_to_move_forward[0] + " to continue.
";
        }
        } else {
        html_str += "
If you press the wrong key, press " +
        keysToContinue + " " + trial.key_to_move_forward[lastKey] + " to continue.
";
      }
    }

    html_str += "
";

    display_element.innerHTML += html_str;

    //show prompt if there is one
    if (trial.prompt !== "") {
      display_element.innerHTML += trial.prompt;
    }

    // store response
    var response = {
      rt: -1,
      key: -1,
      correct: false
    };

    // function to end trial when it is time
    var end_trial = function() {

      // kill any remaining setTimeout handlers
      jsPsych.pluginAPI.clearAllTimeouts();

      // kill keyboard listeners
      if (typeof keyboardListener !== 'undefined') {
        jsPsych.pluginAPI.cancelKeyboardResponse(keyboardListener);
      }

      // gather the data to store for the trial
      var trial_data = {
        "rt": response.rt,
        "stimulus": trial.stimulus,
        "key_press": response.key,
        "correct": response.correct
      };

      jsPsych.data.write(trial_data);
      jsPsych.data.addDataToLastTrial(trial_data);

      // clears the display
      display_element.innerHTML = '';

      // move on to the next trial
      jsPsych.finishTrial(trial_data);
    };

    var leftKeyCode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode(trial.left_category_key);
    var rightKeyCode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode(trial.right_category_key);

    // function to handle responses by the subject
    var after_response = function(info) {
      var wImg = document.getElementById("wrongImgContainer");
      // after a valid response, the stimulus will have the CSS class 'responded'
      // which can be used to provide visual feedback that a response was recorded
      display_element.querySelector('#jspsych-iat-stim').className += ' responded';

      // only record the first response
      if (response.key == -1 ) {
        response = info;
      }

      if(trial.stim_key_association == "right") {
        if(response.rt > -1 && response.key == rightKeyCode) {
          response.correct = true;
          if (trial.response_ends_trial) {
            end_trial();
          }
        } else {
          response.correct = false;
          if(!trial.response_ends_trial && trial.display_feedback == true) {
            wImg.style.visibility = "visible";
          }
          if (trial.response_ends_trial && trial.display_feedback == true) {
            wImg.style.visibility = "visible";
            if(trial.key_to_move_forward[0] == "other key") {
              var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
                callback_function: end_trial,
                valid_responses: [trial.right_category_key]
              });
            } else {
            var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
              callback_function: end_trial,
              valid_responses: trial.key_to_move_forward
            });}
           } else if(trial.response_ends_trial && trial.display_feedback != true) {
            var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
              callback_function: end_trial,
              valid_responses: [jsPsych.ALL_KEYS]
            });
          } else if(!trial.response_ends_trial && trial.display_feedback != true) {
            // end_trial();
          }
        }
      } else if(trial.stim_key_association == "left") {
        if(response.rt > -1 && response.key == leftKeyCode) {
          response.correct = true;
          if (trial.response_ends_trial) {
            end_trial();
          }
        } else {
          response.correct = false;
          if(!trial.response_ends_trial && trial.display_feedback == true) {
            wImg.style.visibility = "visible";
          }
          if (trial.response_ends_trial && trial.display_feedback == true) {
            wImg.style.visibility = "visible";
            if(trial.key_to_move_forward[0] == "other key") {
              var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
                callback_function: end_trial,
                valid_responses: [trial.left_category_key]
              });
            } else {
            var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
              callback_function: end_trial,
              valid_responses: trial.key_to_move_forward
            });}
          } else if(trial.response_ends_trial && trial.display_feedback != true) {
            var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
              callback_function: end_trial,
              valid_responses: [jsPsych.ALL_KEYS]
            });
          } else if(!trial.response_ends_trial && trial.display_feedback != true) {
            // end_trial();
          }
        }
      }
    };

    // start the response listener
    if (trial.left_category_key != jsPsych.NO_KEYS && trial.right_category_key != jsPsych.NO_KEYS) {
      var keyboardListener = jsPsych.pluginAPI.getKeyboardResponse({
        callback_function: after_response,
        valid_responses: [trial.left_category_key, trial.right_category_key],
        rt_method: 'date',
        persist: false,
        allow_held_key: false
      });
    }

    // end trial if time limit is set
    if (trial.timing_response > 0 && trial.response_ends_trial != true) {
      jsPsych.pluginAPI.setTimeout(function() {
        end_trial();
      }, trial.timing_response);
    }

  };

  return plugin;
})();
<commit_msg>set default for false correctly<commit_after>/**
 * jspsych-iat
 * Kristin Diep
 *
 * plugin for displaying a stimulus and getting a keyboard response
 *
 * documentation: docs.jspsych.org
 *
 **/

 jsPsych.plugins["iat"] = (function() {

  var plugin = {};

  jsPsych.pluginAPI.registerPreload('iat', 'stimulus', 'image', function(t){return !t.is_html || t.is_html == 'undefined'});

  plugin.trial = function(display_element, trial) {

    var plugin_id_name = "jspsych-iat";
    var plugin_id_selector = '#' + plugin_id_name;
    var _join = function( /*args*/ ) {
      var arr = Array.prototype.slice.call(arguments, _join.length);
      return arr.join(separator = '-');
    }

    // if any trial variables are functions
    // this evaluates the function and replaces
    // it with the output of the function
    trial = jsPsych.pluginAPI.evaluateFunctionParameters(trial);

    // set default values for the parameters
    trial.display_feedback = typeof trial.display_feedback == 'undefined' ? false : trial.display_feedback;
    trial.image_when_wrong = trial.image_when_wrong || 'undefined';
    trial.wrong_image_name = trial.wrong_image_name || 'wrong image';
    trial.left_category_key = trial.left_category_key || 'E';
    trial.right_category_key = trial.right_category_key || 'I';
    trial.left_category_label = trial.left_category_label || ['left'];
    trial.right_category_label = trial.right_category_label || ['right'];
    trial.stim_key_association = trial.stim_key_association || 'undefined';
    trial.response_ends_trial = (typeof trial.response_ends_trial == 'undefined') ? true : trial.response_ends_trial;
    trial.timing_response = trial.timing_response || -1;
    trial.key_to_move_forward = trial.key_to_move_forward || jsPsych.ALL_KEYS;

    //Get keys to continue and put them in a string
    var keysToContinue = "";
    var lastKey = trial.key_to_move_forward.length - 1;
    for(var i = 0; i < lastKey; i++) {
      keysToContinue += trial.key_to_move_forward[i] + ", ";
    }

    var html_str = "";

    if (!trial.is_html) {
      html_str += "

";
    } else {
      html_str += "

" + trial.stimulus + "

";
    }

    html_str += "
";

    if(trial.left_category_label.length == 1) {
      html_str += "
Press " + trial.left_category_key + " for:
 " +
      trial.left_category_label[0].bold() + "

";
    } else {
      html_str += "
Press " + trial.left_category_key + " for:
 " +
      trial.left_category_label[0].bold() + "
" + "or
" +
      trial.left_category_label[1].bold() + "

";
    }

    html_str += "
";

    if(trial.right_category_label.length == 1) {
      html_str += "
Press " + trial.right_category_key + " for:
 " +
      trial.right_category_label[0].bold() + '

';
    } else {
      html_str += "
Press " + trial.right_category_key + " for:
 " +
      trial.right_category_label[0].bold() + "
" + "or
" +
      trial.right_category_label[1].bold() + "

";
    }

    html_str += "
";

    if(!trial.response_ends_trial && trial.display_feedback == true) {
      html_str += "

";
      var wImg = document.getElementById("wrongImgContainer");
      html_str += "
Trial will continue automatically.
";
    }

    if(!trial.response_ends_trial && !trial.display_feedback) {
      html_str += "
Trial will continue automatically.
";
    }

    if(trial.response_ends_trial && trial.display_feedback == true) {
      html_str += "

";
      var wImg = document.getElementById("wrongImgContainer");
      //wImg.style.visibility = "hidden";

      if(trial.key_to_move_forward.length == 1) {
        if(trial.key_to_move_forward[0] == "other key") {
          html_str += "
If you press the wrong key, a " + trial.wrong_image_name + " will appear. Press the other key to continue.
"
        } else if(trial.key_to_move_forward[0] == jsPsych.ALL_KEYS) {
          html_str += "
If you press the wrong key, a " + trial.wrong_image_name + " will appear. Press any key to continue.
"
        } else {
        html_str += "
If you press the wrong key, a " + trial.wrong_image_name + " will appear. Press " + trial.key_to_move_forward[0] + " to continue.
";
      }
      } else {
        html_str += "
If you press the wrong key, a " + trial.wrong_image_name + " will appear. Press " +
        keysToContinue + " " + trial.key_to_move_forward[lastKey] + " to continue.
";
      }
    } else if (trial.response_ends_trial && trial.display_feedback != true) {
      html_str += "

";
      if(trial.key_to_move_forward.length == 1) {
        if(trial.key_to_move_forward[0] == "other key") {
          html_str += "
If you press the wrong key, press the other key to continue.
"
        } else if(trial.key_to_move_forward[0] == jsPsych.ALL_KEYS) {
          html_str += "
If you press the wrong key, press any key to continue.
"
        } else {
        html_str += "
If you press the wrong key, press " + trial.key_to_move_forward[0] + " to continue.
";
        }
        } else {
        html_str += "
If you press the wrong key, press " +
        keysToContinue + " " + trial.key_to_move_forward[lastKey] + " to continue.
";
      }
    }

    html_str += "
";

    display_element.innerHTML = html_str;

    // store response
    var response = {
      rt: -1,
      key: -1,
      correct: false
    };

    // function to end trial when it is time
    var end_trial = function() {

      // kill any remaining setTimeout handlers
      jsPsych.pluginAPI.clearAllTimeouts();

      // kill keyboard listeners
      if (typeof keyboardListener !== 'undefined') {
        jsPsych.pluginAPI.cancelKeyboardResponse(keyboardListener);
      }

      // gather the data to store for the trial
      var trial_data = {
        "rt": response.rt,
        "stimulus": trial.stimulus,
        "key_press": response.key,
        "correct": response.correct
      };

      // clears the display
      display_element.innerHTML = '';

      // move on to the next trial
      jsPsych.finishTrial(trial_data);
    };

    var leftKeyCode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode(trial.left_category_key);
    var rightKeyCode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode(trial.right_category_key);

    // function to handle responses by the subject
    var after_response = function(info) {
      var wImg = document.getElementById("wrongImgContainer");
      // after a valid response, the stimulus will have the CSS class 'responded'
      // which can be used to provide visual feedback that a response was recorded
      display_element.querySelector('#jspsych-iat-stim').className += ' responded';

      // only record the first response
      if (response.key == -1 ) {
        response = info;
      }

      if(trial.stim_key_association == "right") {
        if(response.rt > -1 && response.key == rightKeyCode) {
          response.correct = true;
          if (trial.response_ends_trial) {
            end_trial();
          }
        } else {
          response.correct = false;
          if(!trial.response_ends_trial && trial.display_feedback == true) {
            wImg.style.visibility = "visible";
          }
          if (trial.response_ends_trial && trial.display_feedback == true) {
            wImg.style.visibility = "visible";
            if(trial.key_to_move_forward[0] == "other key") {
              var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
                callback_function: end_trial,
                valid_responses: [trial.right_category_key]
              });
            } else {
            var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
              callback_function: end_trial,
              valid_responses: trial.key_to_move_forward
            });}
           } else if(trial.response_ends_trial && trial.display_feedback != true) {
            var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
              callback_function: end_trial,
              valid_responses: [jsPsych.ALL_KEYS]
            });
          } else if(!trial.response_ends_trial && trial.display_feedback != true) {
            // end_trial();
          }
        }
      } else if(trial.stim_key_association == "left") {
        if(response.rt > -1 && response.key == leftKeyCode) {
          response.correct = true;
          if (trial.response_ends_trial) {
            end_trial();
          }
        } else {
          response.correct = false;
          if(!trial.response_ends_trial && trial.display_feedback == true) {
            wImg.style.visibility = "visible";
          }
          if (trial.response_ends_trial && trial.display_feedback == true) {
            wImg.style.visibility = "visible";
            if(trial.key_to_move_forward[0] == "other key") {
              var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
                callback_function: end_trial,
                valid_responses: [trial.left_category_key]
              });
            } else {
            var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
              callback_function: end_trial,
              valid_responses: trial.key_to_move_forward
            });}
          } else if(trial.response_ends_trial && trial.display_feedback != true) {
            var keyListener = jsPsych.pluginAPI.getKeyboardResponse({
              callback_function: end_trial,
              valid_responses: [jsPsych.ALL_KEYS]
            });
          } else if(!trial.response_ends_trial && trial.display_feedback != true) {
            // end_trial();
          }
        }
      }
    };

    // start the response listener
    if (trial.left_category_key != jsPsych.NO_KEYS && trial.right_category_key != jsPsych.NO_KEYS) {
      var keyboardListener = jsPsych.pluginAPI.getKeyboardResponse({
        callback_function: after_response,
        valid_responses: [trial.left_category_key, trial.right_category_key],
        rt_method: 'date',
        persist: false,
        allow_held_key: false
      });
    }

    // end trial if time limit is set
    if (trial.timing_response > 0 && trial.response_ends_trial != true) {
      jsPsych.pluginAPI.setTimeout(function() {
        end_trial();
      }, trial.timing_response);
    }

  };

  return plugin;
})();
<|endoftext|>


<commit_before>Package.describe({
    summary: "Accounts Templates styled for Zurb Foundation.",
    version: "1.1.0",
    name: "useraccounts:foundation",
    git: "https://github.com/meteor-useraccounts/foundation.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@1.0");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "useraccounts:core",
    ], ["client", "server"]);

    api.imply([
        "useraccounts:core@1.1.0",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_nav_button.html",
        "lib/at_nav_button.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_foundation.less"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "useraccounts:foundation",
        "useraccounts:core@1.1.0",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});
<commit_msg>patch release - Bump to version 1.1.1<commit_after>Package.describe({
    summary: "Accounts Templates styled for Zurb Foundation.",
    version: "1.1.1",
    name: "useraccounts:foundation",
    git: "https://github.com/meteor-useraccounts/foundation.git",
});

Package.on_use(function(api, where) {
    api.versionsFrom("METEOR@1.0");

    api.use([
        "less",
        "templating",
    ], "client");

    api.use([
        "useraccounts:core",
    ], ["client", "server"]);

    api.imply([
        "useraccounts:core@1.1.1",
    ], ["client", "server"]);

    api.add_files([
        "lib/at_error.html",
        "lib/at_error.js",
        "lib/at_form.html",
        "lib/at_form.js",
        "lib/at_input.html",
        "lib/at_input.js",
        "lib/at_nav_button.html",
        "lib/at_nav_button.js",
        "lib/at_oauth.html",
        "lib/at_oauth.js",
        "lib/at_pwd_form.html",
        "lib/at_pwd_form.js",
        "lib/at_pwd_form_btn.html",
        "lib/at_pwd_form_btn.js",
        "lib/at_pwd_link.html",
        "lib/at_pwd_link.js",
        "lib/at_result.html",
        "lib/at_result.js",
        "lib/at_sep.html",
        "lib/at_sep.js",
        "lib/at_signin_link.html",
        "lib/at_signin_link.js",
        "lib/at_signup_link.html",
        "lib/at_signup_link.js",
        "lib/at_social.html",
        "lib/at_social.js",
        "lib/at_terms_link.html",
        "lib/at_terms_link.js",
        "lib/at_title.html",
        "lib/at_title.js",
        "lib/full_page_at_form.html",
        "lib/at_foundation.less"
    ], ["client"]);
});

Package.on_test(function(api) {
    api.use([
        "useraccounts:foundation",
        "useraccounts:core@1.1.1",
    ]);

    api.use([
        "accounts-password",
        "tinytest",
        "test-helpers"
    ], ["client", "server"]);

    api.add_files([
        "tests/tests.js"
    ], ["client", "server"]);
});
<|endoftext|>


<commit_before>/**
 * pubfood
 *
 * - check to make sure that the bidder's done callback was called
 * - check for core api method calls
 */

/* global describe, it */

'use strict';

/*eslint no-unused-vars: 0*/
/*eslint no-undef: 0*/

// set up some dom stuff
// @todo think about using `node-jsdom` for this
var fakeDom = {
  appendChild: function() {
    return {};
  },
  createElement: function() {
    return {};
  },
};

global.window = {};
if (!global.document) {
  global.document = fakeDom;
  global.document.head = fakeDom;
  global.document.body = fakeDom;
  global.document.documentElement = fakeDom;
}

var assert = require('chai').assert;
var expect = require('chai').expect;
var pubfood = require('../src/pubfood');
var auctionExample = require('./fixture/auctionexample1');

describe('Api Callbacks - Tests', function() {
  it('should call all the callbacks', function(done) {

    //
    var bidProviderDoneCalled = {
      //yieldbot: false,
      //bidderFast: false,
      //bidderSlow: false
    };

    var pf = new pubfood({
      id: 'optionalId',
      auctionProviderCbTimeout: 500,
      bidProviderCbTimeout: 600
    });

    var checkDoneCallbacks = function(_key) {
      describe(_key + ' done callback called', function() {
        it('should be called', function(d) {
          assert(bidProviderDoneCalled[_key], 'done callback was triggered for ' + _key);
          d();
        });
      });
    };

    // add reporter for PUBFOOD_API_START
    pf.observe('PUBFOOD_API_START', function(event) {
      var bidProviders = pf.getBidProviders();
      for(var key in bidProviders){
        bidProviderDoneCalled[key] = false;
      }
    });

    // add reporter for BID_COMPLETE
    pf.observe('BID_COMPLETE', function(event) {
      var data = event.data;
      if (typeof bidProviderDoneCalled[data] !== 'undefined') {
        bidProviderDoneCalled[data] = true;
      }
    });

    // add reporter for AUCTION_COMPLETE
    pf.observe('AUCTION_COMPLETE', function(event) {
      // check to make sure that the bidder's done callback was called
      for (var key in bidProviderDoneCalled) {
        checkDoneCallbacks(key);
      }

      done();
    });

    // add slot
    pf.addSlot(auctionExample.slots[0]);

    // set the auction provider
    pf.setAuctionProvider(auctionExample.auctionProvider);

    // add bid providers
    pf.addBidProvider(auctionExample.bidProviders[0]);
    pf.addBidProvider(auctionExample.bidProviders[1]);
    pf.addBidProvider(auctionExample.bidProviders[2]);

    var now = +(new Date());
    pf.start(now, function(hasErrors, details) {
      if(hasErrors){
        console.log('hasErrors', hasErrors, details);
        done();
      }
    });
  });
});
<commit_msg>tweak timeout in tests<commit_after>/**
 * pubfood
 *
 * - check to make sure that the bidder's done callback was called
 * - check for core api method calls
 */

/* global describe, it */

'use strict';

/*eslint no-unused-vars: 0*/
/*eslint no-undef: 0*/

// set up some dom stuff
// @todo think about using `node-jsdom` for this
var fakeDom = {
  appendChild: function() {
    return {};
  },
  createElement: function() {
    return {};
  },
};

global.window = {};
if (!global.document) {
  global.document = fakeDom;
  global.document.head = fakeDom;
  global.document.body = fakeDom;
  global.document.documentElement = fakeDom;
}

var assert = require('chai').assert;
var expect = require('chai').expect;
var pubfood = require('../src/pubfood');
var auctionExample = require('./fixture/auctionexample1');

describe('Api Callbacks - Tests', function() {
  it('should call all the callbacks', function(done) {

    //
    var bidProviderDoneCalled = {
      //yieldbot: false,
      //bidderFast: false,
      //bidderSlow: false
    };

    var pf = new pubfood({
      id: 'optionalId',
      auctionProviderCbTimeout: 1,
      bidProviderCbTimeout: 1
    });

    var checkDoneCallbacks = function(_key) {
      describe(_key + ' done callback called', function() {
        it('should be called', function(d) {
          assert(bidProviderDoneCalled[_key], 'done callback was triggered for ' + _key);
          d();
        });
      });
    };

    // add reporter for PUBFOOD_API_START
    pf.observe('PUBFOOD_API_START', function(event) {
      var bidProviders = pf.getBidProviders();
      for(var key in bidProviders){
        bidProviderDoneCalled[key] = false;
      }
    });

    // add reporter for BID_COMPLETE
    pf.observe('BID_COMPLETE', function(event) {
      var data = event.data;
      if (typeof bidProviderDoneCalled[data] !== 'undefined') {
        bidProviderDoneCalled[data] = true;
      }
    });

    // add reporter for AUCTION_COMPLETE
    pf.observe('AUCTION_COMPLETE', function(event) {
      // check to make sure that the bidder's done callback was called
      for (var key in bidProviderDoneCalled) {
        checkDoneCallbacks(key);
      }

      done();
    });

    // add slot
    pf.addSlot(auctionExample.slots[0]);

    // set the auction provider
    pf.setAuctionProvider(auctionExample.auctionProvider);

    // add bid providers
    pf.addBidProvider(auctionExample.bidProviders[0]);
    pf.addBidProvider(auctionExample.bidProviders[1]);
    pf.addBidProvider(auctionExample.bidProviders[2]);

    var now = +(new Date());
    pf.start(now, function(hasErrors, details) {
      if(hasErrors){
        console.log('hasErrors', hasErrors, details);
        done();
      }
    });
  });
});
<|endoftext|>


<commit_before>console.log('my nickname is shinshow');
console.log('my nickname is shinshow2');<commit_msg>resolved<commit_after>console.log('my nickname is shinshow');
console.log('my nickname is shinshow2');
console.log('my nickname is shinshow');
<|endoftext|>


<commit_before>/**
 * Movim Javascript Template functions

 * Look at the comments for help.
 */

var MovimTpl = {
    dragged : false,
    moving : false,
    percent : false,
    init : function() {
        if(document.getElementById('back') != null)
            MovimUtils.hideElement(document.getElementById('back'));
    },
    append : function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.insertAdjacentHTML('beforeend', html);
        }
    },
    back : function() {
        // If the context menu is shown
        var cm = document.querySelector('ul.context_menu');
        if(cm != null && cm.className.includes('shown')) {
            MovimTpl.toggleContextMenu(document);
            // If a drawer is shown
        } else if(Drawer.filled()) {
            Drawer.clear();
            // If a dialog box is shown
        } else if(Dialog.filled()) {
            Dialog.clear();
            // If the menu is shown
        } else if(MovimUtils.hasClass('body > nav', 'active')) {
            MovimUtils.removeClass('body > nav', 'active');
            // If the panel is shown
        } else if(MovimTpl.isPanel()) {
            MovimTpl.hidePanel();
            window.history.back();
        } else {
            history.back();
        }
    },
    fill : function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.innerHTML = html;
        }
    },
    hideContextMenu : function() {
        MovimUtils.removeClass('ul.context_menu', 'shown');
    },
    hideMenu: function() {
        MovimUtils.removeClass('body > nav', 'active');
    },
    showPanel: function() {
        MovimUtils.addClass('main section', 'enabled');
        MovimTpl.scrollPanelTop();
    },
    hidePanel: function() {
        MovimUtils.removeClass('main section', 'enabled');
    },
    isPanel: function() {
        return MovimUtils.hasClass('main section', 'enabled');
    },
    isPanelScrolled: function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div div');

        if(selector != null) {
            return (selector.scrollHeight - Math.floor(selector.scrollTop) <= selector.clientHeight + 3);
        }
    },
    prepend: function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.insertAdjacentHTML('afterbegin', html);
        }
    },
    remove: function(selector) {
        target = document.querySelector(selector);
        if(target)
            target.parentNode.removeChild(target);
    },
    replace: function (selector, html) {
        target = document.querySelector(selector);
        if(target) {
            var div = document.createElement('div');
            div.innerHTML = html;
            var element = div.firstChild;
            replacedNode = target.parentNode.replaceChild(element, target);
        }
    },
    scrollPanel : function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div div');

        if(selector != null) {
            selector.scrollTop = selector.scrollHeight;
        }
    },
    scrollPanelTop : function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div');

        if(selector != null) {
            selector.scrollTop = 0;
        }
    },
    toggleActionButton : function() {
        MovimUtils.toggleClass('.button.action', 'active');
    },
    toggleContextMenu : function(e) {
        var element = 'ul.context_menu';
        var classname = 'shown';

        if(document.querySelector(element) == null) {
            return;
        }

        if(document.querySelector('.show_context_menu').contains(e.target)) {
            MovimUtils.addClass(element, classname);
            return;
        }

        //if(!document.querySelector(element).contains(e.target))
        MovimUtils.removeClass(element, classname);
    },
    toggleMenu : function() {
        MovimUtils.toggleClass('body > nav', 'active');
    },
    touchEvents: function() {
        nav = document.querySelector('body > nav');

        document.body.addEventListener('touchstart', function(event) {
            startX = event.targetTouches[0].pageX;

            if(
            (
                startX < 5 ||
                (nav.classList.contains('active') && startX > document.body.clientWidth - 25)
            )
            && MovimTpl.dragged == false) {
                nav.classList.add('moving');
                MovimTpl.dragged = true;
            }
        }, true);

        document.body.addEventListener('touchmove', function(event) {
            moveX = event.targetTouches[0].pageX;

            if(MovimTpl.dragged) {
                event.preventDefault();
                event.stopPropagation();

                position = moveX - document.body.clientWidth;

                MovimTpl.percent = 1 - Math.abs(moveX) / Math.abs(document.body.clientWidth);
                nav.style.transform = 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, '+position+', 0, 0, 1)';
            }
        }, true);

        document.body.addEventListener('touchend', function(event) {
            nav.style.transform = '';

            if(MovimTpl.dragged) {
                nav.classList.remove('moving');

                if(!nav.classList.contains('active')
                && MovimTpl.percent < 0.80) {
                    nav.classList.add('active');
                } else if(MovimTpl.percent > 0.20) {
                    nav.classList.remove('active');
                }
            }

            MovimTpl.dragged = false;
        }, true);
    }
};

movim_add_onload(function() {
    MovimTpl.init();
    MovimTpl.touchEvents();
    document.body.addEventListener('click', MovimTpl.toggleContextMenu, false);
});
<commit_msg>Other small fixes for the menu and touch screens<commit_after>/**
 * Movim Javascript Template functions

 * Look at the comments for help.
 */

var MovimTpl = {
    dragged : false,
    moving : false,
    percent : false,
    init : function() {
        if(document.getElementById('back') != null)
            MovimUtils.hideElement(document.getElementById('back'));
    },
    append : function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.insertAdjacentHTML('beforeend', html);
        }
    },
    back : function() {
        // If the context menu is shown
        var cm = document.querySelector('ul.context_menu');
        if(cm != null && cm.className.includes('shown')) {
            MovimTpl.toggleContextMenu(document);
            // If a drawer is shown
        } else if(Drawer.filled()) {
            Drawer.clear();
            // If a dialog box is shown
        } else if(Dialog.filled()) {
            Dialog.clear();
            // If the menu is shown
        } else if(MovimUtils.hasClass('body > nav', 'active')) {
            MovimUtils.removeClass('body > nav', 'active');
            // If the panel is shown
        } else if(MovimTpl.isPanel()) {
            MovimTpl.hidePanel();
            window.history.back();
        } else {
            history.back();
        }
    },
    fill : function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.innerHTML = html;
        }
    },
    hideContextMenu : function() {
        MovimUtils.removeClass('ul.context_menu', 'shown');
    },
    hideMenu: function() {
        MovimUtils.removeClass('body > nav', 'active');
    },
    showPanel: function() {
        MovimUtils.addClass('main section', 'enabled');
        MovimTpl.scrollPanelTop();
    },
    hidePanel: function() {
        MovimUtils.removeClass('main section', 'enabled');
    },
    isPanel: function() {
        return MovimUtils.hasClass('main section', 'enabled');
    },
    isPanelScrolled: function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div div');

        if(selector != null) {
            return (selector.scrollHeight - Math.floor(selector.scrollTop) <= selector.clientHeight + 3);
        }
    },
    prepend: function(selector, html) {
        target = document.querySelector(selector);
        if(target) {
            target.insertAdjacentHTML('afterbegin', html);
        }
    },
    remove: function(selector) {
        target = document.querySelector(selector);
        if(target)
            target.parentNode.removeChild(target);
    },
    replace: function (selector, html) {
        target = document.querySelector(selector);
        if(target) {
            var div = document.createElement('div');
            div.innerHTML = html;
            var element = div.firstChild;
            replacedNode = target.parentNode.replaceChild(element, target);
        }
    },
    scrollPanel : function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div div');

        if(selector != null) {
            selector.scrollTop = selector.scrollHeight;
        }
    },
    scrollPanelTop : function() {
        var selector = document.querySelector('main section > div:first-child:nth-last-child(2) ~ div');

        if(selector != null) {
            selector.scrollTop = 0;
        }
    },
    toggleActionButton : function() {
        MovimUtils.toggleClass('.button.action', 'active');
    },
    toggleContextMenu : function(e) {
        var element = 'ul.context_menu';
        var classname = 'shown';

        if(document.querySelector(element) == null) {
            return;
        }

        if(document.querySelector('.show_context_menu').contains(e.target)) {
            MovimUtils.addClass(element, classname);
            return;
        }

        //if(!document.querySelector(element).contains(e.target))
        MovimUtils.removeClass(element, classname);
    },
    toggleMenu : function() {
        MovimUtils.toggleClass('body > nav', 'active');
    },
    touchEvents: function() {
        nav = document.querySelector('body > nav');

        document.body.addEventListener('touchstart', function(event) {
            startX = event.targetTouches[0].pageX;

            if(
            (
                startX < 10 ||
                (nav.classList.contains('active') && startX > document.body.clientWidth - 50)
            )
            && MovimTpl.dragged == false) {
                nav.classList.add('moving');
                MovimTpl.dragged = true;
            }
        }, true);

        document.body.addEventListener('touchmove', function(event) {
            moveX = event.targetTouches[0].pageX;

            if(MovimTpl.dragged) {
                event.preventDefault();
                event.stopPropagation();

                position = moveX - document.body.clientWidth;

                MovimTpl.percent = 1 - Math.abs(moveX) / Math.abs(document.body.clientWidth);
                nav.style.transform = 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, '+position+', 0, 0, 1)';
            }
        }, true);

        document.body.addEventListener('touchend', function(event) {
            nav.style.transform = '';

            if(MovimTpl.dragged) {
                nav.classList.remove('moving');

                if(!nav.classList.contains('active')
                && MovimTpl.percent < 0.80) {
                    nav.classList.add('active');
                } else if(MovimTpl.percent > 0.20) {
                    nav.classList.remove('active');
                }
            }

            MovimTpl.dragged = false;
        }, true);
    }
};

movim_add_onload(function() {
    MovimTpl.init();
    MovimTpl.touchEvents();
    document.body.addEventListener('click', MovimTpl.toggleContextMenu, false);
});
<|endoftext|>


<commit_before>var exists  = require('./exists')
var rmFile  = require('./rmFile')
var dir     = require('../path/directory')
var forEach = require('../array/forEach')
var fs      = require('fs')
var path    = require('path')

// make async version
function rmdir (dirName, cb) {
  exists(dirName, function (res) {
    if (!res) {
      cb('Directory does not exist.')
    } else {
      dir.files(dirName, 'all', function (err, res) {
        forEach(res.files, function (val, key, arr) {
          rmFile(val)
        })
        forEach(res.dirs, function (val, key, arr) {
          fs.rmdirSync(val)
        })
        fs.rmdirSync(dirName)
        cb(null, 'All done')
      })
    }
  })
}

function rmdirSync (dirName) {
  if (!exists(dirName)) return
  fs.readdirSync(dirName).forEach(function (file) {
    var fullPath = path.join(dirName, file)
    if (fs.statSync(fullPath).isDirectory()) rmdir(fullPath)
    else fs.unlinkSync(fullPath)
  })

  fs.rmdirSync(dirName)
}

module.exports = rmdir
module.exports.sync = rmdirSync
<commit_msg>refactor file/rmDir.js<commit_after>var exists    = require('./exists')
var rmFile    = require('./rmFile')
var dir       = require('../path/directory')
var eachAsync = require('../async/iterate').each
var fs        = require('fs')
var path      = require('path')

function rmdir (dirName, cb) {
  exists(dirName, function (res) {
    if (!res) {
      cb('Directory ' + dirName + ' does not exist.')
    } else {
      dir.files(dirName, 'all', function (err, res) {
        eachAsync(res.files, function (val, key, done) {
          rmFile(val, function (res) {
            done(null, val)
          })
        }, function (err, results) {
          eachAsync(res.dirs, function (val, key, done) {
            fs.rmdir(val, function (res) {
              done(null, val)
            })
          }, function (err, results) {
            fs.rmdir(dirName, function (res) {
              return cb('Directory ' + dirName + ' removed')
            })
          })
        })
      })
    }
  })
}

function rmdirSync (dirName) {
  if (!exists(dirName)) return
  fs.readdirSync(dirName).forEach(function (file) {
    var fullPath = path.join(dirName, file)
    if (fs.statSync(fullPath).isDirectory()) rmdir(fullPath)
    else fs.unlinkSync(fullPath)
  })

  fs.rmdirSync(dirName)
}

module.exports = rmdir
module.exports.sync = rmdirSync
<|endoftext|>


<commit_before>/*! userinfo 0.0.1 [20-09-2014] */
!function(a,b){"function"==typeof define&&define.amd?define(b):a.UserInfo=b()}(this,function(){var a="http://userinfo.io/userinfos";return{getInfo:function(b){var c;c=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),c.onreadystatechange=function(){if(4==c.readyState)if(200==c.status)b(JSON.parse(c.responseText),null);else{var a;a=null!==c.responseText&&""!==c.responseText?JSON.parse(c.responseText):{message:"Error with HTTP status code: "+c.status},b(null,a)}},c.open("GET",a,!0),c.send()}}});<commit_msg>Recompile the library<commit_after>/*! userinfo 0.0.1 [20-09-2014] */
!function(a,b){"function"==typeof define&&define.amd?define(b):a.UserInfo=b()}(this,function(){var a="http://api.userinfo.io/userinfos";return{getInfo:function(b){var c;c=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),c.onreadystatechange=function(){if(4==c.readyState)if(200==c.status)b(JSON.parse(c.responseText),null);else{var a;a=null!==c.responseText&&""!==c.responseText?JSON.parse(c.responseText):{message:"Error with HTTP status code: "+c.status},b(null,a)}},c.open("GET",a,!0),c.send()}}});<|endoftext|>


<commit_before>enyo.kind({
	name: "Ares",
	kind: "Control",
	classes: "onyx",
	fit: true,
	components: [
		{kind: "Panels", arrangerKind: "CarouselArranger", draggable: false, classes:"enyo-fit ares-panels", components: [
			{components: [
				{kind: "Phobos", onSaveDocument: "saveDocument", onSaveAsDocument: "saveAsDocument", onCloseDocument: "closeDocument", onDesignDocument: "designDocument", onUpdate: "phobosUpdate"}
			]},
			{components: [
				{kind: "Deimos", onCloseDesigner: "closeDesigner", onDesignerUpdate: "designerUpdate", onUndo: "designerUndo", onRedo: "designerRedo"}
			]}
		]},
		{kind: "Slideable", layoutKind: "FittableRowsLayout", classes: "onyx ares-files-slider", axis: "v", value: 0, min: -500, max: 0, unit: "px", onAnimateFinish: "finishedSliding", components: [
			{name: "projectView", kind: "ProjectView", fit: true, classes: "onyx", onFileDblClick: "openDocument", onProjectSelected: "projectSelected"},
			{name: "bottomBar", kind: "DocumentToolbar",
				onToggleOpen: "toggleFiles",
				onSwitchFile: "switchFile",
				onSave: "bounceSave",
				onDesign: "bounceDesign",
				onNewKind: "bounceNew",
				onClose: "bounceClose"
			}
		]},
		{name: "waitPopup", kind: "onyx.Popup", centered: true, floating: true, autoDismiss: false, modal: true, style: "text-align: center; padding: 20px;", components: [
			{kind: "Image", src: "$phobos/assets/images/save-spinner.gif", style: "width: 54px; height: 55px;"},
			{name: "waitPopupMessage", content: "Ongoing...", style: "padding-top: 10px;"}
		]},
		{kind: "ServiceRegistry"}
	],
	handlers: {
		onReloadServices: "handleReloadServices",
		onUpdateAuth: "handleUpdateAuth",
		onShowWaitPopup: "showWaitPopup",
		onHideWaitPopup: "hideWaitPopup"
	},
	phobosViewIndex: 0,
	deimosViewIndex: 1,
	create: function() {
		this.inherited(arguments);
		this.$.panels.setIndex(this.phobosViewIndex);
		this.adjustBarMode();

		window.onbeforeunload = enyo.bind(this, "handleBeforeUnload");
		if (Ares.TestController) {
			Ares.Workspace.loadProjects("com.enyojs.ares.tests", true);
			this.createComponent({kind: "Ares.TestController", aresObj: this});
		} else {
			Ares.Workspace.loadProjects();
		}
		this.calcSlideableLimit();
		Ares.instance = this;
	},
	rendered: function() {
		this.inherited(arguments);
		this.calcSlideableLimit();
	},
	draggable: false,
	/**
	 * @private
	 */
	handleReloadServices: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		this.$.serviceRegistry.reloadServices();
	},
	/**
	 * @private
	 */
	handleUpdateAuth: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		this.$.serviceRegistry.setConfig(inEvent.serviceId, {auth: inEvent.auth}, inEvent.next);
	},
	projectSelected: function() {
		setTimeout(enyo.bind(this, function() { this.$.deimos.projectSelected(this.$.projectView.currentProject); }), 500);	// <-- TODO - using timeout here because project url is set asynchronously
		return true;
	},
	openDocument: function(inSender, inEvent) {
		this._openDocument(inEvent.projectData, inEvent.file, function(inErr) {});
	},
	/** @private */
	_openDocument: function(projectData, file, next) {
		var self = this;
		var fileDataId = Ares.Workspace.files.computeId(file);
		var fileData = Ares.Workspace.files.get(fileDataId);
		if (fileData) {
			this.switchToDocument(fileData);
		} else {
			this.showWaitPopup(this, {msg: $L("Opening...")});
			this.$.bottomBar.createFileTab(file.name, fileDataId);
			this.$.slideable.setDraggable(true);
			this._fetchDocument(projectData, file, function(inErr, inContent) {
				self.hideWaitPopup();
				if (inErr) {
					self.warn("Open failed", inErr);
				} else {
					fileData = Ares.Workspace.files.newEntry(file, inContent, projectData);
					self.switchToDocument(fileData);
				}
			});
		}
	},
	/** @private */
	_fetchDocument: function(projectData, file, next) {
		if (this.debug) this.log("projectData:", projectData, ", file:", file);
		var service = projectData.getService();
		service.getFile(file.id)
			.response(this, function(inEvent, inData) {
				next(null, inData && inData.content || "");
			})
			.error(this, function(inEvent, inErr) {
				next(inErr);
			});
	},
	saveDocument: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		var self = this;
		this._saveDocument(inEvent.content, {service: inEvent.file.service, fileId: inEvent.file.id}, function(err) {
			if (err) {
				self.$.phobos.saveFailed(err);
			} else {
				self.$.phobos.saveComplete();
				self.$.deimos.saveComplete();
			}
		});
	},
	_saveDocument: function(content, where, next) {
		var req;
		if (where.fileId) {
			req = where.service.putFile(where.fileId, content);
		} else {
			req = where.service.createFile(where.folderId, where.name, content);
		}
		req.response(this, function(inEvent, inData) {
			next(null, inData);
		}).error(this, function(inEvent, inErr) {
			next(inErr);
		});

	},
	saveAsDocument: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		var self = this,
		    file = inEvent.file,
		    name = inEvent.name,
		    content = inEvent.content;

		if (!file) {
			_footer(new Error("missing file/folder description"));
			return;
		}

		async.waterfall([
			this._closeDocument.bind(this, inEvent.docId),
			function(next) {
				var where, err;
				if (file.isDir && name) {
					// create given file in given dir
					where = {
						service: file.service,
						folderId: file.id,
						name: name
					};
				} else if (!file.isDir && !name) {
					// overwrite the given file
					where = {
						service: file.service,
						fileId: file.id
					};
				} else if (!file.isDir && name) {
					// create a new file in the same folder as the
					// given file
					where = {
						service: file.service,
						folderId: file.parent.id,
						name: name
					};
				} else {
					err = new Error("wrong file/folder description");
				}
				next(err, where);
			},
			this._saveDocument.bind(this, inEvent.content),
			_savedToOpen.bind(this),
			this._openDocument.bind(this, inEvent.projectData)
		], _footer);

		function _savedToOpen(inData, next) {
			this.$.projectView.refreshFile(file);
			// FIXME: only HermesFileTree report built-in file#service
			var hermesFile = inData[0];
			hermesFile.service = file.service;
			hermesFile.name = ares.basename(hermesFile.path);
			next(null, hermesFile);
		}

		function _footer(err, result) {
			if (self.debug) enyo.log("err:", err, "result:", result);
			if (typeof inEvent.next === 'function') {
				inEvent.next(err, result);
			}
		}
	},
	closeDocument: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		this._closeDocument(inEvent.id, function() {});
	},
	/** @private */
	_closeDocument: function(docId, next) {
		// remove file from cache
		Ares.Workspace.files.removeEntry(docId);
		this.$.bottomBar.removeTab(docId);
		this.$.slideable.setDraggable(Ares.Workspace.files.length > 0);
		this.showFiles();
		next();
	},
	designDocument: function(inSender, inEvent) {
		this.syncEditedFiles();
		this.$.deimos.load(inEvent);
		this.$.panels.setIndex(this.deimosViewIndex);
		this.adjustBarMode();
		this.activeDocument.setCurrentIF('designer');
	},
	//* A code change happened in Phobos - push change to Deimos
	phobosUpdate: function(inSender, inEvent) {
		this.$.deimos.load(inEvent);
	},
	//* A design change happened in Deimos - push change to Phobos
	designerUpdate: function(inSender, inEvent) {
		if (inEvent && inEvent.docHasChanged) {
			this.$.phobos.updateComponents(inSender, inEvent);
		}
	},
	closeDesigner: function(inSender, inEvent) {
		this.designerUpdate(inSender, inEvent);
		this.$.panels.setIndex(this.phobosViewIndex);
		this.adjustBarMode();
		this.activeDocument.setCurrentIF('code');
	},
	//* Undo event from Deimos
	designerUndo: function(inSender, inEvent) {
		this.$.phobos.undoAndUpdate();
	},
	//* Redo event from Deimos
	designerRedo: function(inSender, inEvent) {
		this.$.phobos.redoAndUpdate();
	},
	handleBeforeUnload: function() {
		if (window.location.search.indexOf("debug") == -1) {
			return 'You may have some unsaved data';
		}
	},
	hideFiles: function(inSender, inEvent) {
		this.$.slideable.animateToMin();
	},
	showFiles: function(inSender, inEvent) {
		this.$.slideable.animateToMax();
	},
	toggleFiles: function(inSender, inEvent) {
		if (this.$.slideable.value < 0 || Ares.Workspace.files.length === 0) {
			this.showFiles();
		} else {
			this.hideFiles();
		}
	},
	resizeHandler: function(inSender, inEvent) {
		this.inherited(arguments);
		this.calcSlideableLimit();
		if (this.$.slideable.value < 0) {
			this.$.slideable.setValue(this.$.slideable.min);
		}
	},
	calcSlideableLimit: function() {
		var min = this.getBounds().height-this.$.bottomBar.getBounds().height;
		this.$.slideable.setMin(-min);
	},
	switchFile: function(inSender, inEvent) {
		var d = Ares.Workspace.files.get(inEvent.id);
		if (d) {
			this.switchToDocument(d);
		} else {
			alert("File ID not found in cache!");
		}
	},
	switchToDocument: function(d) {
		// We no longer save the data as the ACE edit session will keep the data for us
		if (!this.activeDocument || d !== this.activeDocument) {
			this.$.phobos.openDoc(d);
		}
		var currentIF = d.getCurrentIF();
		this.activeDocument = d;
		if (currentIF === 'code') {
			this.$.panels.setIndex(this.phobosViewIndex);
		} else {
			this.$.phobos.designerAction();
		}
		this.adjustBarMode();
		this.$.bottomBar.activateFileWithId(d.getId());
		this.hideFiles();
	},
	finishedSliding: function(inSender, inEvent) {
		if (this.$.slideable.value < 0) {
			this.$.bottomBar.showControls();
		} else {
			this.$.bottomBar.hideControls();
		}
	},
	// FIXME: This trampoline function probably needs some refactoring
	bounceSave: function(inSender, inEvent) {
		this.$.phobos.saveDocAction(inSender, inEvent);
	},
	// FIXME: This trampoline function probably needs some refactoring
	bounceDesign: function(inSender, inEvent) {
		var editorMode = this.$.panels.getIndex() == this.phobosViewIndex;
		if (editorMode) {
			this.$.phobos.designerAction(inSender, inEvent);
		} else {
			this.$.deimos.closeDesignerAction();
		}
	},
	adjustBarMode: function() {
		var designMode = this.$.panels.getIndex() == this.deimosViewIndex;
		this.$.bottomBar.setDesignMode(designMode);
	},
	// FIXME: This trampoline function probably needs some refactoring
	bounceNew: function(inSender, inEvent) {
		this.$.phobos.newKindAction(inSender, inEvent);
	},
	// FIXME: This trampoline function probably needs some refactoring
	// Close is a special case, because it can be invoked on a document other than the currently-active one
	bounceClose: function(inSender, inEvent) {
		this.switchFile(inSender, inEvent);
		enyo.asyncMethod(this.$.phobos, "closeDocAction");
	},
	//* Update code running in designer
	syncEditedFiles: function() {
		var files = Ares.Workspace.files,
			model,
			i;

		for(i=0;i<files.models.length;i++) {
			model = files.models[i];

			if(model.getFile().name === "package.js") {
				continue;
			}

			this.updateCode(files.get(model.id));
		}
	},
	updateCode: function(inDoc) {
		var filename = inDoc.getFile().path,
			code = inDoc.getAceSession().getValue();

		if(filename.slice(-4) === ".css") {
			doc = inDoc;
			this.syncCSSFile(filename, code);
		} else if(filename.slice(-3) === ".js") {
			this.syncJSFile(code);
		}
	},
	syncCSSFile: function(inFilename, inCode) {
		this.$.deimos.syncCSSFile(inFilename, inCode);
	},
	syncJSFile: function(inCode) {
		this.$.deimos.syncJSFile(inCode);
	},
	showWaitPopup: function(inSender, inEvent) {
		this.$.waitPopupMessage.setContent(inEvent.msg);
		this.$.waitPopup.show();
	},
	hideWaitPopup: function() {
		this.$.waitPopup.hide();
	},
	statics: {
		isBrowserSupported: function() {
			if (enyo.platform.ie && enyo.platform.ie <= 8) {
				return false;
			} else {
				return true;
			}
		},
		instance: null
	}
});
<commit_msg>ENYO-1020: address review comment (clarify)<commit_after>enyo.kind({
	name: "Ares",
	kind: "Control",
	classes: "onyx",
	fit: true,
	components: [
		{kind: "Panels", arrangerKind: "CarouselArranger", draggable: false, classes:"enyo-fit ares-panels", components: [
			{components: [
				{kind: "Phobos", onSaveDocument: "saveDocument", onSaveAsDocument: "saveAsDocument", onCloseDocument: "closeDocument", onDesignDocument: "designDocument", onUpdate: "phobosUpdate"}
			]},
			{components: [
				{kind: "Deimos", onCloseDesigner: "closeDesigner", onDesignerUpdate: "designerUpdate", onUndo: "designerUndo", onRedo: "designerRedo"}
			]}
		]},
		{kind: "Slideable", layoutKind: "FittableRowsLayout", classes: "onyx ares-files-slider", axis: "v", value: 0, min: -500, max: 0, unit: "px", onAnimateFinish: "finishedSliding", components: [
			{name: "projectView", kind: "ProjectView", fit: true, classes: "onyx", onFileDblClick: "openDocument", onProjectSelected: "projectSelected"},
			{name: "bottomBar", kind: "DocumentToolbar",
				onToggleOpen: "toggleFiles",
				onSwitchFile: "switchFile",
				onSave: "bounceSave",
				onDesign: "bounceDesign",
				onNewKind: "bounceNew",
				onClose: "bounceClose"
			}
		]},
		{name: "waitPopup", kind: "onyx.Popup", centered: true, floating: true, autoDismiss: false, modal: true, style: "text-align: center; padding: 20px;", components: [
			{kind: "Image", src: "$phobos/assets/images/save-spinner.gif", style: "width: 54px; height: 55px;"},
			{name: "waitPopupMessage", content: "Ongoing...", style: "padding-top: 10px;"}
		]},
		{kind: "ServiceRegistry"}
	],
	handlers: {
		onReloadServices: "handleReloadServices",
		onUpdateAuth: "handleUpdateAuth",
		onShowWaitPopup: "showWaitPopup",
		onHideWaitPopup: "hideWaitPopup"
	},
	phobosViewIndex: 0,
	deimosViewIndex: 1,
	create: function() {
		this.inherited(arguments);
		this.$.panels.setIndex(this.phobosViewIndex);
		this.adjustBarMode();

		window.onbeforeunload = enyo.bind(this, "handleBeforeUnload");
		if (Ares.TestController) {
			Ares.Workspace.loadProjects("com.enyojs.ares.tests", true);
			this.createComponent({kind: "Ares.TestController", aresObj: this});
		} else {
			Ares.Workspace.loadProjects();
		}
		this.calcSlideableLimit();
		Ares.instance = this;
	},
	rendered: function() {
		this.inherited(arguments);
		this.calcSlideableLimit();
	},
	draggable: false,
	/**
	 * @private
	 */
	handleReloadServices: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		this.$.serviceRegistry.reloadServices();
	},
	/**
	 * @private
	 */
	handleUpdateAuth: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		this.$.serviceRegistry.setConfig(inEvent.serviceId, {auth: inEvent.auth}, inEvent.next);
	},
	projectSelected: function() {
		setTimeout(enyo.bind(this, function() { this.$.deimos.projectSelected(this.$.projectView.currentProject); }), 500);	// <-- TODO - using timeout here because project url is set asynchronously
		return true;
	},
	openDocument: function(inSender, inEvent) {
		this._openDocument(inEvent.projectData, inEvent.file, function(inErr) {});
	},
	/** @private */
	_openDocument: function(projectData, file, next) {
		var self = this;
		var fileDataId = Ares.Workspace.files.computeId(file);
		var fileData = Ares.Workspace.files.get(fileDataId);
		if (fileData) {
			this.switchToDocument(fileData);
		} else {
			this.showWaitPopup(this, {msg: $L("Opening...")});
			this.$.bottomBar.createFileTab(file.name, fileDataId);
			this.$.slideable.setDraggable(true);
			this._fetchDocument(projectData, file, function(inErr, inContent) {
				self.hideWaitPopup();
				if (inErr) {
					self.warn("Open failed", inErr);
				} else {
					fileData = Ares.Workspace.files.newEntry(file, inContent, projectData);
					self.switchToDocument(fileData);
				}
			});
		}
	},
	/** @private */
	_fetchDocument: function(projectData, file, next) {
		if (this.debug) this.log("projectData:", projectData, ", file:", file);
		var service = projectData.getService();
		service.getFile(file.id)
			.response(this, function(inEvent, inData) {
				next(null, inData && inData.content || "");
			})
			.error(this, function(inEvent, inErr) {
				next(inErr);
			});
	},
	saveDocument: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		var self = this;
		this._saveDocument(inEvent.content, {service: inEvent.file.service, fileId: inEvent.file.id}, function(err) {
			if (err) {
				self.$.phobos.saveFailed(err);
			} else {
				self.$.phobos.saveComplete();
				self.$.deimos.saveComplete();
			}
		});
	},
	_saveDocument: function(content, where, next) {
		var req;
		if (where.fileId) {
			req = where.service.putFile(where.fileId, content);
		} else {
			req = where.service.createFile(where.folderId, where.name, content);
		}
		req.response(this, function(inEvent, inData) {
			next(null, inData);
		}).error(this, function(inEvent, inErr) {
			next(inErr);
		});

	},
	saveAsDocument: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		var self = this,
		    file = inEvent.file,
		    name = inEvent.name,
		    content = inEvent.content;

		if (!file) {
			_footer(new Error("Internal error: missing file/folder description"));
			return;
		}

		async.waterfall([
			this._closeDocument.bind(this, inEvent.docId),
			_prepareNewLocation.bind(this),
			this._saveDocument.bind(this, inEvent.content),
			_savedToOpen.bind(this),
			this._openDocument.bind(this, inEvent.projectData)
		], _footer);

		function _prepareNewLocation(next) {
			var where, err;
			if (file.isDir && name) {
				// create given file in given dir
				where = {
					service: file.service,
					folderId: file.id,
					name: name
				};
			} else if (!file.isDir && !name) {
				// overwrite the given file
				where = {
					service: file.service,
					fileId: file.id
				};
			} else if (!file.isDir && name) {
				// create a new file in the same folder as the
				// given file
				where = {
					service: file.service,
					folderId: file.parent.id,
					name: name
				};
			} else {
				err = new Error("Internal error: wrong file/folder description");
			}
			next(err, where);
		}

		function _savedToOpen(inData, next) {
			this.$.projectView.refreshFile(file);
			// FIXME: only HermesFileTree report built-in file#service
			var hermesFile = inData[0];
			hermesFile.service = file.service;
			hermesFile.name = ares.basename(hermesFile.path);
			next(null, hermesFile);
		}

		function _footer(err, result) {
			if (self.debug) enyo.log("err:", err, "result:", result);
			if (typeof inEvent.next === 'function') {
				inEvent.next(err, result);
			}
		}
	},
	closeDocument: function(inSender, inEvent) {
		if (this.debug) this.log("sender:", inSender, ", event:", inEvent);
		this._closeDocument(inEvent.id, function() {});
	},
	/** @private */
	_closeDocument: function(docId, next) {
		// remove file from cache
		Ares.Workspace.files.removeEntry(docId);
		this.$.bottomBar.removeTab(docId);
		this.$.slideable.setDraggable(Ares.Workspace.files.length > 0);
		this.showFiles();
		next();
	},
	designDocument: function(inSender, inEvent) {
		this.syncEditedFiles();
		this.$.deimos.load(inEvent);
		this.$.panels.setIndex(this.deimosViewIndex);
		this.adjustBarMode();
		this.activeDocument.setCurrentIF('designer');
	},
	//* A code change happened in Phobos - push change to Deimos
	phobosUpdate: function(inSender, inEvent) {
		this.$.deimos.load(inEvent);
	},
	//* A design change happened in Deimos - push change to Phobos
	designerUpdate: function(inSender, inEvent) {
		if (inEvent && inEvent.docHasChanged) {
			this.$.phobos.updateComponents(inSender, inEvent);
		}
	},
	closeDesigner: function(inSender, inEvent) {
		this.designerUpdate(inSender, inEvent);
		this.$.panels.setIndex(this.phobosViewIndex);
		this.adjustBarMode();
		this.activeDocument.setCurrentIF('code');
	},
	//* Undo event from Deimos
	designerUndo: function(inSender, inEvent) {
		this.$.phobos.undoAndUpdate();
	},
	//* Redo event from Deimos
	designerRedo: function(inSender, inEvent) {
		this.$.phobos.redoAndUpdate();
	},
	handleBeforeUnload: function() {
		if (window.location.search.indexOf("debug") == -1) {
			return 'You may have some unsaved data';
		}
	},
	hideFiles: function(inSender, inEvent) {
		this.$.slideable.animateToMin();
	},
	showFiles: function(inSender, inEvent) {
		this.$.slideable.animateToMax();
	},
	toggleFiles: function(inSender, inEvent) {
		if (this.$.slideable.value < 0 || Ares.Workspace.files.length === 0) {
			this.showFiles();
		} else {
			this.hideFiles();
		}
	},
	resizeHandler: function(inSender, inEvent) {
		this.inherited(arguments);
		this.calcSlideableLimit();
		if (this.$.slideable.value < 0) {
			this.$.slideable.setValue(this.$.slideable.min);
		}
	},
	calcSlideableLimit: function() {
		var min = this.getBounds().height-this.$.bottomBar.getBounds().height;
		this.$.slideable.setMin(-min);
	},
	switchFile: function(inSender, inEvent) {
		var d = Ares.Workspace.files.get(inEvent.id);
		if (d) {
			this.switchToDocument(d);
		} else {
			alert("File ID not found in cache!");
		}
	},
	switchToDocument: function(d) {
		// We no longer save the data as the ACE edit session will keep the data for us
		if (!this.activeDocument || d !== this.activeDocument) {
			this.$.phobos.openDoc(d);
		}
		var currentIF = d.getCurrentIF();
		this.activeDocument = d;
		if (currentIF === 'code') {
			this.$.panels.setIndex(this.phobosViewIndex);
		} else {
			this.$.phobos.designerAction();
		}
		this.adjustBarMode();
		this.$.bottomBar.activateFileWithId(d.getId());
		this.hideFiles();
	},
	finishedSliding: function(inSender, inEvent) {
		if (this.$.slideable.value < 0) {
			this.$.bottomBar.showControls();
		} else {
			this.$.bottomBar.hideControls();
		}
	},
	// FIXME: This trampoline function probably needs some refactoring
	bounceSave: function(inSender, inEvent) {
		this.$.phobos.saveDocAction(inSender, inEvent);
	},
	// FIXME: This trampoline function probably needs some refactoring
	bounceDesign: function(inSender, inEvent) {
		var editorMode = this.$.panels.getIndex() == this.phobosViewIndex;
		if (editorMode) {
			this.$.phobos.designerAction(inSender, inEvent);
		} else {
			this.$.deimos.closeDesignerAction();
		}
	},
	adjustBarMode: function() {
		var designMode = this.$.panels.getIndex() == this.deimosViewIndex;
		this.$.bottomBar.setDesignMode(designMode);
	},
	// FIXME: This trampoline function probably needs some refactoring
	bounceNew: function(inSender, inEvent) {
		this.$.phobos.newKindAction(inSender, inEvent);
	},
	// FIXME: This trampoline function probably needs some refactoring
	// Close is a special case, because it can be invoked on a document other than the currently-active one
	bounceClose: function(inSender, inEvent) {
		this.switchFile(inSender, inEvent);
		enyo.asyncMethod(this.$.phobos, "closeDocAction");
	},
	//* Update code running in designer
	syncEditedFiles: function() {
		var files = Ares.Workspace.files,
			model,
			i;

		for(i=0;i<files.models.length;i++) {
			model = files.models[i];

			if(model.getFile().name === "package.js") {
				continue;
			}

			this.updateCode(files.get(model.id));
		}
	},
	updateCode: function(inDoc) {
		var filename = inDoc.getFile().path,
			code = inDoc.getAceSession().getValue();

		if(filename.slice(-4) === ".css") {
			doc = inDoc;
			this.syncCSSFile(filename, code);
		} else if(filename.slice(-3) === ".js") {
			this.syncJSFile(code);
		}
	},
	syncCSSFile: function(inFilename, inCode) {
		this.$.deimos.syncCSSFile(inFilename, inCode);
	},
	syncJSFile: function(inCode) {
		this.$.deimos.syncJSFile(inCode);
	},
	showWaitPopup: function(inSender, inEvent) {
		this.$.waitPopupMessage.setContent(inEvent.msg);
		this.$.waitPopup.show();
	},
	hideWaitPopup: function() {
		this.$.waitPopup.hide();
	},
	statics: {
		isBrowserSupported: function() {
			if (enyo.platform.ie && enyo.platform.ie <= 8) {
				return false;
			} else {
				return true;
			}
		},
		instance: null
	}
});
<|endoftext|>