<commit_before>import API, { Settings } from "api"
import { gql } from "apollo-boost"
import AppContext from "components/AppContext"
import Fieldset from "components/Fieldset"
import LinkTo from "components/LinkTo"
import { mapDispatchToProps, useBoilerplate } from "components/Page"
import UltimatePagination from "components/UltimatePagination"
import { Person, Task } from "models"
import pluralize from "pluralize"
import PropTypes from "prop-types"
import React, { useState } from "react"
import { Table } from "react-bootstrap"
import { connect } from "react-redux"

const GQL_GET_TASK_LIST = gql`
  query($taskQuery: TaskSearchQueryInput) {
    taskList(query: $taskQuery) {
      pageNum
      pageSize
      totalCount
      list {
        uuid
        shortName
        longName
      }
    }
  }
`

const BaseOrganizationTasks = props => {
  const { queryParams } = props
  const [pageNum, setPageNum] = useState(0)
  const taskQuery = Object.assign({}, queryParams, { pageNum })
  const { loading, error, data } = API.useApiQuery(GQL_GET_TASK_LIST, {
    taskQuery
  })
  const { done, result } = useBoilerplate({
    loading,
    error,
    ...props
  })
  if (done) {
    return result
  }

  const paginatedTasks = data.taskList
  const tasks = paginatedTasks ? paginatedTasks.list : []
  const { currentUser, organization } = props
  const isAdminUser = currentUser && currentUser.isAdmin()
  const taskShortLabel = Settings.fields.task.shortLabel

  if (!organization.isAdvisorOrg()) {
    return

  }

  const { pageSize, totalCount } = paginatedTasks

  return (
    <Fieldset
      id="tasks"
      title={pluralize(taskShortLabel)}
      action={
        isAdminUser && (
          <LinkTo
            task={Task.pathForNew({ responsibleOrgUuid: organization.uuid })}
            button
          >
            Create {taskShortLabel}
          </LinkTo>
        )
      }
    >
      <UltimatePagination
        Component="header"
        componentClassName="searchPagination"
        className="pull-right"
        pageNum={pageNum}
        pageSize={pageSize}
        totalCount={totalCount}
        goToPage={setPageNum}
      />

            Name
            Description

          {Task.map(tasks, (task, idx) => (
            <tr key={task.uuid} id={`task_${idx}`}>

                <LinkTo task={task}>{task.shortName}</LinkTo>

              {task.longName}

          ))}

      {tasks.length === 0 && (
        This organization doesn't have any {pluralize(taskShortLabel)}
      )}
    </Fieldset>
  )
}

BaseOrganizationTasks.propTypes = {
  currentUser: PropTypes.instanceOf(Person),
  organization: PropTypes.object.isRequired,
  queryParams: PropTypes.object
}

const OrganizationTasks = props => (
  <AppContext.Consumer>
    {context => (
      <BaseOrganizationTasks currentUser={context.currentUser} {...props} />
    )}
  </AppContext.Consumer>
)

export default connect(
  null,
  mapDispatchToProps
)(OrganizationTasks)
<commit_msg>NCI-Agency/anet#2293: Add pagination to the bottom of lists<commit_after>import API, { Settings } from "api"
import { gql } from "apollo-boost"
import AppContext from "components/AppContext"
import Fieldset from "components/Fieldset"
import LinkTo from "components/LinkTo"
import { mapDispatchToProps, useBoilerplate } from "components/Page"
import UltimatePaginationTopDown from "components/UltimatePaginationTopDown"
import { Person, Task } from "models"
import pluralize from "pluralize"
import PropTypes from "prop-types"
import React, { useState } from "react"
import { Table } from "react-bootstrap"
import { connect } from "react-redux"
import _get from "lodash/get"

const GQL_GET_TASK_LIST = gql`
  query($taskQuery: TaskSearchQueryInput) {
    taskList(query: $taskQuery) {
      pageNum
      pageSize
      totalCount
      list {
        uuid
        shortName
        longName
      }
    }
  }
`

const BaseOrganizationTasks = props => {
  const { queryParams } = props
  const [pageNum, setPageNum] = useState(0)
  const taskQuery = Object.assign({}, queryParams, { pageNum })
  const { loading, error, data } = API.useApiQuery(GQL_GET_TASK_LIST, {
    taskQuery
  })
  const { done, result } = useBoilerplate({
    loading,
    error,
    ...props
  })
  if (done) {
    return result
  }

  const paginatedTasks = data.taskList
  const tasks = paginatedTasks ? paginatedTasks.list : []
  const { currentUser, organization } = props
  const isAdminUser = currentUser && currentUser.isAdmin()
  const taskShortLabel = Settings.fields.task.shortLabel

  if (!organization.isAdvisorOrg()) {
    return

  }

  const { pageSize, totalCount } = paginatedTasks

  if (_get(tasks, "length", 0) === 0) {
    return (
      This organization doesn't have any {pluralize(taskShortLabel)}
    )
  }

  const tableElement = (

          Name
          Description

        {Task.map(tasks, (task, idx) => (
          <tr key={task.uuid} id={`task_${idx}`}>

              <LinkTo task={task}>{task.shortName}</LinkTo>

            {task.longName}

        ))}

  )

  return (
    <Fieldset
      id="tasks"
      title={pluralize(taskShortLabel)}
      action={
        isAdminUser && (
          <LinkTo
            task={Task.pathForNew({ responsibleOrgUuid: organization.uuid })}
            button
          >
            Create {taskShortLabel}
          </LinkTo>
        )
      }
    >
      <UltimatePaginationTopDown
        componentClassName="searchPagination"
        className="pull-right"
        pageNum={pageNum}
        pageSize={pageSize}
        totalCount={totalCount}
        goToPage={setPageNum}
        contentElement={tableElement}
      />
    </Fieldset>
  )
}

BaseOrganizationTasks.propTypes = {
  currentUser: PropTypes.instanceOf(Person),
  organization: PropTypes.object.isRequired,
  queryParams: PropTypes.object
}

const OrganizationTasks = props => (
  <AppContext.Consumer>
    {context => (
      <BaseOrganizationTasks currentUser={context.currentUser} {...props} />
    )}
  </AppContext.Consumer>
)

export default connect(
  null,
  mapDispatchToProps
)(OrganizationTasks)
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require ckeditor/init
//= require bootstrap-alert
//= require bootstrap-dropdown
//= require bootstrap-datepicker/core
//= require bootstrap-datepicker/locales/bootstrap-datepicker.pt-BR
//= require bootstrap-fileupload
//= require jquery.tipsy
//= require bindWithDelay
//= require reorder
//= require_self

// Bootstrap Datepicker

$(document).ready(function() {
  $('[data-behaviour~=datepicker]').datepicker({
    language: 'pt-BR',
    format:   'dd/mm/yyyy'
  });
});

// Tooltips

$(window).load(function() {
  $('.has-tipsy').tipsy({
    gravity: 's',
    fade: true
  });
});

// File Upload
$(document).ready(function() {
  $('.fileupload').fileupload();
});
<commit_msg>Add ckeditor/config.js to manifest<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require ckeditor/init
//= require ckeditor/config.js
//= require bootstrap-alert
//= require bootstrap-dropdown
//= require bootstrap-datepicker/core
//= require bootstrap-datepicker/locales/bootstrap-datepicker.pt-BR
//= require bootstrap-fileupload
//= require jquery.tipsy
//= require bindWithDelay
//= require reorder
//= require_self

// Bootstrap Datepicker

$(document).ready(function() {
  $('[data-behaviour~=datepicker]').datepicker({
    language: 'pt-BR',
    format:   'dd/mm/yyyy'
  });
});

// Tooltips

$(window).load(function() {
  $('.has-tipsy').tipsy({
    gravity: 's',
    fade: true
  });
});

// File Upload
$(document).ready(function() {
  $('.fileupload').fileupload();
});
<|endoftext|>


<commit_before>import { create_float_buffer, create_index_buffer } from './context.js';
import { math } from './math.js';
import { zero_vector, unit_vector } from '../misc/defaults.js';
import { materials } from '../materials/materials.js';
import { hex_to_vec } from '../misc/utils.js';

class Entity {
  constructor(options = {}) {
    this.local_matrix = math.mat4.create();
    this.world_matrix = math.mat4.create();

    this.position = options.position || zero_vector.slice();
    this.scale = options.scale || unit_vector.slice();
    this.origin = options.origin || zero_vector.slice();

    this.material = options.material;

    if (this.material) {
      this.color_vec = [];
      this.color_opacity = 1.0;
      this.color = options.color || '#ffffff';
    }

    this.entities = [];

    this.keyboard_controlled = false;

    this.move_speed = 3.5;
    this.rotate_speed = 1.5;

    this.indices = this.indices || options.indices;
    this.vertices = this.vertices || options.vertices;
    this.normals = this.normals || options.normals;

    this.material_desc = this.material && new materials[this.material];
    this.program = this.material_desc && this.material_desc.program;

    this.skip = false;

    this.dir = {};

    this.dir_desc = {
      87: 'f',
      65: 'l',
      68: 'r',
      83: 'b',
      81: 'u',
      69: 'd',
      38: 'r_u',
      40: 'r_d',
      39: 'r_r',
      37: 'r_l'
    };

    if (this.vertices && this.indices && this.normals) {
      this.create_buffers();
    }
  }

  look_at(vec, up = this.up) {
    math.mat4.target_to(this.local_matrix, this.position, vec, up);
  }

  get right() {
    const out = this.local_matrix.slice(0, 3);
    return math.vec3.normalize(out, out);
  }

  get up() {
    const out = this.local_matrix.slice(4, 7);
    return math.vec3.normalize(out, out);
  }

  get forward() {
    const out = this.local_matrix.slice(8, 11);
    return math.vec3.normalize(out, out);
  }

  set position(vec) {
    const offset = [];
    math.vec3.subtract(offset, vec, this.position);
    math.mat4.translate(this.local_matrix, this.local_matrix, offset);
  }

  get position() {
    return this.local_matrix.slice(12, 15);
  }

  set scale(vec) {
    math.mat4.scale(this.local_matrix, this.local_matrix, vec);
  }

  set color(hex) {
    this._color = hex || '#ffffff';
    this.color_vec = [...hex_to_vec(this._color), this.color_opacity];
  }

  get color() {
    return this._color;
  }

  create_buffers() {
    this.buffers = {
      vertices: create_float_buffer(this.vertices),
      indices: create_index_buffer(this.indices),
      qty: this.indices.length,
      normals: create_float_buffer(this.normals)
    }
  }

  add(entity) {
    entity.parent = this;
    this.entities.push(entity);
  }

  get_view_matrix(out) {
    const look_at_vect = [];
    math.vec3.add(look_at_vect, this.position, this.forward);
    math.mat4.look_at(out, this.position, look_at_vect, this.up);
    return out;
  }

  rotate_along(vec, rad) {
    const rotation_matrix = math.mat4.create();
    math.mat4.from_rotation(rotation_matrix, rad, vec);
    math.mat4.multiply(this.local_matrix, this.local_matrix, rotation_matrix);
  }

  rotate_rl(rad) {
    this.rotate_along(math.vec3.from_values(0, 1, 0), rad);
  }

  rotate_ud(rad) {
    this.rotate_along(math.vec3.from_values(1, 0, 0), rad);
  }

  move_along(vec, dist) {
    const move = zero_vector.slice();
    math.vec3.scale(move, vec, dist);
    math.mat4.translate(this.local_matrix, this.local_matrix, move);
  }

  move_r(dist) {
    this.move_along(math.vec3.from_values(1, 0, 0), dist);
  }

  move_u(dist) {
    this.move_along(math.vec3.from_values(0, 1, 0), dist);
  }

  move_f(dist) {
    this.move_along(math.vec3.from_values(0, 0, 1), dist);
  }

  do_step(tick_length) {
    if (this.dir.f && !this.dir.b) {
      this.move_f(tick_length / 1000 * this.move_speed);
    }

    if (this.dir.b && !this.dir.f) {
      this.move_f(-tick_length / 1000 * this.move_speed);
    }

    if (this.dir.r && !this.dir.l) {
      this.move_r(-tick_length / 1000 * this.move_speed);
    }

    if (this.dir.l && !this.dir.r) {
      this.move_r(tick_length / 1000 * this.move_speed);
    }

    if (this.dir.u && !this.dir.d) {
      this.move_u(tick_length / 1000 * this.move_speed);
    }

    if (this.dir.d && !this.dir.u) {
      this.move_u(-tick_length / 1000 * this.move_speed);
    }

    if (this.dir.r_r && !this.dir.r_l) {
      this.rotate_rl(-tick_length / 1000 * this.rotate_speed);
    }

    if (this.dir.r_l && !this.dir.r_r) {
      this.rotate_rl(tick_length / 1000 * this.rotate_speed);
    }

    if (this.dir.r_u && !this.dir.r_d) {
      this.rotate_ud(-tick_length / 1000 * this.rotate_speed);
    }

    if (this.dir.r_d && !this.dir.r_u) {
      this.rotate_ud(tick_length / 1000 * this.rotate_speed);
    }
  }

  update(tick_length) {
    if (this.skip) {
      return;
    }

    if (this.keyboard_controlled && this.game) {
      Object.keys(this.dir_desc).forEach((key) => {
        if (this.dir_desc[key]) {
          this.dir[this.dir_desc[key]] = this.game.keys[key] || false;
        }
      });
      this.do_step(tick_length);
    }

    if (!this.material && !this.entities.length) {
      return;
    }

    if (this.parent) {
      math.mat4.multiply(
        this.world_matrix, this.parent.world_matrix, this.local_matrix
      );
    } else {
      this.world_matrix = this.local_matrix.slice();
    }

    this.entities.forEach(entity => entity.update());
  }

  render(ticks) {
    !this.skip && this.material && this.material_desc.render(this);
    !this.skip && this.entities.forEach((entity) => {
      entity.render(ticks);
    });
  }

  // generate_shadow_map() {
  //   this.material_desc.generate_shadow_map && this.material_desc.generate_shadow_map(this);
  // }
}

export { Entity }
<commit_msg>rename Entity.right to Entity.left<commit_after>import { create_float_buffer, create_index_buffer } from './context.js';
import { math } from './math.js';
import { zero_vector, unit_vector } from '../misc/defaults.js';
import { materials } from '../materials/materials.js';
import { hex_to_vec } from '../misc/utils.js';

class Entity {
  constructor(options = {}) {
    this.local_matrix = math.mat4.create();
    this.world_matrix = math.mat4.create();

    this.position = options.position || zero_vector.slice();
    this.scale = options.scale || unit_vector.slice();
    this.origin = options.origin || zero_vector.slice();

    this.material = options.material;

    if (this.material) {
      this.color_vec = [];
      this.color_opacity = 1.0;
      this.color = options.color || '#ffffff';
    }

    this.entities = [];

    this.keyboard_controlled = false;

    this.move_speed = 3.5;
    this.rotate_speed = 1.5;

    this.indices = this.indices || options.indices;
    this.vertices = this.vertices || options.vertices;
    this.normals = this.normals || options.normals;

    this.material_desc = this.material && new materials[this.material];
    this.program = this.material_desc && this.material_desc.program;

    this.skip = false;

    this.dir = {};

    this.dir_desc = {
      87: 'f',
      65: 'l',
      68: 'r',
      83: 'b',
      81: 'u',
      69: 'd',
      38: 'r_u',
      40: 'r_d',
      39: 'r_r',
      37: 'r_l'
    };

    if (this.vertices && this.indices && this.normals) {
      this.create_buffers();
    }
  }

  look_at(vec, up = this.up) {
    math.mat4.target_to(this.local_matrix, this.position, vec, up);
  }

  get left() {
    const out = this.local_matrix.slice(0, 3);
    return math.vec3.normalize(out, out);
  }

  get up() {
    const out = this.local_matrix.slice(4, 7);
    return math.vec3.normalize(out, out);
  }

  get forward() {
    const out = this.local_matrix.slice(8, 11);
    return math.vec3.normalize(out, out);
  }

  set position(vec) {
    const offset = [];
    math.vec3.subtract(offset, vec, this.position);
    math.mat4.translate(this.local_matrix, this.local_matrix, offset);
  }

  get position() {
    return this.local_matrix.slice(12, 15);
  }

  set scale(vec) {
    math.mat4.scale(this.local_matrix, this.local_matrix, vec);
  }

  set color(hex) {
    this._color = hex || '#ffffff';
    this.color_vec = [...hex_to_vec(this._color), this.color_opacity];
  }

  get color() {
    return this._color;
  }

  create_buffers() {
    this.buffers = {
      vertices: create_float_buffer(this.vertices),
      indices: create_index_buffer(this.indices),
      qty: this.indices.length,
      normals: create_float_buffer(this.normals)
    }
  }

  add(entity) {
    entity.parent = this;
    this.entities.push(entity);
  }

  get_view_matrix(out) {
    const look_at_vect = [];
    math.vec3.add(look_at_vect, this.position, this.forward);
    math.mat4.look_at(out, this.position, look_at_vect, this.up);
    return out;
  }

  rotate_along(vec, rad) {
    const rotation_matrix = math.mat4.create();
    math.mat4.from_rotation(rotation_matrix, rad, vec);
    math.mat4.multiply(this.local_matrix, this.local_matrix, rotation_matrix);
  }

  rotate_rl(rad) {
    this.rotate_along(math.vec3.from_values(0, 1, 0), rad);
  }

  rotate_ud(rad) {
    this.rotate_along(math.vec3.from_values(1, 0, 0), rad);
  }

  move_along(vec, dist) {
    const move = zero_vector.slice();
    math.vec3.scale(move, vec, dist);
    math.mat4.translate(this.local_matrix, this.local_matrix, move);
  }

  move_r(dist) {
    this.move_along(math.vec3.from_values(1, 0, 0), dist);
  }

  move_u(dist) {
    this.move_along(math.vec3.from_values(0, 1, 0), dist);
  }

  move_f(dist) {
    this.move_along(math.vec3.from_values(0, 0, 1), dist);
  }

  do_step(tick_length) {
    if (this.dir.f && !this.dir.b) {
      this.move_f(tick_length / 1000 * this.move_speed);
    }

    if (this.dir.b && !this.dir.f) {
      this.move_f(-tick_length / 1000 * this.move_speed);
    }

    if (this.dir.r && !this.dir.l) {
      this.move_r(-tick_length / 1000 * this.move_speed);
    }

    if (this.dir.l && !this.dir.r) {
      this.move_r(tick_length / 1000 * this.move_speed);
    }

    if (this.dir.u && !this.dir.d) {
      this.move_u(tick_length / 1000 * this.move_speed);
    }

    if (this.dir.d && !this.dir.u) {
      this.move_u(-tick_length / 1000 * this.move_speed);
    }

    if (this.dir.r_r && !this.dir.r_l) {
      this.rotate_rl(-tick_length / 1000 * this.rotate_speed);
    }

    if (this.dir.r_l && !this.dir.r_r) {
      this.rotate_rl(tick_length / 1000 * this.rotate_speed);
    }

    if (this.dir.r_u && !this.dir.r_d) {
      this.rotate_ud(-tick_length / 1000 * this.rotate_speed);
    }

    if (this.dir.r_d && !this.dir.r_u) {
      this.rotate_ud(tick_length / 1000 * this.rotate_speed);
    }
  }

  update(tick_length) {
    if (this.skip) {
      return;
    }

    if (this.keyboard_controlled && this.game) {
      Object.keys(this.dir_desc).forEach((key) => {
        if (this.dir_desc[key]) {
          this.dir[this.dir_desc[key]] = this.game.keys[key] || false;
        }
      });
      this.do_step(tick_length);
    }

    if (!this.material && !this.entities.length) {
      return;
    }

    if (this.parent) {
      math.mat4.multiply(
        this.world_matrix, this.parent.world_matrix, this.local_matrix
      );
    } else {
      this.world_matrix = this.local_matrix.slice();
    }

    this.entities.forEach(entity => entity.update());
  }

  render(ticks) {
    !this.skip && this.material && this.material_desc.render(this);
    !this.skip && this.entities.forEach((entity) => {
      entity.render(ticks);
    });
  }

  // generate_shadow_map() {
  //   this.material_desc.generate_shadow_map && this.material_desc.generate_shadow_map(this);
  // }
}

export { Entity }
<|endoftext|>


<commit_before>var styleParser = require('style-attr');
var mixin = require('../vr-utils').mixin;

var mixAttributes = function (str, obj) {
  var attrs = str;
  if (!str) { return; }
  // Attributes can come in the form of a string or pre-parsed as an object
  // such as pos/rot/scale.
  if (typeof str === 'string') {
    attrs = styleParser.parse(str);
  }
  mixin(obj, attrs);
};

var Component = function (el) {
  var str = el.getAttribute(this.name);
  this.el = el;
  // To store the component specific data
  this.data = {};
  this.parseAttributes(str);
  this.init();
  this.update();
};

Component.prototype = {
  /**
   * Parses the data coming from the entity attribute
   * and updates the component
   */
  updateAttributes: function (str) {
    this.parseAttributes(str);
    this.update();
  },

  /**
   * Called on component initialization
   */
  init: function () { /* no-op */ },

  /**
   * It is called on the component
   * each time there's a change on the associated
   * data of the entity.
   */
  update: function () { /* no-op */ },

  /**
   * Parses the data coming from the entity attribute
   * If there's a style its values will be mixed in
   */
  parseAttributes: function (str) {
    var mixinEl = this.el.mixinEl;
    var styleStr = mixinEl && mixinEl.getAttribute(this.name);
    mixAttributes(styleStr, this.data);
    mixAttributes(str, this.data);
  }
};

module.exports = Component;
<commit_msg>When updating a component we were using the previous data object to mixin the element attribute string and the mixin. Removed component attributes were not eliminated from the data object.<commit_after>var styleParser = require('style-attr');
var mixin = require('../vr-utils').mixin;

var mixAttributes = function (str, obj) {
  var attrs = str;
  if (!str) { return; }
  // Attributes can come in the form of a string or pre-parsed as an object
  // such as pos/rot/scale.
  if (typeof str === 'string') {
    attrs = styleParser.parse(str);
  }
  mixin(obj, attrs);
};

var Component = function (el) {
  var str = el.getAttribute(this.name);
  this.el = el;
  // To store the component specific data
  this.data = {};
  this.parseAttributes(str);
  this.init();
  this.update();
};

Component.prototype = {
  /**
   * Parses the data coming from the entity attribute
   * and updates the component
   */
  updateAttributes: function (str) {
    this.parseAttributes(str);
    this.update();
  },

  /**
   * Called on component initialization
   */
  init: function () { /* no-op */ },

  /**
   * It is called on the component
   * each time there's a change on the associated
   * data of the entity.
   */
  update: function () { /* no-op */ },

  /**
   * Parses the data coming from the entity attribute
   * If there's a style its values will be mixed in
   */
  parseAttributes: function (str) {
    var mixinEl = this.el.mixinEl;
    var styleStr = mixinEl && mixinEl.getAttribute(this.name);
    var data = {};
    mixAttributes(styleStr, data);
    mixAttributes(str, data);
    this.data = data;
  }
};

module.exports = Component;
<|endoftext|>


<commit_before>/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	var $ = __webpack_require__(1);

	module.exports = {

	    created: function () {

	        this.Nodes = this.$resource('api/site/node/:id');
	        this.Menus = this.$resource('api/site/menu/:id', {}, { 'update': { method: 'PUT' }});

	        this.$add('nodes', []);
	        this.$add('menus', []);
	        this.$add('tree', {});

	        this.load();

	    },

	    events: {

	        loaded: function() {

	            var parents = _(this.nodes).sortBy('priority').groupBy('parentId').value(),
	                build = function (collection) {
	                    return collection.map(function(node) {
	                        return { node: node, children: build(parents[node.id] || [])}
	                    })
	                };

	            this.$set('tree', _.groupBy(build(parents[0] || []), function(node) { return node.node.menu }));
	        }

	    },

	    methods: {

	        load: function () {

	            var d1 = $.Deferred(), d2 = $.Deferred(), deferred = $.when(d1, d2);

	            deferred.done(function(nodes, menus) {

	                this.$set('nodes', nodes);
	                this.$set('menus', menus);

	                this.$emit('loaded');

	            }.bind(this));

	            this.Nodes.query(function (nodes) {
	                d1.resolve(nodes);
	            });

	            this.Menus.query(function (menus) {
	                d2.resolve(menus);
	            });

	            return deferred;
	        }

	    }

	};

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = jQuery;

/***/ }
/******/ ]);<commit_msg>cleanup<commit_after><|endoftext|>


<commit_before>// -*- coding: utf-8 -*-
//
// Copyright 2015 Red Hat, Inc.
//
// 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.

'use strict';

var app = angular.module('app', ['ngRoute', 'restangular', 'ngCookies',
'angular-loading-bar', 'ui.router']);

// Configure the application
app.config(function(RestangularProvider) {
    RestangularProvider.setBaseUrl('/api');
    // https://github.com/mgonto/restangular#my-response-is-actually-wrapped-with-some-metadata-how-do-i-get-the-data-in-that-case
    RestangularProvider.addResponseInterceptor(function(
    data, operation, what, url, response, deferred) {
        var extractedData = [];
        if (operation === 'getList') {
            extractedData._items = data._items;
            extractedData._meta = data._meta;
        } else {
            extractedData = data;
        }
        return extractedData;
    });
});

app.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
    $stateProvider
    .state('jobs', {
        url: '/jobs?page',
        templateUrl: 'partials/jobs.html',
        controller: 'ListJobsController'
    }).state('jobdetails', {
        url:'/jobdetails/:jobId',
        templateUrl: 'partials/jobdetails.html',
        controller: 'JobDetailsController'
    }).state('remotecis', {
        url:'/remotecis',
        templateUrl: 'partials/remotecis.html',
        controller: 'ListRemotecisController'
    }).state('products', {
        url:'/products',
        templateUrl: 'partials/products.html',
        controller: 'ProductsController'
    }).state('signin', {
        url: '/signin',
        templateUrl: 'partials/signin.html',
        controller: 'LoginController'
    }).state('signout', {
        url: '/signout',
        templateUrl: 'partials/signout.html',
        controller: 'LogoutController'
    });

    $urlRouterProvider.otherwise('/jobs');
    $httpProvider.interceptors.push('BasicAuthInjector');
});

app.factory('CommonCode', function($window, Restangular, $cookies) {
    // jscs:disable requireCamelCaseOrUpperCaseIdentifiers

    var getRemoteCis = function($scope) {
        Restangular.one('remotecis').get().then(
            function(remotecis) {
                $scope.remotecis = remotecis._items;
                $cookies.remotecisTotalPages = parseInt((
                remotecis._meta.total / remotecis._meta.max_results + 1));
                $scope.remotecisTotalPages = $cookies.remotecisTotalPages;
            }
        );
    };

    var getJobInfo = function($scope, job_id) {
        Restangular.one('jobs', job_id).get(
        {'embedded': {'remoteci':1, 'testversion':1}}).then(
        function(job) {
            $scope.job = job;
            Restangular.one('jobstates').get(
                {'where': {'job_id': job_id},
                 'embedded': {'files_collection':1}}).then(
                 function(jobstates) {
                     $scope.job['jobstates'] = jobstates._items;
                 });

            Restangular.one('testversions', job.testversion.id).get(
                {'embedded': {'version':1, 'test':1}}).then(
                function(testversion) {
                    $scope.job['version'] = testversion.version.name;
                    $scope.job['test'] = testversion.test.name;
                    Restangular.one('products',
                    testversion.version.product_id).get().then(
                        function(product) {
                            $scope.job['product'] = product.name;
                        }
                )});
        });
    };

    return {'getJobInfo': getJobInfo,
            'getRemoteCis': getRemoteCis};
});

app.factory('BasicAuthInjector', function($cookies) {
    var injector = {
        request: function(config) {
            config.headers['Authorization'] = 'Basic ' + $cookies.auth;
            return config;
        }
    };
    return injector;
});

app.controller('ListJobsController', function($scope, $location, $cookies,
CommonCode, Restangular, $state, $stateParams) {

    var loadPage = function() {
        var targetPage = $scope.jobCurrentPage;
        var searchObject = $location.search();
        if (searchObject.page != undefined) {
            var totalPages = $cookies.jobsTotalPages;
            var pageNumber = parseInt(searchObject.page);

            if ((pageNumber < ((parseInt(totalPages) + 1) | 0)) &&
                (pageNumber > 1)) {
                targetPage = parseInt(searchObject.page);
                $scope.jobCurrentPage = targetPage;
            }
        }

        Restangular.one('jobs').get({'page': targetPage,
                                     'extra_data': 1,
                                     'sort': '-created_at'}).
        then(function(jobs) {
            $scope.jobs = jobs._items
            $cookies.jobsTotalPages = parseInt((jobs._meta.total /
                jobs._meta.max_results + 1));
            $scope.jobsTotalPages = $cookies.jobsTotalPages;
        });

    };

    $scope.jobsNextPage = function() {
        if ($scope.jobCurrentPage < $cookies.jobsTotalPages) {
            $scope.jobCurrentPage++;
            $state.go('jobs', {page:$scope.jobCurrentPage});
        }
    }

    $scope.jobsPreviousPage = function() {
        if ($scope.jobCurrentPage > 1) {
            $scope.jobCurrentPage--;
            $state.go('jobs', {page:$scope.jobCurrentPage});
        }
    }

    if ($scope.jobCurrentPage == undefined) {
        $scope.jobCurrentPage = 1;
    }

    loadPage();
});

app.controller('ListRemotecisController', function($scope, $location,
CommonCode, Restangular) {

    $scope.remotecisNextPage = function() {
        if ($scope.remoteciCurrentPage < $cookies.remotecisTotalPages) {
            $scope.remoteciCurrentPage++;
            $state.go('jobs', {page:$scope.jobCurrentPage});
        }
    }

    $scope.remotecisPreviousPage = function() {
        if ($scope.remoteciCurrentPage > 1) {
            $scope.remoteciCurrentPage--;
            $state.go('jobs', {page:$scope.remoteciCurrentPage});
        }
    }

    if ($scope.remoteciCurrentPage == undefined) {
        $scope.remoteciCurrentPage = 1;
    }
    CommonCode.getRemoteCis($scope);
});

app.controller('JobDetailsController', function(
    $scope, CommonCode, Restangular, $stateParams) {
    CommonCode.getJobInfo($scope, $stateParams.jobId);
});

app.controller('ProductsController', function(
    $scope, CommonCode, Restangular, $stateParams) {

    Restangular.one('products').get().
        then(function(products) {
            $scope.products = products._items;
            $scope.myProduct = products._items[0];
        });

    $scope.$watch('myProduct', function(currentProduct, previousProduct) {
        if (currentProduct != undefined) {
            Restangular.one('versions').
            get({'where': {'product_id': currentProduct.id}, 'extra_data': 1}).
            then(function(versions) {
                $scope.versions_status = versions._items;
            });
        }
    });
});

app.controller('LoginController', ['$scope', '$cookies', '$state',
    function($scope, $cookies, $state) {
        $scope.submit = function() {
            var loginb64 = btoa($scope.username.concat(':', $scope.password));
            $cookies.auth = loginb64;
            $state.go('jobs');
        };
    }
]);

app.controller('LogoutController', ['$scope', '$templateCache',
'$cookies', '$state',
  function($scope, $templateCache, $cookies, $state) {
      $templateCache.removeAll();
      $cookies.auth = btoa('None');
      $state.go('jobs');
  }
]);
<commit_msg>Print job details only if a job id is provided.<commit_after>// -*- coding: utf-8 -*-
//
// Copyright 2015 Red Hat, Inc.
//
// 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.

'use strict';

var app = angular.module('app', ['ngRoute', 'restangular', 'ngCookies',
'angular-loading-bar', 'ui.router']);

// Configure the application
app.config(function(RestangularProvider) {
    RestangularProvider.setBaseUrl('/api');
    // https://github.com/mgonto/restangular#my-response-is-actually-wrapped-with-some-metadata-how-do-i-get-the-data-in-that-case
    RestangularProvider.addResponseInterceptor(function(
    data, operation, what, url, response, deferred) {
        var extractedData = [];
        if (operation === 'getList') {
            extractedData._items = data._items;
            extractedData._meta = data._meta;
        } else {
            extractedData = data;
        }
        return extractedData;
    });
});

app.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
    $stateProvider
    .state('jobs', {
        url: '/jobs?page',
        templateUrl: 'partials/jobs.html',
        controller: 'ListJobsController'
    }).state('jobdetails', {
        url:'/jobdetails/:jobId',
        templateUrl: 'partials/jobdetails.html',
        controller: 'JobDetailsController'
    }).state('remotecis', {
        url:'/remotecis',
        templateUrl: 'partials/remotecis.html',
        controller: 'ListRemotecisController'
    }).state('products', {
        url:'/products',
        templateUrl: 'partials/products.html',
        controller: 'ProductsController'
    }).state('signin', {
        url: '/signin',
        templateUrl: 'partials/signin.html',
        controller: 'LoginController'
    }).state('signout', {
        url: '/signout',
        templateUrl: 'partials/signout.html',
        controller: 'LogoutController'
    });

    $urlRouterProvider.otherwise('/jobs');
    $httpProvider.interceptors.push('BasicAuthInjector');
});

app.factory('CommonCode', function($window, Restangular, $cookies) {
    // jscs:disable requireCamelCaseOrUpperCaseIdentifiers

    var getRemoteCis = function($scope) {
        Restangular.one('remotecis').get().then(
            function(remotecis) {
                $scope.remotecis = remotecis._items;
                $cookies.remotecisTotalPages = parseInt((
                remotecis._meta.total / remotecis._meta.max_results + 1));
                $scope.remotecisTotalPages = $cookies.remotecisTotalPages;
            }
        );
    };

    var getJobInfo = function($scope, job_id) {
        Restangular.one('jobs', job_id).get(
        {'embedded': {'remoteci':1, 'testversion':1}}).then(
        function(job) {
            $scope.job = job;
            Restangular.one('jobstates').get(
                {'where': {'job_id': job_id},
                 'embedded': {'files_collection':1}}).then(
                 function(jobstates) {
                     $scope.job['jobstates'] = jobstates._items;
                 });

            Restangular.one('testversions', job.testversion.id).get(
                {'embedded': {'version':1, 'test':1}}).then(
                function(testversion) {
                    $scope.job['version'] = testversion.version.name;
                    $scope.job['test'] = testversion.test.name;
                    Restangular.one('products',
                    testversion.version.product_id).get().then(
                        function(product) {
                            $scope.job['product'] = product.name;
                        }
                )});
        });
    };

    return {'getJobInfo': getJobInfo,
            'getRemoteCis': getRemoteCis};
});

app.factory('BasicAuthInjector', function($cookies) {
    var injector = {
        request: function(config) {
            config.headers['Authorization'] = 'Basic ' + $cookies.auth;
            return config;
        }
    };
    return injector;
});

app.controller('ListJobsController', function($scope, $location, $cookies,
CommonCode, Restangular, $state, $stateParams) {

    var loadPage = function() {
        var targetPage = $scope.jobCurrentPage;
        var searchObject = $location.search();
        if (searchObject.page != undefined) {
            var totalPages = $cookies.jobsTotalPages;
            var pageNumber = parseInt(searchObject.page);

            if ((pageNumber < ((parseInt(totalPages) + 1) | 0)) &&
                (pageNumber > 1)) {
                targetPage = parseInt(searchObject.page);
                $scope.jobCurrentPage = targetPage;
            }
        }

        Restangular.one('jobs').get({'page': targetPage,
                                     'extra_data': 1,
                                     'sort': '-created_at'}).
        then(function(jobs) {
            $scope.jobs = jobs._items
            $cookies.jobsTotalPages = parseInt((jobs._meta.total /
                jobs._meta.max_results + 1));
            $scope.jobsTotalPages = $cookies.jobsTotalPages;
        });

    };

    $scope.jobsNextPage = function() {
        if ($scope.jobCurrentPage < $cookies.jobsTotalPages) {
            $scope.jobCurrentPage++;
            $state.go('jobs', {page:$scope.jobCurrentPage});
        }
    }

    $scope.jobsPreviousPage = function() {
        if ($scope.jobCurrentPage > 1) {
            $scope.jobCurrentPage--;
            $state.go('jobs', {page:$scope.jobCurrentPage});
        }
    }

    if ($scope.jobCurrentPage == undefined) {
        $scope.jobCurrentPage = 1;
    }

    loadPage();
});

app.controller('ListRemotecisController', function($scope, $location,
CommonCode, Restangular) {

    $scope.remotecisNextPage = function() {
        if ($scope.remoteciCurrentPage < $cookies.remotecisTotalPages) {
            $scope.remoteciCurrentPage++;
            $state.go('jobs', {page:$scope.jobCurrentPage});
        }
    }

    $scope.remotecisPreviousPage = function() {
        if ($scope.remoteciCurrentPage > 1) {
            $scope.remoteciCurrentPage--;
            $state.go('jobs', {page:$scope.remoteciCurrentPage});
        }
    }

    if ($scope.remoteciCurrentPage == undefined) {
        $scope.remoteciCurrentPage = 1;
    }
    CommonCode.getRemoteCis($scope);
});

app.controller('JobDetailsController', function(
    $scope, CommonCode, Restangular, $stateParams) {

    if ($stateParams.jobId) {
        CommonCode.getJobInfo($scope, $stateParams.jobId);
    }
});

app.controller('ProductsController', function(
    $scope, CommonCode, Restangular, $stateParams) {

    Restangular.one('products').get().
        then(function(products) {
            $scope.products = products._items;
            $scope.myProduct = products._items[0];
        });

    $scope.$watch('myProduct', function(currentProduct, previousProduct) {
        if (currentProduct != undefined) {
            Restangular.one('versions').
            get({'where': {'product_id': currentProduct.id}, 'extra_data': 1}).
            then(function(versions) {
                $scope.versions_status = versions._items;
            });
        }
    });
});

app.controller('LoginController', ['$scope', '$cookies', '$state',
    function($scope, $cookies, $state) {
        $scope.submit = function() {
            var loginb64 = btoa($scope.username.concat(':', $scope.password));
            $cookies.auth = loginb64;
            $state.go('jobs');
        };
    }
]);

app.controller('LogoutController', ['$scope', '$templateCache',
'$cookies', '$state',
  function($scope, $templateCache, $cookies, $state) {
      $templateCache.removeAll();
      $cookies.auth = btoa('None');
      $state.go('jobs');
  }
]);
<|endoftext|>


<commit_before>(function() { 'use strict';

/************************************************************************************
* @ngdoc controller
* @name SettingsController
* @module metricapp
* @requires $location
* @requires SettingService
*
* @description
* Realizes the control layer for `settings.view`.
************************************************************************************/

angular.module('metricapp')

.controller('SettingsController', SettingsController);

SettingsController.$inject = ['$location', 'SettingService'];

function SettingsController($location, SettingService) {

    var vm = this;

    _init();

    function _loadSettings() {
        vm.loading = true;
        vm.success = false;
        SettingService.getAllSettings().then(
            function(resolve) {
                var settings = resolve.settings;
                for (var info in settings) {
                    vm.settings[info] = settings[info];
                }
                vm.numsettings = Object.keys(vm.settings).length;
                vm.success = true;
            },
            function(reject) {
                vm.success = false;
            }
        ).finally(function() {
            vm.loading = false;
        });
    }

    function _init() {
        vm.loading = true;
        vm.success = false;
        vm.settings = {};
        vm.numsettings = 0;
        _loadSettings();
    }

}

})();
<commit_msg>settigns final mock<commit_after>(function() { 'use strict';

/************************************************************************************
* @ngdoc controller
* @name SettingsController
* @module metricapp
* @requires $location
* @requires SettingService
*
* @description
* Realizes the control layer for `settings.view`.
************************************************************************************/

angular.module('metricapp')

.controller('SettingsController', SettingsController);

SettingsController.$inject = ['$location', 'SettingService'];

function SettingsController($location, SettingService) {

    var vm = this;

    _init();

    function _loadAll() {
        vm.loading = true;
        vm.success = false;
        SettingService.getAllSettings().then(
            function(resolve) {
                var settings = angular.copy(resolve.settings);
                vm.numsettings = Object.keys(vm.settings).length;
                vm.success = true;
            },
            function(reject) {
                vm.success = false;
            }
        ).finally(function() {
            vm.loading = false;
        });
    }

    function _init() {
        vm.loading = true;
        vm.success = false;
        vm.settings = {};
        vm.numsettings = 0;
        _loadAllSettings();
    }

}

})();
<|endoftext|>


<commit_before>module.exports = function(app, logger, io, db, argv) {
    var fs = require("fs");
    var express = require('express');
    var router = express.Router();
    var fpga = new Object;
    fpga.led = function(id, r, b, g) {
        logger.info("led on");
    };
    fpga.add = function(a, b) {
        return (a + b)
    };
    fpga.sleep = function(i) {
        logger.info("sleep")
    };
    fpga.fpga_open = function() {
        logger.info("open fpga")
    };
    logger.info("Initial fpga module");

    router.get('/', function(req, res) {
        res.json({
            message: 'hooray! welcome to our fpga api!'
        });
    });

    router.get('/device', function(req, res) {
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    router.post('/device', function(req, res) {
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    router.get('/memory', function(req, res) {
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    router.post('/memory', function(req, res) {
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    router.get('/config', function(req, res) {
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    router.post('/config', function(req, res) {
        res.json({
            message: 'Write file success'
        });
    });

    router.get('/api/list/', function(req, res) {
        var method = [];
        for (m in fpga) {
            method.push(m.toString);
        }
        req.json({
            "method": method
        });
    });

    router.get('/api/list/:method', function(req, res) {
        var method = req.params.method;
        if (fpga[method]) {
            req.json({
                "method": fpga[method]
            });
        }
    });

    router.post('/api/call/:method', function(req, res) {
        var method = req.params.method;
        var paramter = req.body;
        logger.info("method is " + method);
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    io.sockets.on('connection', function(socket) {
        socket.emit('news', {
            hello: 'world'
        });
        socket.on('my other event', function(data) {
            console.log(data);
        });
    });

    app.use('/fpga', router);

}<commit_msg>Add fpga mock test<commit_after>module.exports = function(app, logger, io, db, argv) {
    var fs = require("fs");
    var express = require('express');
    var router = express.Router();
    var fpga = new Object;
    fpga.led = function(id, r, b, g) {
        logger.info("led on");
    };
    fpga.add = function(a, b) {
        return (a + b)
    };
    fpga.sleep = function(i) {
        logger.info("sleep")
    };
    fpga.fpga_open = function() {
        logger.info("open fpga")
    };
    logger.info("Initial sim fpga module");

    router.get('/', function(req, res) {
        res.json({
            message: 'hooray! welcome to our fpga api!'
        });
    });

    router.get('/device', function(req, res) {
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    router.post('/device', function(req, res) {
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    router.get('/memory', function(req, res) {
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    router.post('/memory', function(req, res) {
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    router.get('/config', function(req, res) {
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    router.post('/config', function(req, res) {
        res.json({
            message: 'Write file success'
        });
    });

    router.get('/config/list', function(req, res) {
        var filelist = [];
        fs.readdirSync("./uploads/").forEach(function(filename) {
            if (!/\.rbf$/.test(filename)) {
                return;
            }
            filelist.push(filename);
        });
        res.json(
            filelist
        );
    });

    router.post('/config', function(req, res) {
        res.json({
            message: 'Write file success'
        });
    });

    router.get('/api/list/', function(req, res) {
        var method = [];
        for (m in fpga) {
            method.push(m.toString);
        }
        req.json({
            "method": method
        });
    });

    router.get('/api/list/:method', function(req, res) {
        var method = req.params.method;
        if (fpga[method]) {
            req.json({
                "method": fpga[method]
            });
        }
    });

    router.post('/api/call/:method', function(req, res) {
        var method = req.params.method;
        var paramter = req.body;
        logger.info("method is " + method);
        res.json({
            message: 'hooray! welcome to our api!'
        });
    });

    io.sockets.on('connection', function(socket) {
        socket.emit('news', {
            hello: 'world'
        });
        socket.on('my other event', function(data) {
            console.log(data);
        });
    });

    app.use('/fpga', router);

}<|endoftext|>


<commit_before>(function($) {
  var mapInstance
  var defaults = {
    element: null,
    center: {
      lat: 59.3293358,
      lng: 18.0686101
    },
    zoom: 4,
    google: {
      map: null,
      markers: [],
      cluster: null
    },
    autorun: true
  }

  $.fn.googleMap = function(options) {
    var settings = $.extend(defaults, options)

    google.maps.InfoWindow.prototype.isOpen = function(){
        var map = this.map
        return (map !== null && typeof map !== "undefined")
    }

    fn = {
      init: function() {
        try {
          settings.google.map = new google.maps.Map(settings.element, {
            zoom: settings.zoom,
            center: settings.center
          })
          return true
        } catch (err) {
          throw err
        }
      },
      setMarker: function(options) {
        settings.google.markers.push(new google.maps.Marker({
          position: options.position,
          map: settings.google.map,
          title: options.title,
          icon: options.icon
        }))

        var index = settings.google.markers.length -1

        settings.google.markers[index].infowindow = new google.maps.InfoWindow({
          content: options.content,
          maxWidth: 200,
          minWidth: 200
        })

        settings.google.markers[index].addListener('click', function() {
          if( settings.google.markers[index].infowindow.isOpen() ) {
            settings.google.markers[index].infowindow.close()
          } else {
            for (var i = settings.google.markers.length - 1; i >= 0; i--) {
              settings.google.markers[i].infowindow.close()
            }
            settings.google.markers[index].infowindow.open(settings.google.map, settings.google.markers[index])
          }
        })
      },
      clusterMarkers: function() {
        settings.google.cluster = new MarkerClusterer(settings.google.map, settings.google.markers, {
          minimumClusterSize: 2,
          maxZoom: 13,
          gridSize: 20,
          styles: [
            {
              textColor: 'white',
              url: '/assets/images/map/cluster.png',
              height: 28,
              width: 31
            },

          ]
        })
      },
      setCenter: function(position) {
        try {
          settings.google.map.setCenter(position)
        } catch(err) {
          throw err
        }
      },
      setZoom: function(zoom) {
          try {
              settings.google.map.setZoom( parseInt(zoom) )
          } catch(err) {
              throw err
          }
      },
      setBounds: function(bounds) {
        try {
          settings.google.map.fitBounds(bounds);
        } catch(err) {
          throw err
        }
      },
      getSettings: function() {
        return settings
      },
      getBounds: function() {
        return settings.google.map.getBounds()
      },
      getCenter: function() {
        return settings.google.map.getCenter()
      },
      triggerResize: function() {
        google.maps.event.trigger(settings.google.map, 'resize');
      }
    }

    if (settings.autorun === true && ($(this).length)) {
      settings.element = $(this)[0]
      fn.init()
    }

    return fn
  }
}(jQuery))

//Place markers on map
function setMarkers(data, settings) {
  for (var i = 0; i < data.length; i++) {
    entry = data[i]
    if(typeof(entry.post.coordinates) !== 'undefined') {
      var iconUrl = '/assets/images/'

      switch(entry.type) {
        case '3':
          iconUrl += 'pin-restaurant.png'
          break
        case '5':
          iconUrl += 'pin-store.png'
          break
        default:
          iconUrl = false //use default google marker
          break
      }

      var infoWindowContent = function(entry) {
        var content = (entry.post.content.length > 90) ? entry.post.content.substr(0, 90) + '...' : entry.post.content
        return $('<div>', {
          class: 'infowindow-content'
        })
        .html(content)
      }

      var entryContent = $('<div>', {
        class: 'infowindow-container'
      })
      .append(
        $('<div>', {
          class: 'infowindow-header'
        })
        .append(
          $('<div>', {
            class: 'infowindow-image'
          })
          .append(
            $('<img>', {
              src: '/uploads/' + entry.post.cover.filename + '.jpg'
            })
          ),
          $('<div>', {
            class: 'infowindow-title'
          })
          .append(
            $('<a>', {
              href: entry.url
            })
            .html(entry.title)
          ),
          $('<div>', {
            class: 'infowindow-stars-container'
          })
          .append(
            $('<div>', {
              class: 'star'
            })
            .append(
              $('<span>', {
                class: 'glyphicon glyphicon-star'
              })
            )
          )
        ),
        infoWindowContent(entry)
      )

      mapInstance.setMarker({
        position: {
          lat: parseFloat(entry.post.coordinates.latitude),
          lng: parseFloat(entry.post.coordinates.longitude)
        },
        title: entry.title,
        content: entryContent.html(),
        icon: {
          url: iconUrl,
          size: new google.maps.Size(32, 32)
        }
      })
    } else {
      console.log(entry.title + ' has no coordinates!')
    }
  }
  if(typeof(settings) !== 'undefined' && settings.hasOwnProperty('cluster')) {
    if(settings.cluster === true) {
      mapInstance.clusterMarkers()
    }
  }
}

function zoomToUserLocation() {
  $.fn.geoLocation(function(result) {
    if (result.success === true) {
      mapInstance.setMarker({
        position: {
          lat: parseFloat(result.position.latitude),
          lng: parseFloat(result.position.longitude)
        },
        title: 'Din plats',
        content: 'Du är här!',
        icon: '/assets/images/pin-my-position.png'
      })
      mapInstance.setCenter({
        lat: parseFloat(result.position.latitude),
        lng: parseFloat(result.position.longitude)
      })
      mapInstance.setZoom(11)
    } else {
      //TODO display error
    }
  })
}

function getMarkerData(options, callback) {
  var settings = $.extend({
    url: '/ajax/map'
  }, options)

  $.ajax(settings)
  .done(function(data) {
    callback(data)
  })
}

function getMapOptions(element) {
  var options = {}
  var mapData = $('#map').data()

  //Check if map is configured to auto initialize
  if(mapData.hasOwnProperty('mapInit')) {
    options.init = mapData.mapInit
  }

  if(mapData.hasOwnProperty('mapCluster')) {
    options.cluster = mapData.mapCluster
  }

  if(mapData.hasOwnProperty('mapFilter')) {
    var filters = {
      single: function() {
        return {
          id: $('.content')[0].id
        }
      },
      restaurant: function() {
        return {
          type: '3'
        }
      },
      butik: function() {
        return {
          type: '5'
        }
      }
    }

    if(mapData.mapFilter in filters) {
      options.data = {
        filter: filters[mapData.mapFilter](),
        filterName: mapData.mapFilter
      }
    }
  }

  if(mapData.hasOwnProperty('markerLatitude')) {
    options.markerLatitude = mapData.markerLatitude
  }

  if(mapData.hasOwnProperty('markerLongitude')) {
    options.markerLongitude = mapData.markerLongitude
  }

  if(mapData.hasOwnProperty('markerTitle')) {
    options.markerTitle = mapData.markerTitle
  }

  return options
}

function applyMarkerData(data, options) {
  if(options.hasOwnProperty('data')) {
    if(options.data.filterName === 'single') {
      if(data.length > 0 && data[0].post.hasOwnProperty('coordinates')) {
        mapInstance.setCenter({
          lat: parseFloat(data[0].post.coordinates.latitude),
          lng: parseFloat(data[0].post.coordinates.longitude)
        })

        mapInstance.setZoom(11)
      } else {
        return
      }
    }
  }

  setMarkers(data, options)
}

function setSingleOpenMarker(obj) {
  mapInstance.setMarker({
    position: {
      lat: parseFloat(obj.coordinates.latitude),
      lng: parseFloat(obj.coordinates.longitude)
    },
    content: obj.content
  })

  mapInstance.setZoom(11)

  mapInstance.setCenter({
    lat: parseFloat(obj.coordinates.latitude),
    lng: parseFloat(obj.coordinates.longitude)
  })

  settings = mapInstance.getSettings()
  marker = settings.google.markers[0]
  marker.infowindow.open(settings.google.map, marker)
}

function fullscreenSupported() {
  return (document.fullscreenEnabled ||
    document.webkitFullscreenEnabled ||
    document.mozFullScreenEnabled ||
    document.msFullscreenEnabled
  )
}

function isFullscreen() {
  return ( document.fullscreenElement ||
    document.webkitFullscreenElement ||
    document.mozFullScreenElement ||
    document.msFullscreenElement ) ? true : false
}

function enterFullscreen(element) {
  if (element.requestFullscreen) {
    element.requestFullscreen()
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen()
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen()
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen()
  }
}

function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  }
}

$(document).bind('mapready', function(e) {
  //Initialize map
  mapInstance = $('#map').googleMap()

  $('#show-map').on('click', function(e) {
    e.preventDefault()

    $('.filter').addClass('hidden') //Remove overlay filter

    //Get map options
    var options = getMapOptions()

    //Get marker data
    getMarkerData(options, function(data) {
      applyMarkerData(data, options)
    })
  })

  $('.showMyLocation').on('click', function(e) {
    e.preventDefault()
    zoomToUserLocation()
  })

  $('.showFullscreen').on('click', function(e) {
    e.preventDefault()
    if( fullscreenSupported() ) {
      var element = document.getElementById('mapContainer')

      if( isFullscreen() ) {
        exitFullscreen()
        $(element).css({
          margin: '',
          width: '',
          height: '',
          position: '',
          top: ''
        })
        return
      }

      var data = $('#map').data()
      data.center = mapInstance.getCenter()

      enterFullscreen( element )

      $(element).css({
        margin: '0',
        width: '100%',
        height: '100%',
        position: 'absolute',
        top: '0'
      })

      $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange', function(e) {
        mapInstance.triggerResize()
        mapInstance.setCenter( data.center )
      })
    } else {
      console.log('no fullscreen support')
      //TODO notify user
    }
  })

  if($('#map').length > 0) {
    var options = getMapOptions()

    if('init' in options && options.init === true) {
      if('markerLatitude' in options && 'markerLongitude' in options) {
        //Map provides it's own coordinates

        setSingleOpenMarker({
          coordinates: {
            latitude: options.markerLatitude,
            longitude: options.markerLongitude
          },
          content: options.markerTitle
        })

      } else {
        getMarkerData(options, function(data) {
          applyMarkerData(data, options)
        })
      }

      $('.filter').addClass('visible-xs') //Remove overlay filter
    }
  }
})
<commit_msg>Reset styles correctly after exiting fullscreen by browser provided methods<commit_after>(function($) {
  var mapInstance
  var defaults = {
    element: null,
    center: {
      lat: 59.3293358,
      lng: 18.0686101
    },
    zoom: 4,
    google: {
      map: null,
      markers: [],
      cluster: null
    },
    autorun: true
  }

  $.fn.googleMap = function(options) {
    var settings = $.extend(defaults, options)

    google.maps.InfoWindow.prototype.isOpen = function(){
        var map = this.map
        return (map !== null && typeof map !== "undefined")
    }

    fn = {
      init: function() {
        try {
          settings.google.map = new google.maps.Map(settings.element, {
            zoom: settings.zoom,
            center: settings.center
          })
          return true
        } catch (err) {
          throw err
        }
      },
      setMarker: function(options) {
        settings.google.markers.push(new google.maps.Marker({
          position: options.position,
          map: settings.google.map,
          title: options.title,
          icon: options.icon
        }))

        var index = settings.google.markers.length -1

        settings.google.markers[index].infowindow = new google.maps.InfoWindow({
          content: options.content,
          maxWidth: 200,
          minWidth: 200
        })

        settings.google.markers[index].addListener('click', function() {
          if( settings.google.markers[index].infowindow.isOpen() ) {
            settings.google.markers[index].infowindow.close()
          } else {
            for (var i = settings.google.markers.length - 1; i >= 0; i--) {
              settings.google.markers[i].infowindow.close()
            }
            settings.google.markers[index].infowindow.open(settings.google.map, settings.google.markers[index])
          }
        })
      },
      clusterMarkers: function() {
        settings.google.cluster = new MarkerClusterer(settings.google.map, settings.google.markers, {
          minimumClusterSize: 2,
          maxZoom: 13,
          gridSize: 20,
          styles: [
            {
              textColor: 'white',
              url: '/assets/images/map/cluster.png',
              height: 28,
              width: 31
            },

          ]
        })
      },
      setCenter: function(position) {
        try {
          settings.google.map.setCenter(position)
        } catch(err) {
          throw err
        }
      },
      setZoom: function(zoom) {
          try {
              settings.google.map.setZoom( parseInt(zoom) )
          } catch(err) {
              throw err
          }
      },
      setBounds: function(bounds) {
        try {
          settings.google.map.fitBounds(bounds);
        } catch(err) {
          throw err
        }
      },
      getSettings: function() {
        return settings
      },
      getBounds: function() {
        return settings.google.map.getBounds()
      },
      getCenter: function() {
        return settings.google.map.getCenter()
      },
      triggerResize: function() {
        google.maps.event.trigger(settings.google.map, 'resize');
      }
    }

    if (settings.autorun === true && ($(this).length)) {
      settings.element = $(this)[0]
      fn.init()
    }

    return fn
  }
}(jQuery))

//Place markers on map
function setMarkers(data, settings) {
  for (var i = 0; i < data.length; i++) {
    entry = data[i]
    if(typeof(entry.post.coordinates) !== 'undefined') {
      var iconUrl = '/assets/images/'

      switch(entry.type) {
        case '3':
          iconUrl += 'pin-restaurant.png'
          break
        case '5':
          iconUrl += 'pin-store.png'
          break
        default:
          iconUrl = false //use default google marker
          break
      }

      var infoWindowContent = function(entry) {
        var content = (entry.post.content.length > 90) ? entry.post.content.substr(0, 90) + '...' : entry.post.content
        return $('<div>', {
          class: 'infowindow-content'
        })
        .html(content)
      }

      var entryContent = $('<div>', {
        class: 'infowindow-container'
      })
      .append(
        $('<div>', {
          class: 'infowindow-header'
        })
        .append(
          $('<div>', {
            class: 'infowindow-image'
          })
          .append(
            $('<img>', {
              src: '/uploads/' + entry.post.cover.filename + '.jpg'
            })
          ),
          $('<div>', {
            class: 'infowindow-title'
          })
          .append(
            $('<a>', {
              href: entry.url
            })
            .html(entry.title)
          ),
          $('<div>', {
            class: 'infowindow-stars-container'
          })
          .append(
            $('<div>', {
              class: 'star'
            })
            .append(
              $('<span>', {
                class: 'glyphicon glyphicon-star'
              })
            )
          )
        ),
        infoWindowContent(entry)
      )

      mapInstance.setMarker({
        position: {
          lat: parseFloat(entry.post.coordinates.latitude),
          lng: parseFloat(entry.post.coordinates.longitude)
        },
        title: entry.title,
        content: entryContent.html(),
        icon: {
          url: iconUrl,
          size: new google.maps.Size(32, 32)
        }
      })
    } else {
      console.log(entry.title + ' has no coordinates!')
    }
  }
  if(typeof(settings) !== 'undefined' && settings.hasOwnProperty('cluster')) {
    if(settings.cluster === true) {
      mapInstance.clusterMarkers()
    }
  }
}

function zoomToUserLocation() {
  $.fn.geoLocation(function(result) {
    if (result.success === true) {
      mapInstance.setMarker({
        position: {
          lat: parseFloat(result.position.latitude),
          lng: parseFloat(result.position.longitude)
        },
        title: 'Din plats',
        content: 'Du är här!',
        icon: '/assets/images/pin-my-position.png'
      })
      mapInstance.setCenter({
        lat: parseFloat(result.position.latitude),
        lng: parseFloat(result.position.longitude)
      })
      mapInstance.setZoom(11)
    } else {
      //TODO display error
    }
  })
}

function getMarkerData(options, callback) {
  var settings = $.extend({
    url: '/ajax/map'
  }, options)

  $.ajax(settings)
  .done(function(data) {
    callback(data)
  })
}

function getMapOptions(element) {
  var options = {}
  var mapData = $('#map').data()

  //Check if map is configured to auto initialize
  if(mapData.hasOwnProperty('mapInit')) {
    options.init = mapData.mapInit
  }

  if(mapData.hasOwnProperty('mapCluster')) {
    options.cluster = mapData.mapCluster
  }

  if(mapData.hasOwnProperty('mapFilter')) {
    var filters = {
      single: function() {
        return {
          id: $('.content')[0].id
        }
      },
      restaurant: function() {
        return {
          type: '3'
        }
      },
      butik: function() {
        return {
          type: '5'
        }
      }
    }

    if(mapData.mapFilter in filters) {
      options.data = {
        filter: filters[mapData.mapFilter](),
        filterName: mapData.mapFilter
      }
    }
  }

  if(mapData.hasOwnProperty('markerLatitude')) {
    options.markerLatitude = mapData.markerLatitude
  }

  if(mapData.hasOwnProperty('markerLongitude')) {
    options.markerLongitude = mapData.markerLongitude
  }

  if(mapData.hasOwnProperty('markerTitle')) {
    options.markerTitle = mapData.markerTitle
  }

  return options
}

function applyMarkerData(data, options) {
  if(options.hasOwnProperty('data')) {
    if(options.data.filterName === 'single') {
      if(data.length > 0 && data[0].post.hasOwnProperty('coordinates')) {
        mapInstance.setCenter({
          lat: parseFloat(data[0].post.coordinates.latitude),
          lng: parseFloat(data[0].post.coordinates.longitude)
        })

        mapInstance.setZoom(11)
      } else {
        return
      }
    }
  }

  setMarkers(data, options)
}

function setSingleOpenMarker(obj) {
  mapInstance.setMarker({
    position: {
      lat: parseFloat(obj.coordinates.latitude),
      lng: parseFloat(obj.coordinates.longitude)
    },
    content: obj.content
  })

  mapInstance.setZoom(11)

  mapInstance.setCenter({
    lat: parseFloat(obj.coordinates.latitude),
    lng: parseFloat(obj.coordinates.longitude)
  })

  settings = mapInstance.getSettings()
  marker = settings.google.markers[0]
  marker.infowindow.open(settings.google.map, marker)
}

function fullscreenSupported() {
  return (document.fullscreenEnabled ||
    document.webkitFullscreenEnabled ||
    document.mozFullScreenEnabled ||
    document.msFullscreenEnabled
  )
}

function isFullscreen() {
  return ( document.fullscreenElement ||
    document.webkitFullscreenElement ||
    document.mozFullScreenElement ||
    document.msFullscreenElement ) ? true : false
}

function enterFullscreen(element) {
  if (element.requestFullscreen) {
    element.requestFullscreen()
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen()
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen()
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen()
  }
}

function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  }
}

$(document).bind('mapready', function(e) {
  //Initialize map
  mapInstance = $('#map').googleMap()

  $('#show-map').on('click', function(e) {
    e.preventDefault()

    $('.filter').addClass('hidden') //Remove overlay filter

    //Get map options
    var options = getMapOptions()

    //Get marker data
    getMarkerData(options, function(data) {
      applyMarkerData(data, options)
    })
  })

  $('.showMyLocation').on('click', function(e) {
    e.preventDefault()
    zoomToUserLocation()
  })

  $('.showFullscreen').on('click', function(e) {
    e.preventDefault()
    if( fullscreenSupported() ) {
      var element = document.getElementById('mapContainer')

      if( isFullscreen() ) {
        exitFullscreen()
        $(element).css({
          margin: '',
          width: '',
          height: '',
          position: '',
          top: ''
        })
        return
      }

      var data = $('#map').data()
      data.center = mapInstance.getCenter()

      enterFullscreen( element )

      $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange', function(e) {
        if( isFullscreen() ) {
          $(element).css({
            margin: '0',
            width: '100%',
            height: '100%',
            position: 'absolute',
            top: '0'
          })
        } else {
          $(element).css({
            margin: '',
            width: '',
            height: '',
            position: '',
            top: ''
          })
        }

        mapInstance.triggerResize()
        mapInstance.setCenter( data.center )
      })
    } else {
      console.log('no fullscreen support')
      //TODO notify user
    }
  })

  if($('#map').length > 0) {
    var options = getMapOptions()

    if('init' in options && options.init === true) {
      if('markerLatitude' in options && 'markerLongitude' in options) {
        //Map provides it's own coordinates

        setSingleOpenMarker({
          coordinates: {
            latitude: options.markerLatitude,
            longitude: options.markerLongitude
          },
          content: options.markerTitle
        })

      } else {
        getMarkerData(options, function(data) {
          applyMarkerData(data, options)
        })
      }

      $('.filter').addClass('visible-xs') //Remove overlay filter
    }
  }
})
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require bootstrap
//= require bootstrap-dropdown
//= require bootstrap-tab
//= require bootstrap-transition
//= require highcharts
//= require jquery.gravatar
//= require jquery.highlight
//= require jquery.noty
//= require jquery.relative-date
//= require md5
//= require services
//= require users
<commit_msg>Really getting aggravated now<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require bootstrap
//= require jquery
//= require bootstrap-dropdown
//= require bootstrap-tab
//= require bootstrap-transition
//= require highcharts
//= require jquery.gravatar
//= require jquery.highlight
//= require jquery.noty
//= require jquery.relative-date
//= require md5
//= require services
//= require users
<|endoftext|>