<commit_before>var assert = require("assert");
var types = require("./types");
var n = types.namedTypes;
var Node = n.Node;
var isArray = types.builtInTypes.array;
var isNumber = types.builtInTypes.number;

function FastPath(value) {
  assert.ok(this instanceof FastPath);
  this.stack = [value];
}

var FPp = FastPath.prototype;
module.exports = FastPath;

// Static convenience function for coercing a value to a FastPath.
FastPath.from = function(obj) {
  if (obj instanceof FastPath) {
    // Return a defensive copy of any existing FastPath instances.
    return obj.copy();
  }

  if (obj instanceof types.NodePath) {
    // For backwards compatibility, unroll NodePath instances into
    // lightweight FastPath [..., name, value] stacks.
    var copy = Object.create(FastPath.prototype);
    var stack = [obj.value];
    for (var pp; (pp = obj.parentPath); obj = pp)
      stack.push(obj.name, pp.value);
    copy.stack = stack.reverse();
    return copy;
  }

  // Otherwise use obj as the value of the new FastPath instance.
  return new FastPath(obj);
};

FPp.copy = function copy() {
  var copy = Object.create(FastPath.prototype);
  copy.stack = this.stack.slice(0);
  return copy;
};

// The name of the current property is always the penultimate element of
// this.stack, and always a String.
FPp.getName = function getName() {
  var s = this.stack;
  var len = s.length;
  if (len > 1) {
    return s[len - 2];
  }
  // Since the name is always a string, null is a safe sentinel value to
  // return if we do not know the name of the (root) value.
  return null;
};

// The value of the current property is always the final element of
// this.stack.
FPp.getValue = function getValue() {
  var s = this.stack;
  return s[s.length - 1];
};

FPp.valueIsDuplicate = function () {
  var s = this.stack;
  var valueIndex = s.length - 1;
  return s.lastIndexOf(s[valueIndex], valueIndex - 1) >= 0;
};

function getNodeHelper(path, count) {
  var s = path.stack;

  for (var i = s.length - 1; i >= 0; i -= 2) {
    var value = s[i];
    if (n.Node.check(value) && --count < 0) {
      return value;
    }
  }

  return null;
}

FPp.getNode = function getNode(count) {
  return getNodeHelper(this, ~~count);
};

FPp.getParentNode = function getParentNode(count) {
  return getNodeHelper(this, ~~count + 1);
};

// The length of the stack can be either even or odd, depending on whether
// or not we have a name for the root value. The difference between the
// index of the root value and the index of the final value is always
// even, though, which allows us to return the root value in constant time
// (i.e. without iterating backwards through the stack).
FPp.getRootValue = function getRootValue() {
  var s = this.stack;
  if (s.length % 2 === 0) {
    return s[1];
  }
  return s[0];
};

// Temporarily push properties named by string arguments given after the
// callback function onto this.stack, then call the callback with a
// reference to this (modified) FastPath object. Note that the stack will
// be restored to its original state after the callback is finished, so it
// is probably a mistake to retain a reference to the path.
FPp.call = function call(callback/*, name1, name2, ... */) {
  var s = this.stack;
  var origLen = s.length;
  var value = s[origLen - 1];
  var argc = arguments.length;
  for (var i = 1; i < argc; ++i) {
    var name = arguments[i];
    value = value[name];
    s.push(name, value);
  }
  var result = callback(this);
  s.length = origLen;
  return result;
};

// Similar to FastPath.prototype.call, except that the value obtained by
// accessing this.getValue()[name1][name2]... should be array-like. The
// callback will be called with a reference to this path object for each
// element of the array.
FPp.each = function each(callback/*, name1, name2, ... */) {
  var s = this.stack;
  var origLen = s.length;
  var value = s[origLen - 1];
  var argc = arguments.length;

  for (var i = 1; i < argc; ++i) {
    var name = arguments[i];
    value = value[name];
    s.push(name, value);
  }

  for (var i = 0; i < value.length; ++i) {
    if (i in value) {
      s.push(i, value[i]);
      // If the callback needs to know the value of i, call
      // path.getName(), assuming path is the parameter name.
      callback(this);
      s.length -= 2;
    }
  }

  s.length = origLen;
};

// Similar to FastPath.prototype.each, except that the results of the
// callback function invocations are stored in an array and returned at
// the end of the iteration.
FPp.map = function map(callback/*, name1, name2, ... */) {
  var s = this.stack;
  var origLen = s.length;
  var value = s[origLen - 1];
  var argc = arguments.length;

  for (var i = 1; i < argc; ++i) {
    var name = arguments[i];
    value = value[name];
    s.push(name, value);
  }

  var result = new Array(value.length);

  for (var i = 0; i < value.length; ++i) {
    if (i in value) {
      s.push(i, value[i]);
      result[i] = callback(this, i);
      s.length -= 2;
    }
  }

  s.length = origLen;

  return result;
};

// Inspired by require("ast-types").NodePath.prototype.needsParens, but
// more efficient because we're iterating backwards through a stack.
FPp.needsParens = function(assumeExpressionContext) {
  var node = this.getNode();

  // This needs to come before `if (!parent) { return false }` because
  // an object destructuring assignment requires parens for
  // correctness even when it's the topmost expression.
  if (node.type === "AssignmentExpression" && node.left.type === 'ObjectPattern') {
    return true;
  }

  var parent = this.getParentNode();
  if (!parent) {
    return false;
  }

  var name = this.getName();

  // If the value of this path is some child of a Node and not a Node
  // itself, then it doesn't need parentheses. Only Node objects (in fact,
  // only Expression nodes) need parentheses.
  if (this.getValue() !== node) {
    return false;
  }

  // Only statements don't need parentheses.
  if (n.Statement.check(node)) {
    return false;
  }

  // Identifiers never need parentheses.
  if (node.type === "Identifier") {
    return false;
  }

  if (parent.type === "ParenthesizedExpression") {
    return false;
  }

  switch (node.type) {
  case "UnaryExpression":
  case "SpreadElement":
  case "SpreadProperty":
    return parent.type === "MemberExpression"
      && name === "object"
      && parent.object === node;

  case "BinaryExpression":
  case "LogicalExpression":
    switch (parent.type) {
    case "CallExpression":
      return name === "callee"
        && parent.callee === node;

    case "UnaryExpression":
    case "SpreadElement":
    case "SpreadProperty":
      return true;

    case "MemberExpression":
      return name === "object"
        && parent.object === node;

    case "BinaryExpression":
    case "LogicalExpression":
      var po = parent.operator;
      var pp = PRECEDENCE[po];
      var no = node.operator;
      var np = PRECEDENCE[no];

      if (pp > np) {
        return true;
      }

      if (pp === np && name === "right") {
        assert.strictEqual(parent.right, node);
        return true;
      }

    default:
      return false;
    }

  case "SequenceExpression":
    switch (parent.type) {
    case "ReturnStatement":
      return false;

    case "ForStatement":
      // Although parentheses wouldn't hurt around sequence expressions in
      // the head of for loops, traditional style dictates that e.g. i++,
      // j++ should not be wrapped with parentheses.
      return false;

    case "ExpressionStatement":
      return name !== "expression";

    default:
      // Otherwise err on the side of overparenthesization, adding
      // explicit exceptions above if this proves overzealous.
      return true;
    }

  case "YieldExpression":
    switch (parent.type) {
    case "BinaryExpression":
    case "LogicalExpression":
    case "UnaryExpression":
    case "SpreadElement":
    case "SpreadProperty":
    case "CallExpression":
    case "MemberExpression":
    case "NewExpression":
    case "ConditionalExpression":
    case "YieldExpression":
      return true;

    default:
      return false;
    }

  case "IntersectionTypeAnnotation":
  case "UnionTypeAnnotation":
    return parent.type === "NullableTypeAnnotation";

  case "Literal":
    return parent.type === "MemberExpression"
      && isNumber.check(node.value)
      && name === "object"
      && parent.object === node;

  // Babel 6 Literal split
  case "NumericLiteral":
    return parent.type === "MemberExpression"
      && name === "object"
      && parent.object === node;

  case "AssignmentExpression":
  case "ConditionalExpression":
    switch (parent.type) {
    case "UnaryExpression":
    case "SpreadElement":
    case "SpreadProperty":
    case "BinaryExpression":
    case "LogicalExpression":
      return true;

    case "CallExpression":
      return name === "callee"
        && parent.callee === node;

    case "ConditionalExpression":
      return name === "test"
        && parent.test === node;

    case "MemberExpression":
      return name === "object"
        && parent.object === node;

    default:
      return false;
    }

  case "ArrowFunctionExpression":
    if(n.CallExpression.check(parent) && name === 'callee') {
      return true;
    }
    if(n.MemberExpression.check(parent) && name === 'object') {
      return true;
    }

    return isBinary(parent);

  case "ObjectExpression":
    if (parent.type === "ArrowFunctionExpression" &&
        name === "body") {
      return true;
    }

  default:
    if (parent.type === "NewExpression" &&
        name === "callee" &&
        parent.callee === node) {
      return containsCallExpression(node);
    }
  }

  if (assumeExpressionContext !== true &&
      !this.canBeFirstInStatement() &&
      this.firstInStatement())
    return true;

  return false;
};

function isBinary(node) {
  return n.BinaryExpression.check(node)
    || n.LogicalExpression.check(node);
}

function isUnaryLike(node) {
  return n.UnaryExpression.check(node)
  // I considered making SpreadElement and SpreadProperty subtypes of
  // UnaryExpression, but they're not really Expression nodes.
    || (n.SpreadElement && n.SpreadElement.check(node))
    || (n.SpreadProperty && n.SpreadProperty.check(node));
}

var PRECEDENCE = {};
[["||"],
 ["&&"],
 ["|"],
 ["^"],
 ["&"],
 ["==", "===", "!=", "!=="],
 ["<", ">", "<=", ">=", "in", "instanceof"],
 [">>", "<<", ">>>"],
 ["+", "-"],
 ["*", "/", "%", "**"]
].forEach(function(tier, i) {
  tier.forEach(function(op) {
    PRECEDENCE[op] = i;
  });
});

function containsCallExpression(node) {
  if (n.CallExpression.check(node)) {
    return true;
  }

  if (isArray.check(node)) {
    return node.some(containsCallExpression);
  }

  if (n.Node.check(node)) {
    return types.someField(node, function(name, child) {
      return containsCallExpression(child);
    });
  }

  return false;
}

FPp.canBeFirstInStatement = function() {
  var node = this.getNode();

  if (n.FunctionExpression.check(node)) {
    return false;
  }

  if (n.ObjectExpression.check(node)) {
    return false;
  }

  if (n.ClassExpression.check(node)) {
    return false;
  }

  return true;
};

FPp.firstInStatement = function() {
  var s = this.stack;
  var parentName, parent;
  var childName, child;

  for (var i = s.length - 1; i >= 0; i -= 2) {
    if (n.Node.check(s[i])) {
      childName = parentName;
      child = parent;
      parentName = s[i - 1];
      parent = s[i];
    }

    if (!parent || !child) {
      continue;
    }

    if (n.BlockStatement.check(parent) &&
        parentName === "body" &&
        childName === 0) {
      assert.strictEqual(parent.body[0], child);
      return true;
    }

    if (n.ExpressionStatement.check(parent) &&
        childName === "expression") {
      assert.strictEqual(parent.expression, child);
      return true;
    }

    if (n.SequenceExpression.check(parent) &&
        parentName === "expressions" &&
        childName === 0) {
      assert.strictEqual(parent.expressions[0], child);
      continue;
    }

    if (n.CallExpression.check(parent) &&
        childName === "callee") {
      assert.strictEqual(parent.callee, child);
      continue;
    }

    if (n.MemberExpression.check(parent) &&
        childName === "object") {
      assert.strictEqual(parent.object, child);
      continue;
    }

    if (n.ConditionalExpression.check(parent) &&
        childName === "test") {
      assert.strictEqual(parent.test, child);
      continue;
    }

    if (isBinary(parent) &&
        childName === "left") {
      assert.strictEqual(parent.left, child);
      continue;
    }

    if (n.UnaryExpression.check(parent) &&
        !parent.prefix &&
        childName === "argument") {
      assert.strictEqual(parent.argument, child);
      continue;
    }

    return false;
  }

  return true;
};
<commit_msg>Always wrap body expression of an arrow function in parens<commit_after>var assert = require("assert");
var types = require("./types");
var n = types.namedTypes;
var Node = n.Node;
var isArray = types.builtInTypes.array;
var isNumber = types.builtInTypes.number;

function FastPath(value) {
  assert.ok(this instanceof FastPath);
  this.stack = [value];
}

var FPp = FastPath.prototype;
module.exports = FastPath;

// Static convenience function for coercing a value to a FastPath.
FastPath.from = function(obj) {
  if (obj instanceof FastPath) {
    // Return a defensive copy of any existing FastPath instances.
    return obj.copy();
  }

  if (obj instanceof types.NodePath) {
    // For backwards compatibility, unroll NodePath instances into
    // lightweight FastPath [..., name, value] stacks.
    var copy = Object.create(FastPath.prototype);
    var stack = [obj.value];
    for (var pp; (pp = obj.parentPath); obj = pp)
      stack.push(obj.name, pp.value);
    copy.stack = stack.reverse();
    return copy;
  }

  // Otherwise use obj as the value of the new FastPath instance.
  return new FastPath(obj);
};

FPp.copy = function copy() {
  var copy = Object.create(FastPath.prototype);
  copy.stack = this.stack.slice(0);
  return copy;
};

// The name of the current property is always the penultimate element of
// this.stack, and always a String.
FPp.getName = function getName() {
  var s = this.stack;
  var len = s.length;
  if (len > 1) {
    return s[len - 2];
  }
  // Since the name is always a string, null is a safe sentinel value to
  // return if we do not know the name of the (root) value.
  return null;
};

// The value of the current property is always the final element of
// this.stack.
FPp.getValue = function getValue() {
  var s = this.stack;
  return s[s.length - 1];
};

FPp.valueIsDuplicate = function () {
  var s = this.stack;
  var valueIndex = s.length - 1;
  return s.lastIndexOf(s[valueIndex], valueIndex - 1) >= 0;
};

function getNodeHelper(path, count) {
  var s = path.stack;

  for (var i = s.length - 1; i >= 0; i -= 2) {
    var value = s[i];
    if (n.Node.check(value) && --count < 0) {
      return value;
    }
  }

  return null;
}

FPp.getNode = function getNode(count) {
  return getNodeHelper(this, ~~count);
};

FPp.getParentNode = function getParentNode(count) {
  return getNodeHelper(this, ~~count + 1);
};

// The length of the stack can be either even or odd, depending on whether
// or not we have a name for the root value. The difference between the
// index of the root value and the index of the final value is always
// even, though, which allows us to return the root value in constant time
// (i.e. without iterating backwards through the stack).
FPp.getRootValue = function getRootValue() {
  var s = this.stack;
  if (s.length % 2 === 0) {
    return s[1];
  }
  return s[0];
};

// Temporarily push properties named by string arguments given after the
// callback function onto this.stack, then call the callback with a
// reference to this (modified) FastPath object. Note that the stack will
// be restored to its original state after the callback is finished, so it
// is probably a mistake to retain a reference to the path.
FPp.call = function call(callback/*, name1, name2, ... */) {
  var s = this.stack;
  var origLen = s.length;
  var value = s[origLen - 1];
  var argc = arguments.length;
  for (var i = 1; i < argc; ++i) {
    var name = arguments[i];
    value = value[name];
    s.push(name, value);
  }
  var result = callback(this);
  s.length = origLen;
  return result;
};

// Similar to FastPath.prototype.call, except that the value obtained by
// accessing this.getValue()[name1][name2]... should be array-like. The
// callback will be called with a reference to this path object for each
// element of the array.
FPp.each = function each(callback/*, name1, name2, ... */) {
  var s = this.stack;
  var origLen = s.length;
  var value = s[origLen - 1];
  var argc = arguments.length;

  for (var i = 1; i < argc; ++i) {
    var name = arguments[i];
    value = value[name];
    s.push(name, value);
  }

  for (var i = 0; i < value.length; ++i) {
    if (i in value) {
      s.push(i, value[i]);
      // If the callback needs to know the value of i, call
      // path.getName(), assuming path is the parameter name.
      callback(this);
      s.length -= 2;
    }
  }

  s.length = origLen;
};

// Similar to FastPath.prototype.each, except that the results of the
// callback function invocations are stored in an array and returned at
// the end of the iteration.
FPp.map = function map(callback/*, name1, name2, ... */) {
  var s = this.stack;
  var origLen = s.length;
  var value = s[origLen - 1];
  var argc = arguments.length;

  for (var i = 1; i < argc; ++i) {
    var name = arguments[i];
    value = value[name];
    s.push(name, value);
  }

  var result = new Array(value.length);

  for (var i = 0; i < value.length; ++i) {
    if (i in value) {
      s.push(i, value[i]);
      result[i] = callback(this, i);
      s.length -= 2;
    }
  }

  s.length = origLen;

  return result;
};

// Inspired by require("ast-types").NodePath.prototype.needsParens, but
// more efficient because we're iterating backwards through a stack.
FPp.needsParens = function(assumeExpressionContext) {
  var node = this.getNode();

  // This needs to come before `if (!parent) { return false }` because
  // an object destructuring assignment requires parens for
  // correctness even when it's the topmost expression.
  if (node.type === "AssignmentExpression" && node.left.type === 'ObjectPattern') {
    return true;
  }

  var parent = this.getParentNode();
  if (!parent) {
    return false;
  }

  var name = this.getName();

  // If the value of this path is some child of a Node and not a Node
  // itself, then it doesn't need parentheses. Only Node objects (in fact,
  // only Expression nodes) need parentheses.
  if (this.getValue() !== node) {
    return false;
  }

  // Only statements don't need parentheses.
  if (n.Statement.check(node)) {
    return false;
  }

  // Identifiers never need parentheses.
  if (node.type === "Identifier") {
    return false;
  }

  if (parent.type === "ParenthesizedExpression") {
    return false;
  }

  if (parent.type === "ArrowFunctionExpression" && name === "body") {
    // TODO does this expression start with a {?
    return true;
  }

  switch (node.type) {
  case "UnaryExpression":
  case "SpreadElement":
  case "SpreadProperty":
    return parent.type === "MemberExpression"
      && name === "object"
      && parent.object === node;

  case "BinaryExpression":
  case "LogicalExpression":
    switch (parent.type) {
    case "CallExpression":
      return name === "callee"
        && parent.callee === node;

    case "UnaryExpression":
    case "SpreadElement":
    case "SpreadProperty":
      return true;

    case "MemberExpression":
      return name === "object"
        && parent.object === node;

    case "BinaryExpression":
    case "LogicalExpression":
      var po = parent.operator;
      var pp = PRECEDENCE[po];
      var no = node.operator;
      var np = PRECEDENCE[no];

      if (pp > np) {
        return true;
      }

      if (pp === np && name === "right") {
        assert.strictEqual(parent.right, node);
        return true;
      }

    default:
      return false;
    }

  case "SequenceExpression":
    switch (parent.type) {
    case "ReturnStatement":
      return false;

    case "ForStatement":
      // Although parentheses wouldn't hurt around sequence expressions in
      // the head of for loops, traditional style dictates that e.g. i++,
      // j++ should not be wrapped with parentheses.
      return false;

    case "ExpressionStatement":
      return name !== "expression";

    default:
      // Otherwise err on the side of overparenthesization, adding
      // explicit exceptions above if this proves overzealous.
      return true;
    }

  case "YieldExpression":
    switch (parent.type) {
    case "BinaryExpression":
    case "LogicalExpression":
    case "UnaryExpression":
    case "SpreadElement":
    case "SpreadProperty":
    case "CallExpression":
    case "MemberExpression":
    case "NewExpression":
    case "ConditionalExpression":
    case "YieldExpression":
      return true;

    default:
      return false;
    }

  case "IntersectionTypeAnnotation":
  case "UnionTypeAnnotation":
    return parent.type === "NullableTypeAnnotation";

  case "Literal":
    return parent.type === "MemberExpression"
      && isNumber.check(node.value)
      && name === "object"
      && parent.object === node;

  // Babel 6 Literal split
  case "NumericLiteral":
    return parent.type === "MemberExpression"
      && name === "object"
      && parent.object === node;

  case "AssignmentExpression":
  case "ConditionalExpression":
    switch (parent.type) {
    case "UnaryExpression":
    case "SpreadElement":
    case "SpreadProperty":
    case "BinaryExpression":
    case "LogicalExpression":
      return true;

    case "CallExpression":
      return name === "callee"
        && parent.callee === node;

    case "ConditionalExpression":
      return name === "test"
        && parent.test === node;

    case "MemberExpression":
      return name === "object"
        && parent.object === node;

    default:
      return false;
    }

  case "ArrowFunctionExpression":
    if(n.CallExpression.check(parent) && name === 'callee') {
      return true;
    }
    if(n.MemberExpression.check(parent) && name === 'object') {
      return true;
    }

    return isBinary(parent);

  case "ObjectExpression":
    if (parent.type === "ArrowFunctionExpression" &&
        name === "body") {
      return true;
    }

  default:
    if (parent.type === "NewExpression" &&
        name === "callee" &&
        parent.callee === node) {
      return containsCallExpression(node);
    }
  }

  if (assumeExpressionContext !== true &&
      !this.canBeFirstInStatement() &&
      this.firstInStatement())
    return true;

  return false;
};

function isBinary(node) {
  return n.BinaryExpression.check(node)
    || n.LogicalExpression.check(node);
}

function isUnaryLike(node) {
  return n.UnaryExpression.check(node)
  // I considered making SpreadElement and SpreadProperty subtypes of
  // UnaryExpression, but they're not really Expression nodes.
    || (n.SpreadElement && n.SpreadElement.check(node))
    || (n.SpreadProperty && n.SpreadProperty.check(node));
}

var PRECEDENCE = {};
[["||"],
 ["&&"],
 ["|"],
 ["^"],
 ["&"],
 ["==", "===", "!=", "!=="],
 ["<", ">", "<=", ">=", "in", "instanceof"],
 [">>", "<<", ">>>"],
 ["+", "-"],
 ["*", "/", "%", "**"]
].forEach(function(tier, i) {
  tier.forEach(function(op) {
    PRECEDENCE[op] = i;
  });
});

function containsCallExpression(node) {
  if (n.CallExpression.check(node)) {
    return true;
  }

  if (isArray.check(node)) {
    return node.some(containsCallExpression);
  }

  if (n.Node.check(node)) {
    return types.someField(node, function(name, child) {
      return containsCallExpression(child);
    });
  }

  return false;
}

FPp.canBeFirstInStatement = function() {
  var node = this.getNode();

  if (n.FunctionExpression.check(node)) {
    return false;
  }

  if (n.ObjectExpression.check(node)) {
    return false;
  }

  if (n.ClassExpression.check(node)) {
    return false;
  }

  return true;
};

FPp.firstInStatement = function() {
  var s = this.stack;
  var parentName, parent;
  var childName, child;

  for (var i = s.length - 1; i >= 0; i -= 2) {
    if (n.Node.check(s[i])) {
      childName = parentName;
      child = parent;
      parentName = s[i - 1];
      parent = s[i];
    }

    if (!parent || !child) {
      continue;
    }

    if (n.BlockStatement.check(parent) &&
        parentName === "body" &&
        childName === 0) {
      assert.strictEqual(parent.body[0], child);
      return true;
    }

    if (n.ExpressionStatement.check(parent) &&
        childName === "expression") {
      assert.strictEqual(parent.expression, child);
      return true;
    }

    if (n.SequenceExpression.check(parent) &&
        parentName === "expressions" &&
        childName === 0) {
      assert.strictEqual(parent.expressions[0], child);
      continue;
    }

    if (n.CallExpression.check(parent) &&
        childName === "callee") {
      assert.strictEqual(parent.callee, child);
      continue;
    }

    if (n.MemberExpression.check(parent) &&
        childName === "object") {
      assert.strictEqual(parent.object, child);
      continue;
    }

    if (n.ConditionalExpression.check(parent) &&
        childName === "test") {
      assert.strictEqual(parent.test, child);
      continue;
    }

    if (isBinary(parent) &&
        childName === "left") {
      assert.strictEqual(parent.left, child);
      continue;
    }

    if (n.UnaryExpression.check(parent) &&
        !parent.prefix &&
        childName === "argument") {
      assert.strictEqual(parent.argument, child);
      continue;
    }

    return false;
  }

  return true;
};
<|endoftext|>


<commit_before>'use strict';

var objectAssign = require('object-assign'),
    FluxexObject = require('./fluxobj'),
    EventEmitter = require('eventemitter2').EventEmitter2,

FluxStore = function FluxStore() {
    FluxexObject.apply(this, arguments);
    this.eventEmitter = new EventEmitter();
};

FluxStore.prototype = new FluxexObject();

objectAssign(FluxStore.prototype, {
    constructor: FluxStore,
    emitChange: function () {
        this.eventEmitter(this.eventEmitter.emit('CHANGE'));
    },
    addChangeListener: function (callback) {
        this.eventEmitter.on('CHANGE', callback);
    }
});

module.exports = FluxStore;
<commit_msg>Add more api<commit_after>'use strict';

var objectAssign = require('object-assign'),
    FluxexObject = require('./fluxobj'),
    EventEmitter = require('eventemitter2').EventEmitter2,

FluxStore = function FluxStore() {
    FluxexObject.apply(this, arguments);
    this.eventEmitter = new EventEmitter();
};

FluxStore.prototype = new FluxexObject();

objectAssign(FluxStore.prototype, {
    constructor: FluxStore,
    emitChange: function () {
        this.eventEmitter(this.eventEmitter.emit('CHANGE'));
    },
    addChangeListener: function (callback) {
        this.eventEmitter.addListener('CHANGE', callback);
    },
    removeChangeListener: function (callback) {
        this.eventEmitter.removeListener('CHANGE', callback);
    }
});

module.exports = FluxStore;
<|endoftext|>


<commit_before>var myBranch	=draw2d.shape.basic.Diamond.extend({
		init:function(fn)
		{
			this._super();
			this.createPort("input");
   			this.createPort("output");
			this.setResizeable(false);
			//this.dbfun2=fn;
			this.createPort("output");
		},
		onDoubleClick: function(){
        	//this.dbfun2(this);
    	},
		onContextMenu:function(x,y){
        $.contextMenu({
            selector: 'body',
            events:
            {
                hide:function(){ $.contextMenu( 'destroy' ); }
            },
            callback: $.proxy(function(key, options)
            {
               switch(key){
               case "removelastport":
			   		console.log("mydiamond removelastport");
				   this.removeLastPort();
                   break;
               case "newport":
					this.createPort("output");
                   break;
               case "delete":
                   var cmd = new draw2d.command.CommandDelete(this);
                   this.getCanvas().getCommandStack().execute(cmd);
               default:
                   break;
               }
             },this),
            x:x,
            y:y,
            items:
            {
                //"restart":    {name: "restart", icon: "edit"},
                //"removelastport":  {name: "移除端口", icon: "cut"},
                //"newport":   {name: "新增端口", icon: "copy"},
                //"sep1":   "---------",
                "delete": {name: "删除", icon: "delete"}
            }
        });
   }
});
var myJob= draw2d.shape.basic.Image2.extend({
    init:function(path,fn)
    {
      this.dbfun2=fn;
	  this._super(path,50, 50);
	  this.setResizeable(false);
    },
	onDoubleClick: function(){
        this.dbfun2(this);
    },
	onContextMenu:function(x,y){
        $.contextMenu({
            selector: 'body',
            events:
            {
                hide:function(){ $.contextMenu( 'destroy' ); }
            },
            callback: $.proxy(function(key, options)
            {
               switch(key){
               case "delete":
                   var cmd = new draw2d.command.CommandDelete(this);
                   this.getCanvas().getCommandStack().execute(cmd);
               default:
                   break;
               }
            },this),
            x:x,
            y:y,
            items:
            {
                "delete": {name: "删除", icon: "delete"}
            }
        });
   }
});
function jobdbclick(node){
	$('#form_job_property')[0].reset();
	var Target2=document.getElementById("div_job_property");
	var Target=document.getElementById("div_branch_property");
	Target.style.display="none";
	Target2.style.display="block";
	$("#job_id_text").val(node.id);
	var userData = node .getUserData();
	if( userData != null)
	{
		$("#job_name_text").val(userData.name);
		$("#job_description_text").val(userData.description);
		$("#job_command_text").val(userData.command);
		$("#job_parameter_text").val(userData.parameter);
		$("#job_owner_text").val(userData.owner);
		$("#job_num_try_text").val(userData.num_try);
		$("#job_try_interval_text").val(userData.try_interval);
	}
	displayJSON(canvas);
};

function branchdbclick(node){
	$('#form_branch_property')[0].reset();
	var Target=document.getElementById("div_job_property");
	var Target2=document.getElementById("div_branch_property");
	Target.style.display="none";
	Target2.style.display="block";
	$("#branch_property_tbody").children().remove();
	$("#branch_property_tbody").append(" <input type='hidden' id='branch_id_text'>");
/*	$("#branch_property_tbody").append("\

\
                    	branch_id	\
                        <input type='text' id='branch_id_text'>	\

\
						");
*/
	$("#branch_id_text").val(node.id);
	//console.log("diamond db click size:" + node.outputPorts.getSize());
	for (var len=0 ; len<node.outputPorts.getSize(); len ++)
	{
			$("#branch_property_tbody").append("\

\
                    	port"+len+"	\
                        <input type='text' id='branch_port"+len+"_text'>	\

\
						");
	}
	$("#branch_property_tbody").append("\

\
                    	<input type='button' id='branch_save' value='保存到diamond的userdata中'>	\

\
						");
	$("#branch_save").click(branch_save_fn);
	var userData = node .getUserData();
	if( userData != null)
	{
		$.each(userData ,function(i){
				var textinput_id="#branch_"+i+"_text";
				$(textinput_id).val(userData[i]);
				//console.log(i);
		});
	}
};
function form_job_property_to_json()
{
	var jsondata={
					"name":$("#job_name_text").val(),
					"description":$("#job_description_text").val(),
					"owner":$("#job_owner_text").val(),
					"command":$("#job_command_text").val(),
					"parameter":$("#job_parameter_text").val(),
					"num_try":$("#job_num_try_text").val(),
					"try_interval":$("#job_try_interval_text").val()
	};
	return jsondata;
}
function form_branch_property_to_json()
{
	var jsondatastring = "{";
	for (var len=0 ; len<canvas.getFigure($("#branch_id_text").val()).outputPorts.getSize(); len ++)
	{
		var name="port"+len;
		var textinput_id="#branch_port"+len+"_text";
//		console.log(name+ " " + textinput_id + " "+ $(textinput_id).val());
		if ( len == canvas.getFigure($("#branch_id_text").val()).outputPorts.getSize() -1 )
		{
			jsondatastring = jsondatastring + '"'+name +'"'+":" + '"'+$(textinput_id).val()  +'"';
		}else {
			jsondatastring = jsondatastring + '"'+name +'"'+":" + '"'+$(textinput_id).val()  +'"'+ ",";
		}

	}
	jsondatastring = jsondatastring + '}'
	//console.log(jsondatastring);
	return eval("("+jsondatastring+")");
}
function job_save_fun(){

	if ($("#job_id_text").val() !="")
	{

		var data =form_job_property_to_json();
		canvas.getFigure($("#job_id_text").val()).setUserData(data);
		canvas.getFigure($("#job_id_text").val()).setLabelText ($("#job_name_text").val());
	}else {
	}
	//$('#form_job_property')[0].reset();
	document.getElementById("div_job_property").style.display="none";
	displayJSON(canvas);
};
function branch_save_fn(){
	//console.log("branch_save_fn");
	if ($("#branch_id_text").val() !="")
	{
		var data=form_branch_property_to_json();
		canvas.getFigure($("#branch_id_text").val()).setUserData(data);
	}else{
	}
	$('#form_branch_property')[0].reset();
	document.getElementById("div_branch_property").style.display="none";
	displayJSON(canvas);
}
function new_job_fun()
{
	var figure = new myJob("pic/icon.png",jobdbclick);
	canvas.addFigure( figure,0,0);
}
function new_branch_fun()
{
	var d =new myBranch(branchdbclick);
	canvas.addFigure( d,0,0);
}
function get_procedure_property_json()
{
	var tempData ={
		"id":0,
		"name":$("#pro_name").val(),
		"bulit_datetime":0,
		"last_modify_datetime":0,
		"start_datetime":$("#runtime").val()

	};
 	return tempData;
}
function procedure_save_fun()
{
	var writer = new draw2d.io.json.Writer();
	var procedure_job_json=writer.marshal(canvas);
    //$("#json").text(JSON.stringify(writer.marshal(canvas),null,2));
	var jsondata={
		"procedure_property":get_procedure_property_json(),
		"jobs_draw2d":procedure_job_json
	}
	console.log(jsondata);
	$.ajax({
		type:"POST",
		url:"cgi-bin/readjson",
		data:jsondata,
		success:function(data,textStatus){
			console.log("post success");
		},
		error:function(xhr,status,errMsg){
			console.log(status + " "+errMsg);
		}
	});
}
var canvas;
$(window).load(function () {

	$("#new_node").click(  new_job_fun    );
	$("#new_diamond").click(  new_branch_fun    );
	$("#job_save").click(  job_save_fun    );
	$("#procedure_save").click(  procedure_save_fun    );

  canvas = new draw2d.Canvas("gfx_holder");
  canvas.installEditPolicy( new draw2d.policy.canvas.CoronaDecorationPolicy( ) );
  canvas.getCommandStack().addEventListener(function(e){
	      if(e.isPostChangeEvent()){
	          displayJSON(canvas);
	      }
	  });

});
function displayJSON(canvas){
    //var writer = new draw2d.io.json.Writer();
    //$("#json").text(JSON.stringify(writer.marshal(canvas),null,2));
}
<commit_msg>modify event.js for test<commit_after>var myBranch	=draw2d.shape.basic.Diamond.extend({
		init:function(fn)
		{
			//this._super();
			//this.createPort("input");
   			this.createPort("output");
			this.setResizeable(false);
			//this.dbfun2=fn;
			this.createPort("output");
		},
		onDoubleClick: function(){
        	//this.dbfun2(this);
    	},
		onContextMenu:function(x,y){
        $.contextMenu({
            selector: 'body',
            events:
            {
                hide:function(){ $.contextMenu( 'destroy' ); }
            },
            callback: $.proxy(function(key, options)
            {
               switch(key){
               case "removelastport":
			   		console.log("mydiamond removelastport");
				   this.removeLastPort();
                   break;
               case "newport":
					this.createPort("output");
                   break;
               case "delete":
                   var cmd = new draw2d.command.CommandDelete(this);
                   this.getCanvas().getCommandStack().execute(cmd);
               default:
                   break;
               }
             },this),
            x:x,
            y:y,
            items:
            {
                //"restart":    {name: "restart", icon: "edit"},
                //"removelastport":  {name: "移除端口", icon: "cut"},
                //"newport":   {name: "新增端口", icon: "copy"},
                //"sep1":   "---------",
                "delete": {name: "删除", icon: "delete"}
            }
        });
   }
});
var myJob= draw2d.shape.basic.Image2.extend({
    init:function(path,fn)
    {
      this.dbfun2=fn;
	  this._super(path,50, 50);
	  this.setResizeable(false);
    },
	onDoubleClick: function(){
        this.dbfun2(this);
    },
	onContextMenu:function(x,y){
        $.contextMenu({
            selector: 'body',
            events:
            {
                hide:function(){ $.contextMenu( 'destroy' ); }
            },
            callback: $.proxy(function(key, options)
            {
               switch(key){
               case "delete":
                   var cmd = new draw2d.command.CommandDelete(this);
                   this.getCanvas().getCommandStack().execute(cmd);
               default:
                   break;
               }
            },this),
            x:x,
            y:y,
            items:
            {
                "delete": {name: "删除", icon: "delete"}
            }
        });
   }
});
function jobdbclick(node){
	$('#form_job_property')[0].reset();
	var Target2=document.getElementById("div_job_property");
	var Target=document.getElementById("div_branch_property");
	Target.style.display="none";
	Target2.style.display="block";
	$("#job_id_text").val(node.id);
	var userData = node .getUserData();
	if( userData != null)
	{
		$("#job_name_text").val(userData.name);
		$("#job_description_text").val(userData.description);
		$("#job_command_text").val(userData.command);
		$("#job_parameter_text").val(userData.parameter);
		$("#job_owner_text").val(userData.owner);
		$("#job_num_try_text").val(userData.num_try);
		$("#job_try_interval_text").val(userData.try_interval);
	}
	displayJSON(canvas);
};

function branchdbclick(node){
	$('#form_branch_property')[0].reset();
	var Target=document.getElementById("div_job_property");
	var Target2=document.getElementById("div_branch_property");
	Target.style.display="none";
	Target2.style.display="block";
	$("#branch_property_tbody").children().remove();
	$("#branch_property_tbody").append(" <input type='hidden' id='branch_id_text'>");
/*	$("#branch_property_tbody").append("\

\
                    	branch_id	\
                        <input type='text' id='branch_id_text'>	\

\
						");
*/
	$("#branch_id_text").val(node.id);
	//console.log("diamond db click size:" + node.outputPorts.getSize());
	for (var len=0 ; len<node.outputPorts.getSize(); len ++)
	{
			$("#branch_property_tbody").append("\

\
                    	port"+len+"	\
                        <input type='text' id='branch_port"+len+"_text'>	\

\
						");
	}
	$("#branch_property_tbody").append("\

\
                    	<input type='button' id='branch_save' value='保存到diamond的userdata中'>	\

\
						");
	$("#branch_save").click(branch_save_fn);
	var userData = node .getUserData();
	if( userData != null)
	{
		$.each(userData ,function(i){
				var textinput_id="#branch_"+i+"_text";
				$(textinput_id).val(userData[i]);
				//console.log(i);
		});
	}
};
function form_job_property_to_json()
{
	var jsondata={
					"name":$("#job_name_text").val(),
					"description":$("#job_description_text").val(),
					"owner":$("#job_owner_text").val(),
					"command":$("#job_command_text").val(),
					"parameter":$("#job_parameter_text").val(),
					"num_try":$("#job_num_try_text").val(),
					"try_interval":$("#job_try_interval_text").val()
	};
	return jsondata;
}
function form_branch_property_to_json()
{
	var jsondatastring = "{";
	for (var len=0 ; len<canvas.getFigure($("#branch_id_text").val()).outputPorts.getSize(); len ++)
	{
		var name="port"+len;
		var textinput_id="#branch_port"+len+"_text";
//		console.log(name+ " " + textinput_id + " "+ $(textinput_id).val());
		if ( len == canvas.getFigure($("#branch_id_text").val()).outputPorts.getSize() -1 )
		{
			jsondatastring = jsondatastring + '"'+name +'"'+":" + '"'+$(textinput_id).val()  +'"';
		}else {
			jsondatastring = jsondatastring + '"'+name +'"'+":" + '"'+$(textinput_id).val()  +'"'+ ",";
		}

	}
	jsondatastring = jsondatastring + '}'
	//console.log(jsondatastring);
	return eval("("+jsondatastring+")");
}
function job_save_fun(){

	if ($("#job_id_text").val() !="")
	{

		var data =form_job_property_to_json();
		canvas.getFigure($("#job_id_text").val()).setUserData(data);
		canvas.getFigure($("#job_id_text").val()).setLabelText ($("#job_name_text").val());
	}else {
	}
	//$('#form_job_property')[0].reset();
	document.getElementById("div_job_property").style.display="none";
	displayJSON(canvas);
};
function branch_save_fn(){
	//console.log("branch_save_fn");
	if ($("#branch_id_text").val() !="")
	{
		var data=form_branch_property_to_json();
		canvas.getFigure($("#branch_id_text").val()).setUserData(data);
	}else{
	}
	$('#form_branch_property')[0].reset();
	document.getElementById("div_branch_property").style.display="none";
	displayJSON(canvas);
}
function new_job_fun()
{
	var figure = new myJob("pic/icon.png",jobdbclick);
	canvas.addFigure( figure,0,0);
}
function new_branch_fun()
{
	var d =new myBranch(branchdbclick);
	canvas.addFigure( d,0,0);
}
function get_procedure_property_json()
{
	var tempData ={
		"id":0,
		"name":$("#pro_name").val(),
		"bulit_datetime":0,
		"last_modify_datetime":0,
		"start_datetime":$("#runtime").val()

	};
 	return tempData;
}
function procedure_save_fun()
{
	var writer = new draw2d.io.json.Writer();
	var procedure_job_json=writer.marshal(canvas);
    //$("#json").text(JSON.stringify(writer.marshal(canvas),null,2));
	var jsondata={
		"procedure_property":get_procedure_property_json(),
		"jobs_draw2d":procedure_job_json
	}
	console.log(jsondata);
	$.ajax({
		type:"POST",
		url:"cgi-bin/readjson",
		data:jsondata,
		success:function(data,textStatus){
			console.log("post success");
		},
		error:function(xhr,status,errMsg){
			console.log(status + " "+errMsg);
		}
	});
}
var canvas;
$(window).load(function () {

	$("#new_node").click(  new_job_fun    );
	$("#new_diamond").click(  new_branch_fun    );
	$("#job_save").click(  job_save_fun    );
	$("#procedure_save").click(  procedure_save_fun    );

  canvas = new draw2d.Canvas("gfx_holder");
  canvas.installEditPolicy( new draw2d.policy.canvas.CoronaDecorationPolicy( ) );
  canvas.getCommandStack().addEventListener(function(e){
	      if(e.isPostChangeEvent()){
	          displayJSON(canvas);
	      }
	  });

});
function displayJSON(canvas){
    //var writer = new draw2d.io.json.Writer();
    //$("#json").text(JSON.stringify(writer.marshal(canvas),null,2));
}
<|endoftext|>


<commit_before>/* global InstanceDetails,Utils */

var UI = (function () {
    "use strict";

    /*****************************************************************
    *                        C O N S T A N T S                       *
    *****************************************************************/

    var NONUSABLEWIDTH = 204;
    var PROGRESSNONUSABLEWIDTH = 100;

    // Colors
    var RED = 'rgb(217, 83, 79)';
    var GREEN = 'green';
    var AMBAR = 'rgb(239, 163, 0)';
    var GRAY = 'gray';

    var statuses = {

        // GREEN
        'ACTIVE': {
            'class': 'glyphicon glyphicon-ok  fa-inverse',
            'color': GREEN
        },
        'BUILDING': {
            'class': 'fa fa-spinner fa-pulse  fa-inverse',
            'color': GREEN
        },
        'PASSWORD': {
            'class': 'fa fa-terminal  fa-inverse',
            'color': GREEN
        },

        // AMBAR
        'HARD_REBOOT': {
            'class': 'fa fa-repeat fa-spin  fa-inverse',
            'color': AMBAR
        },
        'PAUSED': {
            'class': 'fa fa-pause  fa-inverse',
            'color': AMBAR
        },
        'REBOOT': {
            'class': 'fa fa-repeat fa-spin  fa-inverse',
            'color': AMBAR
        },
        'BUILD': {
            'class': 'fa fa-repeat fa-spin  fa-inverse',
            'color': AMBAR
        },
        'RESCUED': {
            'class': 'fa fa-life-ring  fa-inverse',
            'color': AMBAR
        },
        'RESIZED': {
            'class': 'fa fa-arrows-alt  fa-inverse',
            'color': AMBAR
        },
        'VERIFY_RESIZE': {
            'class': 'fa fa-arrows-alt  fa-inverse',
            'color': AMBAR
        },
        'SHUTOFF': {
            'class': 'fa fa-stop  fa-inverse',
            'color': AMBAR
        },
        'SOFT_DELETED': {
            'class': 'fa fa-trash  fa-inverse',
            'color': AMBAR
        },
        'STOPPED': {
            'class': 'fa fa-stop  fa-inverse',
            'color': AMBAR
        },
        'SUSPENDED': {
            'class': 'fa fa-pause  fa-inverse',
            'color': AMBAR
        },

        // GRAY
        'UNKNOWN': {
            'class': 'fa fa-question  fa-inverse',
            'color': GRAY
        },

        // RED
        'DELETED': {
            'class': 'fa fa-trash  fa-inverse',
            'color': RED
        },
        'ERROR': {
            'class': 'fa fa-times  fa-inverse',
            'color': RED
        },
        'DELETING': {
            'class': 'fa fa-trash fa-inverse',
            'color': RED,
            'animation': 'working-animation'
        },
        'REVERT_RESIZE': {
            'class': 'fa fa-arrows-alt  fa-inverse',
            'color': RED
        }
    };

    var flavors = {
        '1': '1 VCPU | 512MB RAM | 0GB Disk',
        '2': '1 VCPU | 2048MB RAM | 10GB Disk',
        '3': '2 VCPU | 2MB RAM | 20GB Disk'
    };

    /*****************************************************************
    *                          P R I V A T E                         *
    *****************************************************************/

    function setNameMaxWidth (nonUsableWidth) {

        var bodyWidth = $('body').attr('width');

        if (bodyWidth >= 360) {
            $('#instance-name').css('max-width', bodyWidth - nonUsableWidth);
        }
        else {
            $('#instance-name').css('max-width', 360 - nonUsableWidth);
        }
    }

    function setProgressBarWidth (progressNonUsableWidth) {

        var bodyWidth = $('body').attr('width') >= 360 ? $('body').attr('width') : 360;
        var progressBarWidth = bodyWidth/2 - progressNonUsableWidth;
        $('#progress-bar').css('width', progressBarWidth);

        // Inner text
        $('#progress-bar span').css('left', progressNonUsableWidth + progressBarWidth/2);

        if (bodyWidth <= 360) {
            $('#progress-bar span').css('max-width', 76);
        }
        else {
            $('#progress-bar span').css('max-width', "None");
        }
    }

    /*****************************************************************
    *                          P U B L I C                           *
    *****************************************************************/

    function init (callbacks) {

        // Register resize callback
        MashupPlatform.widget.context.registerCallback(function (newValues) {
            if ("heightInPixels" in newValues || "widthInPixels" in newValues) {

                // Set body size
                $('body').attr('height', newValues.heightInPixels);
                $('body').attr('width', newValues.widthInPixels);

                // Set progress bar width
                setProgressBarWidth(PROGRESSNONUSABLEWIDTH);

                // Set name max-width
                setNameMaxWidth(NONUSABLEWIDTH);
            }
        });

        // Init click events
        $('#refresh-button').click(function () {
            callbacks.refresh();
        }.bind(this));
        $('#instance-reboot').click(function () {
            callbacks.reboot();
        }.bind(this));
        $('#instance-terminate').click(function () {
            callbacks.delete();
        }.bind(this));
        $('#instance-image > span').click(function () {

            var id = $(this).text();
            var data = {
                id: id,
                access: JSTACK.Keystone.params.access
            };

            MashupPlatform.wiring.pushEvent('image_id', JSON.stringify(data));
        });

        $('body').attr('width', window.innerWidth);

    }

    function buildDetailView (instanceData) {

        var addresses = instanceData.addresses ? Utils.getDisplayableAddresses(instanceData.addresses) : '';
        var power_state = Utils.getDisplayablePowerState(instanceData['OS-EXT-STS:power_state']);
        var displayableTask = (instanceData["OS-EXT-STS:task_state"] && instanceData["OS-EXT-STS:task_state"] !== "") ? instanceData["OS-EXT-STS:task_state"] : "None";
        var statusTooltip = 'Status: ' + instanceData.status + ', ' + 'Power State: ' + power_state + ', ' + 'VM State: ' + instanceData["OS-EXT-STS:vm_state"];

        // Hide other views
        $('#error-view').addClass('hide');
        $('#default-view').addClass('hide');
        $('body').removeClass('stripes angled-135');

        // Fields
        $('#instance-name').text(instanceData.name);
        $('#instance-owner > span').text(instanceData.user_id);
        $('#instance-id > span').text(instanceData.id);
        $('#instance-image > span').text(instanceData.image.id);
        $('#instance-key-pair > span').text(instanceData.key_name);
        $('#instance-addresses > span').text(addresses);
        $('#instance-flavor > span').text(flavors[instanceData.flavor.id.toString()]);
        $('#instance-created > span').text(instanceData.created);
        $('#instance-updated > span').text(instanceData.updated);

        // Status & Task
        $('#instance-status').removeClass('working-animation');
        $('#instance-status > div > i').removeClass();

        if (displayableTask === 'deleting') {
            $('#instance-status > div > i').addClass(statuses.DELETING.class);
            $('#instance-status').css('background-color', statuses.DELETING.color);
            $('#instance-status').addClass(statuses.DELETING.animation);
        }
        else {
            $('#instance-status > div > i').addClass(statuses[instanceData.status].class);
            $('#instance-status').css('background-color', statuses[instanceData.status].color);
        }

        if (displayableTask !== 'None') {
            $('#instance-task > span').empty();
            $('#progress-bar span').text(displayableTask);
            $('#progress-bar').removeClass('hide');
            $('#progress').css('background', statuses[instanceData.status].color);
        }
        else {
            $('#instance-task > span').text(displayableTask);
            $('#progress-bar').addClass('hide');
        }

        // Set name max-width
        setNameMaxWidth(NONUSABLEWIDTH);

        // Set progress bar width
        setProgressBarWidth(PROGRESSNONUSABLEWIDTH);

        // Fix tooltips
        $('#instance-status').attr('title', statusTooltip);
        $('#instance-status').attr('data-original-title', $('#instance-status').attr('title'));
        $('#instance-status').attr('title', '');

        $('#instance-name').attr('title', instanceData.name);
        $('#instance-name').attr('data-original-title', $('#instance-name').attr('title'));
        $('#instance-name').attr('title', '');

        $('#progress-bar span').attr('title', instanceData["OS-EXT-STS:task_state"]);
        $('#progress-bar span').attr('data-original-title', instanceData["OS-EXT-STS:task_state"]);
        $('#progress-bar span').attr('title', '');

        // Initialize tooltips
        $('[data-toggle="tooltip"]').tooltip();

        // Build
        $('#detail-view').removeClass('hide');
    }

    function buildDefaultView () {

        // Hide other views
        $('#error-view').addClass('hide');
        $('#detail-view').addClass('hide');
        $('body').addClass('stripes angled-135');

        // Build
        $('#default-view').removeClass('hide');
    }

    function buildErrorView (errorResponse) {

        // Hide other views
        $('#default-view').addClass('hide');
        $('#detail-view').addClass('hide');
        $('body').addClass('stripes angled-135');

        // Build
        if (errorResponse.message) {
            $('#error-view').text(errorResponse.message);
        }
        else {
            $('#error-view').text(errorResponse);
        }

        $('#error-view').removeClass('hide');
    }

    return {
        buildDetailView: buildDetailView,
        buildDefaultView: buildDefaultView,
        buildErrorView: buildErrorView,
        init: init
    };
})();<commit_msg>Refactor buildDetailsView function<commit_after>/* global InstanceDetails,Utils */

var UI = (function () {
    "use strict";

    /*****************************************************************
    *                        C O N S T A N T S                       *
    *****************************************************************/

    var NONUSABLEWIDTH = 204;
    var PROGRESSNONUSABLEWIDTH = 100;

    // Colors
    var RED = 'rgb(217, 83, 79)';
    var GREEN = 'green';
    var AMBAR = 'rgb(239, 163, 0)';
    var GRAY = 'gray';

    var statuses = {

        // GREEN
        'ACTIVE': {
            'class': 'glyphicon glyphicon-ok  fa-inverse',
            'color': GREEN
        },
        'BUILDING': {
            'class': 'fa fa-spinner fa-pulse  fa-inverse',
            'color': GREEN
        },
        'PASSWORD': {
            'class': 'fa fa-terminal  fa-inverse',
            'color': GREEN
        },

        // AMBAR
        'HARD_REBOOT': {
            'class': 'fa fa-repeat fa-spin  fa-inverse',
            'color': AMBAR
        },
        'PAUSED': {
            'class': 'fa fa-pause  fa-inverse',
            'color': AMBAR
        },
        'REBOOT': {
            'class': 'fa fa-repeat fa-spin  fa-inverse',
            'color': AMBAR
        },
        'BUILD': {
            'class': 'fa fa-repeat fa-spin  fa-inverse',
            'color': AMBAR
        },
        'RESCUED': {
            'class': 'fa fa-life-ring  fa-inverse',
            'color': AMBAR
        },
        'RESIZED': {
            'class': 'fa fa-arrows-alt  fa-inverse',
            'color': AMBAR
        },
        'VERIFY_RESIZE': {
            'class': 'fa fa-arrows-alt  fa-inverse',
            'color': AMBAR
        },
        'SHUTOFF': {
            'class': 'fa fa-stop  fa-inverse',
            'color': AMBAR
        },
        'SOFT_DELETED': {
            'class': 'fa fa-trash  fa-inverse',
            'color': AMBAR
        },
        'STOPPED': {
            'class': 'fa fa-stop  fa-inverse',
            'color': AMBAR
        },
        'SUSPENDED': {
            'class': 'fa fa-pause  fa-inverse',
            'color': AMBAR
        },

        // GRAY
        'UNKNOWN': {
            'class': 'fa fa-question  fa-inverse',
            'color': GRAY
        },

        // RED
        'DELETED': {
            'class': 'fa fa-trash  fa-inverse',
            'color': RED
        },
        'ERROR': {
            'class': 'fa fa-times  fa-inverse',
            'color': RED
        },
        'DELETING': {
            'class': 'fa fa-trash fa-inverse',
            'color': RED,
            'animation': 'working-animation'
        },
        'REVERT_RESIZE': {
            'class': 'fa fa-arrows-alt  fa-inverse',
            'color': RED
        }
    };

    var flavors = {
        '1': '1 VCPU | 512MB RAM | 0GB Disk',
        '2': '1 VCPU | 2048MB RAM | 10GB Disk',
        '3': '2 VCPU | 2MB RAM | 20GB Disk'
    };

    /*****************************************************************
    *                          P R I V A T E                         *
    *****************************************************************/

    function setNameMaxWidth (nonUsableWidth) {

        var bodyWidth = $('body').attr('width');

        if (bodyWidth >= 360) {
            $('#instance-name').css('max-width', bodyWidth - nonUsableWidth);
        }
        else {
            $('#instance-name').css('max-width', 360 - nonUsableWidth);
        }
    }

    function setProgressBarWidth (progressNonUsableWidth) {

        var bodyWidth = $('body').attr('width') >= 360 ? $('body').attr('width') : 360;
        var progressBarWidth = bodyWidth/2 - progressNonUsableWidth;
        $('#progress-bar').css('width', progressBarWidth);

        // Inner text
        $('#progress-bar span').css('left', progressNonUsableWidth + progressBarWidth/2);

        if (bodyWidth <= 360) {
            $('#progress-bar span').css('max-width', 76);
        }
        else {
            $('#progress-bar span').css('max-width', "None");
        }
    }

    function showView(viewId) {

        // Hide all views
        $('#error-view').addClass('hide');
        $('#default-view').addClass('hide');
        $('#detail-view').addClass('hide');
        $('body').removeClass('stripes angled-135');

        // Show view
        $('#' + viewId).removeClass('hide');
    }

    function fixTooltips (instanceData) {

        var power_state = Utils.getDisplayablePowerState(instanceData['OS-EXT-STS:power_state']);
        var statusTooltip = 'Status: ' + instanceData.status + ', ' +
                            'Power State: ' + power_state + ', ' +
                            'VM State: ' + instanceData["OS-EXT-STS:vm_state"];

        $('#instance-status')
            .attr('title', statusTooltip)
            .attr('data-original-title', $('#instance-status').attr('title'))
            .attr('title', '');

        $('#instance-name')
            .attr('title', instanceData.name)
            .attr('data-original-title', $('#instance-name').attr('title'))
            .attr('title', '');

        $('#progress-bar span')
            .attr('title', instanceData["OS-EXT-STS:task_state"])
            .attr('data-original-title', instanceData["OS-EXT-STS:task_state"])
            .attr('title', '');

    }

    function buildDetails (instanceData) {

        var addresses = instanceData.addresses ? Utils.getDisplayableAddresses(instanceData.addresses) : '';
        var power_state = Utils.getDisplayablePowerState(instanceData['OS-EXT-STS:power_state']);
        var displayableTask = (instanceData["OS-EXT-STS:task_state"] && instanceData["OS-EXT-STS:task_state"] !== "") ? instanceData["OS-EXT-STS:task_state"] : "None";

        // Fields
        $('#instance-name').text(instanceData.name);
        $('#instance-owner > span').text(instanceData.user_id);
        $('#instance-id > span').text(instanceData.id);
        $('#instance-image > span').text(instanceData.image.id);
        $('#instance-key-pair > span').text(instanceData.key_name);
        $('#instance-addresses > span').text(addresses);
        $('#instance-flavor > span').text(flavors[instanceData.flavor.id.toString()]);
        $('#instance-created > span').text(instanceData.created);
        $('#instance-updated > span').text(instanceData.updated);

        // Remove previous status
        $('#instance-status').removeClass('working-animation');
        $('#instance-status > div > i').removeClass();

        // Deleting task
        if (displayableTask === 'deleting') {
            $('#instance-status > div > i').addClass(statuses.DELETING.class);
            $('#instance-status').css('background-color', statuses.DELETING.color);
            $('#instance-status').addClass(statuses.DELETING.animation);
        }
        else {
            $('#instance-status > div > i').addClass(statuses[instanceData.status].class);
            $('#instance-status').css('background-color', statuses[instanceData.status].color);
        }

        // Every other task
        if (displayableTask !== 'None') {
            $('#instance-task > span').empty();
            $('#progress-bar span').text(displayableTask);
            $('#progress-bar').removeClass('hide');
            $('#progress').css('background', statuses[instanceData.status].color);
        }
        else {
            $('#instance-task > span').text(displayableTask);
            $('#progress-bar').addClass('hide');
        }
    }

    /*****************************************************************
    *                          P U B L I C                           *
    *****************************************************************/

    function init (callbacks) {

        // Register resize callback
        MashupPlatform.widget.context.registerCallback(function (newValues) {
            if ("heightInPixels" in newValues || "widthInPixels" in newValues) {

                // Set body size
                $('body').attr('height', newValues.heightInPixels);
                $('body').attr('width', newValues.widthInPixels);

                // Set progress bar width
                setProgressBarWidth(PROGRESSNONUSABLEWIDTH);

                // Set name max-width
                setNameMaxWidth(NONUSABLEWIDTH);
            }
        });

        // Init click events
        $('#refresh-button').click(function () {
            callbacks.refresh();
        }.bind(this));
        $('#instance-reboot').click(function () {
            callbacks.reboot();
        }.bind(this));
        $('#instance-terminate').click(function () {
            callbacks.delete();
        }.bind(this));
        $('#instance-image > span').click(function () {

            var id = $(this).text();
            var data = {
                id: id,
                access: JSTACK.Keystone.params.access
            };

            MashupPlatform.wiring.pushEvent('image_id', JSON.stringify(data));
        });

        $('body').attr('width', window.innerWidth);

    }

    function buildDetailView (instanceData) {

        buildDetails(instanceData);
        setNameMaxWidth(NONUSABLEWIDTH);
        setProgressBarWidth(PROGRESSNONUSABLEWIDTH);
        fixTooltips(instanceData);

        // Initialize tooltips
        $('[data-toggle="tooltip"]').tooltip();

        showView('detail-view');
    }

    function buildDefaultView () {

        showView('default-view');
    }

    function buildErrorView (errorResponse) {

        // Build
        if (errorResponse.message) {
            $('#error-view').text(errorResponse.message);
        }
        else {
            $('#error-view').text(errorResponse);
        }

        showView('error-view');
    }

    return {
        buildDetailView: buildDetailView,
        buildDefaultView: buildDefaultView,
        buildErrorView: buildErrorView,
        init: init
    };
})();<|endoftext|>


<commit_before>// TO ADD GLOBALLY
var timerClearObserver = {
	onEnd:function(){
		if(WebFXtimer) clearTimeout(WebFXtimer);
	}
}
Event.observe(window, "load", function(){
	Draggables.addObserver(timerClearObserver);
	//Event.observe('tree_container', "mouseout", function(){timerClearObserver.onEnd();});
});
Event.observe(window, "unload", function(){
	Draggables.removeObserver(timerClearObserver);
	ajaxplorer.filesList.allDraggables.each(function(el){
		el.destroy();
	});
	ajaxplorer.filesList.allDroppables.each(function(el){
		Droppables.remove(el);
	});
});

var AjxpDraggable = Class.create(Draggable, {

    startDrag : function(event){

    if(!this.delta)
    this.delta = this.currentDelta();

	this.dragging = true;
	this._draggingMultiple = false;

	if(this.options.zindex) {
		this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
		this.element.style.zIndex = this.options.zindex;
	}

	if(this.options.ghosting) {
		var selection = ajaxplorer.filesList.getUserSelection();
		//console.log(selection);
		if(selection.isMultiple()){
			// Move all selection
			// Make new div for element, clone all others.
			this._draggingMultiple = true;
			this._clone = document.createElement('div');
			//this._clone.innerHTML = 'files selected';
			this._clone.setAttribute('user_selection', 'true');
			if (browser == 'Internet Explorer'){
				$('browser').appendChild(this._clone);
			}else{
				this.element.parentNode.appendChild(this._clone);
			}
			this.original = this.element;
			this.element = this._clone;
			Position.absolutize(this.element);
			var selectedItems = ajaxplorer.filesList.getSelectedItems();
			for(var i=0; i<selectedItems.length;i++)
			{
				var objectToClone;
				if(ajaxplorer.filesList._displayMode == 'thumb') objectToClone = $(selectedItems[i]);
				else objectToClone = $(selectedItems[i]).getElementsBySelector('span.list_selectable_span')[0];

				this.element.appendChild(refreshPNGImages(objectToClone.cloneNode(true)));
			}
		}else{
			this._clone = this.element.cloneNode(true);
			refreshPNGImages(this._clone);
			Position.absolutize(this.element);
			this.element.parentNode.insertBefore(this._clone, this.element);
			if(browser == 'Internet Explorer') // MOVE ELEMENT TO $('browser')
			{
				var newclone = this.element.cloneNode(true);
				refreshPNGImages(newclone);
				$('browser').appendChild(newclone);
				Element.remove(this.element);
				this.element = newclone;
			}
		}
	}

	if(this.options.scroll) {
		if (this.options.scroll == window) {
			var where = this._getWindowScroll(this.options.scroll);
			this.originalScrollLeft = where.left;
			this.originalScrollTop = where.top;
		} else {
			this.originalScrollLeft = this.options.scroll.scrollLeft;
			this.originalScrollTop = this.options.scroll.scrollTop;
		}
	}

	Draggables.notify('onStart', this, event);

	if(this.options.starteffect){
		if(this._draggingMultiple){
			this.options.starteffect(this.original);
		} else {
			this.options.starteffect(this.element);
		}
	}

},

	finishDrag : function(event, success) {
	this.dragging = false;

	if(this.options.quiet){
		Position.prepare();
		var pointer = [Event.pointerX(event), Event.pointerY(event)];
		Droppables.show(pointer, this.element);
	}

	if(this.options.ghosting && !this._draggingMultiple) {
		removeCopySpan(this.element);
		if(browser == 'Internet Explorer') // MOVE ELEMENT TO $('browser')
		{
			//var newclone = this.element.cloneNode(true);
			this._clone.parentNode.insertBefore(this.element, this._clone);
			//Element.remove(this.element);
			//this.element = newclone;
		}
		Position.relativize(this.element);
		Element.remove(this._clone);
		this._clone = null;
	}

	var dropped = false;
	if(success) {
		dropped = Droppables.fire(event, this.element);
		if (!dropped) dropped = false;
	}
	if(dropped && this.options.onDropped) this.options.onDropped(this.element);
	Draggables.notify('onEnd', this, event);

	var revert = this.options.revert;
	if(revert && typeof revert == 'function') revert = revert(this.element);

	var d = this.currentDelta();
	if(revert && this.options.reverteffect) {
		if (dropped == 0 || revert != 'failure'){
			if(!this._draggingMultiple){
				this.options.reverteffect(this.element,	d[1]-this.delta[1], d[0]-this.delta[0]);
			}
		}
	} else {
		this.delta = d;
	}

	if(this.options.zindex){
		this.element.style.zIndex = this.originalZ;
	}

	if(this.options.endeffect){
		if(this._draggingMultiple){
			this.options.endeffect(this.original);
		}else{
			this.options.endeffect(this.element);
		}
	}

	if(this._draggingMultiple){
		var selectDiv = this.element;
		this.element = this.original;
		Element.remove(selectDiv);
		//this.original = null;
	}

	Draggables.deactivate(this);
	Droppables.reset();
}
});

function updateCtrlKey(draggable, event)
{
	var ctrl = event['ctrlKey'];
	var element = draggable.element;
	if(!$(element).getElementsBySelector('span#copy').length){
		cop = document.createElement('span');
		cop.id = 'copy';
		element.appendChild(cop);
	}else{
		cop = $(element).getElementsBySelector('span#copy')[0];
	}
	cop.innerHTML = (ctrl?'+':'');
}

function removeCopySpan(element)
{
	Element.remove($(element).getElementsBySelector('span#copy')[0]);
}

Draggables.addObserver({onDrag:function(eventName,element,event){updateCtrlKey(element,event);}});<commit_msg>End DragNDrop implementation<commit_after>// TO ADD GLOBALLY
var timerClearObserver = {
	onEnd:function(){
		if(WebFXtimer) clearTimeout(WebFXtimer);
	}
}
Event.observe(window, "load", function(){
	Draggables.addObserver(timerClearObserver);
	//Event.observe('tree_container', "mouseout", function(){timerClearObserver.onEnd();});
});
Event.observe(window, "unload", function(){
	Draggables.removeObserver(timerClearObserver);
	ajaxplorer.filesList.allDraggables.each(function(el){
		el.destroy();
	});
	ajaxplorer.filesList.allDroppables.each(function(el){
		Droppables.remove(el);
	});
});

var AjxpDraggable = Class.create(Draggable, {

    startDrag : function(event){

    if(!this.delta)
    this.delta = this.currentDelta();

	this.dragging = true;
	this._draggingMultiple = false;

	if(this.options.zindex) {
		this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
		this.element.style.zIndex = this.options.zindex;
	}

	if(this.options.ghosting) {
		var selection = ajaxplorer.filesList.getUserSelection();
		//console.log(selection);
		if(selection.isMultiple()){
			// Move all selection
			// Make new div for element, clone all others.
			this._draggingMultiple = true;
			this._clone = document.createElement('div');
			if(ajaxplorer.filesList._displayMode == 'thumb'){
				$(this._clone).addClassName('multiple_thumbnails_draggable');
			}else{
				$(this._clone).addClassName('multiple_selection_draggable');
			}
			this._clone.setAttribute('user_selection', 'true');
			if (browser == 'Internet Explorer'){
				$('browser').appendChild(this._clone);
				$(this._clone).setStyle({width:$(this.element).getWidth()+'px'});
			}else{
				this.element.parentNode.appendChild(this._clone);
			}
			this.original = this.element;
			this.element = this._clone;
			var selectedItems = ajaxplorer.filesList.getSelectedItems();
			for(var i=0; i<selectedItems.length;i++)
			{
				var objectToClone;
				if(ajaxplorer.filesList._displayMode == 'thumb'){
					 objectToClone = $(selectedItems[i]);
				}
				else {
					objectToClone = $(selectedItems[i]).getElementsBySelector('span.list_selectable_span')[0];
				}
				var newObj = refreshPNGImages(objectToClone.cloneNode(true));
				this.element.appendChild(newObj);
				if(ajaxplorer.filesList._displayMode == 'thumb'){
					$(newObj).addClassName('simple_selection_draggable');
				}
			}
			Position.absolutize(this.element);
		}else{
			this._clone = this.element.cloneNode(true);
			refreshPNGImages(this._clone);
			Position.absolutize(this.element);
			this.element.parentNode.insertBefore(this._clone, this.element);
			$(this.element).addClassName('simple_selection_draggable');
			if(browser == 'Internet Explorer') // MOVE ELEMENT TO $('browser')
			{
				var newclone = this.element.cloneNode(true);
				refreshPNGImages(newclone);
				$('browser').appendChild(newclone);
				$(newclone).setStyle({width:$(this._clone).getWidth()+'px'});
				Element.remove(this.element);
				this.element = newclone;
			}
		}
	}

	if(this.options.scroll) {
		if (this.options.scroll == window) {
			var where = this._getWindowScroll(this.options.scroll);
			this.originalScrollLeft = where.left;
			this.originalScrollTop = where.top;
		} else {
			this.originalScrollLeft = this.options.scroll.scrollLeft;
			this.originalScrollTop = this.options.scroll.scrollTop;
		}
	}

	Draggables.notify('onStart', this, event);

	if(this.options.starteffect){
		this.options.starteffect(this.element);
	}

},

	finishDrag : function(event, success) {
	this.dragging = false;

	if(this.options.quiet){
		Position.prepare();
		var pointer = [Event.pointerX(event), Event.pointerY(event)];
		Droppables.show(pointer, this.element);
	}

	if(this.options.ghosting && !this._draggingMultiple) {
		this.removeCopyClass();
		if(browser == 'Internet Explorer') // MOVE ELEMENT TO $('browser')
		{
			this._clone.parentNode.insertBefore(this.element, this._clone);
		}
		this.element.removeClassName('simple_selection_draggable');
		Position.relativize(this.element);
		Element.remove(this._clone);
		this._clone = null;
	}

	var dropped = false;
	if(success) {
		dropped = Droppables.fire(event, this.element);
		if (!dropped) dropped = false;
	}
	if(dropped && this.options.onDropped) this.options.onDropped(this.element);
	Draggables.notify('onEnd', this, event);

	var revert = this.options.revert;
	if(revert && typeof revert == 'function') revert = revert(this.element);

	var d = this.currentDelta();
	if(revert && this.options.reverteffect) {
		if (dropped == 0 || revert != 'failure'){
			if(!this._draggingMultiple){
				this.options.reverteffect(this.element,	d[1]-this.delta[1], d[0]-this.delta[0]);
			}
		}
	} else {
		this.delta = d;
	}

	if(this.options.zindex){
		this.element.style.zIndex = this.originalZ;
	}

	if(this.options.endeffect){
			this.options.endeffect(this.element);
	}

	if(this._draggingMultiple){
		var selectDiv = this.element;
		this.element = this.original;
		Element.remove(selectDiv);
	}

	Draggables.deactivate(this);
	Droppables.reset();
},

	updateCtrlKey: function(event)
	{
		var ctrl = event['ctrlKey'];
		if(ctrl){
			this.addCopyClass();
		}else{
			this.removeCopyClass();
		}
	},

	addCopyClass : function()
	{
		if(this._draggingMultiple && ajaxplorer.filesList._displayMode == 'thumb')
		{
			$(this.element).select('div.thumbnail_selectable_cell').each(function(el){
				el.addClassName('selection_ctrl_key');
			});
		}else{
			$(this.element).addClassName('selection_ctrl_key');
		}
	},

	removeCopyClass : function()
	{
		if(this._draggingMultiple && ajaxplorer.filesList._displayMode == 'thumb')
		{
			$(this.element).select('div.thumbnail_selectable_cell').each(function(el){
				el.removeClassName('selection_ctrl_key');
			});
		}else{
			$(this.element).removeClassName('selection_ctrl_key');
		}
	}

});

Draggables.addObserver({onDrag:function(eventName,element,event){
	if(element.updateCtrlKey){
		element.updateCtrlKey(event);
	}
}});<|endoftext|>


<commit_before>var app=angular.module('login',[]);
app.controller('auth',function($scope){

});
var app=angular.module('registration',[]);
app.controller('create',function($scope){
    $scope.validateForm=function(){
        var fullname=$.trim(document.accountform.user_name.value);
        if(fullname!=""){
            var email=$.trim(document.accountform.user_email.value);
            if(email!=""){
                var pass1=document.accountform.user_password.value;
                if(pass1.length>=8){
                    var pass2=document.accountform.user_password2.value;
                    if(pass2===pass1){
                        $(".btn-primary").addClass("disabled");
                        document.accountform.submit();
                    }
                    else{
                        messageBox("Password Mismatch","Please ensure that the password you repeat matches the first password.");
                    }
                }
                else{
                    messageBox("Invalid Password","Please enter a valid password with at least 8 characters.");
                }
            }
            else{
                messageBox("Invalid Email","Please enter a valid email ID.");
            }
        }
        else{
            messageBox("Invalid Name","Please enter a valid full name.");
        }
    };
});
var app=angular.module('applications',[]);
app.controller('apps',function($scope,$http,$compile){
    $scope.applicationArray=[];
    $scope.application_id=null;
    $scope.appCount=0;
    $scope.getApplications=function(){
        $http({
            method: 'GET',
            url: 'getApplications'
        }).then(function success(response){
            console.log(response);
            response=response.data;
            if(response=="INVALID_USER_ID"){
                window.location='logout';
            }
            else if(response=="NO_APPLICATIONS_FOUND"){
                var p=document.createElement("p");
                $(p).html("No applications found.");
                $("#appHolder").html(p);
            }
            else{
                console.log("here");
                response=JSON.parse(response);
                $scope.applicationArray=response.slice();
                $scope.displayApplications();
            }
        }, function error(response){
            messageBox("Problem","Something went wrong while loading your list of applications. Please try again later. This is the error we see: "+response);
        });
    };
    $scope.displayApplications=function(){
        var applications=$scope.applicationArray.slice();

    };
    $scope.createApplicationForm=function(){
        var form=document.createElement("form");
        $(form).attr("method","post");
        $(form).attr("action","createApplication");
        $(form).attr("autocomplete","off");
        $(form).attr("name","createapp");
            var appTitleGroup=document.createElement("div");
            $(appTitleGroup).addClass("form-group");
            $(appTitleGroup).attr("id","apptitlegroup");
                var appTitleLabel=document.createElement("label");
                $(appTitleLabel).attr("for","apptitle");
                $(appTitleLabel).html("Application title");
                $(appTitleGroup).append(appTitleLabel);
                var appTitle=document.createElement("input");
                $(appTitle).attr("type","text");
                $(appTitle).addClass("form-control");
                $(appTitle).attr("id","apptitle");
                $(appTitle).attr("name","apptitle");
                $(appTitle).attr("placeholder","Enter a valid application name");
                $(appTitle).attr("required","true");
                $(appTitleGroup).append(appTitle);
            $(form).append(appTitleGroup);
            var appDescGroup=document.createElement("div");
            $(appDescGroup).addClass("form-group");
            $(appDescGroup).attr("id","appdescgroup");
                var appDescLabel=document.createElement("label");
                $(appDescLabel).attr("for","appdesc");
                $(appDescLabel).html("Application description");
                $(appDescGroup).append(appDescLabel);
                var appDescTA=document.createElement("textarea");
                $(appDescTA).addClass("form-control");
                $(appDescTA).attr("rows","5");
                $(appDescTA).attr("id","appdesc");
                $(appDescTA).attr("name","appdesc");
                $(appDescTA).attr("placeholder","Enter some description of this application.");
                $(appDescGroup).append(appDescTA);
            $(form).append(appDescGroup);
            var button=document.createElement("button");
            $(button).attr("type","button");
            $(button).addClass("btn btn-primary");
            $(button).attr("ng-click","createApplication()");
            $(button).html("Create");
            $(form).append(button);
        messageBox("Create Application",form);
        $compile("#myModal")($scope);
        $("#apptitle").focus();
    };
    $scope.createApplication=function(){
        var appTitle=$.trim(document.createapp.apptitle.value);
        if(appTitle!=""){
            $("#apptitlegroup").removeClass("has-error");
            var appDesc=$.trim(document.createpp.appdesc.value);
            if(appDesc!=""){
                $("#appdescgroup").removeClass("has-error");
                document.createapp.submit();
            }
            else{
                $("#appdescgroup").addClass("has-error");
            }
        }
        else{
            $("#apptitlegroup").addClass("has-error");
        }
    };
});<commit_msg>Application creation<commit_after>var app=angular.module('login',[]);
app.controller('auth',function($scope){

});
var app=angular.module('registration',[]);
app.controller('create',function($scope){
    $scope.validateForm=function(){
        var fullname=$.trim(document.accountform.user_name.value);
        if(fullname!=""){
            var email=$.trim(document.accountform.user_email.value);
            if(email!=""){
                var pass1=document.accountform.user_password.value;
                if(pass1.length>=8){
                    var pass2=document.accountform.user_password2.value;
                    if(pass2===pass1){
                        $(".btn-primary").addClass("disabled");
                        document.accountform.submit();
                    }
                    else{
                        messageBox("Password Mismatch","Please ensure that the password you repeat matches the first password.");
                    }
                }
                else{
                    messageBox("Invalid Password","Please enter a valid password with at least 8 characters.");
                }
            }
            else{
                messageBox("Invalid Email","Please enter a valid email ID.");
            }
        }
        else{
            messageBox("Invalid Name","Please enter a valid full name.");
        }
    };
});
var app=angular.module('applications',[]);
app.controller('apps',function($scope,$http,$compile){
    $scope.applicationArray=[];
    $scope.application_id=null;
    $scope.appCount=0;
    $scope.getApplications=function(){
        $http({
            method: 'GET',
            url: 'getApplications'
        }).then(function success(response){
            response=$.trim(response.data);
            if(response=="INVALID_USER_ID"){
                window.location='logout';
            }
            else if(response=="NO_APPLICATIONS_FOUND"){
                var p=document.createElement("p");
                $(p).html("No applications found.");
                $("#appHolder").html(p);
            }
            else{
                response=JSON.parse(response);
                $scope.applicationArray=response.slice();
                $scope.displayApplications();
            }
        }, function error(response){
            messageBox("Problem","Something went wrong while loading your list of applications. Please try again later. This is the error we see: "+response);
        });
    };
    $scope.displayApplications=function(){
        var applications=$scope.applicationArray.slice();

    };
    $scope.createApplicationForm=function(){
        var form=document.createElement("form");
        $(form).attr("method","post");
        $(form).attr("action","createApplication");
        $(form).attr("autocomplete","off");
        $(form).attr("name","createapp");
            var appTitleGroup=document.createElement("div");
            $(appTitleGroup).addClass("form-group");
            $(appTitleGroup).attr("id","apptitlegroup");
                var appTitleLabel=document.createElement("label");
                $(appTitleLabel).attr("for","apptitle");
                $(appTitleLabel).html("Application title");
                $(appTitleGroup).append(appTitleLabel);
                var appTitle=document.createElement("input");
                $(appTitle).attr("type","text");
                $(appTitle).addClass("form-control");
                $(appTitle).attr("id","apptitle");
                $(appTitle).attr("name","apptitle");
                $(appTitle).attr("placeholder","Enter a valid application name");
                $(appTitle).attr("required","true");
                $(appTitleGroup).append(appTitle);
            $(form).append(appTitleGroup);
            var appDescGroup=document.createElement("div");
            $(appDescGroup).addClass("form-group");
            $(appDescGroup).attr("id","appdescgroup");
                var appDescLabel=document.createElement("label");
                $(appDescLabel).attr("for","appdesc");
                $(appDescLabel).html("Application description");
                $(appDescGroup).append(appDescLabel);
                var appDescTA=document.createElement("textarea");
                $(appDescTA).addClass("form-control");
                $(appDescTA).attr("rows","5");
                $(appDescTA).attr("id","appdesc");
                $(appDescTA).attr("name","appdesc");
                $(appDescTA).attr("placeholder","Enter some description of this application.");
                $(appDescGroup).append(appDescTA);
            $(form).append(appDescGroup);
            var button=document.createElement("button");
            $(button).attr("type","button");
            $(button).addClass("btn btn-primary");
            $(button).attr("ng-click","createApplication()");
            $(button).html("Create");
            $(form).append(button);
        messageBox("Create Application",form);
        $compile("#myModal")($scope);
        $("#apptitle").focus();
    };
    $scope.createApplication=function(){
        var appTitle=$.trim(document.createapp.apptitle.value);
        if(appTitle!=""){
            $("#apptitlegroup").removeClass("has-error");
            var appDesc=$.trim(document.createpp.appdesc.value);
            if(appDesc!=""){
                $("#appdescgroup").removeClass("has-error");
                document.createapp.submit();
            }
            else{
                $("#appdescgroup").addClass("has-error");
            }
        }
        else{
            $("#apptitlegroup").addClass("has-error");
        }
    };
});<|endoftext|>