<commit_before>/*
 * jQuery treeTable Plugin 2.3.0
 * http://ludo.cubicphuse.nl/jquery-plugins/treeTable/
 *
 * Copyright 2010, Ludo van den Boom
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */
(function($) {
  // Helps to make options available to all functions
  // TODO: This gives problems when there are both expandable and non-expandable
  // trees on a page. The options shouldn't be global to all these instances!
  var options;
  var defaultPaddingLeft;

  $.fn.treeTable = function(opts) {
    options = $.extend({}, $.fn.treeTable.defaults, opts);

    return this.each(function() {
      $(this).addClass("treeTable").find("tbody tr").each(function() {
        // Initialize root nodes only if possible
        if(!options.expandable || $(this)[0].className.search(options.childPrefix) == -1) {
          // To optimize performance of indentation, I retrieve the padding-left
          // value of the first root node. This way I only have to call +css+
          // once.
          if (isNaN(defaultPaddingLeft)) {
            defaultPaddingLeft = parseInt($($(this).children("td")[options.treeColumn]).css('padding-left'), 10);
          }

          initialize($(this));
        } else if(options.initialState == "collapsed") {
          this.style.display = "none"; // Performance! $(this).hide() is slow...
        }
      });
    });
  };

  $.fn.treeTable.defaults = {
    childPrefix: "child-of-",
    clickableNodeNames: false,
    expandable: true,
    indent: 19,
    initialState: "collapsed",
    treeColumn: 0
  };

  // Recursively hide all node's children in a tree
  $.fn.collapse = function() {
    $(this).addClass("collapsed");

    childrenOf($(this)).each(function() {
      if(!$(this).hasClass("collapsed")) {
        $(this).collapse();
      }

      this.style.display = "none"; // Performance! $(this).hide() is slow...
    });

    return this;
  };

  // Recursively show all node's children in a tree
  $.fn.expand = function() {
    $(this).removeClass("collapsed").addClass("expanded");

    childrenOf($(this)).each(function() {
      initialize($(this));

      if($(this).is(".expanded.parent")) {
        $(this).expand();
      }

      // this.style.display = "table-row"; // Unfortunately this is not possible with IE :-(
      $(this).show();
    });

    return this;
  };

  // Reveal a node by expanding all ancestors
  $.fn.reveal = function() {
    $(ancestorsOf($(this)).reverse()).each(function() {
      initialize($(this));
      $(this).expand().show();
    });

    return this;
  };

  // Add an entire branch to +destination+
  $.fn.appendBranchTo = function(destination) {
    var node = $(this);
    var parent = parentOf(node);

    var ancestorNames = $.map(ancestorsOf($(destination)), function(a) { return a.id; });

    // Conditions:
    // 1: +node+ should not be inserted in a location in a branch if this would
    //    result in +node+ being an ancestor of itself.
    // 2: +node+ should not have a parent OR the destination should not be the
    //    same as +node+'s current parent (this last condition prevents +node+
    //    from being moved to the same location where it already is).
    // 3: +node+ should not be inserted as a child of +node+ itself.
    if($.inArray(node[0].id, ancestorNames) == -1 && (!parent || (destination.id != parent[0].id)) && destination.id != node[0].id) {
      indent(node, ancestorsOf(node).length * options.indent * -1); // Remove indentation

      if(parent) { node.removeClass(options.childPrefix + parent[0].id); }

      node.addClass(options.childPrefix + destination.id);
      move(node, destination); // Recursively move nodes to new location
      indent(node, ancestorsOf(node).length * options.indent);
    }

    return this;
  };

  // Add reverse() function from JS Arrays
  $.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
  };

  // Toggle an entire branch
  $.fn.toggleBranch = function() {
    if($(this).hasClass("collapsed")) {
      $(this).expand();
    } else {
      $(this).removeClass("expanded").collapse();
    }

    return this;
  };

  // === Private functions

  function ancestorsOf(node) {
    var ancestors = [];
    while(node = parentOf(node)) {
      ancestors[ancestors.length] = node[0];
    }
    return ancestors;
  };

  function childrenOf(node) {
    return $("table.treeTable tbody tr." + options.childPrefix + node[0].id);
  };

  function getPaddingLeft(node) {
    var paddingLeft = parseInt(node[0].style.paddingLeft, 10);
    return (isNaN(paddingLeft)) ? defaultPaddingLeft : paddingLeft;
  }

  function indent(node, value) {
    var cell = $(node.children("td")[options.treeColumn]);
    cell[0].style.paddingLeft = getPaddingLeft(cell) + value + "px";

    childrenOf(node).each(function() {
      indent($(this), value);
    });
  };

  function initialize(node) {
    if(!node.hasClass("initialized")) {
      node.addClass("initialized");

      var childNodes = childrenOf(node);

      if(!node.hasClass("parent") && childNodes.length > 0) {
        node.addClass("parent");
      }

      if(node.hasClass("parent")) {
        var cell = $(node.children("td")[options.treeColumn]);
        var padding = getPaddingLeft(cell) + options.indent;

        childNodes.each(function() {
          $(this).children("td")[options.treeColumn].style.paddingLeft = padding + "px";
        });

        if(options.expandable) {
          cell.prepend('');
          $(cell[0].firstChild).click(function() { node.toggleBranch(); });

          if(options.clickableNodeNames) {
            cell[0].style.cursor = "pointer";
            $(cell).click(function(e) {
              // Don't double-toggle if the click is on the existing expander icon
              if (e.target.className != 'expander') {
                node.toggleBranch();
              }
            });
          }

          // Check for a class set explicitly by the user, otherwise set the default class
          if(!(node.hasClass("expanded") || node.hasClass("collapsed"))) {
            node.addClass(options.initialState);
          }

          if(node.hasClass("expanded")) {
            node.expand();
          }
        }
      }
    }
  };

  function move(node, destination) {
    node.insertAfter(destination);
    childrenOf(node).reverse().each(function() { move($(this), node[0]); });
  };

  function parentOf(node) {
    var classNames = node[0].className.split(' ');

    for(key in classNames) {
      if(classNames[key].match(options.childPrefix)) {
        return $("#" + classNames[key].substring(9));
      }
    }
  };
})(jQuery);
<commit_msg>Prototype conflict<commit_after>/*
 * jQuery treeTable Plugin 2.3.0
 * http://ludo.cubicphuse.nl/jquery-plugins/treeTable/
 *
 * Copyright 2010, Ludo van den Boom
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */
(function($) {
  // Helps to make options available to all functions
  // TODO: This gives problems when there are both expandable and non-expandable
  // trees on a page. The options shouldn't be global to all these instances!
  var options;
  var defaultPaddingLeft;

  $.fn.treeTable = function(opts) {
    options = $.extend({}, $.fn.treeTable.defaults, opts);

    return this.each(function() {
      $(this).addClass("treeTable").find("tbody tr").each(function() {
        // Initialize root nodes only if possible
        if(!options.expandable || $(this)[0].className.search(options.childPrefix) == -1) {
          // To optimize performance of indentation, I retrieve the padding-left
          // value of the first root node. This way I only have to call +css+
          // once.
          if (isNaN(defaultPaddingLeft)) {
            defaultPaddingLeft = parseInt($($(this).children("td")[options.treeColumn]).css('padding-left'), 10);
          }

          initialize($(this));
        } else if(options.initialState == "collapsed") {
          this.style.display = "none"; // Performance! $(this).hide() is slow...
        }
      });
    });
  };

  $.fn.treeTable.defaults = {
    childPrefix: "child-of-",
    clickableNodeNames: false,
    expandable: true,
    indent: 19,
    initialState: "collapsed",
    treeColumn: 0
  };

  // Recursively hide all node's children in a tree
  $.fn.collapse = function() {
    $(this).addClass("collapsed");

    childrenOf($(this)).each(function() {
      if(!$(this).hasClass("collapsed")) {
        $(this).collapse();
      }

      this.style.display = "none"; // Performance! $(this).hide() is slow...
    });

    return this;
  };

  // Recursively show all node's children in a tree
  $.fn.expand = function() {
    $(this).removeClass("collapsed").addClass("expanded");

    childrenOf($(this)).each(function() {
      initialize($(this));

      if($(this).is(".expanded.parent")) {
        $(this).expand();
      }

      // this.style.display = "table-row"; // Unfortunately this is not possible with IE :-(
      $(this).show();
    });

    return this;
  };

  // Reveal a node by expanding all ancestors
  $.fn.reveal = function() {
    $(ancestorsOf($(this)).reverse()).each(function() {
      initialize($(this));
      $(this).expand().show();
    });

    return this;
  };

  // Add an entire branch to +destination+
  $.fn.appendBranchTo = function(destination) {
    var node = $(this);
    var parent = parentOf(node);

    var ancestorNames = $.map(ancestorsOf($(destination)), function(a) { return a.id; });

    // Conditions:
    // 1: +node+ should not be inserted in a location in a branch if this would
    //    result in +node+ being an ancestor of itself.
    // 2: +node+ should not have a parent OR the destination should not be the
    //    same as +node+'s current parent (this last condition prevents +node+
    //    from being moved to the same location where it already is).
    // 3: +node+ should not be inserted as a child of +node+ itself.
    if($.inArray(node[0].id, ancestorNames) == -1 && (!parent || (destination.id != parent[0].id)) && destination.id != node[0].id) {
      indent(node, ancestorsOf(node).length * options.indent * -1); // Remove indentation

      if(parent) { node.removeClass(options.childPrefix + parent[0].id); }

      node.addClass(options.childPrefix + destination.id);
      move(node, destination); // Recursively move nodes to new location
      indent(node, ancestorsOf(node).length * options.indent);
    }

    return this;
  };

  // Add reverse() function from JS Arrays
  $.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
  };

  // Toggle an entire branch
  $.fn.toggleBranch = function() {
    if($(this).hasClass("collapsed")) {
      $(this).expand();
    } else {
      $(this).removeClass("expanded").collapse();
    }

    return this;
  };

  // === Private functions

  function ancestorsOf(node) {
    var ancestors = [];
    while(node = parentOf(node)) {
      ancestors[ancestors.length] = node[0];
    }
    return ancestors;
  };

  function childrenOf(node) {
    return $("table.treeTable tbody tr." + options.childPrefix + node[0].id);
  };

  function getPaddingLeft(node) {
    var paddingLeft = parseInt(node[0].style.paddingLeft, 10);
    return (isNaN(paddingLeft)) ? defaultPaddingLeft : paddingLeft;
  }

  function indent(node, value) {
    var cell = $(node.children("td")[options.treeColumn]);
    cell[0].style.paddingLeft = getPaddingLeft(cell) + value + "px";

    childrenOf(node).each(function() {
      indent($(this), value);
    });
  };

  function initialize(node) {
    if(!node.hasClass("initialized")) {
      node.addClass("initialized");

      var childNodes = childrenOf(node);

      if(!node.hasClass("parent") && childNodes.length > 0) {
        node.addClass("parent");
      }

      if(node.hasClass("parent")) {
        var cell = $(node.children("td")[options.treeColumn]);
        var padding = getPaddingLeft(cell) + options.indent;

        childNodes.each(function() {
          $(this).children("td")[options.treeColumn].style.paddingLeft = padding + "px";
        });

        if(options.expandable) {
          cell.prepend('');
          $(cell[0].firstChild).click(function() { node.toggleBranch(); });

          if(options.clickableNodeNames) {
            cell[0].style.cursor = "pointer";
            $(cell).click(function(e) {
              // Don't double-toggle if the click is on the existing expander icon
              if (e.target.className != 'expander') {
                node.toggleBranch();
              }
            });
          }

          // Check for a class set explicitly by the user, otherwise set the default class
          if(!(node.hasClass("expanded") || node.hasClass("collapsed"))) {
            node.addClass(options.initialState);
          }

          if(node.hasClass("expanded")) {
            node.expand();
          }
        }
      }
    }
  };

  function move(node, destination) {
    node.insertAfter(destination);
    childrenOf(node).reverse().each(function() { move($(this), node[0]); });
  };

  function parentOf(node) {
    var classNames = node[0].className.split(' ');

    for(key in classNames) {
      if (!key.match(/^[0-9]+$/)) { continue; }
      if(classNames[key].match(options.childPrefix)) {
        return $("#" + classNames[key].substring(9));
      }
    }
  };
})(jQuery);
<|endoftext|>


<commit_before>window.G = (function () {
    "use strict";

    var shortcutNew = function (Constructor) {
        return function () {
            var instance = Object.create(Constructor.prototype);
            Constructor.apply(instance, arguments);
            return instance;
        };
    }

    // Frame ------------------------------------------------------------------

    var Frame = function (elem) {
        if (typeof elem === 'string') {
            elem = document.getElementById(elem);
        }

        var width = elem.scrollWidth;
        var height = elem.scrollHeight;

        this.scene = new THREE.Scene();

        this._initCamera(width, height);
        this.scene.add();

        this._initRenderer(width, height);
        elem.appendChild(this.renderer.domElement);

        this._initControls();
    };

    var frame = shortcutNew(Frame);

    Frame.prototype._initCamera = function (width, height) {
        var viewAngle = 45;
        var aspect = width / (1.0 * height);
        var near = 0.1;
        var far = 10000;

        var camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
        camera.position.z = 10;

        this.camera = camera;
    };

    Frame.prototype._initRenderer = function (width, height) {
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize(width, height);

        this.renderer = renderer;
    };

    Frame.prototype._initControls = function () {
        var self = this;
        var controls = new THREE.TrackballControls(this.camera);

        // A S D
        controls.keys = [ 65, 83, 68 ];

        controls.addEventListener('change', function () {
            self.renderer.render(self.scene, self.camera);
        });

        this.controls = controls;
    };

    Frame.prototype.addNode = function (node) {
        this.scene.add(node.mesh);
    };

    Frame.prototype.addEdge = function (edge) {
        this.scene.add(edge.line);
    };

    Frame.prototype.render = function () {
        var self = this;

        (function animate() {
            window.requestAnimationFrame(animate);
            self.controls.update();
        }());
    };

    // Node -------------------------------------------------------------------

    var Node = function (x, y, z) {
        var geometry = new THREE.SphereGeometry(0.2, 8, 8);
        var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
        this.mesh = new THREE.Mesh(geometry, material);
        this.mesh.position = new THREE.Vector3(x, y, z);
    };

    var node = shortcutNew(Node);

    Node.prototype.addTo = function (frame) {
        frame.addNode(this);
        return this;
    };

    // Edge -------------------------------------------------------------------

    var Edge = function (n1, n2) {
        var material = new THREE.LineBasicMaterial({color: 0x0000ff});
        var geometry = new THREE.Geometry();

        var n1Coords = n1.mesh.position;
        var n2Coords = n2.mesh.position;

        geometry.vertices.push(n1Coords);
        geometry.vertices.push(n2Coords);

        this.line = new THREE.Line(geometry, material);
    };

    var edge = shortcutNew(Edge);

    Edge.prototype.addTo = function (frame) {
        frame.addEdge(this);
        return this;
    };

    return {
        "Frame": Frame,
        "frame": frame,
        "Node": Node,
        "node": node,
        "Edge": Edge,
        "edge": edge,
    };
}());
<commit_msg>A S D keybindings are already added by default<commit_after>window.G = (function () {
    "use strict";

    var shortcutNew = function (Constructor) {
        return function () {
            var instance = Object.create(Constructor.prototype);
            Constructor.apply(instance, arguments);
            return instance;
        };
    }

    // Frame ------------------------------------------------------------------

    var Frame = function (elem) {
        if (typeof elem === 'string') {
            elem = document.getElementById(elem);
        }

        var width = elem.scrollWidth;
        var height = elem.scrollHeight;

        this.scene = new THREE.Scene();

        this._initCamera(width, height);
        this.scene.add();

        this._initRenderer(width, height);
        elem.appendChild(this.renderer.domElement);

        this._initControls();
    };

    var frame = shortcutNew(Frame);

    Frame.prototype._initCamera = function (width, height) {
        var viewAngle = 45;
        var aspect = width / (1.0 * height);
        var near = 0.1;
        var far = 10000;

        var camera = new THREE.PerspectiveCamera(viewAngle, aspect, near, far);
        camera.position.z = 10;

        this.camera = camera;
    };

    Frame.prototype._initRenderer = function (width, height) {
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize(width, height);

        this.renderer = renderer;
    };

    Frame.prototype._initControls = function () {
        var self = this;
        var controls = new THREE.TrackballControls(this.camera);

        controls.addEventListener('change', function () {
            self.renderer.render(self.scene, self.camera);
        });

        this.controls = controls;
    };

    Frame.prototype.addNode = function (node) {
        this.scene.add(node.mesh);
    };

    Frame.prototype.addEdge = function (edge) {
        this.scene.add(edge.line);
    };

    Frame.prototype.render = function () {
        var self = this;

        (function animate() {
            window.requestAnimationFrame(animate);
            self.controls.update();
        }());
    };

    // Node -------------------------------------------------------------------

    var Node = function (x, y, z) {
        var geometry = new THREE.SphereGeometry(0.2, 8, 8);
        var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
        this.mesh = new THREE.Mesh(geometry, material);
        this.mesh.position = new THREE.Vector3(x, y, z);
    };

    var node = shortcutNew(Node);

    Node.prototype.addTo = function (frame) {
        frame.addNode(this);
        return this;
    };

    // Edge -------------------------------------------------------------------

    var Edge = function (n1, n2) {
        var material = new THREE.LineBasicMaterial({color: 0x0000ff});
        var geometry = new THREE.Geometry();

        var n1Coords = n1.mesh.position;
        var n2Coords = n2.mesh.position;

        geometry.vertices.push(n1Coords);
        geometry.vertices.push(n2Coords);

        this.line = new THREE.Line(geometry, material);
    };

    var edge = shortcutNew(Edge);

    Edge.prototype.addTo = function (frame) {
        frame.addEdge(this);
        return this;
    };

    return {
        "Frame": Frame,
        "frame": frame,
        "Node": Node,
        "node": node,
        "Edge": Edge,
        "edge": edge,
    };
}());
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import { shuffle } from 'lodash/collection'
import { camelCase, upperCase, lowerCase } from 'lodash/string'
import SearchTextResult from 'js/components/Search/SearchTextResult'

// Just for fun in development.
const getFakeSearchResults = query => {
  const encodedQuery = encodeURIComponent(query)
  const reversedQuery = query.split('').reverse().join('')
  return shuffle([
    {
      title: `You want ${query}?`,
      linkURL: `https://www.google.com/search?q=${encodedQuery}`,
      snippet: `I guess you want ${query}? That's awesome. It's truly one of the best
        things you could be searching for. I hope you find a search result you like,
        because we're trying to ...`
    },
    {
      title: `"${query}", the new hit single from Kesha`,
      linkURL: `https://www.google.com/search?q=kesha%20${encodedQuery}`,
      snippet: `This track will most likely change your life.`
    },
    {
      title: `How to say "${query}" in Latin`,
      linkURL: `https://www.google.com/search?q=latin%20lessons`,
      snippet: `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
       eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
       veniam, quis nostrud exercitation ...`
    },
    {
      title: `Tab for a Cause, the search result you're looking for`,
      linkURL: `https://tab.gladly.io/`,
      snippet: `Raise money for charity simply by surfing the web! It takes less
        than 30 seconds to start having an impact.`
    },
    {
      title: `${reversedQuery}: taking a different perspective`,
      linkURL: `https://en.wikipedia.org/wiki/Mirror`,
      snippet: `We'll help you look at ${query} from a different perspective.`
    },
    {
      title: `House majority leader: Opponents support "unlimited ${query}"`,
      linkURL: `https://www.nytimes.com/`,
      snippet: `"Our friends across the aisle want every American to have
        unlimited ${query}, regardless of the remarkable costs. We cannot keep
        spending profligately like this."`
    },
    {
      title: `${camelCase(query)} ${lowerCase(query)} ${lowerCase(query)}
        ${upperCase(query)} ${query}`,
      linkURL: `http://www.example.com/`,
      snippet: `${camelCase(query)} ${upperCase(query)} ${query} ${query} ${upperCase(query)}
        (plus tacos) ${lowerCase(query)}`
    }
  ])
}

class SearchResults extends React.PureComponent {
  render () {
    const { query } = this.props
    if (!query) {
      return null
    }
    const results = getFakeSearchResults(this.props.query)
    return (
      <div
        data-test-id='search-results-container'
        style={{
          background: 'none',
          marginLeft: 170,
          maxWidth: 600,
          paddingTop: 20
        }}
      >
        {
          results.map((result, index) => (
            <SearchTextResult
              key={`key-${index}`}
              result={{
                title: result.title,
                linkURL: result.linkURL,
                snippet: result.snippet
              }}
            />
          ))
        }
      </div>
    )
  }
}

SearchResults.propTypes = {
  query: PropTypes.string
}

SearchResults.defaultProps = {}

export default SearchResults
<commit_msg>Tweak fake result<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import { shuffle } from 'lodash/collection'
import { capitalize, camelCase, upperCase, lowerCase } from 'lodash/string'
import SearchTextResult from 'js/components/Search/SearchTextResult'

// Just for fun in development.
const getFakeSearchResults = query => {
  const encodedQuery = encodeURIComponent(query)
  const reversedQuery = query.split('').reverse().join('')
  return shuffle([
    {
      title: `You want ${query}?`,
      linkURL: `https://www.google.com/search?q=${encodedQuery}`,
      snippet: `I guess you want ${query}? That's awesome. It's truly one of the best
        things you could be searching for. I hope you find a search result you like,
        because we're trying to ...`
    },
    {
      title: `"${capitalize(query)}", the new hit single from Kesha`,
      linkURL: `https://www.google.com/search?q=kesha%20${encodedQuery}`,
      snippet: `This track will most likely change your life.`
    },
    {
      title: `How to say "${query}" in Latin`,
      linkURL: `https://www.google.com/search?q=latin%20lessons`,
      snippet: `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
       eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
       veniam, quis nostrud exercitation ...`
    },
    {
      title: `Tab for a Cause, the search result you're looking for`,
      linkURL: `https://tab.gladly.io/`,
      snippet: `Raise money for charity simply by surfing the web! It takes less
        than 30 seconds to start having an impact.`
    },
    {
      title: `${reversedQuery}: taking a different perspective`,
      linkURL: `https://en.wikipedia.org/wiki/Mirror`,
      snippet: `We'll help you look at ${query} from a different perspective.`
    },
    {
      title: `House majority leader: Opponents support "unlimited ${query}"`,
      linkURL: `https://www.nytimes.com/`,
      snippet: `"Our friends across the aisle want every American to have
        unlimited ${query}, regardless of the remarkable costs. We cannot keep
        spending profligately like this."`
    },
    {
      title: `${camelCase(query)} ${lowerCase(query)} ${lowerCase(query)}
        ${upperCase(query)} ${query}`,
      linkURL: `http://www.example.com/`,
      snippet: `${camelCase(query)} ${upperCase(query)} ${query} ${query} ${upperCase(query)}
        (plus tacos) ${lowerCase(query)}`
    }
  ])
}

class SearchResults extends React.PureComponent {
  render () {
    const { query } = this.props
    if (!query) {
      return null
    }
    const results = getFakeSearchResults(this.props.query)
    return (
      <div
        data-test-id='search-results-container'
        style={{
          background: 'none',
          marginLeft: 170,
          maxWidth: 600,
          paddingTop: 20
        }}
      >
        {
          results.map((result, index) => (
            <SearchTextResult
              key={`key-${index}`}
              result={{
                title: result.title,
                linkURL: result.linkURL,
                snippet: result.snippet
              }}
            />
          ))
        }
      </div>
    )
  }
}

SearchResults.propTypes = {
  query: PropTypes.string
}

SearchResults.defaultProps = {}

export default SearchResults
<|endoftext|>


<commit_before>ManageIQ.angular.app.controller('pagingDivButtonGroupController', ['$scope', 'miqService', '$compile', '$attrs', function($scope, miqService, $compile, $attrs) {
  var init = function() {
    saveButton();
    resetButton();
    cancelButton();

    $scope.saveable = miqService.saveable;
    $scope.disabledClick = miqService.disabledClick;
  }

  var saveButton = function() {
    var disabledSaveHtml = '<button name="button" id="save_disabled" type="submit" class="btn btn-primary btn-disabled" ' +
      'alt="Save changes" title="Save changes" ng-click="disabledClick($event)" style="cursor:not-allowed" ' +
      'ng-show="!newRecord && !saveable(angularForm)">Save</button>';
    var compiledDisabledSave = $compile(disabledSaveHtml)($scope);

    var enabledSaveHtml = '<button name="button" id="save_enabled" type="submit" class="btn btn-primary ng-hide" ' +
      'alt="Save changes" title="Save changes" ng-click="saveClicked($event, true)" ' +
      'ng-show="!newRecord && saveable(angularForm)">Save</button>';
    var compiledEnabledSave = $compile(enabledSaveHtml)($scope);

    if (angular.element(document.getElementById('save_disabled')).length == 0) {
      angular.element(document.getElementById($attrs.pagingDivButtonsId)).append(compiledDisabledSave);
    }

    if (angular.element(document.getElementById('save_enabled')).length == 0) {
      angular.element(document.getElementById($attrs.pagingDivButtonsId)).append(compiledEnabledSave);
    }
  }

  var resetButton = function() {
    var resetHtml = '<button name="button" id="reset_enabled_diabled" type="submit" ' +
      'class="btn btn-default btn-disabled" alt="Reset changes" title="Reset changes" ' +
      'ng-class="{\'btn-disabled\': angularForm.$pristine}" ng-click="resetClicked()" ' +
      'ng-disabled="angularForm.$pristine" ng-hide="newRecord" disabled="disabled">Reset</button>';
    var compiledReset = $compile(resetHtml)($scope);

    if (angular.element(document.getElementById('reset_enabled_diabled')).length == 0) {
      angular.element(document.getElementById($attrs.pagingDivButtonsId)).append(compiledReset);
    }
  }

  var cancelButton = function() {
    var cancelHtml = '<button name="button" id="cancel_enabled" type="submit" class="btn btn-default" alt="Cancel" ' +
      'title="Cancel" ng-click="cancelClicked($event)">Cancel</button>';
    var compiledCancel = $compile(cancelHtml)($scope);

    if (angular.element(document.getElementById('cancel_enabled')).length == 0) {
      angular.element(document.getElementById($attrs.pagingDivButtonsId)).append(compiledCancel);
    }
  }
  init();
}]);
<commit_msg>Add i18n support<commit_after>ManageIQ.angular.app.controller('pagingDivButtonGroupController', ['$scope', 'miqService', '$compile', '$attrs', function($scope, miqService, $compile, $attrs) {
  var init = function() {
    saveButton();
    resetButton();
    cancelButton();

    $scope.saveable = miqService.saveable;
    $scope.disabledClick = miqService.disabledClick;
  }

  var saveButton = function() {
    var disabledSaveHtml = sprintf('<button name="button" id="save_disabled" type="submit" class="btn btn-primary btn-disabled" ' +
      'alt=%s title=%s ng-click="disabledClick($event)" style="cursor:not-allowed" ' +
      'ng-show="!newRecord && !saveable(angularForm)">%s</button>', __("Save changes"), __("Save changes"), __("Save"));
    var compiledDisabledSave = $compile(disabledSaveHtml)($scope);

    var enabledSaveHtml = sprintf('<button name="button" id="save_enabled" type="submit" class="btn btn-primary ng-hide" ' +
      'alt=%s title=%s ng-click="saveClicked($event, true)" ' +
      'ng-show="!newRecord && saveable(angularForm)">%s</button>', __("Save changes"), __("Save changes"), __("Save"));
    var compiledEnabledSave = $compile(enabledSaveHtml)($scope);

    if (angular.element(document.getElementById('save_disabled')).length == 0) {
      angular.element(document.getElementById($attrs.pagingDivButtonsId)).append(compiledDisabledSave);
    }

    if (angular.element(document.getElementById('save_enabled')).length == 0) {
      angular.element(document.getElementById($attrs.pagingDivButtonsId)).append(compiledEnabledSave);
    }
  }

  var resetButton = function() {
    var resetHtml = sprintf('<button name="button" id="reset_enabled_diabled" type="submit" ' +
      'class="btn btn-default btn-disabled" alt=%s title=%s ' +
      'ng-class="{\'btn-disabled\': angularForm.$pristine}" ng-click="resetClicked()" ' +
      'ng-disabled="angularForm.$pristine" ng-hide="newRecord" disabled="disabled">%s</button>', __("Reset changes"), __("Reset changes"), __("Reset"));
    var compiledReset = $compile(resetHtml)($scope);

    if (angular.element(document.getElementById('reset_enabled_diabled')).length == 0) {
      angular.element(document.getElementById($attrs.pagingDivButtonsId)).append(compiledReset);
    }
  }

  var cancelButton = function() {
    var cancelHtml = sprintf('<button name="button" id="cancel_enabled" type="submit" class="btn btn-default" alt=%s ' +
      'title=%s ng-click="cancelClicked($event)">%s</button>', __("Cancel"), __("Cancel"), __("Cancel"));
    var compiledCancel = $compile(cancelHtml)($scope);

    if (angular.element(document.getElementById('cancel_enabled')).length == 0) {
      angular.element(document.getElementById($attrs.pagingDivButtonsId)).append(compiledCancel);
    }
  }
  init();
}]);
<|endoftext|>


<commit_before>'use strict';

angular.module('impactApp')
  .factory('FormStepService', function FormStepService($state, formSteps) {
    var stepsById = _.indexBy(formSteps, 'id');

    return {
      getFormSteps: function(form) {
        var currentStep;

        if (form === null) {
          currentStep = stepsById.questionnaire;
          currentStep.state = 'start';
        } else {
          angular.forEach(form.steps, function(step) {
            currentStep = stepsById[step.name];
            currentStep.isEnabled = true;
            debugger;
            currentStep.isFinished = _.find(currentStep.states, {'name' : step.state }).isFinal;
          });
        }

        $state.go(currentStep.sref);
        return formSteps;
      }
    };
  });
<commit_msg>Clean debugger<commit_after>'use strict';

angular.module('impactApp')
  .factory('FormStepService', function FormStepService($state, formSteps) {
    var stepsById = _.indexBy(formSteps, 'id');

    return {
      getFormSteps: function(form) {
        var currentStep;

        if (form === null) {
          currentStep = stepsById.questionnaire;
          currentStep.state = 'start';
        } else {
          angular.forEach(form.steps, function(step) {
            currentStep = stepsById[step.name];
            currentStep.isEnabled = true;
            currentStep.isFinished = _.find(currentStep.states, {'name' : step.state }).isFinal;
          });
        }

        $state.go(currentStep.sref);
        return formSteps;
      }
    };
  });
<|endoftext|>


<commit_before>"use strict";

var fsWalkParallel = require("../lib/fs-walk-parallel");
var mockFs = require("mock-fs");
var test = require("tape");

function setup(t, fakeFs) {
	mockFs.restore();
	mockFs(fakeFs);
}

test("nonexistant folder should return error", function(t) {
	setup(t, {});
	t.plan(1);
	fsWalkParallel("doesntExist", function() {
		throw "should never happen";
	}, function(err) {
		t.ok(err, "should have an error");
		t.end();
	});
});
test("empty folder should return no errors", function(t) {
	setup(t, { "folder": {} });
	t.plan(1);
	fsWalkParallel("folder", function() {
		throw "should never happen";
	}, function(err) {
		t.notOk(err, "should have no errors");
		t.end();
	});
});
test("single file should call iterator once with stat", function(t) {
	setup(t, { "folder": { "file": "contents" } });
	t.plan(2);
	fsWalkParallel("folder", function(stat) {
		t.ok(stat.isFile(), "should return a fs.Stats");
	}, function(err) {
		t.notOk(err, "should have no errors");
		t.end();
	});
});
<commit_msg>Add test for two files<commit_after>"use strict";

var fsWalkParallel = require("../lib/fs-walk-parallel");
var mockFs = require("mock-fs");
var test = require("tape");

function setup(t, fakeFs) {
	mockFs.restore();
	mockFs(fakeFs);
}

test("nonexistant folder should return error", function(t) {
	setup(t, {});
	t.plan(1);
	fsWalkParallel("doesntExist", function() {
		throw "should never happen";
	}, function(err) {
		t.ok(err, "should have an error");
		t.end();
	});
});
test("empty folder should return no errors", function(t) {
	setup(t, { "folder": {} });
	t.plan(1);
	fsWalkParallel("folder", function() {
		throw "should never happen";
	}, function(err) {
		t.notOk(err, "should have no errors");
		t.end();
	});
});
test("two files should call iterator twice with stat", function(t) {
	setup(t, { "folder": { "file1": "contents1", "file2": "contents2" } });
	t.plan(3);
	fsWalkParallel("folder", function(stat) {
		t.ok(stat.isFile(), "should return a fs.Stats");
	}, function(err) {
		t.notOk(err, "should have no errors");
		t.end();
	});
});
<|endoftext|>


<commit_before>var GM_MenuCommander = {};

GM_MenuCommander.createMenuItem = function(command) {
  var menuItem = document.createElement("menuitem");
  menuItem.setAttribute("label", command.name);
  if ('function' == typeof commandFunc) {
    menuItem.addEventListener("command", command.commandFunc, true);
  }

  if (command.accessKey) {
      menuItem.setAttribute("accesskey", command.accessKey);
  }

  return menuItem;
};

GM_MenuCommander.onPopupShowing = function(aMenuPopup) {
  GM_emptyEl(aMenuPopup);

  // Add menu items for commands for the active window.
  var haveCommands = false;
  GM_BrowserUI.gmSvc.withAllMenuCommandsForWindowId(
      GM_windowId(gBrowser.contentWindow),
      function(index, command) {
        if (command.frozen) return;
        aMenuPopup.insertBefore(
            GM_MenuCommander.createMenuItem(command),
            aMenuPopup.firstChild);
        haveCommands = true;
      });
  aMenuPopup.parentNode.disabled = !haveCommands;
};
<commit_msg>Stupid typo.<commit_after>var GM_MenuCommander = {};

GM_MenuCommander.createMenuItem = function(command) {
  var menuItem = document.createElement("menuitem");
  menuItem.setAttribute("label", command.name);
  if ('function' == typeof command.commandFunc) {
    menuItem.addEventListener("command", command.commandFunc, true);
  }

  if (command.accessKey) {
      menuItem.setAttribute("accesskey", command.accessKey);
  }

  return menuItem;
};

GM_MenuCommander.onPopupShowing = function(aMenuPopup) {
  GM_emptyEl(aMenuPopup);

  // Add menu items for commands for the active window.
  var haveCommands = false;
  GM_BrowserUI.gmSvc.withAllMenuCommandsForWindowId(
      GM_windowId(gBrowser.contentWindow),
      function(index, command) {
        if (command.frozen) return;
        aMenuPopup.insertBefore(
            GM_MenuCommander.createMenuItem(command),
            aMenuPopup.firstChild);
        haveCommands = true;
      });
  aMenuPopup.parentNode.disabled = !haveCommands;
};
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import {Link} from 'react-router'

import {KAPACITOR_RULES_TABLE} from 'src/kapacitor/constants/tableSizing'
const {
  colName,
  colType,
  colMessage,
  colAlerts,
  colEnabled,
  colActions,
} = KAPACITOR_RULES_TABLE

const KapacitorRulesTable = ({
  rules,
  source,
  onDelete,
  onReadTickscript,
  onChangeRuleStatus,
}) =>

          Name
          Rule Type
          Message
          Alerts
          Enabled

        {rules.map(rule => {
          return (
            <RuleRow
              key={rule.id}
              rule={rule}
              source={source}
              onDelete={onDelete}
              onChangeRuleStatus={onChangeRuleStatus}
              onRead={onReadTickscript}
            />
          )
        })}

const RuleRow = ({rule, source, onRead, onDelete, onChangeRuleStatus}) =>

      <RuleTitle rule={rule} source={source} />

    {rule.trigger}

        {rule.message}

      {rule.alerts.join(', ')}

        <input
          id={`kapacitor-enabled ${rule.id}`}
          className="form-control-static"
          type="checkbox"
          defaultChecked={rule.status === 'enabled'}
          onClick={() => onChangeRuleStatus(rule)}
        />
        <label htmlFor={`kapacitor-enabled ${rule.id}`} />

      <button className="btn btn-info btn-xs" onClick={() => onRead(rule)}>
        View TICKscript
      </button>
      <button className="btn btn-danger btn-xs" onClick={() => onDelete(rule)}>
        Delete
      </button>

const RuleTitle = ({rule: {id, name, query}, source}) => {
  // no queryConfig means the rule was manually created outside of Chronograf
  if (!query) {
    return {name}
  }

  return <Link to={`/sources/${source.id}/alert-rules/${id}`}>{name}</Link>
}

const {arrayOf, func, shape, string} = PropTypes

KapacitorRulesTable.propTypes = {
  rules: arrayOf(shape()),
  onChangeRuleStatus: func,
  onDelete: func,
  source: shape({
    id: string.isRequired,
  }).isRequired,
  onReadTickscript: func,
}

RuleRow.propTypes = {
  rule: shape(),
  source: shape(),
  onChangeRuleStatus: func,
  onDelete: func,
  onRead: func,
}

RuleTitle.propTypes = {
  rule: shape({
    name: string.isRequired,
    query: shape(),
    links: shape({
      self: string.isRequired,
    }),
  }),
  source: shape({
    id: string.isRequired,
  }).isRequired,
}

export default KapacitorRulesTable
<commit_msg>Sort alert rules table by rules name a-z<commit_after>import React, {PropTypes} from 'react'
import {Link} from 'react-router'
import _ from 'lodash'

import {KAPACITOR_RULES_TABLE} from 'src/kapacitor/constants/tableSizing'
const {
  colName,
  colType,
  colMessage,
  colAlerts,
  colEnabled,
  colActions,
} = KAPACITOR_RULES_TABLE

const KapacitorRulesTable = ({
  rules,
  source,
  onDelete,
  onReadTickscript,
  onChangeRuleStatus,
}) =>

          Name
          Rule Type
          Message
          Alerts
          Enabled

        {_.sortBy(rules, r => r.name.toLowerCase()).map(rule => {
          return (
            <RuleRow
              key={rule.id}
              rule={rule}
              source={source}
              onDelete={onDelete}
              onChangeRuleStatus={onChangeRuleStatus}
              onRead={onReadTickscript}
            />
          )
        })}

const RuleRow = ({rule, source, onRead, onDelete, onChangeRuleStatus}) =>

      <RuleTitle rule={rule} source={source} />

    {rule.trigger}

        {rule.message}

      {rule.alerts.join(', ')}

        <input
          id={`kapacitor-enabled ${rule.id}`}
          className="form-control-static"
          type="checkbox"
          defaultChecked={rule.status === 'enabled'}
          onClick={() => onChangeRuleStatus(rule)}
        />
        <label htmlFor={`kapacitor-enabled ${rule.id}`} />

      <button className="btn btn-info btn-xs" onClick={() => onRead(rule)}>
        View TICKscript
      </button>
      <button className="btn btn-danger btn-xs" onClick={() => onDelete(rule)}>
        Delete
      </button>

const RuleTitle = ({rule: {id, name, query}, source}) => {
  // no queryConfig means the rule was manually created outside of Chronograf
  if (!query) {
    return {name}
  }

  return <Link to={`/sources/${source.id}/alert-rules/${id}`}>{name}</Link>
}

const {arrayOf, func, shape, string} = PropTypes

KapacitorRulesTable.propTypes = {
  rules: arrayOf(shape()),
  onChangeRuleStatus: func,
  onDelete: func,
  source: shape({
    id: string.isRequired,
  }).isRequired,
  onReadTickscript: func,
}

RuleRow.propTypes = {
  rule: shape(),
  source: shape(),
  onChangeRuleStatus: func,
  onDelete: func,
  onRead: func,
}

RuleTitle.propTypes = {
  rule: shape({
    name: string.isRequired,
    query: shape(),
    links: shape({
      self: string.isRequired,
    }),
  }),
  source: shape({
    id: string.isRequired,
  }).isRequired,
}

export default KapacitorRulesTable
<|endoftext|>


<commit_before>// import { addNotification } from 'reapop'
import * as notifications from 'utils/notifications'
import * as t from 'subscriptions/redux/action-types'
import { createAction } from 'utils/redux'
import * as AwaitActions from 'components/await/redux/action-creators'

//
// Action to fetch the user subscription data.
// For more informations about the endpoint, @see https://github.com/nossas/bonde-server/pull/185
// @param Object({
//   id: Integer|String (required)
//   token: String (required)
// })
//
export default ({ id, token }) => (dispatch, getState, { api, intl }) => {
  const endpoint = `/subscriptions/${id}`
  const config = { params: { token } }

  dispatch(AwaitActions.setLoading(true))
  return api
    .get(endpoint, config)
    .then(({ data }) => {
      dispatch(AwaitActions.setLoading(false))
      dispatch(createAction(t.ASYNC_FETCH_SUCCESS, data))
    })
    .catch(e => {
      dispatch(AwaitActions.setLoading(false))
      dispatch(createAction(t.ASYNC_FETCH_FAILURE, e))
      toast.error(notifications.genericRequestError(intl).message, {
        autoClose: 5000,
        hideProgressBar: true,
      })
      // dispatch(addNotification(notifications.genericRequestError(intl)))
      return Promise.reject(e)
    })
}
<commit_msg>feat(admin): refactor notification async-subscription-fetch<commit_after>// import { addNotification } from 'reapop'
import { toast } from 'react-toastify'
import * as notifications from 'utils/notifications'
import * as t from 'subscriptions/redux/action-types'
import { createAction } from 'utils/redux'
import * as AwaitActions from 'components/await/redux/action-creators'

//
// Action to fetch the user subscription data.
// For more informations about the endpoint, @see https://github.com/nossas/bonde-server/pull/185
// @param Object({
//   id: Integer|String (required)
//   token: String (required)
// })
//
export default ({ id, token }) => (dispatch, getState, { api, intl }) => {
  const endpoint = `/subscriptions/${id}`
  const config = { params: { token } }

  dispatch(AwaitActions.setLoading(true))
  return api
    .get(endpoint, config)
    .then(({ data }) => {
      dispatch(AwaitActions.setLoading(false))
      dispatch(createAction(t.ASYNC_FETCH_SUCCESS, data))
    })
    .catch(e => {
      dispatch(AwaitActions.setLoading(false))
      dispatch(createAction(t.ASYNC_FETCH_FAILURE, e))
      toast.error(notifications.genericRequestError(intl).message, {
        autoClose: 5000,
        hideProgressBar: true,
      })
      // dispatch(addNotification(notifications.genericRequestError(intl)))
      return Promise.reject(e)
    })
}
<|endoftext|>


<commit_before>import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action, computed } from "@ember/object";
import { next } from '@ember/runloop'

export default class OxifieldSelectComponent extends Component {
    @tracked customMode = false;

    @computed("content.{options,prompt,is_optional}")
    get options() {
        var options, prompt, ref;
        prompt = this.args.content.prompt;
        if (!prompt && this.args.content.is_optional) {
            prompt = "";
        }
        options = this.args.content.options;
        if (typeof prompt === "string" && prompt !== ((ref = options[0]) != null ? ref.label : void 0)) {
            return [
                {
                    label: prompt,
                    value: ""
                }
            ].concat(options);
        } else {
            return options;
        }
    }

    @computed("content.{options,editable,is_optional}")
    get isStatic() {
        var isEditable, isOptional, options;
        options = this.args.content.options;
        isEditable = this.args.content.editable;
        isOptional = this.args.content.is_optional;
        if (options.length === 1 && !isEditable && !isOptional) {
            this.args.content.value = options[0].value;
            return true;
        } else {
            return false;
        }
    }

    @computed("options", "content.value")
    get isCustomValue() {
        let values = this.options.map(o => o.value);
        let isCustom = values.indexOf[this.args.content.value] < 0;
        this.customMode = isCustom;
        return isCustom;
    }

    @computed("content.value")
    get sanitizedValue() {
        var value = this.args.content.value;
        if (typeof value === "string") return value;

        var options = this.options;
        var ref;
        return ((ref = options[0]) != null ? ref.value : void 0) || "";
    }

    @action
    toggleCustomMode() {
        this.toggleProperty("customMode");
        if (!this.customMode) {
            if (this.isCustomValue) {
                this.args.content.value = this.options[0].value;
            }
        }
        next(this, () => {
            this.$("input,select")[0].focus();
        });
    }

    @action
    optionSelected(value, label) {
        this.args.content.value = value;
    }
}
<commit_msg>JS: fix oxifield-select to update value using set()<commit_after>import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action, computed, set } from "@ember/object";
import { next } from '@ember/runloop'

export default class OxifieldSelectComponent extends Component {
    @tracked customMode = false;

    @computed("content.{options,prompt,is_optional}")
    get options() {
        var options, prompt, ref;
        prompt = this.args.content.prompt;
        if (!prompt && this.args.content.is_optional) {
            prompt = "";
        }
        options = this.args.content.options;
        if (typeof prompt === "string" && prompt !== ((ref = options[0]) != null ? ref.label : void 0)) {
            return [ { label: prompt, value: "" } ].concat(options);
        } else {
            return options;
        }
    }

    @computed("content.{options,editable,is_optional}")
    get isStatic() {
        var isEditable, isOptional, options;
        options = this.args.content.options;
        isEditable = this.args.content.editable;
        isOptional = this.args.content.is_optional;
        if (options.length === 1 && !isEditable && !isOptional) {
            // FIXME side effect of setting value - move somewhere else
            set(this.args.content, "value", this.options[0].value);
            return true;
        } else {
            return false;
        }
    }

    @computed("options", "content.value")
    get isCustomValue() {
        let values = this.options.map(o => o.value);
        let isCustom = values.indexOf[this.args.content.value] < 0;
        this.customMode = isCustom;
        return isCustom;
    }

    @computed("content.value")
    get sanitizedValue() {
        var value = this.args.content.value;
        if (typeof value === "string") return value;

        var options = this.options;
        var ref;
        return ((ref = options[0]) != null ? ref.value : void 0) || "";
    }

    @action
    toggleCustomMode() {
        this.toggleProperty("customMode");
        if (!this.customMode) {
            if (this.isCustomValue) {
                set(this.args.content, "value", this.options[0].value);
            }
        }
        next(this, () => {
            this.$("input,select")[0].focus();
        });
    }

    @action
    optionSelected(value, label) {
        console.warn("oxifield-select: optionSelected", value);
        set(this.args.content, "value", value);
        this.args.onChange();
    }
}
<|endoftext|>


<commit_before>var Spaz;
if (!Spaz) Spaz = {};

/**
 * localization helper. Not yet implemented; just returns the passed string
 */
function $L(str) {
	return str;
}

// Spaz.verified = false;
Spaz.startReloadTimer = function() {
	var refreshInterval = Spaz.Prefs.getRefreshInterval();
	sch.debug('started timer with refresh of ' + refreshInterval + ' msecs');
	reloadID = window.setInterval(Spaz.UI.autoReloadCurrentTab, refreshInterval);
	return reloadID;
};

/**
 * this forces a reload of the index.html doc in the HTMLLoader
 */
Spaz.reloadHTMLDoc = function() {
	Spaz.Prefs.savePrefs();
	window.location.reload();
};

Spaz.stopReloadTimer = function() {
	if (reloadID) {
		window.clearInterval(reloadID);
		sch.debug('stopped timer');
	}
};

Spaz.restartReloadTimer = function() {
	sch.debug('trying to restart timer');
	Spaz.stopReloadTimer();
	Spaz.startReloadTimer();
};

Spaz.createUserDirs = function() {
	var appStore = sch.getFileObject(sch.getAppStorageDir());

	var userThemesDir = Titanium.Filesystem.getFile(appStore, USERDIR_THEMES);
	userThemesDir.createDirectory();

	var userPluginsDir = Titanium.Filesystem.getFile(appStore, USERDIR_PLUGINS);
	userPluginsDir.createDirectory();

	var userSmileysDir = Titanium.Filesystem.getFile(appStore, USERDIR_SMILEYS);
	userSmileysDir.createDirectory();

	var userSoundsDir = Titanium.Filesystem.getFile(appStore, USERDIR_SOUND);
	userSoundsDir.createDirectory();

	sch.debug(userThemesDir.toString());
	sch.debug(userPluginsDir.toString());
	sch.debug(userSmileysDir.toString());
	sch.debug(userSoundsDir.toString());
};

/**
 * loads the user.js file, if it exists, and injects it into the script tag with id='userjs'
 */
Spaz.loadUserJS = function() {
	var userjsfile = sch.getFileObject(sch.getAppStorageDir()).resolve('user.js');

	if (userjsfile.exists()) {
		var userJS = Spaz.Sys.getFileContents(userjsfile.toString());
		$('#userjs').text(userJS);
	} else {
		userjsfile.touch();
		Spaz.Sys.setFileContents(userjsfile.toString(), "/* Edit this file to add your own functionality to Spaz */\n\n");
	}

};

Spaz.loadOAuthServices = function() {
	SpazAuth.addService(SPAZCORE_ACCOUNT_TWITTER, {
        authType: SPAZCORE_AUTHTYPE_OAUTH,
        consumerKey: SPAZCORE_CONSUMERKEY_TWITTER,
        consumerSecret: SPAZCORE_CONSUMERSECRET_TWITTER,
        accessURL: 'https://twitter.com/oauth/access_token'
    });
};

/**
 * Bootstraps the app
 */
Spaz.initialize = function() {

	sch.debug('root init begin');

	/* @TODO find equivalent */
	// window.htmlLoader.navigateInSystemBrowser = false;

	/* @TODO find equivalent */
	// air.NativeApplication.nativeApplication.autoExit = true;

	// create user themes and plugins dirs if necessary
	Spaz.createUserDirs();

	/***************************
	 * Load prefs
	 **************************/
	sch.debug('init prefs');
	Spaz.loadOAuthServices();
	Spaz.Prefs.init();
	Spaz.AccountPrefs.init();

	// turn on inspector
	if (Spaz.Prefs.get('inspector-enabled')) {
		Spaz.Debug.openInspector();
	}

	// turn on debugging
	if (Spaz.Prefs.get('debug-enabled')) {

		/*
			wrap this to log
		*/
		function wrap(fn) {
			return function(){
				Spaz.Debug.logToFile.apply(this, arguments);
				return fn.apply(this, arguments);
			};
		}

		sc.helpers.dump = wrap(sc.helpers.dump);

		sc.setDumpLevel(5);
	}

	// sch.debug('init Sections');
	// Spaz.Section.init();

	// Database initialization
	sch.debug("database initialization");
	// Spaz.DB.init();

    sch.debug('JazzRecord initialization');
    JazzRecord.adapter = new JazzRecord.TitaniumAdapter({dbFile: "spaz_jr.db"});
    if (Spaz.Prefs.get('debug-enabled')) {
     JazzRecord.debug = true;
    }
    JazzRecord.depth = 0;
    JazzRecord.migrate();
    // JazzRecord.addIndex('tweets', 'twitter_id');
    // JazzRecord.addIndex('twusers', 'twitter_id');
    // JazzRecord.addIndex('twusers', 'screen_name');
    JazzRecord.addIndex('drafts', 'updated_at_unixtime');

    Spaz.TweetsModel = new Tweets();

	// Docking initialization
	sch.debug("docking initialization");
	Spaz.Dock.init();

	Spaz.Sys.initUserAgentString();

	Spaz.Windows.makeSystrayIcon();

	// ***************************************************************
	// Keyboard shortcut handling
	// ***************************************************************
	Spaz.Controller.setKeyboardShortcuts();

	// insert theme CSS links
	Spaz.Themes.init();

	/***************************
	 * Apply prefs
	 **************************/
	window.moveTo(Spaz.Prefs.get('window-x'), Spaz.Prefs.get('window-y'));
	window.resizeTo(Spaz.Prefs.get('window-width'), Spaz.Prefs.get('window-height'));
	$('#username').val(Spaz.Prefs.getUsername());
	// $('#password').val(Spaz.Prefs.getPassword());

	//DONE: Check for Update
	if (Spaz.Prefs.get('checkupdate')) {
		sch.debug('Starting check for update');
		Spaz.Update.go();
		sch.debug('Ending check for update');
	}

	/************************
	 * Other stuff to do when document is ready
	 ***********************/
	Spaz.Sounds.playSoundStartup();
	sch.debug('Played startup sound');

	Spaz.Windows.makeWindowVisible();
	sch.debug('Made window visible');

	Spaz.Windows.setWindowOpacity(Spaz.Prefs.get('window-alpha'));
	Spaz.Windows.enableDropShadow(Spaz.Prefs.get('window-dropshadow'));
	Spaz.Windows.enableRestoreOnActivate(Spaz.Prefs.get('window-restoreonactivate'));
	Spaz.Windows.enableMinimizeOnBackground(Spaz.Prefs.get('window-minimizeonbackground'));

	if (Spaz.Prefs.get('window-minimizeatstartup')) {
		Spaz.Windows.windowMinimize();
	}

	/*
		this displays the body
	*/
	// $('body').addClass('visible');

	Spaz.UI.tabbedPanels = new Spry.Widget.TabbedPanels("tabs");

	Spaz.UI.prefsCPG = new Spry.Widget.CollapsiblePanelGroup("prefsCPG", {
		contentIsOpen: false,
		duration: 200
	});

	Spaz.UI.buildToolsMenu();

	// $('.panelmenu form input[title="filter"]').hint();

	$('.TabbedPanelsTab').each(function(i) {
		this.title = this.title + '
Shortcut: CMD or CTRL+' + (parseInt(i, 10) + 1) + '';
	});
	sch.debug('Set shortcut info in tab titles');

	/*
		set-up window and app events
	*/
	Titanium.API.addEventListener(Titanium.EXIT, Spaz.Windows.onWindowClose);
	// air.NativeApplication.nativeApplication.addEventListener(air.Event.EXITING, Spaz.Windows.onAppExit);
	Titanium.API.addEventListener(Titanium.CLOSE, Spaz.Windows.onWindowClose);
	Titanium.API.addEventListener(Titanium.FOCUSED, Spaz.Windows.onWindowActive);
	Titanium.API.addEventListener(Titanium.UNFOCUSED, Spaz.Windows.onWindowDeactivate);

	Spaz.Windows.listenForMove();
	Spaz.Windows.listenForResize();

	/*
		Initialize native menus
	*/
	sch.debug('Spaz.Menus.initAll()');
	Spaz.Menus.initAll();

	/*
		Set up event delegation stuff
	*/
	sch.debug('Spaz.Controller.initIntercept()');
	Spaz.Controller.initIntercept();

	/*
		set-up usernameCompleter
	*/
	sch.debug("new usernameCompleter");
	Spaz.uc = new usernameCompleter({
		'usernames':Spaz.Autocomplete.getScreenNames(),
		'hashtags':Spaz.Autocomplete.getHashTags(),
		'displayDiv':'#suggestions',
		'textarea':'#entrybox',
		'maxMatches':15,
		'timeout':100 // timeout in ms before it kicks in
	});

	/*
		set-up post panel
	*/
	sch.debug("new SpazPostPanel");
	Spaz.postPanel = new SpazPostPanel({
		on_submit:function() {
			this.disable();
			var status = sch.trim(this.getMessageText());
			var auth = Spaz.Prefs.getAuthObject();
			var twit = new SpazTwit({'auth':auth});
			Spaz.Data.setAPIUrl(twit);
			var source = Spaz.Prefs.get('twitter-source');
			var irt_id = this.irt_status_id;
			twit.update(status, source, irt_id,

				function(data) {
					Spaz.postPanel.reset();
					Spaz.postPanel.enable();

					$('#entrybox')[0].blur();

					if (data[0].text.length == 140) {
						if (Spaz.Prefs.get('sound-enabled')) {
							if (Spaz.Prefs.get('wilhelm-enabled')) {
								Spaz.Wilhelm.start();
								Spaz.UI.statusBar("Wilhelm!");
								Spaz.Sounds.playSoundWilhelm();
							} else {
								sch.dump('not doing Wilhelm because Wilhelm disabled');
							}
						} else {
							sch.dump('not doing Wilhelm because sound disabled');
						}
					} else {
						Spaz.Sounds.playSoundUpdate();
						Spaz.UI.statusBar("Update succeeded");
					}

					// if (Spaz.Prefs.get('services-pingfm-enabled')) {
					//	Spaz.Data.updatePingFM(msg);
					// }

				},
				function(xhr, msg, exc) {
					Spaz.postPanel.enable();
					Spaz.UI.statusBar('Posting failed!');
				}
			);
		}
	});
	Spaz.Drafts.updateCounter();

	/*
		Set up timeline calls to action
	*/
	Spaz.Timelines.toggleNewUserCTAs();

	/*
		About popbox
	*/
	$('#about-version').text("v"+Spaz.Sys.getVersion());

	/*
		initialize Image uploader popbox
	*/
	window.SpazImgUpl = new Spaz.ImageUploader();
	window.SpazImgUpl.init();

	// load User JS file
	Spaz.loadUserJS();

	/*
		load news popup
	*/
	setTimeout(Spaz.Newspopup.build, 3000);
	/*
		if we have a username and password set, trigger an "account_switched" event
		to kick things off
	*/
	if (Spaz.Prefs.getUsername() && Spaz.Prefs.getCurrentAccountType()) {

		console.log(Spaz.Prefs.getUsername(), Spaz.Prefs.getCurrentAccountType(), Spaz.Prefs.getCurrentAccount());

		Spaz.AccountPrefs.updateWindowTitleAndToolsMenu(Spaz.Prefs.getCurrentAccount().id); 	// Initialize indicators of current account

		sch.trigger('account_switched', document, Spaz.Prefs.getCurrentAccount());

	}

	sch.debug('ended document.ready()');
};
<commit_msg>hide window at start<commit_after>var Spaz;
if (!Spaz) Spaz = {};

/**
 * localization helper. Not yet implemented; just returns the passed string
 */
function $L(str) {
	return str;
}

// Spaz.verified = false;
Spaz.startReloadTimer = function() {
	var refreshInterval = Spaz.Prefs.getRefreshInterval();
	sch.debug('started timer with refresh of ' + refreshInterval + ' msecs');
	reloadID = window.setInterval(Spaz.UI.autoReloadCurrentTab, refreshInterval);
	return reloadID;
};

/**
 * this forces a reload of the index.html doc in the HTMLLoader
 */
Spaz.reloadHTMLDoc = function() {
	Spaz.Prefs.savePrefs();
	window.location.reload();
};

Spaz.stopReloadTimer = function() {
	if (reloadID) {
		window.clearInterval(reloadID);
		sch.debug('stopped timer');
	}
};

Spaz.restartReloadTimer = function() {
	sch.debug('trying to restart timer');
	Spaz.stopReloadTimer();
	Spaz.startReloadTimer();
};

Spaz.createUserDirs = function() {
	var appStore = sch.getFileObject(sch.getAppStorageDir());

	var userThemesDir = Titanium.Filesystem.getFile(appStore, USERDIR_THEMES);
	userThemesDir.createDirectory();

	var userPluginsDir = Titanium.Filesystem.getFile(appStore, USERDIR_PLUGINS);
	userPluginsDir.createDirectory();

	var userSmileysDir = Titanium.Filesystem.getFile(appStore, USERDIR_SMILEYS);
	userSmileysDir.createDirectory();

	var userSoundsDir = Titanium.Filesystem.getFile(appStore, USERDIR_SOUND);
	userSoundsDir.createDirectory();

	sch.debug(userThemesDir.toString());
	sch.debug(userPluginsDir.toString());
	sch.debug(userSmileysDir.toString());
	sch.debug(userSoundsDir.toString());
};

/**
 * loads the user.js file, if it exists, and injects it into the script tag with id='userjs'
 */
Spaz.loadUserJS = function() {
	var userjsfile = sch.getFileObject(sch.getAppStorageDir()).resolve('user.js');

	if (userjsfile.exists()) {
		var userJS = Spaz.Sys.getFileContents(userjsfile.toString());
		$('#userjs').text(userJS);
	} else {
		userjsfile.touch();
		Spaz.Sys.setFileContents(userjsfile.toString(), "/* Edit this file to add your own functionality to Spaz */\n\n");
	}

};

Spaz.loadOAuthServices = function() {
	SpazAuth.addService(SPAZCORE_ACCOUNT_TWITTER, {
        authType: SPAZCORE_AUTHTYPE_OAUTH,
        consumerKey: SPAZCORE_CONSUMERKEY_TWITTER,
        consumerSecret: SPAZCORE_CONSUMERSECRET_TWITTER,
        accessURL: 'https://twitter.com/oauth/access_token'
    });
};

/**
 * Bootstraps the app
 */
Spaz.initialize = function() {

	Spaz.Windows.makeWindowHidden();

	sch.debug('root init begin');

	/* @TODO find equivalent */
	// window.htmlLoader.navigateInSystemBrowser = false;

	/* @TODO find equivalent */
	// air.NativeApplication.nativeApplication.autoExit = true;

	// create user themes and plugins dirs if necessary
	Spaz.createUserDirs();

	/***************************
	 * Load prefs
	 **************************/
	sch.debug('init prefs');
	Spaz.loadOAuthServices();
	Spaz.Prefs.init();
	Spaz.AccountPrefs.init();

	// turn on inspector
	if (Spaz.Prefs.get('inspector-enabled')) {
		Spaz.Debug.openInspector();
	}

	// turn on debugging
	if (Spaz.Prefs.get('debug-enabled')) {

		/*
			wrap this to log
		*/
		function wrap(fn) {
			return function(){
				Spaz.Debug.logToFile.apply(this, arguments);
				return fn.apply(this, arguments);
			};
		}

		sc.helpers.dump = wrap(sc.helpers.dump);

		sc.setDumpLevel(5);
	}

	// sch.debug('init Sections');
	// Spaz.Section.init();

	// Database initialization
	sch.debug("database initialization");
	// Spaz.DB.init();

    sch.debug('JazzRecord initialization');
    JazzRecord.adapter = new JazzRecord.TitaniumAdapter({dbFile: "spaz_jr.db"});
    if (Spaz.Prefs.get('debug-enabled')) {
     JazzRecord.debug = true;
    }
    JazzRecord.depth = 0;
    JazzRecord.migrate();
    // JazzRecord.addIndex('tweets', 'twitter_id');
    // JazzRecord.addIndex('twusers', 'twitter_id');
    // JazzRecord.addIndex('twusers', 'screen_name');
    JazzRecord.addIndex('drafts', 'updated_at_unixtime');

    Spaz.TweetsModel = new Tweets();

	// Docking initialization
	sch.debug("docking initialization");
	Spaz.Dock.init();

	Spaz.Sys.initUserAgentString();

	Spaz.Windows.makeSystrayIcon();

	// ***************************************************************
	// Keyboard shortcut handling
	// ***************************************************************
	Spaz.Controller.setKeyboardShortcuts();

	// insert theme CSS links
	Spaz.Themes.init();

	/***************************
	 * Apply prefs
	 **************************/
	window.moveTo(Spaz.Prefs.get('window-x'), Spaz.Prefs.get('window-y'));
	window.resizeTo(Spaz.Prefs.get('window-width'), Spaz.Prefs.get('window-height'));
	$('#username').val(Spaz.Prefs.getUsername());
	// $('#password').val(Spaz.Prefs.getPassword());

	//DONE: Check for Update
	if (Spaz.Prefs.get('checkupdate')) {
		sch.debug('Starting check for update');
		Spaz.Update.go();
		sch.debug('Ending check for update');
	}

	/************************
	 * Other stuff to do when document is ready
	 ***********************/
	Spaz.Sounds.playSoundStartup();
	sch.debug('Played startup sound');

	Spaz.Windows.makeWindowVisible();
	sch.debug('Made window visible');

	Spaz.Windows.setWindowOpacity(Spaz.Prefs.get('window-alpha'));
	Spaz.Windows.enableDropShadow(Spaz.Prefs.get('window-dropshadow'));
	Spaz.Windows.enableRestoreOnActivate(Spaz.Prefs.get('window-restoreonactivate'));
	Spaz.Windows.enableMinimizeOnBackground(Spaz.Prefs.get('window-minimizeonbackground'));

	if (Spaz.Prefs.get('window-minimizeatstartup')) {
		Spaz.Windows.windowMinimize();
	}

	/*
		this displays the body
	*/
	// $('body').addClass('visible');

	Spaz.UI.tabbedPanels = new Spry.Widget.TabbedPanels("tabs");

	Spaz.UI.prefsCPG = new Spry.Widget.CollapsiblePanelGroup("prefsCPG", {
		contentIsOpen: false,
		duration: 200
	});

	Spaz.UI.buildToolsMenu();

	// $('.panelmenu form input[title="filter"]').hint();

	$('.TabbedPanelsTab').each(function(i) {
		this.title = this.title + '
Shortcut: CMD or CTRL+' + (parseInt(i, 10) + 1) + '';
	});
	sch.debug('Set shortcut info in tab titles');

	/*
		set-up window and app events
	*/
	Titanium.API.addEventListener(Titanium.EXIT, Spaz.Windows.onWindowClose);
	// air.NativeApplication.nativeApplication.addEventListener(air.Event.EXITING, Spaz.Windows.onAppExit);
	Titanium.API.addEventListener(Titanium.CLOSE, Spaz.Windows.onWindowClose);
	Titanium.API.addEventListener(Titanium.FOCUSED, Spaz.Windows.onWindowActive);
	Titanium.API.addEventListener(Titanium.UNFOCUSED, Spaz.Windows.onWindowDeactivate);

	Spaz.Windows.listenForMove();
	Spaz.Windows.listenForResize();

	/*
		Initialize native menus
	*/
	sch.debug('Spaz.Menus.initAll()');
	Spaz.Menus.initAll();

	/*
		Set up event delegation stuff
	*/
	sch.debug('Spaz.Controller.initIntercept()');
	Spaz.Controller.initIntercept();

	/*
		set-up usernameCompleter
	*/
	sch.debug("new usernameCompleter");
	Spaz.uc = new usernameCompleter({
		'usernames':Spaz.Autocomplete.getScreenNames(),
		'hashtags':Spaz.Autocomplete.getHashTags(),
		'displayDiv':'#suggestions',
		'textarea':'#entrybox',
		'maxMatches':15,
		'timeout':100 // timeout in ms before it kicks in
	});

	/*
		set-up post panel
	*/
	sch.debug("new SpazPostPanel");
	Spaz.postPanel = new SpazPostPanel({
		on_submit:function() {
			this.disable();
			var status = sch.trim(this.getMessageText());
			var auth = Spaz.Prefs.getAuthObject();
			var twit = new SpazTwit({'auth':auth});
			Spaz.Data.setAPIUrl(twit);
			var source = Spaz.Prefs.get('twitter-source');
			var irt_id = this.irt_status_id;
			twit.update(status, source, irt_id,

				function(data) {
					Spaz.postPanel.reset();
					Spaz.postPanel.enable();

					$('#entrybox')[0].blur();

					if (data[0].text.length == 140) {
						if (Spaz.Prefs.get('sound-enabled')) {
							if (Spaz.Prefs.get('wilhelm-enabled')) {
								Spaz.Wilhelm.start();
								Spaz.UI.statusBar("Wilhelm!");
								Spaz.Sounds.playSoundWilhelm();
							} else {
								sch.dump('not doing Wilhelm because Wilhelm disabled');
							}
						} else {
							sch.dump('not doing Wilhelm because sound disabled');
						}
					} else {
						Spaz.Sounds.playSoundUpdate();
						Spaz.UI.statusBar("Update succeeded");
					}

					// if (Spaz.Prefs.get('services-pingfm-enabled')) {
					//	Spaz.Data.updatePingFM(msg);
					// }

				},
				function(xhr, msg, exc) {
					Spaz.postPanel.enable();
					Spaz.UI.statusBar('Posting failed!');
				}
			);
		}
	});
	Spaz.Drafts.updateCounter();

	/*
		Set up timeline calls to action
	*/
	Spaz.Timelines.toggleNewUserCTAs();

	/*
		About popbox
	*/
	$('#about-version').text("v"+Spaz.Sys.getVersion());

	/*
		initialize Image uploader popbox
	*/
	window.SpazImgUpl = new Spaz.ImageUploader();
	window.SpazImgUpl.init();

	// load User JS file
	Spaz.loadUserJS();

	/*
		load news popup
	*/
	setTimeout(Spaz.Newspopup.build, 3000);
	/*
		if we have a username and password set, trigger an "account_switched" event
		to kick things off
	*/
	if (Spaz.Prefs.getUsername() && Spaz.Prefs.getCurrentAccountType()) {

		console.log(Spaz.Prefs.getUsername(), Spaz.Prefs.getCurrentAccountType(), Spaz.Prefs.getCurrentAccount());

		Spaz.AccountPrefs.updateWindowTitleAndToolsMenu(Spaz.Prefs.getCurrentAccount().id); 	// Initialize indicators of current account

		sch.trigger('account_switched', document, Spaz.Prefs.getCurrentAccount());

	}

	sch.debug('ended document.ready()');
};
<|endoftext|>


<commit_before>
uiModule.gis = function() {
  if (!(this instanceof uiModule.gis)) {
    return new uiModule.gis();
  }

  return this;
};

/**
 * Create a placeholder to display current layers
 *
 * @param rootId
 * @param heading
 */
uiModule.gis.createList = function(rootId, heading) {
  var listRoot = document.getElementById(rootId);
  var itemRoot = document.createElement("div");
  itemRoot.setAttribute("class", "accordion-group");
  listRoot.appendChild(itemRoot);

  var itemHeading = document.createElement("div");
  itemHeading.setAttribute("class", "accordion-heading");
  itemRoot.appendChild(itemHeading);

  var itemCollection = document.createElement("a");
  itemCollection.setAttribute("class", "accordion-toggle");
  itemCollection.setAttribute("data-toggle", "collapse");
  itemCollection.setAttribute("data-parent", "#"+rootId);
  itemCollection.setAttribute("href", "#collapse-"+rootId);
  itemCollection.appendChild(document.createTextNode(heading));
  itemHeading.appendChild(itemCollection);

  var subItemsRoot = document.createElement("div");
  subItemsRoot.setAttribute("class", "accordion-body collapse in");
  subItemsRoot.setAttribute("id", "collapse-"+rootId);
  itemRoot.appendChild(subItemsRoot);
  var subItemsList = document.createElement("div");
  subItemsList.setAttribute("class", "accordion-inner");
  subItemsRoot.appendChild(subItemsList);

  var tableRoot = document.createElement("table");
  tableRoot.setAttribute("id", rootId + '-table');
  subItemsList.appendChild(tableRoot);

  var tbody = document.createElement("tbody");
  tableRoot.appendChild(tbody);
};

/**
 * Create a list of documents that could be added as a layer
 *
 * @param rootId
 * @param heading
 * @param layersRootId
 * @param data
 */
uiModule.gis.createDataList = function(rootId, heading, layersRootId, data, callback) {
  var listRoot = $(document.getElementById(rootId));

  var itemRoot = $(document.createElement('div'));
  itemRoot.attr('class', 'accordion-group');
  listRoot.append(itemRoot);

  var itemHeading = $(document.createElement('div'));
  itemHeading.attr('class', 'accordion-heading');
  itemRoot.append(itemHeading);

  var itemCollection = $(document.createElement('a'));
  itemCollection.attr('class', 'accordion-toggle');
  itemCollection.attr('data-toggle', 'collapse');
  itemCollection.attr('data-parent', '#'+rootId);
  itemCollection.attr('href', '#collapse-'+rootId);
  itemCollection.append(document.createTextNode(heading));
  itemHeading.append(itemCollection);

  var subItemsRoot = $(document.createElement('div'));
  subItemsRoot.attr('class', 'accordion-body collapse in');
  subItemsRoot.attr('id', 'collapse-'+rootId);
  itemRoot.append(subItemsRoot);

  var subItemsList = $(document.createElement('div'));
  subItemsList.attr('class', 'accordion-inner');
  subItemsRoot.append(subItemsList);

  var tableRoot = $(document.createElement('table'));
  tableRoot.attr('class', 'table-hover');
  subItemsList.append(tableRoot);

  $.each(data, function(i, item) {
    var row = $(document.createElement('tr'));
    row.attr('class', 'success');
    tableRoot.append(row);

    var col = $(document.createElement('td'));
    var he = $(document.createElement('h4'));
    he.html(item.basename);
    col.append(he);
    row.append(col);

    // Add drop-down so that users can select a variable
    col = $(document.createElement('td'));
    var select = $(document.createElement('select'));
    select.attr('class', 'combobox');
    col.append(select);
    for (var k = 0; k < item.variables.length; ++k) {
      var varname = item.variables[k].name;
      var option = $(document.createElement('option'));
      option.attr('value', varname);
      option.html(varname);
      select.append(option);
    }
    row.append(col);

    // Add 'add' button
    col = $(document.createElement('td'));
    var button = $(document.createElement('button'));
    button.attr('type', 'button');
    button.attr('class', 'btn btn-primary');
    button.attr('id', 'btn-add-' + item.name);
    button.attr('_id', item._id);
    button.attr('name', item.name);
    button.attr('basename', item.basename);
    button.attr('data-toggle', 'button');
    button.append($(document.createTextNode('Add')));
    col.append(button);
    row.append(col);

    if (callback != undefined) {
      $(button).on("click", callback);
    }
  });

  $('.combobox').width(Math.max.apply(Math,
                                       $('.combobox').map(function(){
                                         return $(this).outerWidth();}).get()));
  $('.combobox').select2();
};

/**
 * Add a document as a layer to the list
 *
 * @todo Actually load a layer
 *
 * @param layersRootId
 * @param elem
 */
uiModule.gis.addLayer = function(object, layersRootId, elem, selectfunc, togglefunc,
  removefunc, callback) {

  var rootId = "#" + layersRootId;
  var _id = $(elem).attr("_id");
  if (_id !== null) {
    var tbody = $(rootId).find('tbody');
    var basename = $(elem).attr("name");
    $(elem).removeClass("btn-primary");
    $(elem).addClass("btn-success");
    $(elem).addClass("disabled");
    var layerId = basename;

    var tr = $(document.createElement('tr'));
    tr.attr('id', layerId);
    $(tbody).append(tr);

    // Name of the layer
    var td = $(document.createElement('td'));
    td.append($(document.createElement('h4')).html(basename));
    tr.append(td);

    // Select button
    td = $(document.createElement('td'));
    td.attr('class', 'td-btn-layer');
    var button = $(document.createElement('button'));
    button.attr('class', 'btn-layer btn-select-layer btn btn-primary disabled');
    button.attr('disabled', 'disabled');
    button.html('Select');
    button.click(layerId, function() {
      selectfunc(this, layerId);
    });
    td.append(button);

    // Toggle button
    button = $(document.createElement('button'));
    button.attr('class', 'btn-layer btn-toggle-layer btn btn-warning disabled');
    button.attr('disabled', 'disabled');
    button.html('Toggle');
    button.click(layerId, function() {
      togglefunc(this, layedId);
    });
    td.append(button);

    // Remove button
    button = $(document.createElement('button'));
    button.attr('class', 'btn-layer btn-remove-layer btn btn-danger disabled');
    button.attr('disabled', 'disabled');
    button.html('Remove');
    button.click(layerId, function() {
      removefunc(this, layedId);
    });
    td.append(button);
    tr.append(td);

    $('.btn-layer').width(Math.max.apply(Math,
                                            $('.btn-layer').map(function(){
                                              return $(this).outerWidth();}).get()));
    }
    // @todo Just calling fadeIn does not work. It has to be set invisible
    // and then only it works. We need to check if this is expected.
    $('#'+layerId).fadeOut(0);
    $('#'+layerId).fadeIn('slow', callback);
};

/**
 * Remove a layer from the list
 *
 * @param elem
 * @returns {Boolean}
 */
uiModule.gis.removeLayer = function(elem, layerId) {
  var buttonId = $('#btn-add-'+layerId);
  var button = $(buttonId);

  if (button !== null || button !== undefined) {
    button.removeClass('disabled');
    button.removeClass('btn-success');
    button.removeClass('active');
    button.addClass('btn-primary');

    $('#' + layerId).fadeOut(function() {
      $('#' + layerId).remove();
    });

    return true;
  }

  return false;
};

uiModule.gis.toggleLayer = function(elem, layerId) {
  // Do nothing
};

/**
 * Update UI to when a layer is selected
 */
uiModule.gis.selectLayer = function(target, layerId) {
  $('btn-select-layer').siblings().removeClass('active');

  if (target !== null || target !== undefined) {
    $(target).addClass('active');
  }

  return true;
};
<commit_msg>Fixed naming convention<commit_after>
uiModule.gis = function() {
  if (!(this instanceof uiModule.gis)) {
    return new uiModule.gis();
  }

  return this;
};

/**
 * Create a placeholder to display current layers
 *
 * @param rootId
 * @param heading
 */
uiModule.gis.createList = function(rootId, heading) {
  var listRoot = document.getElementById(rootId);
  var itemRoot = document.createElement("div");
  itemRoot.setAttribute("class", "accordion-group");
  listRoot.appendChild(itemRoot);

  var itemHeading = document.createElement("div");
  itemHeading.setAttribute("class", "accordion-heading");
  itemRoot.appendChild(itemHeading);

  var itemCollection = document.createElement("a");
  itemCollection.setAttribute("class", "accordion-toggle");
  itemCollection.setAttribute("data-toggle", "collapse");
  itemCollection.setAttribute("data-parent", "#"+rootId);
  itemCollection.setAttribute("href", "#collapse-"+rootId);
  itemCollection.appendChild(document.createTextNode(heading));
  itemHeading.appendChild(itemCollection);

  var subItemsRoot = document.createElement("div");
  subItemsRoot.setAttribute("class", "accordion-body collapse in");
  subItemsRoot.setAttribute("id", "collapse-"+rootId);
  itemRoot.appendChild(subItemsRoot);
  var subItemsList = document.createElement("div");
  subItemsList.setAttribute("class", "accordion-inner");
  subItemsRoot.appendChild(subItemsList);

  var tableRoot = document.createElement("table");
  tableRoot.setAttribute("id", 'table-' + rootId);
  subItemsList.appendChild(tableRoot);

  var tbody = document.createElement("tbody");
  tableRoot.appendChild(tbody);
};

/**
 * Create a list of documents that could be added as a layer
 *
 * @param rootId
 * @param heading
 * @param layersRootId
 * @param data
 */
uiModule.gis.createDataList = function(rootId, heading, layersRootId, data, callback) {
  var listRoot = $(document.getElementById(rootId));

  var itemRoot = $(document.createElement('div'));
  itemRoot.attr('class', 'accordion-group');
  listRoot.append(itemRoot);

  var itemHeading = $(document.createElement('div'));
  itemHeading.attr('class', 'accordion-heading');
  itemRoot.append(itemHeading);

  var itemCollection = $(document.createElement('a'));
  itemCollection.attr('class', 'accordion-toggle');
  itemCollection.attr('data-toggle', 'collapse');
  itemCollection.attr('data-parent', '#'+rootId);
  itemCollection.attr('href', '#collapse-'+rootId);
  itemCollection.append(document.createTextNode(heading));
  itemHeading.append(itemCollection);

  var subItemsRoot = $(document.createElement('div'));
  subItemsRoot.attr('class', 'accordion-body collapse in');
  subItemsRoot.attr('id', 'collapse-'+rootId);
  itemRoot.append(subItemsRoot);

  var subItemsList = $(document.createElement('div'));
  subItemsList.attr('class', 'accordion-inner');
  subItemsRoot.append(subItemsList);

  var tableRoot = $(document.createElement('table'));
  tableRoot.attr('class', 'table-hover');
  subItemsList.append(tableRoot);

  $.each(data, function(i, item) {
    var row = $(document.createElement('tr'));
    row.attr('class', 'success');
    tableRoot.append(row);

    var col = $(document.createElement('td'));
    var he = $(document.createElement('h4'));
    he.html(item.basename);
    col.append(he);
    row.append(col);

    // Add drop-down so that users can select a variable
    col = $(document.createElement('td'));
    var select = $(document.createElement('select'));
    select.attr('class', 'combobox');
    col.append(select);
    for (var k = 0; k < item.variables.length; ++k) {
      var varname = item.variables[k].name;
      var option = $(document.createElement('option'));
      option.attr('value', varname);
      option.html(varname);
      select.append(option);
    }
    row.append(col);

    // Add 'add' button
    col = $(document.createElement('td'));
    var button = $(document.createElement('button'));
    button.attr('type', 'button');
    button.attr('class', 'btn btn-primary');
    button.attr('id', 'btn-add-' + item.name);
    button.attr('_id', item._id);
    button.attr('name', item.name);
    button.attr('basename', item.basename);
    button.attr('data-toggle', 'button');
    button.append($(document.createTextNode('Add')));
    col.append(button);
    row.append(col);

    if (callback != undefined) {
      $(button).on("click", callback);
    }
  });

  $('.combobox').width(Math.max.apply(Math,
                                       $('.combobox').map(function(){
                                         return $(this).outerWidth();}).get()));
  $('.combobox').select2();
};

/**
 * Add a document as a layer to the list
 *
 * @todo Actually load a layer
 *
 * @param layersRootId
 * @param elem
 */
uiModule.gis.addLayer = function(object, layersRootId, elem, selectfunc, togglefunc,
  removefunc, callback) {

  var rootId = "#" + layersRootId;
  var _id = $(elem).attr("_id");
  if (_id !== null) {
    var tbody = $(rootId).find('tbody');
    var basename = $(elem).attr("name");
    $(elem).removeClass("btn-primary");
    $(elem).addClass("btn-success");
    $(elem).addClass("disabled");
    var layerId = basename;

    var tr = $(document.createElement('tr'));
    tr.attr('id', layerId);
    $(tbody).append(tr);

    // Name of the layer
    var td = $(document.createElement('td'));
    td.append($(document.createElement('h4')).html(basename));
    tr.append(td);

    // Select button
    td = $(document.createElement('td'));
    td.attr('class', 'td-btn-layer');
    var button = $(document.createElement('button'));
    button.attr('class', 'btn-layer btn-select-layer btn btn-primary disabled');
    button.attr('disabled', 'disabled');
    button.html('Select');
    button.click(layerId, function() {
      selectfunc(this, layerId);
    });
    td.append(button);

    // Toggle button
    button = $(document.createElement('button'));
    button.attr('class', 'btn-layer btn-toggle-layer btn btn-warning disabled');
    button.attr('disabled', 'disabled');
    button.html('Toggle');
    button.click(layerId, function() {
      togglefunc(this, layedId);
    });
    td.append(button);

    // Remove button
    button = $(document.createElement('button'));
    button.attr('class', 'btn-layer btn-remove-layer btn btn-danger disabled');
    button.attr('disabled', 'disabled');
    button.html('Remove');
    button.click(layerId, function() {
      removefunc(this, layedId);
    });
    td.append(button);
    tr.append(td);

    $('.btn-layer').width(Math.max.apply(Math,
                                            $('.btn-layer').map(function(){
                                              return $(this).outerWidth();}).get()));
    }
    // @todo Just calling fadeIn does not work. It has to be set invisible
    // and then only it works. We need to check if this is expected.
    $('#'+layerId).fadeOut(0);
    $('#'+layerId).fadeIn('slow', callback);
};

/**
 * Remove a layer from the list
 *
 * @param elem
 * @returns {Boolean}
 */
uiModule.gis.removeLayer = function(elem, layerId) {
  var buttonId = $('#btn-add-'+layerId);
  var button = $(buttonId);

  if (button !== null || button !== undefined) {
    button.removeClass('disabled');
    button.removeClass('btn-success');
    button.removeClass('active');
    button.addClass('btn-primary');

    $('#' + layerId).fadeOut(function() {
      $('#' + layerId).remove();
    });

    return true;
  }

  return false;
};

uiModule.gis.toggleLayer = function(elem, layerId) {
  // Do nothing
};

/**
 * Update UI to when a layer is selected
 */
uiModule.gis.selectLayer = function(target, layerId) {
  $('btn-select-layer').siblings().removeClass('active');

  if (target !== null || target !== undefined) {
    $(target).addClass('active');
  }

  return true;
};
<|endoftext|>


<commit_before>var restify = require('restify');
var config = require('config').config;
var record = require('../model/record');

function authorize(req, res, next) {
  var apiKey = req.params.key;
  if (apiKey == config.apiKey) {
    return true;
  } else {
    next(new restify.errors.InvalidCredentialsError("Invaild API Key"));
    return false;
  }
}

exports.post = function(req, res, next) {
  if (!authorize(req, res, next)) {
    return;
  }

  var host = req.params.host;
  if (!host) {
    next(new restify.errors.BadRequestError('Invalid host'));
    return;
  }

  var ip = req.params.ip || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  var recordType;

  if (ip.match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/)) {
    recordType = 'A';
  } else if (ip.match(/^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$/)) {
    recordType = 'AAAA';
  } else {
    next(new restify.errors.BadRequestError('Invalid IP address'));
    return;
  }

  var recordTtl = parseInt(req.params.ttl || config.ttl, 10);
  if (isNaN(recordTtl)) {
    next(new restify.errors.BadRequestError('Invalid TTL'));
    return;
  }

  record.create(host, ip, recordType, recordTtl, function(err, result) {
    if (err) {
      console.log(err);
      return next(err);
    }

    res.json(result);
  });
}
<commit_msg>Fix IPv6 regexp<commit_after>var restify = require('restify');
var config = require('config').config;
var record = require('../model/record');

function authorize(req, res, next) {
  var apiKey = req.params.key;
  if (apiKey == config.apiKey) {
    return true;
  } else {
    next(new restify.errors.InvalidCredentialsError("Invaild API Key"));
    return false;
  }
}

exports.post = function(req, res, next) {
  if (!authorize(req, res, next)) {
    return;
  }

  var host = req.params.host;
  if (!host) {
    next(new restify.errors.BadRequestError('Invalid host'));
    return;
  }

  var ip = req.params.ip || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
  var recordType;

  if (ip.match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/)) {
    recordType = 'A';
  } else if (ip.match(/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/)) {
    recordType = 'AAAA';
  } else {
    next(new restify.errors.BadRequestError('Invalid IP address'));
    return;
  }

  var recordTtl = parseInt(req.params.ttl || config.ttl, 10);
  if (isNaN(recordTtl)) {
    next(new restify.errors.BadRequestError('Invalid TTL'));
    return;
  }

  record.create(host, ip, recordType, recordTtl, function(err, result) {
    if (err) {
      console.log(err);
      return next(err);
    }

    res.json(result);
  });
}
<|endoftext|>


<commit_before>const { app, BrowserWindow, Notification } = require('electron');
const fs = require('fs');
const path = require('path');
const process = require('child_process').spawn;
const portfinder = require('detect-port');
let io, window, apiProcess, loadURL, ipc;

app.on('ready', () => {
    portfinder(8000, (error, port) => {
        startSocketApiBridge(port);
    });
});

function startSocketApiBridge(port) {
    io = require('socket.io')(port);
    startAspCoreBackend(port);

    io.on('connection', (socket) => {
        console.log('ASP.NET Core Application connected...');

        socket.on('createBrowserWindow', (options) => {
            console.log(options);
            options.show = true;

            window = new BrowserWindow(options);
            window.loadURL(loadURL);

            window.on('closed', function () {
                mainWindow = null;
                apiProcess = null;
            });

            ipc = require('./api/ipc')(socket, window);
        });

        socket.on('createNotification', (options) => {
            const notification = new Notification(options);
            notification.show();
        });

    });
}

function startAspCoreBackend(electronPort) {
    portfinder(8000, (error, electronWebPort) => {
        loadURL = `http://localhost:${electronWebPort}`
        const arguments = [`/electronPort=${electronPort}`, `/electronWebPort=${electronWebPort}`];

        var binPath = path.join(__dirname, 'bin');
        fs.readdir(binPath, (error, files) => {

            // ToDo: Read 'electronnet.json and use the exectuable'
            // add '.exe' to the exectuable name on windows and leave as is on linux/mac and we are done

            const exeFiles = files.filter((name) => name.indexOf('.exe') > -1);
            const exeFileName = exeFiles[0];
            const apipath = path.join(binPath, exeFileName);
            apiProcess = process(apipath, arguments);

            apiProcess.stdout.on('data', (data) => {
                var text = data.toString();
                console.log(`stdout: ${data.toString()}`);
            });
        });
    });
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

//app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
//    if (win === null) {
//        createWindow();
//    }
//});<commit_msg>implement execute binary file from manifest json file config<commit_after>const { app, BrowserWindow, Notification } = require('electron');
const path = require('path');
const process = require('child_process').spawn;
const portfinder = require('detect-port');
let io, window, apiProcess, loadURL, ipc;

app.on('ready', () => {
    portfinder(8000, (error, port) => {
        startSocketApiBridge(port);
    });
});

function startSocketApiBridge(port) {
    io = require('socket.io')(port);
    startAspCoreBackend(port);

    io.on('connection', (socket) => {
        console.log('ASP.NET Core Application connected...');

        socket.on('createBrowserWindow', (options) => {
            console.log(options);
            options.show = true;

            window = new BrowserWindow(options);
            window.loadURL(loadURL);

            window.on('closed', function () {
                mainWindow = null;
                apiProcess = null;
            });

            ipc = require('./api/ipc')(socket, window);
        });

        socket.on('createNotification', (options) => {
            const notification = new Notification(options);
            notification.show();
        });

    });
}

function startAspCoreBackend(electronPort) {
    portfinder(8000, (error, electronWebPort) => {
        loadURL = `http://localhost:${electronWebPort}`
        const parameters = [`/electronPort=${electronPort}`, `/electronWebPort=${electronWebPort}`];

        const manifestFile = require("./bin/electronnet.json");
        let binaryFile = manifestFile.executable;

        const os = require("os");
        if(os.platform() === "win32") {
            binaryFile = binaryFile + '.exe';
        }

        const binFilePath = path.join(__dirname, 'bin', binaryFile);
        apiProcess = process(binFilePath, parameters);

        apiProcess.stdout.on('data', (data) => {
            var text = data.toString();
            console.log(`stdout: ${data.toString()}`);
        });
    });
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

//app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
//    if (win === null) {
//        createWindow();
//    }
//});<|endoftext|>