<commit_before>define(["dojo/_base/declare", "ppwcode-util-contracts/_Mixin", "dojo/_base/lang", "dijit/registry", "dojo/dom-class",
        "dijit/_WidgetBase", "../../SemanticObject",
        "dijit/form/ValidationTextBox", "dojox/mvc/Output", "dojox/form/CheckedMultiSelect", "dijit/form/SimpleTextArea",
         "dijit/form/CheckBox",
         "xstyle/css!./_SemanticObjectPane.css"],
    function(declare, _ContractMixin, lang, registry, domClass,
             _WidgetBase, SemanticObject,
             ValidationTextBox, Output, CheckedMultiSelect, SimpleTextArea,
             CheckBox) {

      var presentationModes = [
        // presentationMode and stylePresentationMode for viewing the data. No interaction allowed.
        "VIEW",

        // presentationMode and stylePresentationMode for editing the data. Interaction allowed.
        "EDIT",

        // presentationMode and stylePresentationMode while the SemanticObject is busy. No interaction allowed.
        "BUSY",

        // presentationMode and stylePresentationMode representing unacceptable data (the object is
        // not civilized, or we have other means of knowing the data is unacceptable).
        // Interaction must be allowed to reset the object, or ammeliorate the data/
        // This means this is a sub-state of EDIT.
        "WILD",

        // presentationMode and stylePresentationMode representing an error occured. We cannot proceed. The widget
        // and its object must be destroyed.
        "ERROR"];

      var stylePresentationModes = presentationModes.slice(0); // copy
      // stylePresentationMode for when there is no target
      stylePresentationModes.push("NOTARGET");

      function setStylepresentationMode(sop, stylePresentationMode) {
        var domNode = sop.get("domNode");
        var innerWidgets = registry.findWidgets(domNode);
        var widgetState = null;
        //noinspection FallthroughInSwitchStatementJS
        switch (stylePresentationMode) {
          case _SemanticObjectPane.prototype.NOTARGET:
            widgetState = { readOnly:false, disabled:true };
            break;
          case _SemanticObjectPane.prototype.EDIT:
          case _SemanticObjectPane.prototype.WILD:
            widgetState = { readOnly:false, disabled:false };
            break;
          case _SemanticObjectPane.prototype.BUSY:
          case _SemanticObjectPane.prototype.ERROR:
            widgetState = { readOnly:false, disabled:true };
            break;
          default: // VIEW
            widgetState = { readOnly:true, disabled:false };
        }
        innerWidgets.forEach(function (w) {
          if (w.isInstanceOf(ValidationTextBox) || w.isInstanceOf(Output)
              || w.isInstanceOf(CheckedMultiSelect) || w.isInstanceOf(SimpleTextArea) || w.isInstanceOf(CheckBox)) {
            w.set("readOnly", widgetState.readOnly);
            w.set("disabled", widgetState.disabled);
          }
        });
        if (stylePresentationMode == _SemanticObjectPane.prototype.VIEW ||
            stylePresentationMode == _SemanticObjectPane.prototype.EDIT) {
          domClass.replace(domNode,
            "SemanticObjectPane_enabled",
            "SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
        }
        else if (stylePresentationMode == _SemanticObjectPane.prototype.BUSY) {
          domClass.replace(domNode,
            "SemanticObjectPane_busy",
            "SemanticObjectPane_enabled SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
        }
        else if (stylePresentationMode == _SemanticObjectPane.prototype.WILD) {
          domClass.replace(domNode,
            "SemanticObjectPane_wild",
            "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
        }
        else if (stylePresentationMode == _SemanticObjectPane.prototype.ERROR) {
          domClass.replace(domNode,
            "SemanticObjectPane_error",
            "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_notarget");
        }
        else { // NOTARGET
          domClass.replace(domNode,
            " SemanticObjectPane_notarget",
            "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_error SemanticObjectPane_disabled");
        }
      }

      var _SemanticObjectPane = declare([_WidgetBase, _ContractMixin], {
        // summary:
        //   Widget that represents a SemanticObject in detail, and that gives the opportunity
        //   to the user the view the details, edit the details, and create a new object.
        //   Abstract class to be extended for particular subtypes of SemanticObject.
        // description:
        //   What is common to all subtypes is that the widget:
        //   - has a `target` that is a SemanticObject; getTargetType() returns the top-most supported
        //     Constructor of supported targets. All targets must be instances of this type.
        //   - has an `presentationMode` (view, edit, busy, wild, error)
        //   - has a `stylePresentationMode`
        //
        //   The representation should reflect the presentationMode in a clear visual way to the user.
        //   This is the `stylePresentationModel`. It is the `presentationMode` if `target !== null`,
        //   and `NOTARGET` otherwise.
        //   Even when the information shown is completely read-only, widgets should extend
        //   this class, to change the representation of the displayed information consistently
        //   with other information in different presentationModes, e.g., in "busy" mode.
        //   The available presentation modes are defined in _SemanticObjectPane.prototype.presentationModes.
        //
        //   Instances can be wrapped around zero or more _SemanticObjectPanes, recursively (no loops!).
        //   We take care of propagating `presentationMode`. Subclasses need to override
        //   getWrappedDetails to return the wrapped details. All instances need to be instances of this class.
        //   The default implementation returns an empty array.
        //   The target of a wrapped detail might be the same target as our target, but it might be
        //   another related object, of a different type. set("target", ...) will call _propagateTarget, which is
        //   chained, so that subclasses can add propagation of setting the target. Our implementation only sets our
        //   target.
        //
        //   This class is concerned with presentation. Other classes might add presentation
        //   and functionality to support interaction with the user (save and cancel buttons, etc. -
        //   see e.g. ppwcode persistence).

        _c_invar: [
          function() {return this.get("presentationMode");},
          function() {return this.presentationModes.indexOf(this.get("presentationMode")) >= 0;},
          function() {return this.getTargetType() != null;},
          // TODO getTargetType is a subtype of SemanticObject
          function() {return this.get("target") == null ||
                        (this.get("target").isInstanceOf && this.get("target").isInstanceOf(this.getTargetType()));},
          function() {return this.get("stylePresentationMode");},
          function() {return this.stylePresentationModes.indexOf(this.get("stylePresentationMode")) >= 0;},
          function() {return (this.get("stylePresentationMode") === this.NOTARGET) === (this.get("target") === null);},
          function() {return this.get("target") !== null ? this.get("stylePresentationMode") === this.get("presentationMode") : true;},
          function() {return this._wrappedDetails() != null;},
          function() {return lang.isArray(this._wrappedDetails());},
          {
            objectSelector: function() {
              return this._wrappedDetails();
            },
            invars: [
              function(wd) {
                return wd && wd != null &&
                  wd.isInstanceOf && wd.isInstanceOf(_SemanticObjectPane);
              },
              // wrapped details might contain other objects of other types as target,
              // or null, but the presentationMode needs to be in sync. The stylePresentationMode
              // can differ.
              function(wd) {
                return wd.get("presentationMode") === this.get("presentationMode");
              }
            ]
          }
        ],

        "-chains-": {
          _propagateTarget: "after",
          _propagateOpener: "after",
          _localPresentationModeChange: "after"
        },

        // target: SemanticObject
        //    SemanticObject that is represented.
        //    Access in declarative template with  ... data-dojo-props="value: at('rel:', BINDING_PROPERTY_NAME)
        target: null,

        // presentationMode: String
        //    The presentation mode is either view, edit, busy, wild, or error
        presentationMode: stylePresentationModes[0], // default value

        // opener: Function
        //   Function that attempts to open a new "window" or "pane" for another PersistentObject
        //   (which is mostly linked to the current one)
        opener: null,

        widgetSize: 0,

        postCreate: function() {
          this.inherited(arguments);
          domClass.add(this.get("domNode"), "SemanticObjectPane");
        },

        // stylePresentationMode: String
        //    The stylePresentationMode is the same as the presentationMode, except when there is no target.
        //    Then it is NOTARGET.
        _getStylePresentationModeAttr: function() {
          return this.target ? this.get("presentationMode") : this.NOTARGET;
        },

        isInEditMode: function() {
          // summary:
          //    This is in a `stylePresentationMode` that allows the user to change the values, if there is a target and
          //    it is editable.
          return this.target &&
            (this.presentationMode === this.EDIT || this.presentationMode === this.BUSY || this.presentationMode === this.WILD);
        },

        _wrappedDetails: function() {
          // summary:
          //   Array containing the wrapped details, a subclass wants the presentationMode propagated to.
          // tags:
          //   protected

          return []; // return Array
        },

        getTargetType: function() {
          // summary:
          //    The supported type of SemanticObjects. All targets must be an instance of this type.
          // description:
          //    Subclasses should overwrite to return the correct type.

          return SemanticObject;
        },

        _propagateTarget: function(/*SemanticObject*/ so) {
          // summary:
          //   Propagate the target as appropriate to wrapped details.
          //   Chained. Subtypes could add propagation to wrapped details.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane.

          this._c_NOP(so);
        },

        _setTargetAttr: function(so) {
          // summary:
          //    Sets the target of this instance. Chained. Subtypes could add propagation to wrapped details.
          this._c_pre(function() {return so == null || (so.isInstanceOf && so.isInstanceOf(this.getTargetType()));});

          if (so !== this.get("target")) {
            this._set("target", so);
          }
          this._propagateTarget(so);
          this.set("presentationMode", so !== null && so.persistenceId === null ? this.EDIT : this.VIEW);
        },

        _propagateOpener: function(/*Function*/ opener) {
          // summary:
          //   Propagate the opener function as appropriate to wrapped details.
          //   Chained. Subtypes could add propagation to wrapped details.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane.

          this._c_NOP(opener);
        },

        _setOpenerAttr: function(opener) {
          if (opener !== this.get("opener")) {
            this._set("opener", opener);
          }
          this._propagateOpener(opener);
        },

        _setPresentationModeAttr: function(value) {
          // summary:
          //    Set the presentationMode, and propagate to the wrapped details.
          //    Also makes all innerWidgets read-only in presentationMode VIEW,
          //    disabled in presentationMode BUSY, and not-read-only and enabled
          //    in the other presentationModes.

          // Called during create by _WidgetBase with default value automatically
          this._c_pre(function() {return value != null});
          this._c_pre(function() {return _SemanticObjectPane.prototype.presentationModes.indexOf(value) >= 0});

          this._set("presentationMode", value);
          this._wrappedDetails().forEach(function(wd) {
            wd.set("presentationMode", value);
          });
          var myDomNode = this.get("domNode");
          var stylePresentationMode = this.get("stylePresentationMode");
          setStylepresentationMode(this, stylePresentationMode);
          this._localPresentationModeChange(value);
        },

        _localPresentationModeChange: function(/*String*/ presentationMode) {
          // summary:
          //   Make changes to representation to represent the
          //   new edit mode. Chained. Overwrite when needed.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane

          this._c_NOP(presentationMode);
        },

        getWidgetSize: function() {
          return this.widgetSize;
        }

      });

      // All supported presentationModes
      _SemanticObjectPane.prototype.presentationModes = presentationModes;
      // All supported stylePresentationModes
      _SemanticObjectPane.prototype.stylePresentationModes = stylePresentationModes;
      stylePresentationModes.forEach(function(em) {
        _SemanticObjectPane.prototype[em] = em;
      });

      return _SemanticObjectPane; // return _SemanticObjectPane

    });
<commit_msg>Bugfix: SimlpleTextArea is renamed to SimpleTextarea. The case was wrong.<commit_after>define(["dojo/_base/declare", "ppwcode-util-contracts/_Mixin", "dojo/_base/lang", "dijit/registry", "dojo/dom-class",
        "dijit/_WidgetBase", "../../SemanticObject",
        "dijit/form/ValidationTextBox", "dojox/mvc/Output", "dojox/form/CheckedMultiSelect", "dijit/form/SimpleTextarea",
         "dijit/form/CheckBox",
         "xstyle/css!./_SemanticObjectPane.css"],
    function(declare, _ContractMixin, lang, registry, domClass,
             _WidgetBase, SemanticObject,
             ValidationTextBox, Output, CheckedMultiSelect, SimpleTextarea,
             CheckBox) {

      var presentationModes = [
        // presentationMode and stylePresentationMode for viewing the data. No interaction allowed.
        "VIEW",

        // presentationMode and stylePresentationMode for editing the data. Interaction allowed.
        "EDIT",

        // presentationMode and stylePresentationMode while the SemanticObject is busy. No interaction allowed.
        "BUSY",

        // presentationMode and stylePresentationMode representing unacceptable data (the object is
        // not civilized, or we have other means of knowing the data is unacceptable).
        // Interaction must be allowed to reset the object, or ammeliorate the data/
        // This means this is a sub-state of EDIT.
        "WILD",

        // presentationMode and stylePresentationMode representing an error occured. We cannot proceed. The widget
        // and its object must be destroyed.
        "ERROR"];

      var stylePresentationModes = presentationModes.slice(0); // copy
      // stylePresentationMode for when there is no target
      stylePresentationModes.push("NOTARGET");

      function setStylepresentationMode(sop, stylePresentationMode) {
        var domNode = sop.get("domNode");
        var innerWidgets = registry.findWidgets(domNode);
        var widgetState = null;
        //noinspection FallthroughInSwitchStatementJS
        switch (stylePresentationMode) {
          case _SemanticObjectPane.prototype.NOTARGET:
            widgetState = { readOnly:false, disabled:true };
            break;
          case _SemanticObjectPane.prototype.EDIT:
          case _SemanticObjectPane.prototype.WILD:
            widgetState = { readOnly:false, disabled:false };
            break;
          case _SemanticObjectPane.prototype.BUSY:
          case _SemanticObjectPane.prototype.ERROR:
            widgetState = { readOnly:false, disabled:true };
            break;
          default: // VIEW
            widgetState = { readOnly:true, disabled:false };
        }
        innerWidgets.forEach(function (w) {
          if (w.isInstanceOf(ValidationTextBox) || w.isInstanceOf(Output)
              || w.isInstanceOf(CheckedMultiSelect) || w.isInstanceOf(SimpleTextarea) || w.isInstanceOf(CheckBox)) {
            w.set("readOnly", widgetState.readOnly);
            w.set("disabled", widgetState.disabled);
          }
        });
        if (stylePresentationMode == _SemanticObjectPane.prototype.VIEW ||
            stylePresentationMode == _SemanticObjectPane.prototype.EDIT) {
          domClass.replace(domNode,
            "SemanticObjectPane_enabled",
            "SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
        }
        else if (stylePresentationMode == _SemanticObjectPane.prototype.BUSY) {
          domClass.replace(domNode,
            "SemanticObjectPane_busy",
            "SemanticObjectPane_enabled SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
        }
        else if (stylePresentationMode == _SemanticObjectPane.prototype.WILD) {
          domClass.replace(domNode,
            "SemanticObjectPane_wild",
            "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_disabled SemanticObjectPane_error SemanticObjectPane_notarget");
        }
        else if (stylePresentationMode == _SemanticObjectPane.prototype.ERROR) {
          domClass.replace(domNode,
            "SemanticObjectPane_error",
            "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_disabled SemanticObjectPane_notarget");
        }
        else { // NOTARGET
          domClass.replace(domNode,
            " SemanticObjectPane_notarget",
            "SemanticObjectPane_enabled SemanticObjectPane_busy SemanticObjectPane_wild SemanticObjectPane_error SemanticObjectPane_disabled");
        }
      }

      var _SemanticObjectPane = declare([_WidgetBase, _ContractMixin], {
        // summary:
        //   Widget that represents a SemanticObject in detail, and that gives the opportunity
        //   to the user the view the details, edit the details, and create a new object.
        //   Abstract class to be extended for particular subtypes of SemanticObject.
        // description:
        //   What is common to all subtypes is that the widget:
        //   - has a `target` that is a SemanticObject; getTargetType() returns the top-most supported
        //     Constructor of supported targets. All targets must be instances of this type.
        //   - has an `presentationMode` (view, edit, busy, wild, error)
        //   - has a `stylePresentationMode`
        //
        //   The representation should reflect the presentationMode in a clear visual way to the user.
        //   This is the `stylePresentationModel`. It is the `presentationMode` if `target !== null`,
        //   and `NOTARGET` otherwise.
        //   Even when the information shown is completely read-only, widgets should extend
        //   this class, to change the representation of the displayed information consistently
        //   with other information in different presentationModes, e.g., in "busy" mode.
        //   The available presentation modes are defined in _SemanticObjectPane.prototype.presentationModes.
        //
        //   Instances can be wrapped around zero or more _SemanticObjectPanes, recursively (no loops!).
        //   We take care of propagating `presentationMode`. Subclasses need to override
        //   getWrappedDetails to return the wrapped details. All instances need to be instances of this class.
        //   The default implementation returns an empty array.
        //   The target of a wrapped detail might be the same target as our target, but it might be
        //   another related object, of a different type. set("target", ...) will call _propagateTarget, which is
        //   chained, so that subclasses can add propagation of setting the target. Our implementation only sets our
        //   target.
        //
        //   This class is concerned with presentation. Other classes might add presentation
        //   and functionality to support interaction with the user (save and cancel buttons, etc. -
        //   see e.g. ppwcode persistence).

        _c_invar: [
          function() {return this.get("presentationMode");},
          function() {return this.presentationModes.indexOf(this.get("presentationMode")) >= 0;},
          function() {return this.getTargetType() != null;},
          // TODO getTargetType is a subtype of SemanticObject
          function() {return this.get("target") == null ||
                        (this.get("target").isInstanceOf && this.get("target").isInstanceOf(this.getTargetType()));},
          function() {return this.get("stylePresentationMode");},
          function() {return this.stylePresentationModes.indexOf(this.get("stylePresentationMode")) >= 0;},
          function() {return (this.get("stylePresentationMode") === this.NOTARGET) === (this.get("target") === null);},
          function() {return this.get("target") !== null ? this.get("stylePresentationMode") === this.get("presentationMode") : true;},
          function() {return this._wrappedDetails() != null;},
          function() {return lang.isArray(this._wrappedDetails());},
          {
            objectSelector: function() {
              return this._wrappedDetails();
            },
            invars: [
              function(wd) {
                return wd && wd != null &&
                  wd.isInstanceOf && wd.isInstanceOf(_SemanticObjectPane);
              },
              // wrapped details might contain other objects of other types as target,
              // or null, but the presentationMode needs to be in sync. The stylePresentationMode
              // can differ.
              function(wd) {
                return wd.get("presentationMode") === this.get("presentationMode");
              }
            ]
          }
        ],

        "-chains-": {
          _propagateTarget: "after",
          _propagateOpener: "after",
          _localPresentationModeChange: "after"
        },

        // target: SemanticObject
        //    SemanticObject that is represented.
        //    Access in declarative template with  ... data-dojo-props="value: at('rel:', BINDING_PROPERTY_NAME)
        target: null,

        // presentationMode: String
        //    The presentation mode is either view, edit, busy, wild, or error
        presentationMode: stylePresentationModes[0], // default value

        // opener: Function
        //   Function that attempts to open a new "window" or "pane" for another PersistentObject
        //   (which is mostly linked to the current one)
        opener: null,

        widgetSize: 0,

        postCreate: function() {
          this.inherited(arguments);
          domClass.add(this.get("domNode"), "SemanticObjectPane");
        },

        // stylePresentationMode: String
        //    The stylePresentationMode is the same as the presentationMode, except when there is no target.
        //    Then it is NOTARGET.
        _getStylePresentationModeAttr: function() {
          return this.target ? this.get("presentationMode") : this.NOTARGET;
        },

        isInEditMode: function() {
          // summary:
          //    This is in a `stylePresentationMode` that allows the user to change the values, if there is a target and
          //    it is editable.
          return this.target &&
            (this.presentationMode === this.EDIT || this.presentationMode === this.BUSY || this.presentationMode === this.WILD);
        },

        _wrappedDetails: function() {
          // summary:
          //   Array containing the wrapped details, a subclass wants the presentationMode propagated to.
          // tags:
          //   protected

          return []; // return Array
        },

        getTargetType: function() {
          // summary:
          //    The supported type of SemanticObjects. All targets must be an instance of this type.
          // description:
          //    Subclasses should overwrite to return the correct type.

          return SemanticObject;
        },

        _propagateTarget: function(/*SemanticObject*/ so) {
          // summary:
          //   Propagate the target as appropriate to wrapped details.
          //   Chained. Subtypes could add propagation to wrapped details.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane.

          this._c_NOP(so);
        },

        _setTargetAttr: function(so) {
          // summary:
          //    Sets the target of this instance. Chained. Subtypes could add propagation to wrapped details.
          this._c_pre(function() {return so == null || (so.isInstanceOf && so.isInstanceOf(this.getTargetType()));});

          if (so !== this.get("target")) {
            this._set("target", so);
          }
          this._propagateTarget(so);
          this.set("presentationMode", so !== null && so.persistenceId === null ? this.EDIT : this.VIEW);
        },

        _propagateOpener: function(/*Function*/ opener) {
          // summary:
          //   Propagate the opener function as appropriate to wrapped details.
          //   Chained. Subtypes could add propagation to wrapped details.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane.

          this._c_NOP(opener);
        },

        _setOpenerAttr: function(opener) {
          if (opener !== this.get("opener")) {
            this._set("opener", opener);
          }
          this._propagateOpener(opener);
        },

        _setPresentationModeAttr: function(value) {
          // summary:
          //    Set the presentationMode, and propagate to the wrapped details.
          //    Also makes all innerWidgets read-only in presentationMode VIEW,
          //    disabled in presentationMode BUSY, and not-read-only and enabled
          //    in the other presentationModes.

          // Called during create by _WidgetBase with default value automatically
          this._c_pre(function() {return value != null});
          this._c_pre(function() {return _SemanticObjectPane.prototype.presentationModes.indexOf(value) >= 0});

          this._set("presentationMode", value);
          this._wrappedDetails().forEach(function(wd) {
            wd.set("presentationMode", value);
          });
          var myDomNode = this.get("domNode");
          var stylePresentationMode = this.get("stylePresentationMode");
          setStylepresentationMode(this, stylePresentationMode);
          this._localPresentationModeChange(value);
        },

        _localPresentationModeChange: function(/*String*/ presentationMode) {
          // summary:
          //   Make changes to representation to represent the
          //   new edit mode. Chained. Overwrite when needed.
          // tags:
          //   protected
          // description:
          //   Does nothing in _SemanticObjectPane

          this._c_NOP(presentationMode);
        },

        getWidgetSize: function() {
          return this.widgetSize;
        }

      });

      // All supported presentationModes
      _SemanticObjectPane.prototype.presentationModes = presentationModes;
      // All supported stylePresentationModes
      _SemanticObjectPane.prototype.stylePresentationModes = stylePresentationModes;
      stylePresentationModes.forEach(function(em) {
        _SemanticObjectPane.prototype[em] = em;
      });

      return _SemanticObjectPane; // return _SemanticObjectPane

    });
<|endoftext|>


<commit_before>(function() {
  var _game;

  var Player = function(game, options) {
    options = options || {};
    _game = game;
    this.element = game.add.isoSprite(
      options.x || 0,
      options.y || 0,
      options.z || 0,
      'kid',
      0,
      options.group || null
    );
    this.onBombMounted = options.onBombMounted || null;
    this.onExplosion = options.onExplosion || null;
    // this.element.tint = options.tint || 0;

    this.element.anchor.set(0.5);
    // window.foobar = this.element;
    game.physics.isoArcade.enable(this.element);
    this.element.body.collideWorldBounds = true;
    this.canLeaveBomb = true;
    this.cursors = null;

    this.element.anchor.set(0.5,0.5);
    this.element.animations.add('2-walk', [1,2,3,4,5,6], 6, true);
    this.element.animations.add('3-walk', [7,8,9,8], 6, true);
    this.element.animations.add('6-walk', [17, 18, 19, 20, 21], 6, true);
    this.element.animations.add('8-walk', [11, 12, 13, 14, 15, 16], 6, true);
    this.element.animations.add('9-walk', [26, 25, 24, 25], 6, true);
    this.element.animations.play('6-walk');
  };

  Player.prototype = {
    get: function() {
      return this.element;
    },
    move: function(cursors, speed) {
      if(!this.cursors) {
        this.cursors = cursors;
        this.cursors.jump.onDown.add(fire.bind(this));
      }

      var direction = [0,0],
          magnitude;
      if (cursors.up.isDown) {
        direction[0]--;
        direction[1]--;
      }
      if (cursors.down.isDown) {
        direction[0]++;
        direction[1]++;
      }
      if (cursors.left.isDown) {
        direction[0]--;
        direction[1]++;
      }
      if (cursors.right.isDown) {
        direction[0]++;
        direction[1]--;
      }

      // computing animation
      this.element.scale.set(1,1,1);
      if (direction[0] === 1 && direction[1] === 1) {
        this.element.animations.play('2-walk');
      } else if (direction[0] === -1 && direction[1] === -1) {
        this.element.animations.play('8-walk');
      } else if (direction[0] === -1 && direction[1] === 1) {
        this.element.animations.play('6-walk');
        this.element.scale.set(-1,1,1);
      } else if (direction[0] === 1 && direction[1] === -1) {
        this.element.animations.play('6-walk');
      } else if (direction[0] === 1 && direction[1] === 0) {
        this.element.animations.play('9-walk');
        this.scale.set(-1,1,1);
      }

      // computing unit vector of the direction...
      magnitude = Math.sqrt(Math.pow(direction[0],2) + Math.pow(direction[1],2));
      direction = [direction[0]/magnitude, direction[1]/magnitude];
      this.element.body.velocity.x = direction[0]*speed;
      this.element.body.velocity.y = direction[1]*speed;
    }
  };

  function fire() {
    if(this.canLeaveBomb) {
      var player = this.element;
      var x = player.isoPosition.x;
      var y = player.isoPosition.y;
      var row = Math.floor(x / 65);
      var col = Math.floor(y / 65);

      if(this.onBombMounted) {
        this.onBombMounted({row:row, col:col});
      }

      this.canLeaveBomb = false;
      setTimeout(function() {
        if(this.onExplosion) {
          this.onExplosion({x: x, y: y});
        }
        this.canLeaveBomb = true;
      }.bind(this), 3000);
    }
  }

  window.Player = Player;
}).call(document);
<commit_msg>animated robots<commit_after>(function() {
  var _game;

  var Player = function(game, options) {
    options = options || {};
    _game = game;
    this.element = game.add.isoSprite(
      options.x || 0,
      options.y || 0,
      options.z || 0,
      'kid',
      0,
      options.group || null
    );
    this.onBombMounted = options.onBombMounted || null;
    this.onExplosion = options.onExplosion || null;
    // this.element.tint = options.tint || 0;

    this.element.anchor.set(0.5);
    // window.foobar = this.element;
    game.physics.isoArcade.enable(this.element);
    this.element.body.collideWorldBounds = true;
    this.canLeaveBomb = true;
    this.cursors = null;

    this.element.anchor.set(0.5,0.5);
    this.element.animations.add('stand', [0]);
    this.element.animations.add('2-walk', [1,2,3,4,5,6], 6, true);
    this.element.animations.add('3-walk', [7,8,9,8], 6, true);
    this.element.animations.add('6-walk', [17, 18, 19, 20, 21], 6, true);
    this.element.animations.add('8-walk', [11, 12, 13, 14, 15, 16], 6, true);
    this.element.animations.add('9-walk', [26, 25, 24, 25], 6, true);
    this.element.animations.play('6-walk');
  };

  Player.prototype = {
    get: function() {
      return this.element;
    },
    move: function(cursors, speed) {
      if(!this.cursors) {
        this.cursors = cursors;
        this.cursors.jump.onDown.add(fire.bind(this));
      }

      var direction = [0,0],
          magnitude;
      if (cursors.up.isDown) {
        direction[0]--;
        direction[1]--;
      }
      if (cursors.down.isDown) {
        direction[0]++;
        direction[1]++;
      }
      if (cursors.left.isDown) {
        direction[0]--;
        direction[1]++;
      }
      if (cursors.right.isDown) {
        direction[0]++;
        direction[1]--;
      }

      // computing animation
      this.element.scale.set(1,1,1);
      if (direction[0] === 1 && direction[1] === 1) {
        this.element.animations.play('2-walk');
      } else if (direction[0] === -1 && direction[1] === -1) {
        this.element.animations.play('8-walk');
      } else if (direction[0] === -1 && direction[1] === 1) {
        this.element.animations.play('6-walk');
        this.element.scale.set(-1,1,1);
      } else if (direction[0] === 1 && direction[1] === -1) {
        this.element.animations.play('6-walk');
      } else if (direction[0] === 1 && direction[1] === 0) {
        this.element.animations.play('9-walk');
        this.scale.set(-1,1,1);
      } else if (direction[0] === 0 && direction[1] === 0) {
        this.element.animations.play('stand');
      }

      // computing unit vector of the direction...
      magnitude = Math.sqrt(Math.pow(direction[0],2) + Math.pow(direction[1],2));
      direction = [direction[0]/magnitude, direction[1]/magnitude];
      // so player will always move with a consistent speed
      this.element.body.velocity.x = direction[0]*speed;
      this.element.body.velocity.y = direction[1]*speed;
    }
  };

  function fire() {
    if(this.canLeaveBomb) {
      var player = this.element;
      var x = player.isoPosition.x;
      var y = player.isoPosition.y;
      var row = Math.floor(x / 65);
      var col = Math.floor(y / 65);

      if(this.onBombMounted) {
        this.onBombMounted({row:row, col:col});
      }

      this.canLeaveBomb = false;
      setTimeout(function() {
        if(this.onExplosion) {
          this.onExplosion({x: x, y: y});
        }
        this.canLeaveBomb = true;
      }.bind(this), 3000);
    }
  }

  window.Player = Player;
}).call(document);
<|endoftext|>


<commit_before>$(document).ready(function(){
    $("#domain").keyup(function(event){
        if(event.keyCode == 13){
            $("#submit").click();
        }
    });
});
window.onload = function() {
//Counts the number of requests in this session
    var requestNum = 0;
    //Choose the correct script to run based on dropdown selection
    document.getElementById("submit").onclick = function callRoute() {
            returnDnsDetails(document.getElementById("domain").value, document.getElementById("file").value, document.getElementById("port").value)
    }

    function requestTitle(callType){
        switch(callType){
            case "txt":
                return "SPF/TXT Lookup";
                break;
            case "mx":
                return "MX Lookup";
                break;
            case "a":
                return "IP Lookup";
                break;
            case "all":
                return "All available DNS records";
                break;
            case "aaaa":
                return "IPV6 Lookup";
                break;
            case "whois":
                return "Who Is Lookup";
                break;
            case "hinfo":
                return "H Info Lookup";
                break;
            case "blacklist":
                return "Blacklist Lookup";
                break;
            case "port":
                return "Ports Lookup";
                break;
            case "reverseLookup":
                return "Host Lookup";
                break;
        }
    }

    //Get DNS Details
    function returnDnsDetails(domain, callType, port) {
        //checks for valid input
        if (domain.length == 0) {
            document.getElementById("txtHint").innerHTML = " Please enter a valid domain";
            return;
        } else {
            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function () {
                var date = new Date();
                if (this.readyState == 4 && this.status == 200) {
                    //Clears the hint field
                    document.getElementById("txtHint").innerHTML = "";
                    document.getElementById("loading").innerHTML= '';
                    //parse the response into a JS Object
                    dnsResp = JSON.parse(this.responseText);
                    console.log(this.responseText);
                    buildTable(dnsResp, callType);
                }
            }
            document.getElementById("loading").innerHTML = '

'
            xmlhttp.open("GET", "operations?domain=" + domain + "&request=" + callType + "&port=" + port, true);
            xmlhttp.send();

        }
    }

    function buildTable(jsonResp, callType) {
        var requestNum = Date.now();
        if (jsonResp.length == 0) {
            $(".responseTable").prepend("

");
            $(".responseRow" + requestNum + " Table").append("
" + requestTitle(callType) + "
");
            $(".responseRow" + requestNum + " Table").append("
NO DATA FOUND
");
        } else {

            //creates thes the table to store the response details each table has a unique class
            $(".responseTable").prepend("

");
            //Creates title bar
            $(".responseRow" + requestNum + " Table").append("
" + requestTitle(callType) + "
");

            for (i = 0, len = jsonResp.length; i < len; i++) {
                var jsonData = jsonResp[i];

                if (i != 0) {$(".responseRow" + (requestNum-1)).append("

");}
                //iterates through object keys
                if(callType === "blacklist.php"){
                    for (j = 0, len2 = Object.keys(jsonData).length; j < len2; j++) {
                        $(".responseRow" + requestNum + " Table").append("
" + Object.getOwnPropertyNames(jsonData)[j] + ":	" + jsonData[Object.keys(jsonData)[j]] + "
");
                    }

                } else {
                    for (j = 0, len2 = Object.keys(jsonData).length; j < len2; j++) {
                        $(".responseRow" + requestNum + " Table").append("
" + Object.getOwnPropertyNames(jsonData)[j] + ":	" + cleanString(jsonData[Object.keys(jsonData)[j]].toString()) + "
");
                    }
                }
                requestNum++;
            }

        }
    }

    function cleanString(data) {
        return data
            .replace(/&/g, "&")
            .replace(/</g, "<")
            .replace(/>/g, ">")
            .replace(/"/g, """)
            .replace(/'/g, "'");
     }

}

function showAdditionalFields() {
    if(document.getElementById("file").value === 'port') {
        document.getElementById("port-container").style.visibility="visible" ;
    } else {
        document.getElementById("port-container").style.visibility="hidden";
    }
}<commit_msg>Avoid debug tools code in production<commit_after>$(document).ready(function(){
    $("#domain").keyup(function(event){
        if(event.keyCode == 13){
            $("#submit").click();
        }
    });
});
window.onload = function() {
//Counts the number of requests in this session
    var requestNum = 0;
    //Choose the correct script to run based on dropdown selection
    document.getElementById("submit").onclick = function callRoute() {
            returnDnsDetails(document.getElementById("domain").value, document.getElementById("file").value, document.getElementById("port").value)
    }

    function requestTitle(callType){
        switch(callType){
            case "txt":
                return "SPF/TXT Lookup";
                break;
            case "mx":
                return "MX Lookup";
                break;
            case "a":
                return "IP Lookup";
                break;
            case "all":
                return "All available DNS records";
                break;
            case "aaaa":
                return "IPV6 Lookup";
                break;
            case "whois":
                return "Who Is Lookup";
                break;
            case "hinfo":
                return "H Info Lookup";
                break;
            case "blacklist":
                return "Blacklist Lookup";
                break;
            case "port":
                return "Ports Lookup";
                break;
            case "reverseLookup":
                return "Host Lookup";
                break;
        }
    }

    //Get DNS Details
    function returnDnsDetails(domain, callType, port) {
        //checks for valid input
        if (domain.length == 0) {
            document.getElementById("txtHint").innerHTML = " Please enter a valid domain";
            return;
        } else {
            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function () {
                var date = new Date();
                if (this.readyState == 4 && this.status == 200) {
                    //Clears the hint field
                    document.getElementById("txtHint").innerHTML = "";
                    document.getElementById("loading").innerHTML= '';
                    //parse the response into a JS Object
                    dnsResp = JSON.parse(this.responseText);
                    buildTable(dnsResp, callType);
                }
            }
            document.getElementById("loading").innerHTML = '

'
            xmlhttp.open("GET", "operations?domain=" + domain + "&request=" + callType + "&port=" + port, true);
            xmlhttp.send();

        }
    }

    function buildTable(jsonResp, callType) {
        var requestNum = Date.now();
        if (jsonResp.length == 0) {
            $(".responseTable").prepend("

");
            $(".responseRow" + requestNum + " Table").append("
" + requestTitle(callType) + "
");
            $(".responseRow" + requestNum + " Table").append("
NO DATA FOUND
");
        } else {

            //creates thes the table to store the response details each table has a unique class
            $(".responseTable").prepend("

");
            //Creates title bar
            $(".responseRow" + requestNum + " Table").append("
" + requestTitle(callType) + "
");

            for (i = 0, len = jsonResp.length; i < len; i++) {
                var jsonData = jsonResp[i];

                if (i != 0) {$(".responseRow" + (requestNum-1)).append("

");}
                //iterates through object keys
                if(callType === "blacklist.php"){
                    for (j = 0, len2 = Object.keys(jsonData).length; j < len2; j++) {
                        $(".responseRow" + requestNum + " Table").append("
" + Object.getOwnPropertyNames(jsonData)[j] + ":	" + jsonData[Object.keys(jsonData)[j]] + "
");
                    }

                } else {
                    for (j = 0, len2 = Object.keys(jsonData).length; j < len2; j++) {
                        $(".responseRow" + requestNum + " Table").append("
" + Object.getOwnPropertyNames(jsonData)[j] + ":	" + cleanString(jsonData[Object.keys(jsonData)[j]].toString()) + "
");
                    }
                }
                requestNum++;
            }

        }
    }

    function cleanString(data) {
        return data
            .replace(/&/g, "&")
            .replace(/</g, "<")
            .replace(/>/g, ">")
            .replace(/"/g, """)
            .replace(/'/g, "'");
     }

}

function showAdditionalFields() {
    if(document.getElementById("file").value === 'port') {
        document.getElementById("port-container").style.visibility="visible" ;
    } else {
        document.getElementById("port-container").style.visibility="hidden";
    }
}
<|endoftext|>


<commit_before>
var gulp = require('gulp');
var runSequence = require('run-sequence');

require('gulp-command')(gulp);

var gulpConfig = require('../../../gulpConfig.js');
var uglifyCompression = gulpConfig.uglifyCompression;

gulp.task('dev', function (callback) {
	return runSequence(
		['copy:appStatic', 'copy:imajsServer', 'copy:environment', 'shim', 'polyfill'],
		['Es6ToEs5:app', 'Es6ToEs5:server', 'Es6ToEs5:vendor'],
		['less', 'doc', 'locale', 'Es6ToEs5:vendor:client', 'Es6ToEs5:vendor:server'],
		['server'],
		['devTest', 'watch'],
		callback
	);
});

gulp
	.option('build', '-e, --env', 'Build environment')
	.task('build', function (callback) {

		if (this.flags.env === 'prod') {
			uglifyCompression.global_defs.$Debug = false;
		}
		return runSequence(
			['copy:appStatic', 'copy:imajsServer', 'copy:environment', 'shim', 'polyfill'], // copy public folder, concat shim
			['Es6ToEs5:app', 'Es6ToEs5:server', 'Es6ToEs5:vendor'], // compile app and vendor script
			['less', 'doc', 'locale', 'Es6ToEs5:vendor:client', 'Es6ToEs5:vendor:server'], // adjust vendors, compile less, create doc
			['bundle:js:app', 'bundle:js:server', 'bundle:css'],
			['bundle:clean', 'Es6ToEs5:vendor:clean'],// clean vendor
			callback
		);
	});
<commit_msg>The build tasks now executes the bundle and clean tasks only when building the application for prod or test environment<commit_after>
var gulp = require('gulp');
var runSequence = require('run-sequence');

require('gulp-command')(gulp);

var gulpConfig = require('../../../gulpConfig.js');
var uglifyCompression = gulpConfig.uglifyCompression;

gulp.task('dev', function (callback) {
	return runSequence(
		['copy:appStatic', 'copy:imajsServer', 'copy:environment', 'shim', 'polyfill'],
		['Es6ToEs5:app', 'Es6ToEs5:server', 'Es6ToEs5:vendor'],
		['less', 'doc', 'locale', 'Es6ToEs5:vendor:client', 'Es6ToEs5:vendor:server'],
		['server'],
		['devTest', 'watch'],
		callback
	);
});

gulp
	.option('build', '-e, --env', 'Build environment')
	.task('build', function (callback) {

		if (this.flags.env === 'prod') {
			uglifyCompression.global_defs.$Debug = false;
		}

		var tasks = [
			['copy:appStatic', 'copy:imajsServer', 'copy:environment', 'shim', 'polyfill'], // copy public folder, concat shim
			['Es6ToEs5:app', 'Es6ToEs5:server', 'Es6ToEs5:vendor'], // compile app and vendor script
			['less', 'doc', 'locale', 'Es6ToEs5:vendor:client', 'Es6ToEs5:vendor:server'] // adjust vendors, compile less, create doc
		];
		if (['prod', 'test'].indexOf(this.flags.env) > -1) {
			tasks.push(
				['bundle:js:app', 'bundle:js:server', 'bundle:css'],
				['bundle:clean', 'Es6ToEs5:vendor:clean'] // clean vendor
			);
		}
		tasks.push(callback);

		return runSequence.apply(null, tasks);
	});
<|endoftext|>


<commit_before>var fs = require('fs');
var gea = require('green-bean');
var devices = require('./chillhub-devices');
var firebase = require("firebase");
var util = require("util");
var fb = require('./firebaseHelper.js');

var configFile = "./share/chillhub.json";
var hwVersion = '1.0.0';
var swVersion = '1.0.0';

var messageRelay = function(data) {
   console.log("<---- In messageRelay ---->");
	console.log(data);
/*
	var myFirebaseRef = new Firebase("https://intense-heat-7203.firebaseio.com/homes/home1/devices" +
		data.devId + "/status");

	myFirebaseRef.set(data);
*/
};

var deviceAnnounce = function(devlist) {
   console.log("<---- In deviceAnnounce ---->");
	console.log(devlist);
/*
	var myFirebaseRef = new Firebase("https://intense-heat-7203.firebaseio.com/homes/home1/devices");

	myFirebaseRef.set(devlist);
*/
};

var messageBroadcast = function(data) {
   console.log("<---- In messageBroadcast ---->");
/*
	for (var field in data)
		devices.subscriberBroadcast(field, data[field]);
*/
};

// open connection to firebase
fb.startConnection(configFile, hwVersion, swVersion, function(e, attachments) {
   if (e) {
      console.log("Error connecting to firebase.");
   } else {
      // got our attachment point
      console.log("Connected to firebase, initializing devices.");
      devices.init(messageRelay, deviceAnnounce, attachments);
   }
});

/*
gea.connect('refrigerator', function(refrigerator) {
	console.log('connected to fridge!');

	refrigerator.filterAlert.subscribe(messageBroadcast);
	refrigerator.filterExpirationStatus.subscribe(messageBroadcast);
	refrigerator.commandFeatures.subscribe(messageBroadcast);
	refrigerator.temperatureAlert.subscribe(messageBroadcast);
	refrigerator.displayTemperature.subscribe(function(data) {
		for (var field in data)
			devices.subscriberBroadcast(field+'Display', data[field]);
	});
	refrigerator.setpointTemperature.subscribe(function(data) {
		for (var field in data)
			devices.subscriberBroadcast(field+'Setpoint', data[field]);
	});
	refrigerator.doorAlarmAlert.subscribe(messageBroadcast);
	refrigerator.iceMakerBucketStatus.subscribe(messageBroadcast);
	refrigerator.odorFilterExpirationStatus.subscribe(messageBroadcast);
	refrigerator.doorState.subscribe(messageBroadcast);
	refrigerator.doorBoard.information.subscribe(messageBroadcast);

	console.log('subscribed to all fridge events');
});
*/
<commit_msg>Dynamically loading SW version from package.json.<commit_after>// Packages...
var fs = require('fs');
var gea = require('green-bean');
var devices = require('./chillhub-devices');
var firebase = require("firebase");
var util = require("util");
var fb = require('./firebaseHelper.js');
// Configs
var packageFile = "./package.json";
var configFile = "./share/chillhub.json";
var hwVersion = '1.0.0';

var messageRelay = function(data) {
   console.log("<---- In messageRelay ---->");
	console.log(data);
};

var deviceAnnounce = function(devlist) {
   console.log("<---- In deviceAnnounce ---->");
	console.log(devlist);
}

var messageBroadcast = function(data) {
   console.log("<---- In messageBroadcast ---->");
};

var startFirebase = function(swVersion) {
   console.log("Sending this SW version to firebase: " + swVersion);
   fb.startConnection(configFile, hwVersion, swVersion, function(e, attachments) {
      if (e) {
         console.log("Error connecting to firebase.");
      } else {
         // got our attachment point
         console.log("Connected to firebase, initializing devices.");
         devices.init(messageRelay, deviceAnnounce, attachments);
      }
   });
}

fs.readFile(packageFile, function(e, data) {
   var ver = "UNKNOWN";
   if (e) {
      console.log("Error opening " + packageFile + ".");
      printError(e);
   } else {
      console.log("Package file opened.");
      var obj = JSON.parse(data);
      if (obj.version) {
         ver = obj.version;
         console.log("Found software version: " + ver);
      } else {
         console.log("Unable to find the chillhub firmware version in " + packageFile + ".");
      }
   }
   startFirebase(ver);
});

/*
gea.connect('refrigerator', function(refrigerator) {
	console.log('connected to fridge!');

	refrigerator.filterAlert.subscribe(messageBroadcast);
	refrigerator.filterExpirationStatus.subscribe(messageBroadcast);
	refrigerator.commandFeatures.subscribe(messageBroadcast);
	refrigerator.temperatureAlert.subscribe(messageBroadcast);
	refrigerator.displayTemperature.subscribe(function(data) {
		for (var field in data)
			devices.subscriberBroadcast(field+'Display', data[field]);
	});
	refrigerator.setpointTemperature.subscribe(function(data) {
		for (var field in data)
			devices.subscriberBroadcast(field+'Setpoint', data[field]);
	});
	refrigerator.doorAlarmAlert.subscribe(messageBroadcast);
	refrigerator.iceMakerBucketStatus.subscribe(messageBroadcast);
	refrigerator.odorFilterExpirationStatus.subscribe(messageBroadcast);
	refrigerator.doorState.subscribe(messageBroadcast);
	refrigerator.doorBoard.information.subscribe(messageBroadcast);

	console.log('subscribed to all fridge events');
});
*/
<|endoftext|>


<commit_before>/*
This file is part of Kronekeeper, a web based application for
recording and managing wiring frame records.

Copyright (C) 2016 NP Broadcast Limited

Kronekeeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Kronekeeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Kronekeeper.  If not, see <http://www.gnu.org/licenses/>.

*/

require([
	'frame/remove_block',
	'frame/title',
	'frame/frame_menu',
	'backbone',
        'jquery',
	'jqueryui'
], function (
	remove_block,
	title
) {
        'use strict';

	/* Keep track of the block we are associated with */
	var jq_block = null;

	/* Initialise the menus and associated events */
	$("#block_menu").menu({
		select: handle_block_menu_selection
	});
	$(".block .menu_button a").on("click", show_block_menu);

	function show_block_menu(e) {

		e.stopPropagation();

		/* Set global block_id - which block opened the menu? */
		jq_block = $(e.target).closest("td");

		set_allowed_menu_options( );
		$("#block_menu").menu("collapseAll", null, true);
		$("#block_menu").menu().show().position({
			my: "left top",
			at: "left bottom",
			of: this,
			collision: "fit flip"
		});

		/* Clicking outside the menu closes it */
		$(document).on("click", function() {
			$("#block_menu").menu().hide();
			$("#block_menu").menu("collapseAll", null, true);
		});
	};

	function set_allowed_menu_options() {

		enable_menu_action_if_true(
			"open",
			!jq_block.hasClass("is_free") && !jq_block.hasClass("unavailable")
		);
		enable_menu_action_if_true(
			"place_submenu",
			jq_block.hasClass("is_free") && !jq_block.hasClass("unavailable")
		);
		enable_menu_action_if_true(
			"remove",
			!jq_block.hasClass("is_free") && !jq_block.hasClass("unavailable")
		);
	}

	function enable_menu_action_if_true(action, t) {

		var selector = "li[data-action='" + action + "']";
		var elements = $("#block_menu").find(selector);

		if(t) {
			elements.removeClass("ui-state-disabled");
		}
		else {
			elements.addClass("ui-state-disabled");
		}
	}

	function handle_block_menu_selection(e, jq_element) {

		switch(e.currentTarget.dataset.action) {

			case "open" :
				jq_block.find("a.link")[0].click();
				break;

			case "place" :
				place_block(
					jq_block.data("block_id"),
					e.currentTarget.dataset.block_type
				);
				break;

			case "remove" :
				$("#block_menu").menu().hide();
				remove_block.activate({
					block_id: jq_block.data("block_id"),
					success: function () {
						jq_block.removeClass("in_use");
						jq_block.addClass("is_free");
						jq_block.find("span.name").first().text("unused");
						console.log("finished removing block");
					}
				});
				break;
		}

	}

	function place_block(block_id, block_type){

		console.log("placing", block_type, "at block_id", block_id);
		var url = '/api/frame/place_block';
		var data = {
			block_id: block_id,
			block_type: block_type
		};

		$.ajax({
			url: url,
			type: "POST",
			contentType: 'application/json; charset=utf-8',
			data: JSON.stringify(data),
			dataType: "json",
			success: function(json) {
				console.log("placed block ok");
				jq_block.removeClass("is_free");
				jq_block.addClass("in_use");
				jq_block.find("span.name").first().text("");
			},
			error: function(xhr, status) {
				var error_code = xhr.status + " " + xhr.statusText;
				alert("ERROR placing block: " + error_code);
			}
		});
	}

	var title_view = new title.view({
		model: new title.model(window.frame_info)
	});

	console.log("loaded frame.js");
});

<commit_msg>Frame view: dynamically update after block removal<commit_after>/*
This file is part of Kronekeeper, a web based application for
recording and managing wiring frame records.

Copyright (C) 2016 NP Broadcast Limited

Kronekeeper is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Kronekeeper is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with Kronekeeper.  If not, see <http://www.gnu.org/licenses/>.

*/

require([
	'frame/remove_block',
	'frame/title',
	'frame/frame_menu',
	'backbone',
        'jquery',
	'jqueryui'
], function (
	remove_block,
	title
) {
        'use strict';

	/* Keep track of the block we are associated with */
	var jq_block = null;

	/* Initialise the menus and associated events */
	$("#block_menu").menu({
		select: handle_block_menu_selection
	});
	$(".block .menu_button a").on("click", show_block_menu);

	function show_block_menu(e) {

		e.stopPropagation();

		/* Set global block_id - which block opened the menu? */
		jq_block = $(e.target).closest("td");

		set_allowed_menu_options( );
		$("#block_menu").menu("collapseAll", null, true);
		$("#block_menu").menu().show().position({
			my: "left top",
			at: "left bottom",
			of: this,
			collision: "fit flip"
		});

		/* Clicking outside the menu closes it */
		$(document).on("click", function() {
			$("#block_menu").menu().hide();
			$("#block_menu").menu("collapseAll", null, true);
		});
	};

	function set_allowed_menu_options() {

		enable_menu_action_if_true(
			"open",
			!jq_block.hasClass("is_free") && !jq_block.hasClass("unavailable")
		);
		enable_menu_action_if_true(
			"place_submenu",
			jq_block.hasClass("is_free") && !jq_block.hasClass("unavailable")
		);
		enable_menu_action_if_true(
			"remove",
			!jq_block.hasClass("is_free") && !jq_block.hasClass("unavailable")
		);
	}

	function enable_menu_action_if_true(action, t) {

		var selector = "li[data-action='" + action + "']";
		var elements = $("#block_menu").find(selector);

		if(t) {
			elements.removeClass("ui-state-disabled");
		}
		else {
			elements.addClass("ui-state-disabled");
		}
	}

	function handle_block_menu_selection(e, jq_element) {

		switch(e.currentTarget.dataset.action) {

			case "open" :
				jq_block.find("a.link")[0].click();
				break;

			case "place" :
				place_block(
					jq_block.data("block_id"),
					e.currentTarget.dataset.block_type
				);
				break;

			case "remove" :
				$("#block_menu").menu().hide();
				remove_block.activate({
					block_id: jq_block.data("block_id"),
					success: function () {
						jq_block.removeClass("in_use");
						jq_block.removeAttr("style");
						jq_block.addClass("is_free");
						jq_block.find("span.name").first().text("unused");
						jq_block.find("div.block_type").first().text("");
						console.log("finished removing block");
					}
				});
				break;
		}

	}

	function place_block(block_id, block_type){

		console.log("placing", block_type, "at block_id", block_id);
		var url = '/api/frame/place_block';
		var data = {
			block_id: block_id,
			block_type: block_type
		};

		$.ajax({
			url: url,
			type: "POST",
			contentType: 'application/json; charset=utf-8',
			data: JSON.stringify(data),
			dataType: "json",
			success: function(json) {
				console.log("placed block ok");
				jq_block.removeClass("is_free");
				jq_block.addClass("in_use");
				jq_block.find("span.name").first().text("");
			},
			error: function(xhr, status) {
				var error_code = xhr.status + " " + xhr.statusText;
				alert("ERROR placing block: " + error_code);
			}
		});
	}

	var title_view = new title.view({
		model: new title.model(window.frame_info)
	});

	console.log("loaded frame.js");
});

<|endoftext|>


<commit_before>'use strict';

(function () {

  function argsToArray (args) {
    return Array.prototype.slice.call(args);
  }

  function getNodeProperties (args, getChildren) {
    var argsArray = argsToArray(args);
    var name = argsArray.shift();
    var options = argsArray.shift() || {};

    var properties = {
      name: name,
      options: options
    };

    if (getChildren) {
      properties.children = argsArray;
    }

    return properties;
  }

  function validateName (name) {
    if (typeof name !== 'string') {
      throw new Error('Names and aliases must be a string');
    }

    if (!name) {
      throw new Error('Names and aliases cannot be empty');
    }

    if (name.indexOf(' ') >= 0) {
      throw new Error('Names and aliases cannot contain spaces');
    }

    if (name.indexOf('-') === 0) {
      throw new Error('Names and aliases cannot begin with \'-\'');
    }
  }

  function serializeOptions (options, validOptions) {
    for (var key in options) {
      var option = options[key];

      if (!(key in validOptions)) {
        throw new Error('Invalid option \'' + key + '\'');
      }

      if (key === 'alias') {
        validateName(option);
      }

      var valid = validOptions[key];

      if (
        (valid.type === 'string' && typeof option !== 'string') ||
        (valid.type === 'number' && typeof option !== 'number') ||
        (valid.type === 'object' && (typeof option !== 'object' || option === null)) ||
        (valid.type === 'array' && !Array.isArray(option)) ||
        (valid.type === 'boolean' && typeof option !== 'boolean')
      ) {
        throw new Error('Option ' + key + ' must be of type ' + valid.type);
      }
    }
  }

  function throwError (error) {
    process.stderr.write(error + '\n\n');
    process.exit(1);
  }

  function find (arr, fn) {
    for (var i = 0; i < arr.length; i += 1) {
      if (fn(arr[i], i)) {
        return arr[i];
      }
    }

    return null;
  }

  function each (arr, fn) {
    for (var i = 0; i < arr.length; i += 1) {
      fn(arr[i], i);
    }
  }

  module.exports = {
    argsToArray: argsToArray,
    getNodeProperties: getNodeProperties,
    validateName: validateName,
    serializeOptions: serializeOptions,
    throwError: throwError,
    find: find,
    each: each
  };

})();
<commit_msg>Throw error in getNodeProperties if unwelcome children provided<commit_after>'use strict';

(function () {

  function argsToArray (args) {
    return Array.prototype.slice.call(args);
  }

  function getNodeProperties (args, getChildren) {
    var argsArray = argsToArray(args);
    var name = argsArray.shift();
    var options = argsArray.shift() || {};

    var properties = {
      name: name,
      options: options
    };

    if (getChildren) {
      properties.children = argsArray;
    } else if (argsArray.length) {
      throw new Error('Only commands can have children');
    }

    return properties;
  }

  function validateName (name) {
    if (typeof name !== 'string') {
      throw new Error('Names and aliases must be a string');
    }

    if (!name) {
      throw new Error('Names and aliases cannot be empty');
    }

    if (name.indexOf(' ') >= 0) {
      throw new Error('Names and aliases cannot contain spaces');
    }

    if (name.indexOf('-') === 0) {
      throw new Error('Names and aliases cannot begin with \'-\'');
    }
  }

  function serializeOptions (options, validOptions) {
    for (var key in options) {
      var option = options[key];

      if (!(key in validOptions)) {
        throw new Error('Invalid option \'' + key + '\'');
      }

      if (key === 'alias') {
        validateName(option);
      }

      var valid = validOptions[key];

      if (
        (valid.type === 'string' && typeof option !== 'string') ||
        (valid.type === 'number' && typeof option !== 'number') ||
        (valid.type === 'object' && (typeof option !== 'object' || option === null)) ||
        (valid.type === 'array' && !Array.isArray(option)) ||
        (valid.type === 'boolean' && typeof option !== 'boolean')
      ) {
        throw new Error('Option ' + key + ' must be of type ' + valid.type);
      }
    }
  }

  function throwError (error) {
    process.stderr.write(error + '\n\n');
    process.exit(1);
  }

  function find (arr, fn) {
    for (var i = 0; i < arr.length; i += 1) {
      if (fn(arr[i], i)) {
        return arr[i];
      }
    }

    return null;
  }

  function each (arr, fn) {
    for (var i = 0; i < arr.length; i += 1) {
      fn(arr[i], i);
    }
  }

  module.exports = {
    argsToArray: argsToArray,
    getNodeProperties: getNodeProperties,
    validateName: validateName,
    serializeOptions: serializeOptions,
    throwError: throwError,
    find: find,
    each: each
  };

})();
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   MySystem.nodesController
// Copyright: ©2010 Concord Consortium
// ==========================================================================
/*globals MySystem */

/** @class

  The whole set of nodes in the system.

  @extends SC.Object
*/
MySystem.nodesController = SC.ArrayController.create( SC.CollectionViewDelegate,
/** @scope MySystem.nodesController.prototype */ {

  // the in-progress links originating and ending terminals
  dragLinkSrcTerminal:     null,
  dragLinkEndTerminal:     null,

  // FIXME dummy method for backward compatibility
  unselectAll: function() {
    this.deselectObjects(this.get('selection'));
  },

  collectionViewDeleteContent: function (view, content, indices) {
    // destroy the records
    var recordsToDestroy = indices.map( function (idx) {
      return this.objectAt(idx);
    }, this);

    recordsToDestroy.invoke('destroy');
  },

  collectionViewSelectionForProposedSelection: function(view, sel) {
    // Is this a shift-click?
    if (view.get('mouseDownInfo') && view.get('mouseDownInfo').event.shiftKey) {
      return null ; // No change to selection
    }
    else {
      return sel ; // Accept new selected set
    }
  },

  propertyEditing: function() {
    MySystem.statechart.sendEvent('diagramSelectionChanged', { });
  }.observes('selection'),

  // If the selection changes on nodes or links, grab the diagramView layer and call focus().
  // This forces the browser focus back onto the application, which ensures that
  // keyboard and other events are properly directed here if we are embedding in an iframe.
  //
  // We need to focus again on every selection change, to account for an author who is
  // going back and forth between an author iframe and preview iframe.
  //
  // Having it here is a bit of a hack, and there might be some more stardard way of dealing
  // with the issue that the selection of svg elements doesn't cause browser to track focus.
  focusMainPaneOnSelectionChange: function() {
    if (MySystem.mainPage.getPath('mainPane.diagramView') && MySystem.mainPage.getPath('mainPane.diagramView').get('layer')){
      MySystem.mainPage.getPath('mainPane.diagramView').get('layer').focus();
    }
  }.observes('selection')
});
<commit_msg>Revert that... focussing on diagram makes iFrame bug reappear.... >:(<commit_after>// ==========================================================================
// Project:   MySystem.nodesController
// Copyright: ©2010 Concord Consortium
// ==========================================================================
/*globals MySystem */

/** @class

  The whole set of nodes in the system.

  @extends SC.Object
*/
MySystem.nodesController = SC.ArrayController.create( SC.CollectionViewDelegate,
/** @scope MySystem.nodesController.prototype */ {

  // the in-progress links originating and ending terminals
  dragLinkSrcTerminal:     null,
  dragLinkEndTerminal:     null,

  // FIXME dummy method for backward compatibility
  unselectAll: function() {
    this.deselectObjects(this.get('selection'));
  },

  collectionViewDeleteContent: function (view, content, indices) {
    // destroy the records
    var recordsToDestroy = indices.map( function (idx) {
      return this.objectAt(idx);
    }, this);

    recordsToDestroy.invoke('destroy');
  },

  collectionViewSelectionForProposedSelection: function(view, sel) {
    // Is this a shift-click?
    if (view.get('mouseDownInfo') && view.get('mouseDownInfo').event.shiftKey) {
      return null ; // No change to selection
    }
    else {
      return sel ; // Accept new selected set
    }
  },

  propertyEditing: function() {
    MySystem.statechart.sendEvent('diagramSelectionChanged', { });
  }.observes('selection'),

  // If the selection changes on nodes or links, grab the top layer and call focus().
  // This forces the browser focus back onto the application, which ensures that
  // keyboard and other events are properly directed here if we are embedding in an iframe.
  //
  // We need to focus again on every selection change, to account for an author who is
  // going back and forth between an author iframe and preview iframe.
  //
  // Having it here is a bit of a hack, and there might be some more stardard way of dealing
  // with the issue that the selection of svg elements doesn't cause browser to track focus.
  focusMainPaneOnSelectionChange: function() {
    if (MySystem.mainPage.getPath('mainPane.diagramView') && MySystem.mainPage.getPath('mainPane.diagramView').get('layer')){
      MySystem.mainPage.getPath('mainPane').get('layer').focus();
    }
  }.observes('selection')
});
<|endoftext|>


<commit_before>define( function( require ) {

    'use strict';

	var Postmonger = require( 'postmonger' );
	var $ = require( 'vendor/jquery.min' );

    var connection = new Postmonger.Session();
    var toJbPayload = {};
    var step = 1;
	var endpoints;

    $(window).ready(onRender);

    connection.on('initActivity', function(payload) {
        var amount;

        if (payload) {
            toJbPayload = payload;
            console.log('payload',payload);

			//merge the array of objects.
			var aArgs = toJbPayload['arguments'].execute.inArguments;
			var oArgs = {};
			for (var i=0; i<aArgs.length; i++) {
				for (var key in aArgs[i]) {
					oArgs[key] = aArgs[i][key];
				}
			}
			//oArgs.amount will contain a value if this activity has already been configured:
			amount = oArgs.amount || toJbPayload['configurationArguments'].defaults.amount;
        }

		$.get( "/version", function( data ) {
			$('#version').html('Version: ' + data.version);
		});

        // If there is no amount selected, disable the next button
        if (!amount) {
            connection.trigger('updateButton', { button: 'next', enabled: false });
        }

		$('#selectAmount').find('option[value='+ amount +']').attr('selected', 'selected');
		gotoStep(step);

    });

    connection.on('requestedEndpoints', function(data) {
		if( data.error ) {
			console.error( data.error );
		} else {
			endpoints = data;
            console.log("endpoints",data);
		}
    });

    connection.on('clickedNext', function() {
        step++;
        gotoStep(step);
        connection.trigger('ready');
    });

    connection.on('clickedBack', function() {
        step--;
        gotoStep(step);
        connection.trigger('ready');
    });

    function onRender() {
        connection.trigger('ready');
        connection.trigger('requestEndpoints');

        // Disable the next button if a value isn't selected
		/*
        $('#selectValueTier').change(function() {
            var valueTier = getValueTier();
            var type = getType();
            var bonus = getBonus();
            var valid = Boolean(valueTier) && Boolean(bonus) && Boolean(type);
            connection.trigger('updateButton', { button: 'next', enabled: valid });
        });

        $('#selectType').change(function() {
            var valueTier = getValueTier();
            var type = getType();
            var bonus = getBonus();
            var valid = Boolean(valueTier) && Boolean(bonus) && Boolean(type);
            connection.trigger('updateButton', { button: 'next', enabled: valid });
        });

        $('#selectBonus').change(function() {
            var valueTier = getValueTier();
            var type = getType();
            var bonus = getBonus();
            var valid = Boolean(valueTier) && Boolean(bonus) && Boolean(type);
            connection.trigger('updateButton', { button: 'next', enabled: valid });
        });
*/
		connection.trigger('updateButton', { button: 'next', enabled: true});

    };

    function gotoStep(step) {
        $('.step').hide();
        switch(step) {
            case 1:
                $('#step1').show();
                //var valueTier = getValueTier();
                //var type = getType();
                //var bonus = getBonus();
                //var valid = Boolean(valueTier) && Boolean(bonus) && Boolean(type);
                connection.trigger('updateButton', { button: 'next', text: 'done', visible: true });
                connection.trigger('updateButton', { button: 'back', visible: false });
                break;
				/*
            case 2:
                $('#step2').show();
                $('#showValueTier').html(getValueTierText());
                $('#showType').html(getTypeText());
                $('#showBonus').html(getBonusText());
                connection.trigger('updateButton', { button: 'back', visible: true });
                connection.trigger('updateButton', { button: 'next', text: 'done', visible: true });
                break;
            case 3: // Only 2 steps, so the equivalent of 'done' - send off the payload
			*/
			default:
                save();
                break;
        }
    };

    function getValueTier() {
        return $('#selectValueTier').find('option:selected').attr('value').trim();
    };
    function getType() {
        return $('#selectType').find('option:selected').attr('value').trim();
    };
    function getBonus() {
        return $('#selectBonus').find('option:selected').attr('value').trim();
    };

    function getValueTierText() {
        return $('#selectValueTier').find('option:selected').text().trim();
    };
    function getTypeText() {
        return $('#selectType').find('option:selected').text().trim();
    };
    function getBonusText() {
        return $('#selectBonus').find('option:selected').text().trim();
    };

    function save() {

        var valueTier = getValueTier();
        var type = getType();
        var bonus = getBonus();

        // toJbPayload is initialized on populateFields above.  Journey Builder sends an initial payload with defaults
        // set by this activity's config.json file.  Any property may be overridden as desired.
        //toJbPayload.name = "my activity";

        //this will be sent into the custom activity body within the inArguments array.
        toJbPayload['arguments'].execute.inArguments.push({"valueTier": valueTier});
        toJbPayload['arguments'].execute.inArguments.push({"type": type});
        toJbPayload['arguments'].execute.inArguments.push({"bonus": bonus});

		/*
        toJbPayload['metaData'].things = 'stuff';
        toJbPayload['metaData'].icon = 'path/to/icon/set/from/iframe/icon.png';
        toJbPayload['configurationArguments'].version = '1.1'; // optional - for 3rd party to track their customActivity.js version
        toJbPayload['configurationArguments'].partnerActivityId = '49198498';
        toJbPayload['configurationArguments'].myConfiguration = 'configuration coming from iframe';
		*/

		toJbPayload.metaData.isConfigured = true;  //this is required by JB to set the activity as Configured.
        connection.trigger('updateActivity', toJbPayload);
    };

});

<commit_msg>updated initactivity()<commit_after>define( function( require ) {

    'use strict';

	var Postmonger = require( 'postmonger' );
	var $ = require( 'vendor/jquery.min' );

    var connection = new Postmonger.Session();
    var toJbPayload = {};
    var step = 1;
	var endpoints;

    $(window).ready(onRender);

    connection.on('initActivity', function(payload) {
        var amount;

        if (payload) {
            toJbPayload = payload;
            console.log('payload',payload);

			//merge the array of objects.
			var aArgs = toJbPayload['arguments'].execute.inArguments;
			var oArgs = {};
			for (var i=0; i<aArgs.length; i++) {
				for (var key in aArgs[i]) {
					oArgs[key] = aArgs[i][key];
				}
			}
			//oArgs.amount will contain a value if this activity has already been configured:
			amount = oArgs.amount || toJbPayload['configurationArguments'].defaults.amount;
        }

		$.get( "/version", function( data ) {
			$('#version').html('Version: ' + data.version);
		});

        // If there is no amount selected, disable the next button
		/*
        if (!amount) {
            connection.trigger('updateButton', { button: 'next', enabled: false });
        }

		$('#selectAmount').find('option[value='+ amount +']').attr('selected', 'selected');
		*/

		connection.trigger('updateButton', { button: 'next', enabled: false });
		gotoStep(step);

    });

    connection.on('requestedEndpoints', function(data) {
		if( data.error ) {
			console.error( data.error );
		} else {
			endpoints = data;
            console.log("endpoints",data);
		}
    });

    connection.on('clickedNext', function() {
        step++;
        gotoStep(step);
        connection.trigger('ready');
    });

    connection.on('clickedBack', function() {
        step--;
        gotoStep(step);
        connection.trigger('ready');
    });

    function onRender() {
        connection.trigger('ready');
        connection.trigger('requestEndpoints');

        // Disable the next button if a value isn't selected
		/*
        $('#selectValueTier').change(function() {
            var valueTier = getValueTier();
            var type = getType();
            var bonus = getBonus();
            var valid = Boolean(valueTier) && Boolean(bonus) && Boolean(type);
            connection.trigger('updateButton', { button: 'next', enabled: valid });
        });

        $('#selectType').change(function() {
            var valueTier = getValueTier();
            var type = getType();
            var bonus = getBonus();
            var valid = Boolean(valueTier) && Boolean(bonus) && Boolean(type);
            connection.trigger('updateButton', { button: 'next', enabled: valid });
        });

        $('#selectBonus').change(function() {
            var valueTier = getValueTier();
            var type = getType();
            var bonus = getBonus();
            var valid = Boolean(valueTier) && Boolean(bonus) && Boolean(type);
            connection.trigger('updateButton', { button: 'next', enabled: valid });
        });
*/
		connection.trigger('updateButton', { button: 'next', enabled: true});

    };

    function gotoStep(step) {
        $('.step').hide();
        switch(step) {
            case 1:
                $('#step1').show();
                //var valueTier = getValueTier();
                //var type = getType();
                //var bonus = getBonus();
                //var valid = Boolean(valueTier) && Boolean(bonus) && Boolean(type);
                connection.trigger('updateButton', { button: 'next', text: 'done', visible: true });
                connection.trigger('updateButton', { button: 'back', visible: false });
                break;
				/*
            case 2:
                $('#step2').show();
                $('#showValueTier').html(getValueTierText());
                $('#showType').html(getTypeText());
                $('#showBonus').html(getBonusText());
                connection.trigger('updateButton', { button: 'back', visible: true });
                connection.trigger('updateButton', { button: 'next', text: 'done', visible: true });
                break;
            case 3: // Only 2 steps, so the equivalent of 'done' - send off the payload
			*/
			default:
                save();
                break;
        }
    };

    function getValueTier() {
        return $('#selectValueTier').find('option:selected').attr('value').trim();
    };
    function getType() {
        return $('#selectType').find('option:selected').attr('value').trim();
    };
    function getBonus() {
        return $('#selectBonus').find('option:selected').attr('value').trim();
    };

    function getValueTierText() {
        return $('#selectValueTier').find('option:selected').text().trim();
    };
    function getTypeText() {
        return $('#selectType').find('option:selected').text().trim();
    };
    function getBonusText() {
        return $('#selectBonus').find('option:selected').text().trim();
    };

    function save() {

        var valueTier = getValueTier();
        var type = getType();
        var bonus = getBonus();

        // toJbPayload is initialized on populateFields above.  Journey Builder sends an initial payload with defaults
        // set by this activity's config.json file.  Any property may be overridden as desired.
        //toJbPayload.name = "my activity";

        //this will be sent into the custom activity body within the inArguments array.
        toJbPayload['arguments'].execute.inArguments.push({"valueTier": valueTier});
        toJbPayload['arguments'].execute.inArguments.push({"type": type});
        toJbPayload['arguments'].execute.inArguments.push({"bonus": bonus});

		/*
        toJbPayload['metaData'].things = 'stuff';
        toJbPayload['metaData'].icon = 'path/to/icon/set/from/iframe/icon.png';
        toJbPayload['configurationArguments'].version = '1.1'; // optional - for 3rd party to track their customActivity.js version
        toJbPayload['configurationArguments'].partnerActivityId = '49198498';
        toJbPayload['configurationArguments'].myConfiguration = 'configuration coming from iframe';
		*/

		toJbPayload.metaData.isConfigured = true;  //this is required by JB to set the activity as Configured.
        connection.trigger('updateActivity', toJbPayload);
    };

});

<|endoftext|>


<commit_before>/**
 * This is the mock binary which allows to 'start' fake APIs by serving the
 * data in the mockify database.
 */

'use strict';

var argv        = require('minimist')(process.argv.slice(2)),
    _           = require('lodash'),
    _s          = require('underscore.string'),
    express     = require('express'),
    bodyParser  = require('body-parser'),
    router      = express.Router(),
    db          = require('../lib/db')(),
    targetId    = argv.targetId;

/**
 * Write log on stdout/stderr.
 */
var log = function (message) {
  process.stdout.write('[mock-out] ' + message + '\n');
};

var logError = function (message) {
  process.stderr.write('[mock-error] ' + message + '\n');
};

var logResponse = function (message) {
  process.stdout.write('[mock-response] ' + message + '\n');
};

/**
 * Express app with an in-memory database which will be used to mock data.
 */
var runApp = function (target, db) {
  var mockData = (function () {
    return function (req, res) {
      // search a record for the current query
      db.model('Record').find({
        method: req.method,
        url: req.url,
        parameters: JSON.stringify(req.body),
        targetId: target.id
      }, function (err, responses) {
        if (err) {
          log('An error has occurred when fetching data. ' + err);
          res.status(500).send(err);
        } else {
          var response = _.first(responses);

          if (!response) {
            response.status = 404;
            res.status(404).send('No response has been found.');

          } else {
            // set headers
            _.forEach(response.resHeaders, function (value, key) {
              res.setHeader(key, value);
            });

            res.setHeader('X-mockify-rowuuid', response.uuid);

            res
              .status(response.status || 500)
              .send(response.body || 'empty body');

            var message = [
              response.status,
              response.method,
              'localhost:' + target.port,
              response.url
            ].join(';');

            logResponse(message);
          }
        }
      });
    };
  })();

  router.route('/*').all(mockData);

  var app = express();

  app
    .set('port', target.port)
    // to support JSON-encoded bodies()
    .use(bodyParser.json())
    // to support URL-encoded bodies
    .use(bodyParser.urlencoded({
      extended: true
    }))
    .use(router)
    .listen(app.get('port'), function () {
      var message = _s.sprintf('%s %d %s %s',
        'Mock listening on port',
        app.get('port'),
        'and mocking the target ID:',
        targetId
      );

      log(message);
    });
};

// search Target in DB
db.whenReady().then(function () {
  if (!targetId) {
    log('The target has not been set.');
  }

  db.model('Target').get(targetId, function (err, target_) {
    if (err) {
      logError('An error has occurred when fetching data. ' +  err);
      process.exit(1);
    }

    // dump the database in memory, used for this process
    db.toMemory(function (err, db_) {
      if (err) {
        logError('err ' + err);
        process.exit(1);
      }

      // run the Express app with the target row and the in-memory database
      runApp(target_, db_);
    });
  });
});
<commit_msg>Rename some stuff and log recordId.<commit_after>/**
 * This is the mock binary which allows to 'start' fake APIs by serving the
 * data in the mockify database.
 */

'use strict';

var argv        = require('minimist')(process.argv.slice(2)),
    _           = require('lodash'),
    _s          = require('underscore.string'),
    express     = require('express'),
    bodyParser  = require('body-parser'),
    router      = express.Router(),
    db          = require('../lib/db')(),
    targetId    = argv.targetId;

/**
 * Write log on stdout/stderr.
 */
var log = function (message) {
  process.stdout.write('[mock-out] ' + message + '\n');
};

var logError = function (message) {
  process.stderr.write('[mock-error] ' + message + '\n');
};

var logMessage = function (message) {
  process.stdout.write('[mock-response] ' + message + '\n');
};

/**
 * Express app with an in-memory database which will be used to mock data.
 */
var runApp = function (target, db) {
  var mockData = (function () {
    return function (req, res) {
      // search a record for the current query
      db.model('Record').find({
        method: req.method,
        url: req.url,
        parameters: JSON.stringify(req.body),
        targetId: target.id
      }, function (err, records) {
        if (err) {
          log('An error has occurred when fetching data. ' + err);
          res.status(500).send(err);
        } else {
          var record = _.first(records);

          if (!record) {
            record.status = 404;
            res.status(404).send('No record has been found.');

          } else {
            // set headers
            _.forEach(record.resHeaders, function (value, key) {
              res.setHeader(key, value);
            });

            res.setHeader('X-mockify-rowuuid', record.uuid);

            res
              .status(record.status || 500)
              .send(record.body || 'empty body');

            var message = [
              record.status,
              record.method,
              'localhost:' + target.port,
              record.url,
              record.id
            ].join(';');

            logMessage(message);
          }
        }
      });
    };
  })();

  router.route('/*').all(mockData);

  var app = express();

  app
    .set('port', target.port)
    // to support JSON-encoded bodies()
    .use(bodyParser.json())
    // to support URL-encoded bodies
    .use(bodyParser.urlencoded({
      extended: true
    }))
    .use(router)
    .listen(app.get('port'), function () {
      var message = _s.sprintf('%s %d %s %s',
        'Mock listening on port',
        app.get('port'),
        'and mocking the target ID:',
        targetId
      );

      log(message);
    });
};

// search Target in DB
db.whenReady().then(function () {
  if (!targetId) {
    log('The target has not been set.');
  }

  db.model('Target').get(targetId, function (err, target_) {
    if (err) {
      logError('An error has occurred when fetching data. ' +  err);
      process.exit(1);
    }

    // dump the database in memory, used for this process
    db.toMemory(function (err, db_) {
      if (err) {
        logError('err ' + err);
        process.exit(1);
      }

      // run the Express app with the target row and the in-memory database
      runApp(target_, db_);
    });
  });
});
<|endoftext|>


<commit_before>/*
 * This file contains all the authentication logic for the Khan Academy Contest Judging System
 */
window.Authentication_Logic = (function() {
	if (!Firebase || !jQuery) {
		console.log("[Authentication_Logic] Firebase and jQuery are both required!");
		return;
	}

	return {
		doesUserExist: function(authData, callback) {
			var fbRef = new Firebase("https://contest-judging-sys.firebaseio.com");
			var usersRef = fbRef.child("users");

			var knownUsers = { };

			usersRef.orderByKey().on("child_added", function(snapshot) {
				knownUsers[snapshot.key()] = snapshot.val();
			});

			usersRef.once("value", function() {
				/* If this user's UID was found in knownUsers... */
				if (knownUsers.hasOwnProperty(authData.uid)) {
					/* ...pass true to our callback! */
					callback(true);
				} else {
					/* ...pass false into our callback. */
					callback(true);
				}
			});
		},
		userHasCorrectPermissions: function(uid, requiredPerms, callback) {
			var fbRef = new Firebase("https://contest-judging-sys.firebaseio.com");
			var usersRef = fbRef.child("users");

			var thisUser = { };

			usersRef.orderByKey().equalTo(uid).on("child_added", function(snapshot) {
				thisUser = snapshot.val();
			});

			usersRef.once("value", function() {
				/* Pass a boolean value to our callback. The boolean is determined based on whether or not the user has the permission level that is required for a certain task. */
				callback(thisUser.permLevel === requiredPerms);
			});
		}
	};
})();<commit_msg>Added more functions to authentication wrapper<commit_after>/*
 * This file contains all the authentication logic for the Khan Academy Contest Judging System
 */
window.Authentication_Logic = (function() {
	if (!Firebase || !jQuery || !Contest_Judging_System) {
		console.log("[Authentication_Logic] Firebase and jQuery are both required!");
		return;
	}

	return {
		doesUserExist: function(authData, callback) {
			var fbRef = new Firebase("https://contest-judging-sys.firebaseio.com");
			var usersRef = fbRef.child("users");

			var knownUsers = { };

			usersRef.orderByKey().on("child_added", function(snapshot) {
				knownUsers[snapshot.key()] = snapshot.val();
			});

			usersRef.once("value", function() {
				/* If this user's UID was found in knownUsers... */
				if (knownUsers.hasOwnProperty(authData.uid)) {
					/* ...pass true to our callback! */
					callback(true);
				} else {
					/* ...pass false into our callback. */
					callback(true);
				}
			});
		},
		createUser: function(userData) {
			var fbRef = new Firebase("https://contest-judging-sys.firebaseio.com");
			var usersRef = fbRef.child("users");

			usersRef.child(userData.uid).set({
				name: userData.google.displayName,
				permLevel: 1
			});
		},
		logUserIn: function(callback) {
			var fbRef = new Firebase("https://contest-judging-sys.firebaseio.com");

			fbRef.authWithOAuthPopup("google", function(error, authData) {
				/* If an error occurred, log the error to the console, and pass false to our callback. */
				if (error) {
					console.log(error);
					callback(false);
				}

				Authentication_Logic.doesUserExist(authData, function(doTheyExist) {
					if (doTheyExist) {
						Contest_Judging_System.setCookie("loggedInUID", authData.uid);
					} else {
						/* The user doesn't exist. Sign them up? */
						Authentication_Logic.createUser(authData);
						Contest_Judging_System.setCookie("loggedInUID", authData.uid);
					}
				});
			});
		},
		userHasCorrectPermissions: function(uid, requiredPerms, callback) {
			var fbRef = new Firebase("https://contest-judging-sys.firebaseio.com");
			var usersRef = fbRef.child("users");

			var thisUser = { };

			usersRef.orderByKey().equalTo(uid).on("child_added", function(snapshot) {
				thisUser = snapshot.val();
			});

			usersRef.once("value", function() {
				/* Pass a boolean value to our callback. The boolean is determined based on whether or not the user has the permission level that is required for a certain task. */
				callback(thisUser.permLevel === requiredPerms);
			});
		},
		getPermLevel: function(uid, callback) {
			var fbRef = new Firebase("https://contest-judging-sys.firebaseio.com");
			var usersRef = fbRef.child("users");
			var thisUserRef = usersRef.child(uid);

			var permLevel = -1;

			thisUserRef.orderByKey().equalTo("permLevel").on("child_added", function(data) {
				permLevel = data.val().permLevel;
			});

			thisUserRef.once("value", function() {
				callback(permLevel);
			});
		}
	};
})();<|endoftext|>