<commit_before>require('../util/angular-material-core-slim');

import {MDCDialog, MDCDialogFoundation} from '@material/dialog';

/**
 * @ngdoc component
 * @name mdcDialog
 * @module mdc.dialog
 */
class MdcDialogController {
}

/**
 * @ngdoc component
 * @name mdcDialogHeader
 * @module mdc.dialog
 */

/**
 * @ngdoc component
 * @name mdcDialogTitle
 * @module mdc.dialog
 */

/**
 * @ngdoc component
 * @name mdcDialogBody
 * @module mdc.dialog
 */

/**
 * @ngdoc component
 * @name mdcDialogFooter
 * @module mdc.dialog
 */

/**
 * @ngdoc service
 * @name $mdcDialog
 * @module mdc.dialog
 */
function $mdcDialogProvider($$interimElementSlimProvider) {
  return $$interimElementSlimProvider('$mdcDialog')
    .setDefaults({
      methods: ['parent'],
      options: defaultDialogOptions,
    })
    .addPreset('alert', {
      methods: ['title', 'htmlContent', 'textContent', 'ok', 'css', 'scrollable'],
      options: presetDialogOptions,
    })
    .addPreset('confirm', {
      methods: ['title', 'htmlContent', 'textContent', 'ok', 'cancel', 'css', 'scrollable'],
      options: presetDialogOptions,
    })
    .addPreset('prompt', {
      methods: ['title', 'htmlContent', 'textContent', 'initialValue', 'placeholder',
        'ok', 'cancel', 'css', 'scrollable'],
      options: presetDialogOptions,
    });

  /* @ngInject */
  function presetDialogOptions($mdcDialog) {
    return {
      template: require('raw-loader!./mdc-dialog-service.html'),
      controller: function mdcDialogCtrl() {
        const isPrompt = this.$type === 'prompt';

        if (isPrompt && this.initialValue) {
          this.result = this.initialValue;
        }

        this.keypress = function($event) {
          if ($event.keyCode === 13) {
            $mdcDialog.hide(this.result);
          }
        };
      },
      controllerAs: 'dialog',
      bindToController: true,
    };
  }

  /* @ngInject */
  function defaultDialogOptions($mdcDialog, $injector, $document, $rootElement, $q, $interval) {
    return {
      isolateScope: true,
      onCompiling: beforeCompile,
      onShow: onShow,
      onShowing: beforeShow,
      onRemove: onRemove,
      autoWrap: true,
      transformTemplate: function(template, options) {
        return validatedTemplate(template);

        /**
         * The specified template should contain a <mdc-dialog> wrapper element
         */
        function validatedTemplate(template) {
          if (options.autoWrap && !/<\/mdc-dialog>/g.test(template)) {
            return '<mdc-dialog>' + (template || '') + '</mdc-dialog>';
          } else {
            return template || '';
          }
        }
      },
    };

    function beforeCompile(options) {
    }

    function beforeShow(scope, element, options, controller) {
      if (controller) {
        const mdcHtmlContent = controller.htmlContent || options.htmlContent || '';
        const mdcTextContent = controller.textContent || options.textContent ||
          controller.content || options.content || '';

        if (mdcHtmlContent && !$injector.has('$sanitize')) {
          throw Error('The ngSanitize module must be loaded in order to use htmlContent.');
        }

        if (mdcHtmlContent && mdcTextContent) {
          throw Error('mdc-dialog cannot have both `htmlContent` and `textContent`');
        }

        // Only assign the content if nothing throws, otherwise it'll still be compiled.
        controller.mdcHtmlContent = mdcHtmlContent;
        controller.mdcTextContent = mdcTextContent;
      }
      options.mdcDialog = new MDCDialog(element[0]);
    }

    function onShow(scope, element, options, controller) {
      options.parent = getDomElement(options.parent, $rootElement);
      angular.element(() => { // wait for the DOM refresh before trying to show the dialog
        addEventListeners(controller, options);
        options.mdcDialog.show();
      });
      options.parent.append(element);
    }

    function onRemove(scope, element, options) {
      return $q(function(resolve, reject) {
        removeEventListeners(options);
        options.mdcDialog.close();
        const interval = $interval(function() {
          // wait for close animation to finish before destroying
          if (!element.hasClass(MDCDialogFoundation.cssClasses.ANIMATING)) {
            $interval.cancel(interval);
            resolve();
          }
        }, 10);
      }).then(function() {
        options.mdcDialog.destroy();
        // Exposed cleanup function from the $mdCompiler.
        options.cleanupElement();
        // Restores the focus to the origin element if the last interaction upon opening was a keyboard.
        if (!options.$destroy && options.originInteraction === 'keyboard') {
          options.origin.focus();
        }
      });
    }

    function addEventListeners(controller, options) {
      options.onAcceptHandler = (e) => {
        e.stopPropagation();
        $mdcDialog.hide(controller ? controller.result : undefined);
      };
      options.onCancelHandler = (e) => {
        e.stopPropagation();
        $mdcDialog.cancel();
      };

      options.mdcDialog.listen(MDCDialogFoundation.strings.ACCEPT_EVENT, options.onAcceptHandler);
      options.mdcDialog.listen(MDCDialogFoundation.strings.CANCEL_EVENT, options.onCancelHandler);
    }

    function removeEventListeners(options) {
      options.mdcDialog.unlisten(MDCDialogFoundation.strings.ACCEPT_EVENT, options.onAcceptHandler);
      options.mdcDialog.unlisten(MDCDialogFoundation.strings.CANCEL_EVENT, options.onCancelHandler);
    }

    /**
     * If the specifier is a simple string selector, then query for
     * the DOM element.
     */
    function getDomElement(element, defaultElement) {
      if (angular.isString(element)) {
        element = $document[0].querySelector(element);
      }

      // If we have a reference to a raw dom element, always wrap it in jqLite
      return angular.element(element || defaultElement);
    }
  }
}

/**
 * @ngdoc method
 * @name $mdcDialog#show
 *
 * @description Show a dialog with the specified options.
 *
 * @param {Object} options - Either provide an `$mdcDialogPreset` or an options object with the following properties:
 * @param {string} [options.templateUrl] - The url of a template that will be used as the content
 *      of the dialog.
 * @param {string} [options.template] - HTML template to show in the dialog. This **must** be trusted HTML
 *      with respect to Angular's [$sce service](https://docs.angularjs.org/api/ng/service/$sce).
 *      This template should **never** be constructed with any kind of user input or user data.
 * @param {string|Element} [options.contentElement] - Instead of using a template, which will be compiled each time a
 *     dialog opens, you can also use a DOM element.
 *     When specifying an element, which is present on the DOM, `$mdcDialog` will temporary fetch the element into
 *     the dialog and restores it at the old DOM position upon close.
 *     When specifying a string, the string be used as a CSS selector, to lookup for the element in the DOM.
 * @param {boolean} [options.autoWrap] - Whether or not to automatically wrap the template with a
 *     `<mdc-dialog>` tag if one is not provided. Defaults to true. Can be disabled if you provide a
 *     custom dialog directive.
 * @param {Object} [options.scope] - the scope to link the template / controller to. If none is specified,
 *     it will create a new isolate scope.
 *     This scope will be destroyed when the dialog is removed unless `preserveScope` is set to true.
 * @param {boolean} [options.preserveScope=false] - whether to preserve the scope when the element is removed.
 * @param {function|string} [options.controller] - The controller to associate with the dialog. The controller
 *     will be injected with the local `$mdcDialog`, which passes along a scope for the dialog.
 * @param {Object} [options.locals] - An object containing key/value pairs. The keys will be used as names
 *     of values to inject into the controller. For example, `locals: {three: 3}` would inject
 *     `three` into the controller, with the value 3. If `bindToController` is true, they will be
 *     copied to the controller instead.
 * @param {boolean} options.bindToController - bind the locals to the controller, instead of passing them in.
 * @param {Object} [options.resolve] - Similar to locals, except it takes promises as values, and the
 *     dialog will not open until all of the promises resolve.
 * @param {string} [options.controllerAs] - An alias to assign the controller to on the scope.
 * @param {Element} [options.parent] - The element to append the dialog to. Defaults to appending
 *     to the root element of the application.
 * @param {function} [options.onShowing] - Callback function used to announce the show() action is
 *     starting.
 * @param {function} [options.onComplete] - Callback function used to announce when the show() action is
 *     finished.
 * @param {function} [options.onRemoving] - Callback function used to announce the
 *      close/hide() action is starting. This allows developers to run custom animations
 *      in parallel the close animations.
 * @returns {promise} A promise that can be resolved with `$mdcDialog.hide()` or rejected with `$mdcDialog.cancel()`.
 */

/**
 * @ngdoc method
 * @name $mdcDialog#alert
 *
 * @description
 * Builds a preconfigured dialog with the specified message.
 *
 * @returns {Object} an `$mdcDialogPreset` with the chainable configuration methods:
 *
 * - $mdcDialogPreset#title(string) - Sets the alert title.
 * - $mdcDialogPreset#textContent(string) - Sets the alert message.
 * - $mdcDialogPreset#htmlContent(string) - Sets the alert message as HTML. Requires ngSanitize
 *     module to be loaded. HTML is not run through Angular's compiler.
 * - $mdcDialogPreset#ok(string) - Sets the alert "Okay" button text.
 * - $mdcDialogPreset#css(string) - Custom classes to apply to mdc-dialog using ng-class
 * - $mdcDialogPreset#scrollable(boolean) - Whether the body of the element has a vertical scrollbar
 *
 */

/**
 * @ngdoc method
 * @name $mdcDialog#confirm
 *
 * @description
 * Builds a preconfigured dialog with the specified message. You can call show and the promise returned
 * will be resolved only if the user clicks the confirm action on the dialog.
 *
 * @returns {Object} an `$mdcDialogPreset` with the chainable configuration methods:
 *
 * Additionally, it supports the following methods:
 *
 * - $mdcDialogPreset#title(string) - Sets the confirm title.
 * - $mdcDialogPreset#textContent(string) - Sets the confirm message.
 * - $mdcDialogPreset#htmlContent(string) - Sets the confirm message as HTML. Requires ngSanitize
 *     module to be loaded. HTML is not run through Angular's compiler.
 * - $mdcDialogPreset#ok(string) - Sets the confirm "Okay" button text.
 * - $mdcDialogPreset#cancel(string) - Sets the confirm "Cancel" button text.
 * - $mdcDialogPreset#css(string) - Custom classes to apply to mdc-dialog using ng-class
 * - $mdcDialogPreset#scrollable(boolean) - Whether the body of the element has a vertical scrollbar
 *
 */

/**
 * @ngdoc method
 * @name $mdcDialog#prompt
 *
 * @description
 * Builds a preconfigured dialog with the specified message and input box. You can call show and the promise returned
 * will be resolved only if the user clicks the prompt action on the dialog, passing the input value
 * as the first argument.
 *
 * @returns {Object} an `$mdcDialogPreset` with the chainable configuration methods:
 *
 * Additionally, it supports the following methods:
 *
 * - $mdcDialogPreset#title(string) - Sets the prompt title.
 * - $mdcDialogPreset#textContent(string) - Sets the prompt message.
 * - $mdcDialogPreset#htmlContent(string) - Sets the prompt message as HTML. Requires ngSanitize
 *     module to be loaded. HTML is not run through Angular's compiler.
 * - $mdcDialogPreset#placeholder(string) - Sets the placeholder text for the input.
 * - $mdcDialogPreset#initialValue(string) - Sets the initial value for the prompt input.
 * - $mdcDialogPreset#ok(string) - Sets the prompt "Okay" button text.
 * - $mdcDialogPreset#cancel(string) - Sets the prompt "Cancel" button text.
 * - $mdcDialogPreset#css(string) - Custom classes to apply to mdc-dialog using ng-class
 * - $mdcDialogPreset#scrollable(boolean) - Whether the body of the element has a vertical scrollbar
 *
 */

/**
 * @ngdoc method
 * @name $mdcDialog#hide
 *
 * @description Hide an existing dialog and resolve the promise returned from `$mdcDialog.show()`.
 *
 * @param {*=} response An argument for the resolved promise.
 *
 * @returns {promise} A promise that is resolved when the dialog has been closed.
 */

/**
 * @ngdoc method
 * @name $mdcDialog#cancel
 *
 * @description Hide an existing dialog and reject the promise returned from `$mdcDialog.show()`.
 *
 * @param {*=} response An argument for the rejected promise.
 *
 * @returns {promise} A promise that is resolved when the dialog has been closed.
 */

angular
  .module('mdc.dialog', ['material.core.slim'])
  .provider('$mdcDialog', $mdcDialogProvider)
  .component('mdcDialog', {
    controller: MdcDialogController,
    template: require('raw-loader!./mdc-dialog-component.html'),
    transclude: true,
  });
<commit_msg>AP-132 Hook into element.ready when waiting for dialog append<commit_after>require('../util/angular-material-core-slim');

import {MDCDialog, MDCDialogFoundation} from '@material/dialog';

/**
 * @ngdoc component
 * @name mdcDialog
 * @module mdc.dialog
 */
class MdcDialogController {
}

/**
 * @ngdoc component
 * @name mdcDialogHeader
 * @module mdc.dialog
 */

/**
 * @ngdoc component
 * @name mdcDialogTitle
 * @module mdc.dialog
 */

/**
 * @ngdoc component
 * @name mdcDialogBody
 * @module mdc.dialog
 */

/**
 * @ngdoc component
 * @name mdcDialogFooter
 * @module mdc.dialog
 */

/**
 * @ngdoc service
 * @name $mdcDialog
 * @module mdc.dialog
 */
function $mdcDialogProvider($$interimElementSlimProvider) {
  return $$interimElementSlimProvider('$mdcDialog')
    .setDefaults({
      methods: ['parent'],
      options: defaultDialogOptions,
    })
    .addPreset('alert', {
      methods: ['title', 'htmlContent', 'textContent', 'ok', 'css', 'scrollable'],
      options: presetDialogOptions,
    })
    .addPreset('confirm', {
      methods: ['title', 'htmlContent', 'textContent', 'ok', 'cancel', 'css', 'scrollable'],
      options: presetDialogOptions,
    })
    .addPreset('prompt', {
      methods: ['title', 'htmlContent', 'textContent', 'initialValue', 'placeholder',
        'ok', 'cancel', 'css', 'scrollable'],
      options: presetDialogOptions,
    });

  /* @ngInject */
  function presetDialogOptions($mdcDialog) {
    return {
      template: require('raw-loader!./mdc-dialog-service.html'),
      controller: function mdcDialogCtrl() {
        const isPrompt = this.$type === 'prompt';

        if (isPrompt && this.initialValue) {
          this.result = this.initialValue;
        }

        this.keypress = function($event) {
          if ($event.keyCode === 13) {
            $mdcDialog.hide(this.result);
          }
        };
      },
      controllerAs: 'dialog',
      bindToController: true,
    };
  }

  /* @ngInject */
  function defaultDialogOptions($mdcDialog, $injector, $document, $rootElement, $q, $interval) {
    return {
      isolateScope: true,
      onCompiling: beforeCompile,
      onShow: onShow,
      onShowing: beforeShow,
      onRemove: onRemove,
      autoWrap: true,
      transformTemplate: function(template, options) {
        return validatedTemplate(template);

        /**
         * The specified template should contain a <mdc-dialog> wrapper element
         */
        function validatedTemplate(template) {
          if (options.autoWrap && !/<\/mdc-dialog>/g.test(template)) {
            return '<mdc-dialog>' + (template || '') + '</mdc-dialog>';
          } else {
            return template || '';
          }
        }
      },
    };

    function beforeCompile(options) {
    }

    function beforeShow(scope, element, options, controller) {
      if (controller) {
        const mdcHtmlContent = controller.htmlContent || options.htmlContent || '';
        const mdcTextContent = controller.textContent || options.textContent ||
          controller.content || options.content || '';

        if (mdcHtmlContent && !$injector.has('$sanitize')) {
          throw Error('The ngSanitize module must be loaded in order to use htmlContent.');
        }

        if (mdcHtmlContent && mdcTextContent) {
          throw Error('mdc-dialog cannot have both `htmlContent` and `textContent`');
        }

        // Only assign the content if nothing throws, otherwise it'll still be compiled.
        controller.mdcHtmlContent = mdcHtmlContent;
        controller.mdcTextContent = mdcTextContent;
      }
      options.mdcDialog = new MDCDialog(element[0]);
    }

    function onShow(scope, element, options, controller) {
      options.parent = getDomElement(options.parent, $rootElement);
      element.ready(() => { // wait for the DOM refresh before trying to show the dialog
        addEventListeners(controller, options);
        options.mdcDialog.show();
      });
      options.parent.append(element);
    }

    function onRemove(scope, element, options) {
      return $q(function(resolve, reject) {
        removeEventListeners(options);
        options.mdcDialog.close();
        const interval = $interval(function() {
          // wait for close animation to finish before destroying
          if (!element.hasClass(MDCDialogFoundation.cssClasses.ANIMATING)) {
            $interval.cancel(interval);
            resolve();
          }
        }, 10);
      }).then(function() {
        options.mdcDialog.destroy();
        // Exposed cleanup function from the $mdCompiler.
        options.cleanupElement();
        // Restores the focus to the origin element if the last interaction upon opening was a keyboard.
        if (!options.$destroy && options.originInteraction === 'keyboard') {
          options.origin.focus();
        }
      });
    }

    function addEventListeners(controller, options) {
      options.onAcceptHandler = (e) => {
        e.stopPropagation();
        $mdcDialog.hide(controller ? controller.result : undefined);
      };
      options.onCancelHandler = (e) => {
        e.stopPropagation();
        $mdcDialog.cancel();
      };

      options.mdcDialog.listen(MDCDialogFoundation.strings.ACCEPT_EVENT, options.onAcceptHandler);
      options.mdcDialog.listen(MDCDialogFoundation.strings.CANCEL_EVENT, options.onCancelHandler);
    }

    function removeEventListeners(options) {
      options.mdcDialog.unlisten(MDCDialogFoundation.strings.ACCEPT_EVENT, options.onAcceptHandler);
      options.mdcDialog.unlisten(MDCDialogFoundation.strings.CANCEL_EVENT, options.onCancelHandler);
    }

    /**
     * If the specifier is a simple string selector, then query for
     * the DOM element.
     */
    function getDomElement(element, defaultElement) {
      if (angular.isString(element)) {
        element = $document[0].querySelector(element);
      }

      // If we have a reference to a raw dom element, always wrap it in jqLite
      return angular.element(element || defaultElement);
    }
  }
}

/**
 * @ngdoc method
 * @name $mdcDialog#show
 *
 * @description Show a dialog with the specified options.
 *
 * @param {Object} options - Either provide an `$mdcDialogPreset` or an options object with the following properties:
 * @param {string} [options.templateUrl] - The url of a template that will be used as the content
 *      of the dialog.
 * @param {string} [options.template] - HTML template to show in the dialog. This **must** be trusted HTML
 *      with respect to Angular's [$sce service](https://docs.angularjs.org/api/ng/service/$sce).
 *      This template should **never** be constructed with any kind of user input or user data.
 * @param {string|Element} [options.contentElement] - Instead of using a template, which will be compiled each time a
 *     dialog opens, you can also use a DOM element.
 *     When specifying an element, which is present on the DOM, `$mdcDialog` will temporary fetch the element into
 *     the dialog and restores it at the old DOM position upon close.
 *     When specifying a string, the string be used as a CSS selector, to lookup for the element in the DOM.
 * @param {boolean} [options.autoWrap] - Whether or not to automatically wrap the template with a
 *     `<mdc-dialog>` tag if one is not provided. Defaults to true. Can be disabled if you provide a
 *     custom dialog directive.
 * @param {Object} [options.scope] - the scope to link the template / controller to. If none is specified,
 *     it will create a new isolate scope.
 *     This scope will be destroyed when the dialog is removed unless `preserveScope` is set to true.
 * @param {boolean} [options.preserveScope=false] - whether to preserve the scope when the element is removed.
 * @param {function|string} [options.controller] - The controller to associate with the dialog. The controller
 *     will be injected with the local `$mdcDialog`, which passes along a scope for the dialog.
 * @param {Object} [options.locals] - An object containing key/value pairs. The keys will be used as names
 *     of values to inject into the controller. For example, `locals: {three: 3}` would inject
 *     `three` into the controller, with the value 3. If `bindToController` is true, they will be
 *     copied to the controller instead.
 * @param {boolean} options.bindToController - bind the locals to the controller, instead of passing them in.
 * @param {Object} [options.resolve] - Similar to locals, except it takes promises as values, and the
 *     dialog will not open until all of the promises resolve.
 * @param {string} [options.controllerAs] - An alias to assign the controller to on the scope.
 * @param {Element} [options.parent] - The element to append the dialog to. Defaults to appending
 *     to the root element of the application.
 * @param {function} [options.onShowing] - Callback function used to announce the show() action is
 *     starting.
 * @param {function} [options.onComplete] - Callback function used to announce when the show() action is
 *     finished.
 * @param {function} [options.onRemoving] - Callback function used to announce the
 *      close/hide() action is starting. This allows developers to run custom animations
 *      in parallel the close animations.
 * @returns {promise} A promise that can be resolved with `$mdcDialog.hide()` or rejected with `$mdcDialog.cancel()`.
 */

/**
 * @ngdoc method
 * @name $mdcDialog#alert
 *
 * @description
 * Builds a preconfigured dialog with the specified message.
 *
 * @returns {Object} an `$mdcDialogPreset` with the chainable configuration methods:
 *
 * - $mdcDialogPreset#title(string) - Sets the alert title.
 * - $mdcDialogPreset#textContent(string) - Sets the alert message.
 * - $mdcDialogPreset#htmlContent(string) - Sets the alert message as HTML. Requires ngSanitize
 *     module to be loaded. HTML is not run through Angular's compiler.
 * - $mdcDialogPreset#ok(string) - Sets the alert "Okay" button text.
 * - $mdcDialogPreset#css(string) - Custom classes to apply to mdc-dialog using ng-class
 * - $mdcDialogPreset#scrollable(boolean) - Whether the body of the element has a vertical scrollbar
 *
 */

/**
 * @ngdoc method
 * @name $mdcDialog#confirm
 *
 * @description
 * Builds a preconfigured dialog with the specified message. You can call show and the promise returned
 * will be resolved only if the user clicks the confirm action on the dialog.
 *
 * @returns {Object} an `$mdcDialogPreset` with the chainable configuration methods:
 *
 * Additionally, it supports the following methods:
 *
 * - $mdcDialogPreset#title(string) - Sets the confirm title.
 * - $mdcDialogPreset#textContent(string) - Sets the confirm message.
 * - $mdcDialogPreset#htmlContent(string) - Sets the confirm message as HTML. Requires ngSanitize
 *     module to be loaded. HTML is not run through Angular's compiler.
 * - $mdcDialogPreset#ok(string) - Sets the confirm "Okay" button text.
 * - $mdcDialogPreset#cancel(string) - Sets the confirm "Cancel" button text.
 * - $mdcDialogPreset#css(string) - Custom classes to apply to mdc-dialog using ng-class
 * - $mdcDialogPreset#scrollable(boolean) - Whether the body of the element has a vertical scrollbar
 *
 */

/**
 * @ngdoc method
 * @name $mdcDialog#prompt
 *
 * @description
 * Builds a preconfigured dialog with the specified message and input box. You can call show and the promise returned
 * will be resolved only if the user clicks the prompt action on the dialog, passing the input value
 * as the first argument.
 *
 * @returns {Object} an `$mdcDialogPreset` with the chainable configuration methods:
 *
 * Additionally, it supports the following methods:
 *
 * - $mdcDialogPreset#title(string) - Sets the prompt title.
 * - $mdcDialogPreset#textContent(string) - Sets the prompt message.
 * - $mdcDialogPreset#htmlContent(string) - Sets the prompt message as HTML. Requires ngSanitize
 *     module to be loaded. HTML is not run through Angular's compiler.
 * - $mdcDialogPreset#placeholder(string) - Sets the placeholder text for the input.
 * - $mdcDialogPreset#initialValue(string) - Sets the initial value for the prompt input.
 * - $mdcDialogPreset#ok(string) - Sets the prompt "Okay" button text.
 * - $mdcDialogPreset#cancel(string) - Sets the prompt "Cancel" button text.
 * - $mdcDialogPreset#css(string) - Custom classes to apply to mdc-dialog using ng-class
 * - $mdcDialogPreset#scrollable(boolean) - Whether the body of the element has a vertical scrollbar
 *
 */

/**
 * @ngdoc method
 * @name $mdcDialog#hide
 *
 * @description Hide an existing dialog and resolve the promise returned from `$mdcDialog.show()`.
 *
 * @param {*=} response An argument for the resolved promise.
 *
 * @returns {promise} A promise that is resolved when the dialog has been closed.
 */

/**
 * @ngdoc method
 * @name $mdcDialog#cancel
 *
 * @description Hide an existing dialog and reject the promise returned from `$mdcDialog.show()`.
 *
 * @param {*=} response An argument for the rejected promise.
 *
 * @returns {promise} A promise that is resolved when the dialog has been closed.
 */

angular
  .module('mdc.dialog', ['material.core.slim'])
  .provider('$mdcDialog', $mdcDialogProvider)
  .component('mdcDialog', {
    controller: MdcDialogController,
    template: require('raw-loader!./mdc-dialog-component.html'),
    transclude: true,
  });
<|endoftext|>


<commit_before>// Config.js
//
// loads configuration from a generated file, provides sensible defaults

(function() {

    var root = this,
        config = null;

    // put config in namespace of importing code
    if (typeof exports !== 'undefined') {
        config = exports;
    } else {
        config = root.config = {};
    }

    config.implementation = 'Unspecified_iOS_Device';
    config.automatorTagsAny = []; // run all by default
    config.automatorTagsAll = []; // none by default
    config.automatorTagsNone = [];
    config.automatorSequenceRandomSeed = undefined;
    config.buildArtifacts = {};

    config.setField = function (key, value) {
        switch (key) {
        case "automatorSequenceRandomSeed":
            config.automatorSequenceRandomSeed = parseInt(value);
            break;
        default:
            config[key] = value;
        }
    }

    // expected keys, and whether they are required
    var expectedKeys = {
        "saltinel": true,
        "entryPoint": true,
        "implementation": true,
        "automatorDesiredSimDevice": true,
        "automatorDesiredSimVersion": true,
        "targetDeviceID": true,
        "targetDeviceLanguage": false,
        "targetDeviceLocale": false,
        "isHardware": true,
        "xcodePath": true,
        "automatorTagsAny": false,
        "automatorTagsAll": false,
        "automatorTagsNone": false,
        "automatorScenarioNames": false,
        "automatorSequenceRandomSeed": false,
        "automatorScenarioOffset": true,
        "customConfig": false,
    };

    var jsonConfig = host().readJSONFromFile(IlluminatorBuildArtifactsDirectory + "/IlluminatorGeneratedConfig.json");
    // check for keys we don't expect
    for (var k in jsonConfig) {
        if (expectedKeys[k] === undefined) {
            UIALogger.logMessage("Config got unexpected key " + k);
        }
    }

    // test for keys we DO expect
    for (var k in expectedKeys) {
        if (jsonConfig[k] !== undefined) {
            config.setField(k, jsonConfig[k]);
        } else if (expectedKeys[k]) {
            UIALogger.logWarning("Couldn't read " + k + " from generated config");
        }
    }

    // find the directory where screenshots will go
    IlluminatorInstrumentsOutputDirectory
    // handles globbing of a path that may have spaces in it, assumes newest directory is the run directory
    var findMostRecentDirCmd = 'eval ls -1td "' + IlluminatorInstrumentsOutputDirectory + '/Run*" | head -n 1';
    var output = host().shellAsFunction("/bin/bash", ["-c", findMostRecentDirCmd], 5);
    config.screenshotDir = output.stdout;

    // create temp dir for build artifacts and note path names
    var tmpDir = IlluminatorBuildArtifactsDirectory + "/UIAutomation-outputs";
    target().host().performTaskWithPathArgumentsTimeout("/bin/mkdir", ["-p", tmpDir], 5);
    config.buildArtifacts.root = tmpDir;
    config.buildArtifacts.appMapMarkdown        = tmpDir + "/appMap.md";
    config.buildArtifacts.automatorMarkdown     = tmpDir + "/automator.md";
    config.buildArtifacts.automatorJSON         = tmpDir + "/automator.json";
    config.buildArtifacts.automatorScenarioJSON = tmpDir + "/automatorScenarios.json";
    config.buildArtifacts.intendedTestList      = tmpDir + "/intendedTestList.json";

    //This line is a placeholder so that the automator can communicate its current operation to the entire set of Illuminator javascript extensions.
    //This is because the logical first choice for implementing this -- automator state -- is not available from Extensions.js
    config.automatorModality                    = "init";

}).call(this);
<commit_msg>whitespace<commit_after>// Config.js
//
// loads configuration from a generated file, provides sensible defaults

(function() {

    var root = this,
        config = null;

    // put config in namespace of importing code
    if (typeof exports !== 'undefined') {
        config = exports;
    } else {
        config = root.config = {};
    }

    config.implementation = 'Unspecified_iOS_Device';
    config.automatorTagsAny = []; // run all by default
    config.automatorTagsAll = []; // none by default
    config.automatorTagsNone = [];
    config.automatorSequenceRandomSeed = undefined;
    config.buildArtifacts = {};

    config.setField = function (key, value) {
        switch (key) {
        case "automatorSequenceRandomSeed":
            config.automatorSequenceRandomSeed = parseInt(value);
            break;
        default:
            config[key] = value;
        }
    }

    // expected keys, and whether they are required
    var expectedKeys = {
        "saltinel": true,
        "entryPoint": true,
        "implementation": true,
        "automatorDesiredSimDevice": true,
        "automatorDesiredSimVersion": true,
        "targetDeviceID": true,
        "targetDeviceLanguage": false,
        "targetDeviceLocale": false,
        "isHardware": true,
        "xcodePath": true,
        "automatorTagsAny": false,
        "automatorTagsAll": false,
        "automatorTagsNone": false,
        "automatorScenarioNames": false,
        "automatorSequenceRandomSeed": false,
        "automatorScenarioOffset": true,
        "customConfig": false,
    };

    var jsonConfig = host().readJSONFromFile(IlluminatorBuildArtifactsDirectory + "/IlluminatorGeneratedConfig.json");
    // check for keys we don't expect
    for (var k in jsonConfig) {
        if (expectedKeys[k] === undefined) {
            UIALogger.logMessage("Config got unexpected key " + k);
        }
    }

    // test for keys we DO expect
    for (var k in expectedKeys) {
        if (jsonConfig[k] !== undefined) {
            config.setField(k, jsonConfig[k]);
        } else if (expectedKeys[k]) {
            UIALogger.logWarning("Couldn't read " + k + " from generated config");
        }
    }

    // find the directory where screenshots will go
    IlluminatorInstrumentsOutputDirectory
    // handles globbing of a path that may have spaces in it, assumes newest directory is the run directory
    var findMostRecentDirCmd = 'eval ls -1td "' + IlluminatorInstrumentsOutputDirectory + '/Run*" | head -n 1';
    var output = host().shellAsFunction("/bin/bash", ["-c", findMostRecentDirCmd], 5);
    config.screenshotDir = output.stdout;

    // create temp dir for build artifacts and note path names
    var tmpDir = IlluminatorBuildArtifactsDirectory + "/UIAutomation-outputs";
    target().host().performTaskWithPathArgumentsTimeout("/bin/mkdir", ["-p", tmpDir], 5);
    config.buildArtifacts.root = tmpDir;
    config.buildArtifacts.appMapMarkdown        = tmpDir + "/appMap.md";
    config.buildArtifacts.automatorMarkdown     = tmpDir + "/automator.md";
    config.buildArtifacts.automatorJSON         = tmpDir + "/automator.json";
    config.buildArtifacts.automatorScenarioJSON = tmpDir + "/automatorScenarios.json";
    config.buildArtifacts.intendedTestList      = tmpDir + "/intendedTestList.json";

    //This line is a placeholder so that the automator can communicate its current operation to the entire set of Illuminator javascript extensions.
    //This is because the logical first choice for implementing this -- automator state -- is not available from Extensions.js
    config.automatorModality                    = "init";

}).call(this);
<|endoftext|>


<commit_before>import _ from 'lodash';

VocabularyEditController.$inject = [
    '$scope',
    'gettext',
    'notify',
    'api',
    'vocabularies',
    'metadata',
    'cvSchema',
];

export function VocabularyEditController($scope, gettext, notify, api, vocabularies, metadata, cvSchema) {
    var origVocabulary = _.cloneDeep($scope.vocabulary);

    $scope.idRegex = '^[a-zA-Z0-9-_]+$';

    function onSuccess(result) {
        notify.success(gettext('Vocabulary saved successfully'));
        $scope.closeVocabulary();
        $scope.updateVocabulary(result);
        $scope.issues = null;
        return result;
    }

    function onError(response) {
        if (angular.isDefined(response.data._issues)) {
            if (angular.isDefined(response.data._issues['validator exception'])) {
                notify.error(gettext('Error: ' +
                                     response.data._issues['validator exception']));
            } else {
                $scope.issues = response.data._issues;
                notify.error(gettext('Error. Vocabulary not saved.'));
            }
        }
    }

    function checkForUniqueValues() {
        const uniqueField = $scope.vocabulary.unique_field || 'qcode';
        const list = $scope.vocabulary.items || {};
        const uniqueList = _.uniqBy(list, (item) => item[uniqueField]);

        return list.length === uniqueList.length;
    }

    /**
     * Save current edit modal contents on backend.
     */
    $scope.save = function() {
        $scope._errorUniqueness = false;
        $scope.errorMessage = null;
        delete $scope.vocabulary._deleted;

        if ($scope.vocabulary._id === 'crop_sizes') {
            var activeItems = _.filter($scope.vocabulary.items, (o) => o.is_active);

            _.each(_.union(_.map(activeItems, 'width'), _.map(activeItems, 'height')), (item) => {
                if (parseInt(item, 10) < 200) {
                    $scope.errorMessage = gettext('Minimum height and width should be greater than or equal to 200');
                }
            });
        }

        if (!checkForUniqueValues()) {
            const uniqueField = $scope.vocabulary.unique_field || 'qcode';

            $scope.errorMessage = gettext('The values should be unique for ') + uniqueField;
        }

        if (_.isNil($scope.errorMessage)) {
            api.save('vocabularies', $scope.vocabulary).then(onSuccess, onError);
        }

        // discard metadata cache:
        metadata.loaded = null;
        metadata.initialize();
    };

    /**
     * Discard changes and close modal.
     */
    $scope.cancel = function() {
        angular.copy(origVocabulary, $scope.vocabulary);
        $scope.closeVocabulary();
    };

    /**
     * Add new blank vocabulary item.
     */
    $scope.addItem = function() {
        var newVocabulary = {};

        _.extend(newVocabulary, $scope.model);
        newVocabulary.is_active = true;

        $scope.vocabulary.items = $scope.vocabulary.items.concat([newVocabulary]);
    };

    // try to reproduce data model of vocabulary:
    var model = _.mapValues(_.keyBy(
        _.uniq(_.flatten(
            _.map($scope.vocabulary.items, (o) => _.keys(o))
        ))
    ), () => null);

    $scope.model = model;
    $scope.schema = $scope.vocabulary.schema || cvSchema[$scope.vocabulary._id] || null;
    if ($scope.schema) {
        $scope.schemaFields = Object.keys($scope.schema)
            .sort()
            .map((key) => angular.extend(
                {key: key},
                $scope.schema[key]
            ));
    }

    $scope.itemsValidation = {valid: true};

    /**
     * Remove item from vocabulary items
     *
     * @param {number} index
     */
    $scope.removeItem = (index) => {
        $scope.vocabulary.items.splice(index, 1);
        $scope.vocabulary.items = $scope.vocabulary.items.slice(); // trigger watch on items collection
    };
}
<commit_msg>[VOCABULARY] added error message when a required field is missing<commit_after>import _ from 'lodash';

VocabularyEditController.$inject = [
    '$scope',
    'gettext',
    '$interpolate',
    'notify',
    'api',
    'vocabularies',
    'metadata',
    'cvSchema',
];

export function VocabularyEditController($scope, gettext, $interpolate, notify, api, vocabularies, metadata, cvSchema) {
    var origVocabulary = _.cloneDeep($scope.vocabulary);

    $scope.idRegex = '^[a-zA-Z0-9-_]+$';

    function onSuccess(result) {
        notify.success(gettext('Vocabulary saved successfully'));
        $scope.closeVocabulary();
        $scope.updateVocabulary(result);
        $scope.issues = null;
        return result;
    }

    function onError(response) {
        if (angular.isDefined(response.data._issues)) {
            if (angular.isDefined(response.data._issues['validator exception'])) {
                notify.error(gettext('Error: ' +
                                     response.data._issues['validator exception']));
            } else if (angular.isDefined(response.data._issues.error) &&
                       response.data._issues.error.required_field) {
                let params = response.data._issues.params;

                notify.error($interpolate(gettext(
                    'Required {{field}} in item {{item}}'))({field: params.field, item: params.item}));
            } else {
                $scope.issues = response.data._issues;
                notify.error(gettext('Error. Vocabulary not saved.'));
            }
        }
    }

    function checkForUniqueValues() {
        const uniqueField = $scope.vocabulary.unique_field || 'qcode';
        const list = $scope.vocabulary.items || {};
        const uniqueList = _.uniqBy(list, (item) => item[uniqueField]);

        return list.length === uniqueList.length;
    }

    /**
     * Save current edit modal contents on backend.
     */
    $scope.save = function() {
        $scope._errorUniqueness = false;
        $scope.errorMessage = null;
        delete $scope.vocabulary._deleted;

        if ($scope.vocabulary._id === 'crop_sizes') {
            var activeItems = _.filter($scope.vocabulary.items, (o) => o.is_active);

            _.each(_.union(_.map(activeItems, 'width'), _.map(activeItems, 'height')), (item) => {
                if (parseInt(item, 10) < 200) {
                    $scope.errorMessage = gettext('Minimum height and width should be greater than or equal to 200');
                }
            });
        }

        if (!checkForUniqueValues()) {
            const uniqueField = $scope.vocabulary.unique_field || 'qcode';

            $scope.errorMessage = gettext('The values should be unique for ') + uniqueField;
        }

        if (_.isNil($scope.errorMessage)) {
            api.save('vocabularies', $scope.vocabulary).then(onSuccess, onError);
        }

        // discard metadata cache:
        metadata.loaded = null;
        metadata.initialize();
    };

    /**
     * Discard changes and close modal.
     */
    $scope.cancel = function() {
        angular.copy(origVocabulary, $scope.vocabulary);
        $scope.closeVocabulary();
    };

    /**
     * Add new blank vocabulary item.
     */
    $scope.addItem = function() {
        var newVocabulary = {};

        _.extend(newVocabulary, $scope.model);
        newVocabulary.is_active = true;

        $scope.vocabulary.items = $scope.vocabulary.items.concat([newVocabulary]);
    };

    // try to reproduce data model of vocabulary:
    var model = _.mapValues(_.keyBy(
        _.uniq(_.flatten(
            _.map($scope.vocabulary.items, (o) => _.keys(o))
        ))
    ), () => null);

    $scope.model = model;
    $scope.schema = $scope.vocabulary.schema || cvSchema[$scope.vocabulary._id] || null;
    if ($scope.schema) {
        $scope.schemaFields = Object.keys($scope.schema)
            .sort()
            .map((key) => angular.extend(
                {key: key},
                $scope.schema[key]
            ));
    }

    $scope.itemsValidation = {valid: true};

    /**
     * Remove item from vocabulary items
     *
     * @param {number} index
     */
    $scope.removeItem = (index) => {
        $scope.vocabulary.items.splice(index, 1);
        $scope.vocabulary.items = $scope.vocabulary.items.slice(); // trigger watch on items collection
    };
}
<|endoftext|>


<commit_before>/*
 Copyright [2016] [Relevance Lab]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
var logger = require('_pr/logger')(module);
var CatalystCronJob = require('_pr/cronjobs/CatalystCronJob');
var appConfig = require('_pr/config');
var AWSProvider = require('_pr/model/classes/masters/cloudprovider/awsCloudProvider.js');
var MasterUtils = require('_pr/lib/utils/masterUtil.js');
var appConfig = require('_pr/config');
var Cryptography = require('_pr/lib/utils/cryptography');
var CW = require('_pr/lib/cloudwatch.js');
var instancesModel = require('_pr/model/classes/instance/instance');
var unManagedInstancesModel = require('_pr/model/unmanaged-instance');
var resourceMetricsModel = require('_pr/model/resource-metrics');
var instanceService = require('_pr/services/instanceService');
var async = require('async');

var AggregateAWSUsage = Object.create(CatalystCronJob);
AggregateAWSUsage.interval = '0 * * * *';
AggregateAWSUsage.execute = aggregateAWSUsage;

module.exports = AggregateAWSUsage;

/**
 *
 */
function aggregateAWSUsage() {
    MasterUtils.getAllActiveOrg(function(err, orgs) {
        if(err) {
            logger.error(err);
        } else {
            aggregateUsageForProvidersOfOrg.apply(aggregateUsageForProvidersOfOrg, orgs);
        }
    });
}

/**
 *
 * @param org
 */
function aggregateUsageForProvidersOfOrg(org) {
    AWSProvider.getAWSProvidersByOrgId(org._id, function(err, providers) {
        if(err) {
            logger.error(err);
        } else {
            aggregateEC2UsageForProvider.apply(aggregateEC2UsageForProvider, providers);
        }
    });
}

/**
 *
 * @param provider
 */
function aggregateEC2UsageForProvider(provider) {
    async.waterfall([
        function (next) {
            logger.debug('EC2 usage aggregation for provider: ' + provider._id + ' started');
            instanceService.getTrackedInstancesForProvider(provider, next);
        },
        function (provider, instances, next) {
            async.parallel({
                managed: function(callback) {
                    generateEC2UsageMetricsForProvider(provider, instances.managed, callback);
                },
                unmanaged: function(callback) {
                    generateEC2UsageMetricsForProvider(provider, instances.unmanaged, callback);
                }
            }, function(err, results){
                if(err) {
                    next(err);
                } else {
                    next(null, results);
                }
            });
        },
        function(usageMetrics, next) {
            async.parallel({
                managed: function(callback) {
                    updateManagedInstanceUsage(usageMetrics.managed, callback);
                },
                unmanaged: function(callback) {
                    updateUnmanagedInstanceUsage(usageMetrics.unmanaged, callback);
                }
            }, function(err, results){
                if(err) {
                    next(err);
                } else {
                    next(null, results);
                }
            });
        }
    ],
    function(err, results) {
        if(err)
            logger.error(err);
        else if(results)
            logger.debug('EC2 usage aggregation for provider: ' + provider._id + ' ended');
    });
}

/**
 *
 * @param provider
 * @param instances
 * @param callback
 */
function generateEC2UsageMetricsForProvider(provider, instances, callback) {
    async.waterfall([
        function (next) {
            getEC2InstanceUsageMetrics(provider, instances, next);
        },
        function (ec2UsageMetrics, next) {
            saveResourceUsageMetrics(ec2UsageMetrics, next);
        }
    ], function(err, results) {
        if(err) {
            callback(err);
        } else {
            callback(null, results);
        }
    });
}

/**
 *
 * @param provider
 * @param instances
 * @param next
 */
function getEC2InstanceUsageMetrics(provider, instances, next) {
    var metricsUnits = appConfig.aws.cwMetricsUnits;
    var instanceUsageMetrics = [];

    if(instances.length == 0)
        next(null, instanceUsageMetrics);

    // @TODO Create promise for creating cw client
    var cryptoConfig = appConfig.cryptoSettings;
    var cryptography = new Cryptography(cryptoConfig.algorithm, cryptoConfig.password);
    var amazonConfig;

    if (provider.isDefault) {
        amazonConfig = {
            "isDefault": true
        };
    } else {
        var cryptoConfig = appConfig.cryptoSettings;
        var cryptography = new Cryptography(cryptoConfig.algorithm,
            cryptoConfig.password);

        var decryptedAccessKey = cryptography.decryptText(provider.accessKey,
            cryptoConfig.decryptionEncoding, cryptoConfig.encryptionEncoding);
        var decryptedSecretKey = cryptography.decryptText(provider.secretKey,
            cryptoConfig.decryptionEncoding, cryptoConfig.encryptionEncoding);

        amazonConfig = {
            "access_key": decryptedAccessKey,
            "secret_key": decryptedSecretKey
        };
    }

    var endTime = new Date();
    var startTime = new Date(endTime.getTime() - 1000*60*60*24);
    for(var i = 0; i < instances.length; i++) {
        (function(j) {
            if('providerData' in instances[j]) {
                amazonConfig.region = instances[j].providerData.region;
                cw = new CW(amazonConfig);

                async.parallel({
                    CPUUtilization: function (callback) {
                        cw.getUsageMetrics('CPUUtilization', metricsUnits.CPUUtilization,
                            instances[j].platformId, startTime, endTime, callback);
                    },
                    NetworkOut: function (callback) {
                        cw.getUsageMetrics('NetworkOut', metricsUnits.NetworkOut,
                            instances[j].platformId, startTime, endTime, callback);
                    },
                    NetworkIn: function (callback) {
                        cw.getUsageMetrics('NetworkIn', metricsUnits.NetworkIn,
                            instances[j].platformId, startTime, endTime, callback);
                    },
                    DiskReadBytes: function (callback) {
                        cw.getUsageMetrics('DiskReadBytes', metricsUnits.DiskReadBytes,
                            instances[j].platformId, startTime, endTime, callback);
                    },
                    DiskWriteBytes: function (callback) {
                        cw.getUsageMetrics('DiskWriteBytes', metricsUnits.DiskWriteBytes,
                            instances[j].platformId, startTime, endTime, callback);
                    }
                },
                function (err, results) {
                    if(err) {
                        logger.error(err)
                    } else {
                        instanceUsageMetrics.push({
                            providerId: provider._id,
                            providerType: provider.providerType,
                            orgId: provider.orgId[0],
                            projectId: instances[j].projectId,
                            instanceId: instances[j]._id,
                            platform: 'AWS',
                            platformId: instances[j].platformId,
                            resourceType: 'EC2',
                            startTime: startTime,
                            endTime: endTime,
                            metrics: results
                        });
                    }

                    if(instanceUsageMetrics.length == instances.length)
                        next(null, instanceUsageMetrics);
                });
            }
        })(i);
    }
}

/**
 *
 * @param resourceMetrics
 * @param next
 */
function saveResourceUsageMetrics (resourceMetrics, next) {
    var results = [];

    if(resourceMetrics.length == 0)
        return next(null, results);

    for(var i = 0; i < resourceMetrics.length; i++) {
        (function(j) {
            resourceMetricsModel.createNew(resourceMetrics[j],
                function(err, resourceMetricsObj) {
                    if(err)
                        next(err);
                    else
                        results.push(resourceMetricsObj);

                    if(results.length == resourceMetrics.length)
                        next(null, results);
                }
            );
        })(i);
    };
}

/**
 *
 * @param instanceUsageMetrics
 * @param next
 */
function updateManagedInstanceUsage(instanceUsageMetrics, next) {
    var results = [];

    if(instanceUsageMetrics.length == 0)
        return next(null, results);

    // @TODO get rid of nesting
    for(var i = 0; i < instanceUsageMetrics.length; i++) {
        (function (j) {
            formatUsageData(instanceUsageMetrics[j], function(err, formattedUsageMetrics) {
                if (err) {
                    next(err);
                } else {
                    instancesModel.updateInstanceUsage(formattedUsageMetrics.instanceId,
                        formattedUsageMetrics.metrics, function (err, result) {
                            if (err)
                                next(err);
                            else
                                results.push(result);

                            if (results.length == instanceUsageMetrics.length)
                                next(null, results);
                        }
                    );
                }
            });
        })(i);
    };
}

/**
 *
 * @param instanceUsageMetrics
 * @param next
 */
function updateUnmanagedInstanceUsage(instanceUsageMetrics, next) {
    var results = [];

    if(instanceUsageMetrics.length == 0)
        return next(null, results);

    // @TODO get rid of nesting
    for(var i = 0; i < instanceUsageMetrics.length; i++) {
        (function (j) {
            formatUsageData(instanceUsageMetrics[j], function(err, formattedUsageMetrics) {
                if(err) {
                    next(err);
                } else {
                    unManagedInstancesModel.updateUsage(formattedUsageMetrics.instanceId,
                        formattedUsageMetrics.metrics, function(err, result) {
                            if(err)
                                next(err);
                            else
                                results.push(result);

                            if(results.length == instanceUsageMetrics.length)
                                next(null, results);
                        }
                    );
                }
            });
        })(i);
    };
}

function formatUsageData(instanceUsageMetrics, next) {
    var metricsDisplayUnits = appConfig.aws.cwMetricsDisplayUnits;

    instanceUsageMetrics.metrics.CPUUtilization.unit = metricsDisplayUnits.CPUUtilization;
    instanceUsageMetrics.metrics.DiskReadBytes.unit = metricsDisplayUnits.DiskReadBytes;
    instanceUsageMetrics.metrics.DiskWriteBytes.unit = metricsDisplayUnits.DiskWriteBytes;
    instanceUsageMetrics.metrics.NetworkIn.unit = metricsDisplayUnits.NetworkIn;
    instanceUsageMetrics.metrics.NetworkOut.unit = metricsDisplayUnits.NetworkOut;

    instanceUsageMetrics.metrics.CPUUtilization.average
        = Math.round(instanceUsageMetrics.metrics.CPUUtilization.average);
    instanceUsageMetrics.metrics.CPUUtilization.minimum
        = Math.round(instanceUsageMetrics.metrics.CPUUtilization.minimum);
    instanceUsageMetrics.metrics.CPUUtilization.maximum
        = Math.round(instanceUsageMetrics.metrics.CPUUtilization.maximum);

    next(null, instanceUsageMetrics);
}<commit_msg>hot fix to change usage cron frequery and check for region<commit_after>/*
 Copyright [2016] [Relevance Lab]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
var logger = require('_pr/logger')(module);
var CatalystCronJob = require('_pr/cronjobs/CatalystCronJob');
var appConfig = require('_pr/config');
var AWSProvider = require('_pr/model/classes/masters/cloudprovider/awsCloudProvider.js');
var MasterUtils = require('_pr/lib/utils/masterUtil.js');
var appConfig = require('_pr/config');
var Cryptography = require('_pr/lib/utils/cryptography');
var CW = require('_pr/lib/cloudwatch.js');
var instancesModel = require('_pr/model/classes/instance/instance');
var unManagedInstancesModel = require('_pr/model/unmanaged-instance');
var resourceMetricsModel = require('_pr/model/resource-metrics');
var instanceService = require('_pr/services/instanceService');
var async = require('async');

var AggregateAWSUsage = Object.create(CatalystCronJob);
AggregateAWSUsage.interval = '*/30 * * * *';
AggregateAWSUsage.execute = aggregateAWSUsage;

module.exports = AggregateAWSUsage;

/**
 *
 */
function aggregateAWSUsage() {
    MasterUtils.getAllActiveOrg(function(err, orgs) {
        if(err) {
            logger.error(err);
        } else {
            aggregateUsageForProvidersOfOrg.apply(aggregateUsageForProvidersOfOrg, orgs);
        }
    });
}

/**
 *
 * @param org
 */
function aggregateUsageForProvidersOfOrg(org) {
    AWSProvider.getAWSProvidersByOrgId(org._id, function(err, providers) {
        if(err) {
            logger.error(err);
        } else {
            aggregateEC2UsageForProvider.apply(aggregateEC2UsageForProvider, providers);
        }
    });
}

/**
 *
 * @param provider
 */
function aggregateEC2UsageForProvider(provider) {
    async.waterfall([
        function (next) {
            logger.debug('EC2 usage aggregation for provider: ' + provider._id + ' started');
            instanceService.getTrackedInstancesForProvider(provider, next);
        },
        function (provider, instances, next) {
            async.parallel({
                managed: function(callback) {
                    generateEC2UsageMetricsForProvider(provider, instances.managed, callback);
                },
                unmanaged: function(callback) {
                    generateEC2UsageMetricsForProvider(provider, instances.unmanaged, callback);
                }
            }, function(err, results){
                if(err) {
                    next(err);
                } else {
                    next(null, results);
                }
            });
        },
        function(usageMetrics, next) {
            async.parallel({
                managed: function(callback) {
                    updateManagedInstanceUsage(usageMetrics.managed, callback);
                },
                unmanaged: function(callback) {
                    updateUnmanagedInstanceUsage(usageMetrics.unmanaged, callback);
                }
            }, function(err, results){
                if(err) {
                    next(err);
                } else {
                    next(null, results);
                }
            });
        }
    ],
    function(err, results) {
        if(err)
            logger.error(err);
        else if(results)
            logger.debug('EC2 usage aggregation for provider: ' + provider._id + ' ended');
    });
}

/**
 *
 * @param provider
 * @param instances
 * @param callback
 */
function generateEC2UsageMetricsForProvider(provider, instances, callback) {
    async.waterfall([
        function (next) {
            getEC2InstanceUsageMetrics(provider, instances, next);
        },
        function (ec2UsageMetrics, next) {
            saveResourceUsageMetrics(ec2UsageMetrics, next);
        }
    ], function(err, results) {
        if(err) {
            callback(err);
        } else {
            callback(null, results);
        }
    });
}

/**
 *
 * @param provider
 * @param instances
 * @param next
 */
function getEC2InstanceUsageMetrics(provider, instances, next) {
    var metricsUnits = appConfig.aws.cwMetricsUnits;
    var instanceUsageMetrics = [];

    if(instances.length == 0)
        next(null, instanceUsageMetrics);

    // @TODO Create promise for creating cw client
    var cryptoConfig = appConfig.cryptoSettings;
    var cryptography = new Cryptography(cryptoConfig.algorithm, cryptoConfig.password);
    var amazonConfig;

    if (provider.isDefault) {
        amazonConfig = {
            "isDefault": true
        };
    } else {
        var cryptoConfig = appConfig.cryptoSettings;
        var cryptography = new Cryptography(cryptoConfig.algorithm,
            cryptoConfig.password);

        var decryptedAccessKey = cryptography.decryptText(provider.accessKey,
            cryptoConfig.decryptionEncoding, cryptoConfig.encryptionEncoding);
        var decryptedSecretKey = cryptography.decryptText(provider.secretKey,
            cryptoConfig.decryptionEncoding, cryptoConfig.encryptionEncoding);

        amazonConfig = {
            "access_key": decryptedAccessKey,
            "secret_key": decryptedSecretKey
        };
    }

    var endTime = new Date();
    var startTime = new Date(endTime.getTime() - 1000*60*60*24);
    for(var i = 0; i < instances.length; i++) {
        (function(j) {
            if(('providerData' in instances[j]) && ('region' in instances[j].providerData)) {
                amazonConfig.region = instances[j].providerData.region;
                cw = new CW(amazonConfig);

                async.parallel({
                    CPUUtilization: function (callback) {
                        cw.getUsageMetrics('CPUUtilization', metricsUnits.CPUUtilization,
                            instances[j].platformId, startTime, endTime, callback);
                    },
                    NetworkOut: function (callback) {
                        cw.getUsageMetrics('NetworkOut', metricsUnits.NetworkOut,
                            instances[j].platformId, startTime, endTime, callback);
                    },
                    NetworkIn: function (callback) {
                        cw.getUsageMetrics('NetworkIn', metricsUnits.NetworkIn,
                            instances[j].platformId, startTime, endTime, callback);
                    },
                    DiskReadBytes: function (callback) {
                        cw.getUsageMetrics('DiskReadBytes', metricsUnits.DiskReadBytes,
                            instances[j].platformId, startTime, endTime, callback);
                    },
                    DiskWriteBytes: function (callback) {
                        cw.getUsageMetrics('DiskWriteBytes', metricsUnits.DiskWriteBytes,
                            instances[j].platformId, startTime, endTime, callback);
                    }
                },
                function (err, results) {
                    if(err) {
                        logger.error(err)
                    } else {
                        instanceUsageMetrics.push({
                            providerId: provider._id,
                            providerType: provider.providerType,
                            orgId: provider.orgId[0],
                            projectId: instances[j].projectId,
                            instanceId: instances[j]._id,
                            platform: 'AWS',
                            platformId: instances[j].platformId,
                            resourceType: 'EC2',
                            startTime: startTime,
                            endTime: endTime,
                            metrics: results
                        });
                    }

                    if(instanceUsageMetrics.length == instances.length)
                        next(null, instanceUsageMetrics);
                });
            }
        })(i);
    }
}

/**
 *
 * @param resourceMetrics
 * @param next
 */
function saveResourceUsageMetrics (resourceMetrics, next) {
    var results = [];

    if(resourceMetrics.length == 0)
        return next(null, results);

    for(var i = 0; i < resourceMetrics.length; i++) {
        (function(j) {
            resourceMetricsModel.createNew(resourceMetrics[j],
                function(err, resourceMetricsObj) {
                    if(err)
                        next(err);
                    else
                        results.push(resourceMetricsObj);

                    if(results.length == resourceMetrics.length)
                        next(null, results);
                }
            );
        })(i);
    };
}

/**
 *
 * @param instanceUsageMetrics
 * @param next
 */
function updateManagedInstanceUsage(instanceUsageMetrics, next) {
    var results = [];

    if(instanceUsageMetrics.length == 0)
        return next(null, results);

    // @TODO get rid of nesting
    for(var i = 0; i < instanceUsageMetrics.length; i++) {
        (function (j) {
            formatUsageData(instanceUsageMetrics[j], function(err, formattedUsageMetrics) {
                if (err) {
                    next(err);
                } else {
                    instancesModel.updateInstanceUsage(formattedUsageMetrics.instanceId,
                        formattedUsageMetrics.metrics, function (err, result) {
                            if (err)
                                next(err);
                            else
                                results.push(result);

                            if (results.length == instanceUsageMetrics.length)
                                next(null, results);
                        }
                    );
                }
            });
        })(i);
    };
}

/**
 *
 * @param instanceUsageMetrics
 * @param next
 */
function updateUnmanagedInstanceUsage(instanceUsageMetrics, next) {
    var results = [];

    if(instanceUsageMetrics.length == 0)
        return next(null, results);

    // @TODO get rid of nesting
    for(var i = 0; i < instanceUsageMetrics.length; i++) {
        (function (j) {
            formatUsageData(instanceUsageMetrics[j], function(err, formattedUsageMetrics) {
                if(err) {
                    next(err);
                } else {
                    unManagedInstancesModel.updateUsage(formattedUsageMetrics.instanceId,
                        formattedUsageMetrics.metrics, function(err, result) {
                            if(err)
                                next(err);
                            else
                                results.push(result);

                            if(results.length == instanceUsageMetrics.length)
                                next(null, results);
                        }
                    );
                }
            });
        })(i);
    };
}

function formatUsageData(instanceUsageMetrics, next) {
    var metricsDisplayUnits = appConfig.aws.cwMetricsDisplayUnits;

    instanceUsageMetrics.metrics.CPUUtilization.unit = metricsDisplayUnits.CPUUtilization;
    instanceUsageMetrics.metrics.DiskReadBytes.unit = metricsDisplayUnits.DiskReadBytes;
    instanceUsageMetrics.metrics.DiskWriteBytes.unit = metricsDisplayUnits.DiskWriteBytes;
    instanceUsageMetrics.metrics.NetworkIn.unit = metricsDisplayUnits.NetworkIn;
    instanceUsageMetrics.metrics.NetworkOut.unit = metricsDisplayUnits.NetworkOut;

    instanceUsageMetrics.metrics.CPUUtilization.average
        = Math.round(instanceUsageMetrics.metrics.CPUUtilization.average);
    instanceUsageMetrics.metrics.CPUUtilization.minimum
        = Math.round(instanceUsageMetrics.metrics.CPUUtilization.minimum);
    instanceUsageMetrics.metrics.CPUUtilization.maximum
        = Math.round(instanceUsageMetrics.metrics.CPUUtilization.maximum);

    next(null, instanceUsageMetrics);
}<|endoftext|>


<commit_before>'use strict';

var Jsdom = require('jsdom');
var Lodash = require('lodash');

var BuildHelpers = require('./../build-helpers');
var EsprimaHelpers = require('./../esprima-helpers');

var QUOTE = '\'';
var EXTENDS_KEY = 'extends';

function fixChildNode(node, tree, imports, doc) {
    fixTree(node, imports, doc);
    var newTagName = imports[node.tagName.toLowerCase()] || node.tagName;
    var newNode = doc.createElement(newTagName);
    newNode.innerHTML = node.innerHTML;
    for (var i = 0; i < node.attributes.length; i++) {
        var attr = node.attributes[i];
        newNode.setAttribute(attr.nodeName, attr.nodeValue);
    }
    tree.replaceChild(newNode, node);
}

function fixTree(tree, imports, doc) {
    for (var i = 0; i < tree.children.length; i++) {
        fixChildNode(tree.children[i], tree, imports, doc);
    }
    return tree.innerHTML;
}

function expandObjectKeyShorthands(facetObj, imports) {
    EsprimaHelpers.eachObjectProperty(facetObj, function(keyName, _2, _3, valueObj, property) {
        if (EsprimaHelpers.isObjectExpression(valueObj)) {
            expandObjectKeyShorthands.call(this, valueObj, imports);
        }
        for (var importNamespace in imports) {
            var importItems = imports[importNamespace];
            for (var i = 0; i < importItems.length; i++) {
                var importItem = importItems[i];
                if (keyName === importItem) {
                    var newKey = BuildHelpers.moduleNamespaceAndBasenameToModuleName.call(this, importNamespace, importItem);
                    property.key.value = newKey;
                    property.key.raw = QUOTE + newKey + QUOTE;
                }
            }
        }
    }.bind(this));
}

function expandExtendsShorthand(facetArray, imports) {
    EsprimaHelpers.eachArrayElement(facetArray, function(elementValue, elementObject){
        for (var importNamespace in imports) {
            var importItems = imports[importNamespace];
            for (var i = 0; i < importItems.length; i++) {
                if (importItems[i] === elementValue) {
                    var expandedExtends = BuildHelpers.moduleNamespaceAndBasenameToModuleName.call(this, importNamespace, elementValue);
                    elementObject.value = expandedExtends;
                    elementObject.raw = QUOTE + expandedExtends + QUOTE;
                }
            }
        }
    }.bind(this));
}

function expandImportsShorthand(info, cb) {
    for (var moduleName in info.moduleDefinitionASTs) {
        var moduleDefinitionAST = info.moduleDefinitionASTs[moduleName];
        var moduleConfigAST = info.moduleConfigASTs[moduleName];

        // Step 1: Get a simplified (complete) imports object.
        var configObject = EsprimaHelpers.getObjectValue(moduleConfigAST || { properties: [] });
        var imports = Lodash.defaults(configObject[this.options.importsKeyName] || {}, this.options.defaultImports);

        // Step 2: Replace shorthand references in the object keys
        var treeNode;
        EsprimaHelpers.eachObjectProperty(moduleDefinitionAST, function(facetName, _1, _2, valueObj) {
            if (facetName === this.options.treeFacetKeyName) {
                treeNode = valueObj;
            }
            else if (EsprimaHelpers.isObjectExpression(valueObj)) {
                expandObjectKeyShorthands.call(this, valueObj, imports);
            }
        }.bind(this));

        // Step 3: Expand the tree from shorthand to long-form.
        if (treeNode) {
            var virtualDOM = Jsdom.jsdom(treeNode.value);
            var doc = virtualDOM.defaultView.document;
            var flatImports = BuildHelpers.importsObjectToFlatImportsObject.call(this, imports);
            var newTree = fixTree(doc.body, flatImports, doc);
            treeNode.value = newTree;
        }

        // Step 4: Expand values in extends array from configuration object
        if (moduleConfigAST) {
            EsprimaHelpers.eachObjectProperty(info.moduleConfigASTs[moduleName], function(keyName, _1, _2, valueObj) {
                if (keyName === EXTENDS_KEY) {
                    expandExtendsShorthand.call(this, valueObj, imports);
                }
            }.bind(this));
        }
    }
    cb(null, info);
}

module.exports = expandImportsShorthand;
<commit_msg>Prevent build step from creating 'direct targetted behaviors'<commit_after>'use strict';

var Jsdom = require('jsdom');
var Lodash = require('lodash');

var BuildHelpers = require('./../build-helpers');
var EsprimaHelpers = require('./../esprima-helpers');

var QUOTE = '\'';
var EXTENDS_KEY = 'extends';

function fixChildNode(node, tree, imports, doc) {
    fixTree(node, imports, doc);
    var newTagName = imports[node.tagName.toLowerCase()] || node.tagName;
    var newNode = doc.createElement(newTagName);
    newNode.innerHTML = node.innerHTML;
    for (var i = 0; i < node.attributes.length; i++) {
        var attr = node.attributes[i];
        newNode.setAttribute(attr.nodeName, attr.nodeValue);
    }
    tree.replaceChild(newNode, node);
}

function fixTree(tree, imports, doc) {
    for (var i = 0; i < tree.children.length; i++) {
        fixChildNode(tree.children[i], tree, imports, doc);
    }
    return tree.innerHTML;
}

function expandObjectKeyShorthands(facetName, facetObj, imports, depth) {
    EsprimaHelpers.eachObjectProperty(facetObj, function(keyName, _2, _3, valueObj, property) {
        if (EsprimaHelpers.isObjectExpression(valueObj)) {
            expandObjectKeyShorthands.call(this, facetName, valueObj, imports, depth + 1);
        }
        // Since so-called "direct targeted behaviors" aren't currently supported --
        // i.e. behaviors that bypass the normal eventing conduit via a syntax such
        // as 'famous:foo:bar:behavior-blah' -- we don't do the imports conversion
        // here since it will raise an error on the client anyway.
        if (facetName !== this.options.behaviorsFacetKeyName || depth < 2) {
            for (var importNamespace in imports) {
                var importItems = imports[importNamespace];
                for (var i = 0; i < importItems.length; i++) {
                    var importItem = importItems[i];
                    if (keyName === importItem) {
                        var newKey = BuildHelpers.moduleNamespaceAndBasenameToModuleName.call(this, importNamespace, importItem);
                        property.key.value = newKey;
                        property.key.raw = QUOTE + newKey + QUOTE;
                    }
                }
            }
        }
    }.bind(this));
}

function expandExtendsShorthand(facetArray, imports) {
    EsprimaHelpers.eachArrayElement(facetArray, function(elementValue, elementObject){
        for (var importNamespace in imports) {
            var importItems = imports[importNamespace];
            for (var i = 0; i < importItems.length; i++) {
                if (importItems[i] === elementValue) {
                    var expandedExtends = BuildHelpers.moduleNamespaceAndBasenameToModuleName.call(this, importNamespace, elementValue);
                    elementObject.value = expandedExtends;
                    elementObject.raw = QUOTE + expandedExtends + QUOTE;
                }
            }
        }
    }.bind(this));
}

function expandImportsShorthand(info, cb) {
    for (var moduleName in info.moduleDefinitionASTs) {
        var moduleDefinitionAST = info.moduleDefinitionASTs[moduleName];
        var moduleConfigAST = info.moduleConfigASTs[moduleName];

        // Step 1: Get a simplified (complete) imports object.
        var configObject = EsprimaHelpers.getObjectValue(moduleConfigAST || { properties: [] });
        var imports = Lodash.defaults(configObject[this.options.importsKeyName] || {}, this.options.defaultImports);

        // Step 2: Replace shorthand references in the object keys
        var treeNode;
        EsprimaHelpers.eachObjectProperty(moduleDefinitionAST, function(facetName, _1, _2, valueObj) {
            if (facetName === this.options.treeFacetKeyName) {
                treeNode = valueObj;
            }
            else if (EsprimaHelpers.isObjectExpression(valueObj)) {
                // The last argument here is the depth, i.e. the depth within the object
                // behaviors: <~ depth 0
                //   selector: <~ depth 1
                //     behaviorName: <~ depth 2
                expandObjectKeyShorthands.call(this, facetName, valueObj, imports, 1); // <~ Recursive
            }
        }.bind(this));

        // Step 3: Expand the tree from shorthand to long-form.
        if (treeNode) {
            var virtualDOM = Jsdom.jsdom(treeNode.value);
            var doc = virtualDOM.defaultView.document;
            var flatImports = BuildHelpers.importsObjectToFlatImportsObject.call(this, imports);
            var newTree = fixTree(doc.body, flatImports, doc);
            treeNode.value = newTree;
        }

        // Step 4: Expand values in extends array from configuration object
        if (moduleConfigAST) {
            EsprimaHelpers.eachObjectProperty(info.moduleConfigASTs[moduleName], function(keyName, _1, _2, valueObj) {
                if (keyName === EXTENDS_KEY) {
                    expandExtendsShorthand.call(this, valueObj, imports);
                }
            }.bind(this));
        }
    }
    cb(null, info);
}

module.exports = expandImportsShorthand;
<|endoftext|>


<commit_before>/* --------------------------------------------------------------

main.js
* Subfolio by AREA 17

-------------------------------------------------------------- */

/* Setting up variables
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
var isSafari = false;
var isSafari3 = false;
var isSafari4 = false;
var isIE = false;
var isIE6 = false;
var isIE7 = false;
var isIE8 = false;
var isMozilla = false;
var isOpera = false;
var isMac = false;
var isIphone = false;

var offsetMac = 0;

/* What to do when DOM is ready
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
$(document).ready(function(){
	//console.time("runOnDOMready");
	runOnDOMready();
	//console.timeEnd("runOnDOMready");
});

/* Run when DOM is ready
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function runOnDOMready() {
	browserDectect();
	gallery(); // runs first to speed vertical/horizontal alignement rendering if needed.
	setUpClasses();
	keyPress();
}

/* Browser Detect
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function browserDectect() {

	function searchVersion(browser) {
		var dataString = navigator.userAgent;
		var index = dataString.indexOf(browser);
		if (index == -1) return;
		var bVersion = parseFloat(dataString.substring(index+browser.length+1));
		return bVersion.toString().split(".")[0];
	}

	// are we on a Mac ?
	if (navigator.appVersion.indexOf("Mac")!=-1) {
		isMac = true;
		$('body').addClass("isMac");
	}

	// Safari versioning
	isSafari =  jQuery.browser.safari;
	if (isSafari) {
		$('body').addClass("isSafari");
		version = searchVersion("Version") || + "";
		$('body').addClass("isSafari"+version);
		isSafari3 = (version == 3) ? true : false;
		isSafari4 = (version == 4) ? true : false;
	}

	// IE versioning
	isIE = jQuery.browser.msie;
	if (isIE) {
		version = searchVersion("MSIE") || "";
		isIE6 = (version == 6) ? true : false;
		isIE7 = (version == 7) ? true : false;
		isIE8 = (version == 8) ? true : false;
	}

	// Mozilla versioning
	isMozilla = jQuery.browser.mozilla;
	if (isMozilla) {
		$('body').addClass("isMozilla");
		version = searchVersion("Firefox") || "";
		$('body').addClass("isMozilla"+version);
	}

	// Opera versioning
	isOpera = jQuery.browser.opera;
	if (isOpera) {
		$('body').addClass("isOpera");
	}

	// iPhone
	if (navigator.userAgent.indexOf("iPhone") != -1) {
		isIphone = true;
		$('body').addClass("isIphone");
	}

}

/* Setting classes to handle cross browser dom parsing
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function setUpClasses() {

	/* Setting border for 1st child of the breadcrumb */
	if ($('#navigation')[0]) {
		$('#navigation').find('span.prev_next').find(":nth-child(1)").addClass("first");
	}

	if ($('#content')[0]) {

		/* Setting margin for all direct children of #content. This is a duplicate of a CSS rule but IE can't handle it so we put it here */
		$('#content > div').css("marginBottom", "15px");

		$('li:nth-child(even)').addClass("even");
		$('li:first-child').addClass("first");
		$('li:last-child').addClass("last");
	}

	bindHeaderEvents();

}

/* Show/Hide the header + cookie
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function bindHeaderEvents() {
	if ($('#showHideSwitch')[0]) {
		$('#showHideSwitch').click(function(e) {
			if ($(this).html() == 'expand header') {
				$(this).addClass('hideSwitch');
				$(this).removeClass('showSwitch');
				$(this).html('collapse header');
				$('#header').show();
				createCookie('header', 'showSwitch');
			} else {
				$(this).addClass('showSwitch');
				$(this).removeClass('hideSwitch');
				$(this).html("expand header");
				$('#header').hide();
				createCookie('header', 'hideSwitch');
			}
		});

		/* TODO = handle cookie in IE6 */
	}
}

/* Cookies functions
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function createCookie(name, value) {
	var today = new Date();
	today.setTime(today.getTime()+(24*60*60*1000*365));
	var expires = "; expires=" + today.toGMTString();
	document.cookie = name+"=" + value + expires+"; path=/";
}

/* Gallery Module
   - Horizontal and vertical alignment of images
   - Handling image hover/click for IE6/7
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function gallery() {

	if ($('#gallery')[0]) {

		// Setting the context to optimize the each function
		var _context = $('#gallery').find('ul').find('li');
		var _galthumb = _context.find('a').find('.gallery_thumbnail');

		_galthumb.each(function() {

			if ($(this).hasClass("custom")) {

				// =TODO fix the bug in IE6/7

			} else {

				_img = $(this).find('img');
				var wImg = _img.width();
				var hImg = _img.height();
				var wP = $(this).parent().find("p").outerWidth();
				var hP = $(this).outerHeight();

				// If the image width is smaller than its container's then we align it horizontally
				if (wImg < wP) {
					// Setting the right width (based on the widest between the img and the filename)
					$(this).css("width", wP + "px");
					var m = wImg / 2;
					_img.css("position", "absolute");
					_img.css("left", "50%");
					_img.css("marginLeft", "-" + m + "px");
				}

				// If the image height is smaller than its container's then we align it vertically
				if (hImg < hP) {
					var m = hImg / 2;
					_img.css("position", "absolute");
					_img.css("top", "50%");
					_img.css("marginTop", "-" + m + "px");
				}
			}

		});

		if (isIE6 || isIE7) {
			$('#gallery').find('ul').find('li').click(function(e) {
				e.preventDefault();
				var href = $(this).find("a").attr("href");
				if (href != "#" && href != "" && href != undefined) {
					window.location = href;
				}
			});
			$('#gallery').find('ul').find('li').hover(function(){
				$(this).addClass("hover");
			}, function() {
				$(this).removeClass("hover");
			});
		}

	}
}

/* Register keypress events on the whole document when navigation exists
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function keyPress () {
	if ($('#navigation')[0]) {
		var _scrollTop = 100;
		$(document).keypress(function(e) {
			switch(e.keyCode) {
				// user pressed "left" arrow
				case 37:
					if ($('#previous')[0]) {
						var previous = $('#previous');
						var previous_url = previous.attr("href");
						if (previous_url) {
							previous.addClass('hover').fadeTo(250, 1, function() {
								window.location = previous_url;
							});
						}
					}
				break;

				// user pressed "top" arrow
				case 38: $('html,body').animate({scrollTop: 0}, 250);
				break;

				// user pressed "right" arrow
				case 39:
					if ($('#next')[0]) {
						var next = $('#next');
						var next_url = next.attr("href");
						if (next_url) {
							next.addClass('hover').fadeTo(250, 1, function() {
								window.location = next_url;
							});
						}
					}
				break;
			}
		});
	}
}

/* Remove the focus of the links
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function removeFocus () {
	// Remove links Focus
	for(i=0;i<document.links.length;i++) {
		document.links[i].onfocus=function() {if(this.blur)this.blur()};
	}
}

/* Open a popup
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function pop(goPage,nom,windowWidth,windowHeight,style) {
	var x = 0;
	var y = 0;
	var offset = 30;
	var popped;

	if (screen) x = (screen.availWidth - windowWidth) / 2;
	if (screen) y = (screen.availHeight - windowHeight) / 2;

	if ( style == 'POP' ) {
	    var popped = window.open(goPage,nom,'width='+windowWidth+',height='+(windowHeight+offsetMac)+',status=no,menubar=no,scrollbars=no,resizable=no,screenX='+x+',screenY='+y+',left='+x+',top='+y);
    }

	if ( style == 'POPSCROLL' ) {
	    var popped = window.open(goPage,nom,'width='+windowWidth+',height='+(windowHeight+offsetMac)+',status=no,menubar=no,scrollbars=yes,resizable=no,screenX='+x+',screenY='+y+',left='+x+',top='+y);
    }

	if ( style == 'WINDOW' ) {
		if (windowHeight > screen.availHeight) windowHeight = (screen.availHeight - offset);
		var popped = window.open(goPage,nom,'width='+windowWidth+',height='+(windowHeight+offsetMac)+',status=yes,menubar=yes,scrollbars=yes,resizable=yes,screenX='+x+',screenY='+y+',left='+x+',top='+y);
	}

	if ( isMozilla || document.all) popped.focus();
	if ( !popped.opener) { popped.opener = window; }
}

/* InfoHideSwitch
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function InfoHideSwitch (box, button) {
    if (document.getElementById) {
        var box_id = document.getElementById(box);
		var button_id = document.getElementById(button);

        if (box_id.className == "show") {
            // collapse
            box_id.className = 'hide';
			button_id.className = '';
        } else {
            // expand
            box_id.className = 'show';
			button_id.className = 'on';
			scrollToBottom();
        }
    }
}

/* Scroll to bottom
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function scrollToBottom () {
	window.scrollTo(0,5000);
}

/* Hide flash
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function hideFlash(theid) {
	if (document.getElementById) {
      var notice_id = document.getElementById(theid);
	  notice_id.className = 'hide';
  }
}

<commit_msg>Updated the keypress function<commit_after>/* --------------------------------------------------------------

main.js
* Subfolio by AREA 17

-------------------------------------------------------------- */

/* Setting up variables
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
var isSafari = false;
var isSafari3 = false;
var isSafari4 = false;
var isIE = false;
var isIE6 = false;
var isIE7 = false;
var isIE8 = false;
var isMozilla = false;
var isOpera = false;
var isMac = false;
var isIphone = false;

var offsetMac = 0;

/* What to do when DOM is ready
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
$(document).ready(function(){
	//console.time("runOnDOMready");
	runOnDOMready();
	//console.timeEnd("runOnDOMready");
});

/* Run when DOM is ready
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function runOnDOMready() {
	browserDectect();
	gallery(); // runs first to speed vertical/horizontal alignement rendering if needed.
	setUpClasses();
	keyPress();
}

/* Browser Detect
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function browserDectect() {

	function searchVersion(browser) {
		var dataString = navigator.userAgent;
		var index = dataString.indexOf(browser);
		if (index == -1) return;
		var bVersion = parseFloat(dataString.substring(index+browser.length+1));
		return bVersion.toString().split(".")[0];
	}

	// are we on a Mac ?
	if (navigator.appVersion.indexOf("Mac")!=-1) {
		isMac = true;
		$('body').addClass("isMac");
	}

	// Safari versioning
	isSafari =  jQuery.browser.safari;
	if (isSafari) {
		$('body').addClass("isSafari");
		version = searchVersion("Version") || + "";
		$('body').addClass("isSafari"+version);
		isSafari3 = (version == 3) ? true : false;
		isSafari4 = (version == 4) ? true : false;
	}

	// IE versioning
	isIE = jQuery.browser.msie;
	if (isIE) {
		version = searchVersion("MSIE") || "";
		isIE6 = (version == 6) ? true : false;
		isIE7 = (version == 7) ? true : false;
		isIE8 = (version == 8) ? true : false;
	}

	// Mozilla versioning
	isMozilla = jQuery.browser.mozilla;
	if (isMozilla) {
		$('body').addClass("isMozilla");
		version = searchVersion("Firefox") || "";
		$('body').addClass("isMozilla"+version);
	}

	// Opera versioning
	isOpera = jQuery.browser.opera;
	if (isOpera) {
		$('body').addClass("isOpera");
	}

	// iPhone
	if (navigator.userAgent.indexOf("iPhone") != -1) {
		isIphone = true;
		$('body').addClass("isIphone");
	}

}

/* Setting classes to handle cross browser dom parsing
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function setUpClasses() {

	/* Setting border for 1st child of the breadcrumb */
	if ($('#navigation')[0]) {
		$('#navigation').find('span.prev_next').find(":nth-child(1)").addClass("first");
	}

	if ($('#content')[0]) {

		/* Setting margin for all direct children of #content. This is a duplicate of a CSS rule but IE can't handle it so we put it here */
		$('#content > div').css("marginBottom", "15px");

		$('li:nth-child(even)').addClass("even");
		$('li:first-child').addClass("first");
		$('li:last-child').addClass("last");
	}

	bindHeaderEvents();

}

/* Show/Hide the header + cookie
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function bindHeaderEvents() {
	if ($('#showHideSwitch')[0]) {
		$('#showHideSwitch').click(function(e) {
			if ($(this).html() == 'expand header') {
				$(this).addClass('hideSwitch');
				$(this).removeClass('showSwitch');
				$(this).html('collapse header');
				$('#header').show();
				createCookie('header', 'showSwitch');
			} else {
				$(this).addClass('showSwitch');
				$(this).removeClass('hideSwitch');
				$(this).html("expand header");
				$('#header').hide();
				createCookie('header', 'hideSwitch');
			}
		});

		/* TODO = handle cookie in IE6 */
	}
}

/* Cookies functions
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function createCookie(name, value) {
	var today = new Date();
	today.setTime(today.getTime()+(24*60*60*1000*365));
	var expires = "; expires=" + today.toGMTString();
	document.cookie = name+"=" + value + expires+"; path=/";
}

/* Gallery Module
   - Horizontal and vertical alignment of images
   - Handling image hover/click for IE6/7
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function gallery() {

	if ($('#gallery')[0]) {

		// Setting the context to optimize the each function
		var _context = $('#gallery').find('ul').find('li');
		var _galthumb = _context.find('a').find('.gallery_thumbnail');

		_galthumb.each(function() {

			if ($(this).hasClass("custom")) {

				// =TODO fix the bug in IE6/7

			} else {

				_img = $(this).find('img');
				var wImg = _img.width();
				var hImg = _img.height();
				var wP = $(this).parent().find("p").outerWidth();
				var hP = $(this).outerHeight();

				// If the image width is smaller than its container's then we align it horizontally
				if (wImg < wP) {
					// Setting the right width (based on the widest between the img and the filename)
					$(this).css("width", wP + "px");
					var m = wImg / 2;
					_img.css("position", "absolute");
					_img.css("left", "50%");
					_img.css("marginLeft", "-" + m + "px");
				}

				// If the image height is smaller than its container's then we align it vertically
				if (hImg < hP) {
					var m = hImg / 2;
					_img.css("position", "absolute");
					_img.css("top", "50%");
					_img.css("marginTop", "-" + m + "px");
				}
			}

		});

		if (isIE6 || isIE7) {
			$('#gallery').find('ul').find('li').click(function(e) {
				e.preventDefault();
				var href = $(this).find("a").attr("href");
				if (href != "#" && href != "" && href != undefined) {
					window.location = href;
				}
			});
			$('#gallery').find('ul').find('li').hover(function(){
				$(this).addClass("hover");
			}, function() {
				$(this).removeClass("hover");
			});
		}

	}
}

/* Register keypress events on the whole document when navigation exists
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function keyPress () {
	$(document).keypress(function(e) {
		switch(e.keyCode) {
			// user pressed "left" arrow
			case 37:
				if ($('#previous')[0]) {
					var previous = $('#previous');
					var previous_url = previous.attr("href");
					if (previous_url) {
						previous.addClass('hover').fadeTo(250, 1, function() {
							window.location = previous_url;
						});
					}
				}
			break;

			// user pressed "top" arrow
			case 38: $('html,body').animate({scrollTop: 0}, 250);
			break;

			// user pressed "right" arrow
			case 39:
				if ($('#next')[0]) {
					var next = $('#next');
					var next_url = next.attr("href");
					if (next_url) {
						next.addClass('hover').fadeTo(250, 1, function() {
							window.location = next_url;
						});
					}
				}
			break;
		}
	});
}

/* Remove the focus of the links
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function removeFocus () {
	// Remove links Focus
	for(i=0;i<document.links.length;i++) {
		document.links[i].onfocus=function() {if(this.blur)this.blur()};
	}
}

/* Open a popup
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function pop(goPage,nom,windowWidth,windowHeight,style) {
	var x = 0;
	var y = 0;
	var offset = 30;
	var popped;

	if (screen) x = (screen.availWidth - windowWidth) / 2;
	if (screen) y = (screen.availHeight - windowHeight) / 2;

	if ( style == 'POP' ) {
	    var popped = window.open(goPage,nom,'width='+windowWidth+',height='+(windowHeight+offsetMac)+',status=no,menubar=no,scrollbars=no,resizable=no,screenX='+x+',screenY='+y+',left='+x+',top='+y);
    }

	if ( style == 'POPSCROLL' ) {
	    var popped = window.open(goPage,nom,'width='+windowWidth+',height='+(windowHeight+offsetMac)+',status=no,menubar=no,scrollbars=yes,resizable=no,screenX='+x+',screenY='+y+',left='+x+',top='+y);
    }

	if ( style == 'WINDOW' ) {
		if (windowHeight > screen.availHeight) windowHeight = (screen.availHeight - offset);
		var popped = window.open(goPage,nom,'width='+windowWidth+',height='+(windowHeight+offsetMac)+',status=yes,menubar=yes,scrollbars=yes,resizable=yes,screenX='+x+',screenY='+y+',left='+x+',top='+y);
	}

	if ( isMozilla || document.all) popped.focus();
	if ( !popped.opener) { popped.opener = window; }
}

/* InfoHideSwitch
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function InfoHideSwitch (box, button) {
    if (document.getElementById) {
        var box_id = document.getElementById(box);
		var button_id = document.getElementById(button);

        if (box_id.className == "show") {
            // collapse
            box_id.className = 'hide';
			button_id.className = '';
        } else {
            // expand
            box_id.className = 'show';
			button_id.className = 'on';
			scrollToBottom();
        }
    }
}

/* Scroll to bottom
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function scrollToBottom () {
	window.scrollTo(0,5000);
}

/* Hide flash
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––*/
function hideFlash(theid) {
	if (document.getElementById) {
      var notice_id = document.getElementById(theid);
	  notice_id.className = 'hide';
  }
}

<|endoftext|>


<commit_before>/* global __dirname, module, require */
const path = require("path");

module.exports = (options) => {
  if (options.entry === undefined) {
    throw Error("options.entry must be specified.")
  }
  if (options.filename === undefined) {
    throw Error("options.Filename must be specified.")
  }
  if (options.library === undefined) {
    throw Error("options.library must be specified.")
  }

  return {
    entry: options.entry,
    output: {
      filename: options.filename,
      library: options.library,
      libraryTarget: "umd2",
      umdNamedDefine: false
    },
    externals: options.externals,
    resolve: {
      extensions: [".ts"]
    },
    devtool: "source-map",
    module: {
      loaders: [
        {
          enforce: "pre",
          test: /\.ts$/,
          loader: "tslint-loader",
          exclude: /node_modules/,
          options: {
            failOnHint: true,
            configFile: path.join("config", "tslint.json"),
          }
        },
        {
          test: /\.ts$/,
          loader: "ts-loader",
          options: {
            configFile: path.join("config", "tsconfig.webpack.json")
          }
        }
      ]
    },
  };
};
<commit_msg>build: define module name for AMD export (#118)<commit_after>/* global __dirname, module, require */
const path = require("path");

module.exports = (options) => {
  if (options.entry === undefined) {
    throw Error("options.entry must be specified.")
  }
  if (options.filename === undefined) {
    throw Error("options.Filename must be specified.")
  }
  if (options.library === undefined) {
    throw Error("options.library must be specified.")
  }

  return {
    entry: options.entry,
    output: {
      filename: options.filename,
      library: options.library,
      libraryTarget: "umd2",
      umdNamedDefine: true
    },
    externals: options.externals,
    resolve: {
      extensions: [".ts"]
    },
    devtool: "source-map",
    module: {
      loaders: [
        {
          enforce: "pre",
          test: /\.ts$/,
          loader: "tslint-loader",
          exclude: /node_modules/,
          options: {
            failOnHint: true,
            configFile: path.join("config", "tslint.json"),
          }
        },
        {
          test: /\.ts$/,
          loader: "ts-loader",
          options: {
            configFile: path.join("config", "tsconfig.webpack.json")
          }
        }
      ]
    },
  };
};
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const ROOT = require('config/path-helper').ROOT;
const config = require('config/config.json');
const webpack = require('webpack');

module.exports = {
  context: ROOT,
  entry: {
    app: [
      path.join(ROOT, config.path.app, 'app')
    ]
  },
  output: {
    path: path.join(ROOT, config.path.publicAssets)
  },
  externals: {},
  resolve: {
    modulesDirectories: ['node_modules', 'bower_components'],
    extensions: ['', '.js']
  },
  module: {
    loaders: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.(gif|jpg|jpeg|png|svg|ttf|eot|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader'
      }
    ]
  },
  plugins: [
    new webpack.optimize.AggressiveMergingPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.ResolverPlugin([
      new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('.bower.json', ['main'])
    ]),
    new webpack.DefinePlugin({
      'process.env.RUNTIME_ENV': "'client'"
    })
  ]
};
<commit_msg>Update built tools<commit_after>'use strict';

const path = require('path');
const ROOT = require('config/path-helper').ROOT;
const config = require('config/config.json');
const webpack = require('webpack');

module.exports = {
  context: ROOT,
  entry: {
    app: [
      path.join(ROOT, config.path.app, 'app')
    ]
  },
  output: {
    path: path.join(ROOT, config.path.publicAssets)
  },
  externals: [],
  resolve: {
    modulesDirectories: ['node_modules', 'bower_components'],
    extensions: ['', '.js']
  },
  module: {
    loaders: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.(gif|jpg|jpeg|png|svg|ttf|eot|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader'
      }
    ]
  },
  plugins: [
    new webpack.optimize.AggressiveMergingPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.ResolverPlugin([
      new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('.bower.json', ['main'])
    ]),
    new webpack.DefinePlugin({
      'process.env.RUNTIME_ENV': "'client'"
    })
  ]
};
<|endoftext|>