<commit_before>/*
Copyright 2016 Aviral Dasgupta
Copyright 2017 Vector Creations Ltd
Copyright 2017, 2018 New Vector Ltd

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.
*/

import React from 'react';
import type {Completion, SelectionRange} from './Autocompleter';

export default class AutocompleteProvider {
    constructor(commandRegex?: RegExp, forcedCommandRegex?: RegExp) {
        if (commandRegex) {
            if (!commandRegex.global) {
                throw new Error('commandRegex must have global flag set');
            }
            this.commandRegex = commandRegex;
        }
        if (forcedCommandRegex) {
            if (!forcedCommandRegex.global) {
                throw new Error('forcedCommandRegex must have global flag set');
            }
            this.forcedCommandRegex = forcedCommandRegex;
        }
    }

    destroy() {
        // stub
    }

    /**
     * Of the matched commands in the query, returns the first that contains or is contained by the selection, or null.
     * @param {string} query The query string
     * @param {SelectionRange} selection Selection to search
     * @param {boolean} force True if the user is forcing completion
     * @return {object} { command, range } where both onjects fields are null if no match
     */
    getCurrentCommand(query: string, selection: SelectionRange, force: boolean = false) {
        let commandRegex = this.commandRegex;

        if (force && this.shouldForceComplete()) {
            commandRegex = this.forcedCommandRegex || /\S+/g;
        }

        if (commandRegex == null) {
            return null;
        }

        commandRegex.lastIndex = 0;

        let match;
        while ((match = commandRegex.exec(query)) != null) {
            const start = match.index;
            const end = start + match[0].length;
            if (selection.start <= end && selection.end >= start) {
                return {
                    command: match,
                    range: {
                        start,
                        end,
                    },
                };
            }
        }
        return {
            command: null,
            range: {
                start: -1,
                end: -1,
            },
        };
    }

    async getCompletions(query: string, selection: SelectionRange, force: boolean = false): Array<Completion> {
        return [];
    }

    getName(): string {
        return 'Default Provider';
    }

    renderCompletions(completions: [React.Component]): ?React.Component {
        console.error('stub; should be implemented in subclasses');
        return null;
    }

    // Whether we should provide completions even if triggered forcefully, without a sigil.
    shouldForceComplete(): boolean {
        return false;
    }
}
<commit_msg>Gah, onjects<commit_after>/*
Copyright 2016 Aviral Dasgupta
Copyright 2017 Vector Creations Ltd
Copyright 2017, 2018 New Vector Ltd

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.
*/

import React from 'react';
import type {Completion, SelectionRange} from './Autocompleter';

export default class AutocompleteProvider {
    constructor(commandRegex?: RegExp, forcedCommandRegex?: RegExp) {
        if (commandRegex) {
            if (!commandRegex.global) {
                throw new Error('commandRegex must have global flag set');
            }
            this.commandRegex = commandRegex;
        }
        if (forcedCommandRegex) {
            if (!forcedCommandRegex.global) {
                throw new Error('forcedCommandRegex must have global flag set');
            }
            this.forcedCommandRegex = forcedCommandRegex;
        }
    }

    destroy() {
        // stub
    }

    /**
     * Of the matched commands in the query, returns the first that contains or is contained by the selection, or null.
     * @param {string} query The query string
     * @param {SelectionRange} selection Selection to search
     * @param {boolean} force True if the user is forcing completion
     * @return {object} { command, range } where both objects fields are null if no match
     */
    getCurrentCommand(query: string, selection: SelectionRange, force: boolean = false) {
        let commandRegex = this.commandRegex;

        if (force && this.shouldForceComplete()) {
            commandRegex = this.forcedCommandRegex || /\S+/g;
        }

        if (commandRegex == null) {
            return null;
        }

        commandRegex.lastIndex = 0;

        let match;
        while ((match = commandRegex.exec(query)) != null) {
            const start = match.index;
            const end = start + match[0].length;
            if (selection.start <= end && selection.end >= start) {
                return {
                    command: match,
                    range: {
                        start,
                        end,
                    },
                };
            }
        }
        return {
            command: null,
            range: {
                start: -1,
                end: -1,
            },
        };
    }

    async getCompletions(query: string, selection: SelectionRange, force: boolean = false): Array<Completion> {
        return [];
    }

    getName(): string {
        return 'Default Provider';
    }

    renderCompletions(completions: [React.Component]): ?React.Component {
        console.error('stub; should be implemented in subclasses');
        return null;
    }

    // Whether we should provide completions even if triggered forcefully, without a sigil.
    shouldForceComplete(): boolean {
        return false;
    }
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';

import SnapshotTransform from '../utils/snapshot-transform';
import ODataQueryAdapter from '../query/odata-adapter';
import { capitalize, camelize } from '../utils/string-functions';

/**
 * The OData adapter class.
 * Uses Flexberry Query as a language for requesting server.
 *
 * @module ember-flexberry-data
 * @namespace Adapter
 * @class OData
 * @extends DS.RESTAdapter
 * @public
 */
export default DS.RESTAdapter.extend({
  headers: {
    Prefer: 'return=representation'
  },

  idType: 'number',

  /**
    Timeout for AJAX-requests.

    @property timeout
    @type Number
    @default 0
  */
  timeout: 0,

  /**
    Overloaded method from `RESTAdapter` (Ember Data).
    Called by the sore in order to fetch data from the server.

    @method query
    @param {DS.Store} store
    @param {DS.Model} type
    @param {Query} query Flexberry Query object.
    @return {Promise}
  */
  query(store, type, query) {
    let url = this._buildURL(query.modelName);
    let builder = new ODataQueryAdapter(url, store);
    let data = builder.getODataQuery(query);
    let timeout = this.get('timeout');

    if (this.sortQueryParams) {
      data = this.sortQueryParams(data);
    }

    Ember.debug(`Flexberry ODataAdapter::query '${type}'`, data);

    // TODO: think about moving request execution into query adapter
    return this.ajax(url, 'GET', { data: data, timeout: timeout, dataType: query.dataType || 'json' });
  },

  /**
    Overloaded method from `RESTAdapter` (Ember Data).
    Customizes ajax options for the requests.

    @method ajaxOptions
    @param {String} url
    @param {DS.Model} type
    @param {Object} options
    @return {Object}
  */
  ajaxOptions: function ajaxOptions(url, type, options) {
    let dataType = options.dataType;
    let hash = this._super(...arguments);
    if (dataType === 'blob') {
      hash.dataType = dataType;
    }

    return hash;
  },

  /**
    Takes an ajax response, and returns the json payload or an error.

    @method handleResponse
    @param {Number} status
    @param {Object} headers
    @param {Object} payload
  */
  handleResponse(status, headers, payload) {
    if (!this.isSuccess(status, headers, payload) && typeof payload === 'object' && payload.error) {
      return new DS.AdapterError(payload.error.details, payload.error.message);
    }

    return this._super(...arguments);
  },

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch single record from the server.
   *
   * @method queryRecord
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {Query} query
   * @return {Promise} promise
   */
  /* jshint unused:vars */
  queryRecord(store, type, query) {
    Ember.debug(`Flexberry ODataAdapter::queryRecord '${type}'`, query);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch single record by ID from the server.
   *
   * @method findRecord
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {String} id
   * @param {DS.Snapshot} snapshot
   * @return {Promise} promise
  */
  /* jshint unused:vars */
  findRecord(store, type, id, snapshot) {
    Ember.debug(`Flexberry ODataAdapter::findRecord '${type}(${id})'`);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch all records from the server.
   *
   * @method findAll
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {String} sinceToken
   * @param {DS.SnapshotRecordArray} snapshotRecordArray
   * @return {Promise} promise
   */
  /* jshint unused:vars */
  findAll(store, type, sinceToken, snapshotRecordArray) {
    Ember.debug(`Flexberry ODataAdapter::findAll '${type}'`);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `build-url-mixin` (Ember Data), that determines the pathname for a given type.
   * Additionally capitalizes the type name (requirement of Flexberry OData Server).
   *
   * @method pathForType
   * @param {String} modelName
   * @return {String} The path for a given type.
   */
  pathForType(modelName) {
    var camelized = camelize(modelName);
    var capitalized = capitalize(camelized);
    return Ember.String.pluralize(capitalized);
  },

  /**
   * Overloaded method from `build-url-mixin` (Ember Data), taht builds URL to OData feed.
   * Appends id as `(id)` (OData specification) instead of `/id`.
   *
   * @method _buildURL
   * @param {String} modelName
   * @param {String} id
   * @return {String}
   * @private
   */
  _buildURL(modelName, id) {
    var url = [];
    var host = Ember.get(this, 'host');
    var prefix = this.urlPrefix();
    var path;

    if (modelName) {
      path = this.pathForType(modelName);
      if (path) {
        url.push(path);
      }
    }

    if (prefix) {
      url.unshift(prefix);
    }

    url = url.join('/');
    if (!host && url && url.charAt(0) !== '/') {
      url = '/' + url;
    }

    if (id != null) {
      // Append id as `(id)` (OData specification) instead of `/id`.
      url = this._appendIdToURL(id, url);
    }

    return url;
  },

  /**
   * Appends id to URL according to the OData specification.
   *
   * @method _appendIdToURL
   * @param {String} id
   * @param {String} url
   * @private
   */
  _appendIdToURL(id, url) {
    let encId = encodeURIComponent(id);
    let idType = Ember.get(this, 'idType');
    if (idType !== 'number') {
      encId = `'${encId}'`;
    }

    url += '(' + encId + ')';
    return url;
  },

  createRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'createRecord');
  },

  updateRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'updateRecord');
  },

  deleteRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'deleteRecord');
  },

  /**
   * Makes HTTP request for creating, updating or deleting the record.
   *
   * @method _sendRecord
   * @private
   */
  _sendRecord(store, type, snapshot, requestType) {
    // TODO: maybe move it into serializer (serialize or serializeIntoHash)?
    let skipUnchangedAttrs = true;
    SnapshotTransform.transformForSerialize(snapshot, skipUnchangedAttrs);

    // NOTE: for newly created records id is not defined.
    let url = this.buildURL(type.modelName, snapshot.id, snapshot, requestType);

    let httpMethod;
    switch (requestType) {
      case 'createRecord':
        httpMethod = 'POST';
        break;

      case 'updateRecord':
        httpMethod = skipUnchangedAttrs ? 'PATCH' : 'PUT';
        break;

      case 'deleteRecord':
        httpMethod = 'DELETE';
        break;

      default:
        throw new Error(`Unknown requestType: ${requestType}`);
    }

    let data;

    // Don't need to send any data for deleting.
    if (requestType !== 'deleteRecord') {
      let serializer = store.serializerFor(type.modelName);
      data = {};
      serializer.serializeIntoHash(data, type, snapshot);
    }

    return this.ajax(url, httpMethod, { data: data }).then(function(response) {
      return response;
    });
  }
});
<commit_msg>Initial commit<commit_after>import Ember from 'ember';
import DS from 'ember-data';

import SnapshotTransform from '../utils/snapshot-transform';
import ODataQueryAdapter from '../query/odata-adapter';
import { capitalize, camelize } from '../utils/string-functions';

/**
 * The OData adapter class.
 * Uses Flexberry Query as a language for requesting server.
 *
 * @module ember-flexberry-data
 * @namespace Adapter
 * @class OData
 * @extends DS.RESTAdapter
 * @public
 */
export default DS.RESTAdapter.extend({
  headers: {
    Prefer: 'return=representation'
  },

  idType: 'number',

  /**
    Timeout for AJAX-requests.

    @property timeout
    @type Number
    @default 0
  */
  timeout: 0,

  /**
    Overloaded method from `RESTAdapter` (Ember Data).
    Called by the sore in order to fetch data from the server.

    @method query
    @param {DS.Store} store
    @param {DS.Model} type
    @param {Query} query Flexberry Query object.
    @return {Promise}
  */
  query(store, type, query) {
    let url = this._buildURL(query.modelName);
    let builder = new ODataQueryAdapter(url, store);
    let data = builder.getODataQuery(query);
    let timeout = this.get('timeout');

    if (this.sortQueryParams) {
      data = this.sortQueryParams(data);
    }

    Ember.debug(`Flexberry ODataAdapter::query '${type}'`, data);

    // TODO: think about moving request execution into query adapter
    return this.ajax(url, 'GET', { data: data, timeout: timeout, dataType: query.dataType || 'json' });
  },

  /**
    Overloaded method from `RESTAdapter` (Ember Data).
    Customizes ajax options for the requests.

    @method ajaxOptions
    @param {String} url
    @param {DS.Model} type
    @param {Object} options
    @return {Object}
  */
  ajaxOptions: function ajaxOptions(url, type, options) {
    let dataType = options.dataType;
    let hash = this._super(...arguments);
    if (dataType === 'blob') {
      hash.dataType = dataType;
    }

    return hash;
  },

  /**
    Takes an ajax response, and returns the json payload or an error.

    @method handleResponse
    @param {Number} status
    @param {Object} headers
    @param {Object} payload
  */
  handleResponse(status, headers, payload) {
    if (!this.isSuccess(status, headers, payload) && typeof payload === 'object' && payload.error) {
      return new DS.AdapterError(payload.error.details, payload.error.message);
    }

    return this._super(...arguments);
  },

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch single record from the server.
   *
   * @method queryRecord
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {Query} query
   * @return {Promise} promise
   */
  /* jshint unused:vars */
  queryRecord(store, type, query) {
    Ember.debug(`Flexberry ODataAdapter::queryRecord '${type}'`, query);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch single record by ID from the server.
   *
   * @method findRecord
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {String} id
   * @param {DS.Snapshot} snapshot
   * @return {Promise} promise
  */
  /* jshint unused:vars */
  findRecord(store, type, id, snapshot) {
    Ember.debug(`Flexberry ODataAdapter::findRecord '${type}(${id})'`);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `RESTAdapter` (Ember Data).
   * Called by the sore in order to fetch all records from the server.
   *
   * @method findAll
   * @param {DS.Store} store
   * @param {DS.Model} type
   * @param {String} sinceToken
   * @param {DS.SnapshotRecordArray} snapshotRecordArray
   * @return {Promise} promise
   */
  /* jshint unused:vars */
  findAll(store, type, sinceToken, snapshotRecordArray) {
    Ember.debug(`Flexberry ODataAdapter::findAll '${type}'`);

    // TODO: query support for direct calls
    return this._super.apply(this, arguments);
  },
  /* jshint unused:true */

  /**
   * Overloaded method from `build-url-mixin` (Ember Data), that determines the pathname for a given type.
   * Additionally capitalizes the type name (requirement of Flexberry OData Server).
   *
   * @method pathForType
   * @param {String} modelName
   * @return {String} The path for a given type.
   */
  pathForType(modelName) {
    var camelized = camelize(modelName);
    var capitalized = capitalize(camelized);
    return Ember.String.pluralize(capitalized);
  },

  /**
   * A method to make ajax requests.
   *
   * @method _makeRequest
   * @param {Object} params
   * @private
   */
  _makeRequest(params) {
    if (!params.type || !params.url) {
      return;
    }

    return Ember.$.ajax(params);
  },

  /**
   * Overloaded method from `build-url-mixin` (Ember Data), taht builds URL to OData feed.
   * Appends id as `(id)` (OData specification) instead of `/id`.
   *
   * @method _buildURL
   * @param {String} modelName
   * @param {String} id
   * @return {String}
   * @private
   */
  _buildURL(modelName, id) {
    var url = [];
    var host = Ember.get(this, 'host');
    var prefix = this.urlPrefix();
    var path;

    if (modelName) {
      path = this.pathForType(modelName);
      if (path) {
        url.push(path);
      }
    }

    if (prefix) {
      url.unshift(prefix);
    }

    url = url.join('/');
    if (!host && url && url.charAt(0) !== '/') {
      url = '/' + url;
    }

    if (id != null) {
      // Append id as `(id)` (OData specification) instead of `/id`.
      url = this._appendIdToURL(id, url);
    }

    return url;
  },

  /**
   * Appends id to URL according to the OData specification.
   *
   * @method _appendIdToURL
   * @param {String} id
   * @param {String} url
   * @private
   */
  _appendIdToURL(id, url) {
    let encId = encodeURIComponent(id);
    let idType = Ember.get(this, 'idType');
    if (idType !== 'number') {
      encId = `'${encId}'`;
    }

    url += '(' + encId + ')';
    return url;
  },

  createRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'createRecord');
  },

  updateRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'updateRecord');
  },

  deleteRecord(store, type, snapshot) {
    return this._sendRecord(store, type, snapshot, 'deleteRecord');
  },

  /**
   * Makes HTTP request for creating, updating or deleting the record.
   *
   * @method _sendRecord
   * @private
   */
  _sendRecord(store, type, snapshot, requestType) {
    // TODO: maybe move it into serializer (serialize or serializeIntoHash)?
    let skipUnchangedAttrs = true;
    SnapshotTransform.transformForSerialize(snapshot, skipUnchangedAttrs);

    // NOTE: for newly created records id is not defined.
    let url = this.buildURL(type.modelName, snapshot.id, snapshot, requestType);

    let httpMethod;
    switch (requestType) {
      case 'createRecord':
        httpMethod = 'POST';
        break;

      case 'updateRecord':
        httpMethod = skipUnchangedAttrs ? 'PATCH' : 'PUT';
        break;

      case 'deleteRecord':
        httpMethod = 'DELETE';
        break;

      default:
        throw new Error(`Unknown requestType: ${requestType}`);
    }

    let data;

    // Don't need to send any data for deleting.
    if (requestType !== 'deleteRecord') {
      let serializer = store.serializerFor(type.modelName);
      data = {};
      serializer.serializeIntoHash(data, type, snapshot);
    }

    return this.ajax(url, httpMethod, { data: data }).then(function(response) {
      return response;
    });
  }
});
<|endoftext|>


<commit_before> var _jm = null;
    function open_empty(){
        var options = {
            container:'jsmind_container',
            theme:'greensea',
            editable:true
        }
        var baseMindmap = {
            "meta":{
                "name":"jsMind Example",
                "version":"0.2"
            },
            "format":"node_tree",
            "data":{"id":"root","topic":"jsMind","children": [] }
        };
        var mindmap = JSON.parse(window.localStorage.getItem('json_data')) || baseMindmap;
        _jm = jsMind.show(options, mindmap);
        // _jm = jsMind.show(options,mind);
    }

    function open_json(){
        var mind = {
            "meta":{
                "name":"jsMind remote",
                "author":"hizzgdev@163.com",
                "version":"0.2"
            },
            "format":"node_tree",
            "data":{"id":"root","topic":"jsMind","children":[
                {"id":"easy","topic":"Easy","direction":"left","children":[
                    {"id":"easy1","topic":"Easy to show"},
                    {"id":"easy2","topic":"Easy to edit"},
                    {"id":"easy3","topic":"Easy to store"},
                    {"id":"easy4","topic":"Easy to embed"},
                    {"id":"other3","background-image":"ant.png", "width": "100", "height": "100"}
                ]},
                {"id":"open","topic":"Open Source","direction":"right","children":[
                    {"id":"open1","topic":"on GitHub", "background-color":"#eee", "foreground-color":"blue"},
                    {"id":"open2","topic":"BSD License"}
                ]},
                {"id":"powerful","topic":"Powerful","direction":"right","children":[
                    {"id":"powerful1","topic":"Base on Javascript"},
                    {"id":"powerful2","topic":"Base on HTML5"},
                    {"id":"powerful3","topic":"Depends on you"}
                ]},
                {"id":"other","topic":"test node","direction":"left","children":[
                    {"id":"other1","topic":"I'm from local variable"},
                    {"id":"other2","topic":"I can do everything"}
                ]}
            ]}
        }
        _jm.show(mind);
    }

    function open_ajax(){
        var mind_url = '/labcourse/doc/data_example.json';
        jsMind.util.ajax.get(mind_url,function(mind){
            _jm.show(mind);
        });
    }

    function screen_shot(){
        _jm.screenshot.shootDownload();
    }

    function show_data(){
        var mind_data = _jm.get_data();
        var mind_string = jsMind.util.json.json2string(mind_data);
        prompt_info(mind_string);
    }

    function save_file(){
        var mind_data = _jm.get_data();
        var mind_name = mind_data.meta.name;
        var mind_str = jsMind.util.json.json2string(mind_data);
        jsMind.util.file.save(mind_str,'text/jsmind',mind_name+'.jm');
    }

    function open_file(){
        var file_input = document.getElementById('file_input');
        var files = file_input.files;
        if(files.length > 0){
            var file_data = files[0];
            jsMind.util.file.read(file_data,function(jsmind_data, jsmind_name){
                var mind = jsMind.util.json.string2json(jsmind_data);
                if(!!mind){
                    _jm.show(mind);
                }else{
                    prompt_info('can not open this file as mindmap');
                }
            });
        }else{
            prompt_info('please choose a file first')
        }
    }

    function select_node(){
        var nodeid = 'other';
        _jm.select_node(nodeid);
    }

    function show_selected(){
        var selected_node = _jm.get_selected_node();
        if(!!selected_node){
            prompt_info(selected_node.topic);
        }else{
            prompt_info('nothing');
        }
    }

    function get_selected_nodeid(){
        var selected_node = _jm.get_selected_node();
        if(!!selected_node){
            return selected_node.id;
        }else{
            return null;
        }
    }

    function add_node(){
        var selected_node = _jm.get_selected_node(); // as parent of new node
        console.log(selected_node);
        if(!selected_node){prompt_info('please select a node first.');return;}

        var nodeid = jsMind.util.uuid.newid();
        var topic = '* Node_'+nodeid.substr(0,5)+' *';
        var node = _jm.add_node(selected_node, nodeid, topic);
    }

	function add_node_id(){
        var nodeid = jsMind.util.uuid.newid();
        var topic = '* Node_'+nodeid.substr(0,5)+' *';
        var node = _jm.add_node(selected_node, nodeid, topic);
    }

    var imageChooser = document.getElementById('image-chooser');

    imageChooser.addEventListener('change', function (event) {
        // Read file here.
        var reader = new FileReader();
        reader.onloadend = (function () {
            var selected_node = _jm.get_selected_node();
            var nodeid = jsMind.util.uuid.newid();
            var topic = undefined;
            var data = {
                "background-image": reader.result,
                "width": "100",
                "height": "100"};
            var node = _jm.add_node(selected_node, nodeid, topic, data);
            //var node = _jm.add_image_node(selected_node, nodeid, reader.result, 100, 100);
        //add_image_node:function(parent_node, nodeid, image, width, height, data, idx, direction, expanded){
        });

        var file = imageChooser.files[0];
        if (file) {
            reader.readAsDataURL(file);
        };

    }, false);

    function add_image_node(){
        var selected_node = _jm.get_selected_node(); // as parent of new node
        if(!selected_node){
            prompt_info('please select a node first.');
            return;
        }

        imageChooser.focus();
        imageChooser.click();
    }

    function modify_node(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        // modify the topic
        _jm.update_node(selected_id, '--- modified ---');
    }

    function move_to_first(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.move_node(selected_id,'_first_');
    }

    function move_to_last(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.move_node(selected_id,'_last_');
    }

    function move_node(){
        // move a node before another
        _jm.move_node('other','open');
    }

    function remove_node(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.remove_node(selected_id);
    }

    function change_text_font(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.set_node_font_style(selected_id, 28);
    }

    function change_text_color(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.set_node_color(selected_id, null, '#000');
    }

    function change_background_color(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.set_node_color(selected_id, '#eee', null);
    }

    function change_background_image(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.set_node_background_image(selected_id, 'ant.png', 100, 100);
    }

    function set_theme(theme_name){
        _jm.set_theme(theme_name);
    }

    var zoomInButton = document.getElementById("zoom-in-button");
    var zoomOutButton = document.getElementById("zoom-out-button");

    function zoomIn() {
        if (_jm.view.zoomIn()) {
            zoomOutButton.disabled = false;
        } else {
            zoomInButton.disabled = true;
        };
    };

    function zoomOut() {
        if (_jm.view.zoomOut()) {
            zoomInButton.disabled = false;
        } else {
            zoomOutButton.disabled = true;
        };
    };

    function toggle_editable(btn){
        var editable = _jm.get_editable();
        if(editable){
            _jm.disable_edit();
            btn.innerHTML = 'enable editable';
        }else{
            _jm.enable_edit();
            btn.innerHTML = 'disable editable';
        }
    }

    // this method change size of container, perpare for adjusting jsmind
    function change_container(){
        var c = document.getElementById('jsmind_container');
        c.style.width = '800px';
        c.style.height = '500px';
    }

    function resize_jsmind(){
        _jm.resize();
    }

    function expand(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.expand_node(selected_id);
    }

    function collapse(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.collapse_node(selected_id);
    }

    function toggle(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.toggle_node(selected_id);
    }

    function expand_all(){
        _jm.expand_all();
    }

    function expand_to_level2(){
        _jm.expand_to_depth(2);
    }

    function expand_to_level3(){
        _jm.expand_to_depth(3);
    }

    function collapse_all(){
        _jm.collapse_all();
    }

    function get_nodearray_data(){
        var mind_data = _jm.get_data('node_array');
        var mind_string = jsMind.util.json.json2string(mind_data);
        prompt_info(mind_string);
    }

    function save_nodearray_file(){
        var mind_data = _jm.get_data('node_array');
        var mind_name = mind_data.meta.name;
        var mind_str = jsMind.util.json.json2string(mind_data);
        jsMind.util.file.save(mind_str,'text/jsmind',mind_name+'.jm');
    }

    function open_nodearray(){
        var file_input = document.getElementById('file_input_nodearray');
        var files = file_input.files;
        if(files.length > 0){
            var file_data = files[0];
            jsMind.util.file.read(file_data,function(jsmind_data, jsmind_name){
                var mind = jsMind.util.json.string2json(jsmind_data);
                if(!!mind){
                    _jm.show(mind);
                }else{
                    prompt_info('can not open this file as mindmap');
                }
            });
        }else{
            prompt_info('please choose a file first')
        }
    }

    function get_freemind_data(){
        var mind_data = _jm.get_data('freemind');
        var mind_string = jsMind.util.json.json2string(mind_data);
        alert(mind_string);
    }

    function save_freemind_file(){
        var mind_data = _jm.get_data('freemind');
        var mind_name = mind_data.meta.name || 'freemind';
        var mind_str = mind_data.data;
        jsMind.util.file.save(mind_str,'text/xml',mind_name+'.mm');
    }

    function open_freemind(){
        var file_input = document.getElementById('file_input_freemind');
        var files = file_input.files;
        if(files.length > 0){
            var file_data = files[0];
            jsMind.util.file.read(file_data, function(freemind_data, freemind_name){
                if(freemind_data){
                    var mind_name = freemind_name;
                    if(/.*\.mm$/.test(mind_name)){
                        mind_name = freemind_name.substring(0,freemind_name.length-3);
                    }
                    var mind = {
                        "meta":{
                            "name":mind_name,
                            "author":"hizzgdev@163.com",
                            "version":"1.0.1"
                        },
                        "format":"freemind",
                        "data":freemind_data
                    };
                    _jm.show(mind);
                }else{
                    prompt_info('can not open this file as mindmap');
                }
            });
        }else{
            prompt_info('please choose a file first')
        }
    }

    function prompt_info(msg){
        alert(msg);
    }

    open_empty();<commit_msg>minor bug fix<commit_after>
    function open_empty(){
        var options = {
            container:'jsmind_container',
            theme:'greensea',
            editable:true
        }
        var baseMindmap = {
            "meta":{
                "name":"jsMind Example",
                "version":"0.2"
            },
            "format":"node_tree",
            "data":{"id":"root","topic":"jsMind","children": [] }
        };
        _jm.show(options,mind);
    }

    function open_json(){
        var mind = {
            "meta":{
                "name":"jsMind remote",
                "author":"hizzgdev@163.com",
                "version":"0.2"
            },
            "format":"node_tree",
            "data":{"id":"root","topic":"jsMind","children":[
                {"id":"easy","topic":"Easy","direction":"left","children":[
                    {"id":"easy1","topic":"Easy to show"},
                    {"id":"easy2","topic":"Easy to edit"},
                    {"id":"easy3","topic":"Easy to store"},
                    {"id":"easy4","topic":"Easy to embed"},
                    {"id":"other3","background-image":"ant.png", "width": "100", "height": "100"}
                ]},
                {"id":"open","topic":"Open Source","direction":"right","children":[
                    {"id":"open1","topic":"on GitHub", "background-color":"#eee", "foreground-color":"blue"},
                    {"id":"open2","topic":"BSD License"}
                ]},
                {"id":"powerful","topic":"Powerful","direction":"right","children":[
                    {"id":"powerful1","topic":"Base on Javascript"},
                    {"id":"powerful2","topic":"Base on HTML5"},
                    {"id":"powerful3","topic":"Depends on you"}
                ]},
                {"id":"other","topic":"test node","direction":"left","children":[
                    {"id":"other1","topic":"I'm from local variable"},
                    {"id":"other2","topic":"I can do everything"}
                ]}
            ]}
        }
        _jm.show(mind);
    }

    function open_ajax(){
        var mind_url = '/labcourse/doc/data_example.json';
        jsMind.util.ajax.get(mind_url,function(mind){
            _jm.show(mind);
        });
    }

    function screen_shot(){
        _jm.screenshot.shootDownload();
    }

    function show_data(){
        var mind_data = _jm.get_data();
        var mind_string = jsMind.util.json.json2string(mind_data);
        prompt_info(mind_string);
    }

    function save_file(){
        var mind_data = _jm.get_data();
        var mind_name = mind_data.meta.name;
        var mind_str = jsMind.util.json.json2string(mind_data);
        jsMind.util.file.save(mind_str,'text/jsmind',mind_name+'.jm');
    }

    function open_file(){
        var file_input = document.getElementById('file_input');
        var files = file_input.files;
        if(files.length > 0){
            var file_data = files[0];
            jsMind.util.file.read(file_data,function(jsmind_data, jsmind_name){
                var mind = jsMind.util.json.string2json(jsmind_data);
                if(!!mind){
                    _jm.show(mind);
                }else{
                    prompt_info('can not open this file as mindmap');
                }
            });
        }else{
            prompt_info('please choose a file first')
        }
    }

    function select_node(){
        var nodeid = 'other';
        _jm.select_node(nodeid);
    }

    function show_selected(){
        var selected_node = _jm.get_selected_node();
        if(!!selected_node){
            prompt_info(selected_node.topic);
        }else{
            prompt_info('nothing');
        }
    }

    function get_selected_nodeid(){
        var selected_node = _jm.get_selected_node();
        if(!!selected_node){
            return selected_node.id;
        }else{
            return null;
        }
    }

    function add_node(){
        var selected_node = _jm.get_selected_node(); // as parent of new node
        console.log(selected_node);
        if(!selected_node){prompt_info('please select a node first.');return;}

        var nodeid = jsMind.util.uuid.newid();
        var topic = '* Node_'+nodeid.substr(0,5)+' *';
        var node = _jm.add_node(selected_node, nodeid, topic);
    }

	function add_node_id(){
        var nodeid = jsMind.util.uuid.newid();
        var topic = '* Node_'+nodeid.substr(0,5)+' *';
        var node = _jm.add_node(selected_node, nodeid, topic);
    }

    var imageChooser = document.getElementById('image-chooser');

    imageChooser.addEventListener('change', function (event) {
        // Read file here.
        var reader = new FileReader();
        reader.onloadend = (function () {
            var selected_node = _jm.get_selected_node();
            var nodeid = jsMind.util.uuid.newid();
            var topic = undefined;
            var data = {
                "background-image": reader.result,
                "width": "100",
                "height": "100"};
            var node = _jm.add_node(selected_node, nodeid, topic, data);
            //var node = _jm.add_image_node(selected_node, nodeid, reader.result, 100, 100);
        //add_image_node:function(parent_node, nodeid, image, width, height, data, idx, direction, expanded){
        });

        var file = imageChooser.files[0];
        if (file) {
            reader.readAsDataURL(file);
        };

    }, false);

    function add_image_node(){
        var selected_node = _jm.get_selected_node(); // as parent of new node
        if(!selected_node){
            prompt_info('please select a node first.');
            return;
        }

        imageChooser.focus();
        imageChooser.click();
    }

    function modify_node(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        // modify the topic
        _jm.update_node(selected_id, '--- modified ---');
    }

    function move_to_first(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.move_node(selected_id,'_first_');
    }

    function move_to_last(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.move_node(selected_id,'_last_');
    }

    function move_node(){
        // move a node before another
        _jm.move_node('other','open');
    }

    function remove_node(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.remove_node(selected_id);
    }

    function change_text_font(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.set_node_font_style(selected_id, 28);
    }

    function change_text_color(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.set_node_color(selected_id, null, '#000');
    }

    function change_background_color(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.set_node_color(selected_id, '#eee', null);
    }

    function change_background_image(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.set_node_background_image(selected_id, 'ant.png', 100, 100);
    }

    function set_theme(theme_name){
        _jm.set_theme(theme_name);
    }

    var zoomInButton = document.getElementById("zoom-in-button");
    var zoomOutButton = document.getElementById("zoom-out-button");

    function zoomIn() {
        if (_jm.view.zoomIn()) {
            zoomOutButton.disabled = false;
        } else {
            zoomInButton.disabled = true;
        };
    };

    function zoomOut() {
        if (_jm.view.zoomOut()) {
            zoomInButton.disabled = false;
        } else {
            zoomOutButton.disabled = true;
        };
    };

    function toggle_editable(btn){
        var editable = _jm.get_editable();
        if(editable){
            _jm.disable_edit();
            btn.innerHTML = 'enable editable';
        }else{
            _jm.enable_edit();
            btn.innerHTML = 'disable editable';
        }
    }

    // this method change size of container, perpare for adjusting jsmind
    function change_container(){
        var c = document.getElementById('jsmind_container');
        c.style.width = '800px';
        c.style.height = '500px';
    }

    function resize_jsmind(){
        _jm.resize();
    }

    function expand(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.expand_node(selected_id);
    }

    function collapse(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.collapse_node(selected_id);
    }

    function toggle(){
        var selected_id = get_selected_nodeid();
        if(!selected_id){prompt_info('please select a node first.');return;}

        _jm.toggle_node(selected_id);
    }

    function expand_all(){
        _jm.expand_all();
    }

    function expand_to_level2(){
        _jm.expand_to_depth(2);
    }

    function expand_to_level3(){
        _jm.expand_to_depth(3);
    }

    function collapse_all(){
        _jm.collapse_all();
    }

    function get_nodearray_data(){
        var mind_data = _jm.get_data('node_array');
        var mind_string = jsMind.util.json.json2string(mind_data);
        prompt_info(mind_string);
    }

    function save_nodearray_file(){
        var mind_data = _jm.get_data('node_array');
        var mind_name = mind_data.meta.name;
        var mind_str = jsMind.util.json.json2string(mind_data);
        jsMind.util.file.save(mind_str,'text/jsmind',mind_name+'.jm');
    }

    function open_nodearray(){
        var file_input = document.getElementById('file_input_nodearray');
        var files = file_input.files;
        if(files.length > 0){
            var file_data = files[0];
            jsMind.util.file.read(file_data,function(jsmind_data, jsmind_name){
                var mind = jsMind.util.json.string2json(jsmind_data);
                if(!!mind){
                    _jm.show(mind);
                }else{
                    prompt_info('can not open this file as mindmap');
                }
            });
        }else{
            prompt_info('please choose a file first')
        }
    }

    function get_freemind_data(){
        var mind_data = _jm.get_data('freemind');
        var mind_string = jsMind.util.json.json2string(mind_data);
        alert(mind_string);
    }

    function save_freemind_file(){
        var mind_data = _jm.get_data('freemind');
        var mind_name = mind_data.meta.name || 'freemind';
        var mind_str = mind_data.data;
        jsMind.util.file.save(mind_str,'text/xml',mind_name+'.mm');
    }

    function open_freemind(){
        var file_input = document.getElementById('file_input_freemind');
        var files = file_input.files;
        if(files.length > 0){
            var file_data = files[0];
            jsMind.util.file.read(file_data, function(freemind_data, freemind_name){
                if(freemind_data){
                    var mind_name = freemind_name;
                    if(/.*\.mm$/.test(mind_name)){
                        mind_name = freemind_name.substring(0,freemind_name.length-3);
                    }
                    var mind = {
                        "meta":{
                            "name":mind_name,
                            "author":"hizzgdev@163.com",
                            "version":"1.0.1"
                        },
                        "format":"freemind",
                        "data":freemind_data
                    };
                    _jm.show(mind);
                }else{
                    prompt_info('can not open this file as mindmap');
                }
            });
        }else{
            prompt_info('please choose a file first')
        }
    }

    function prompt_info(msg){
        alert(msg);
    }
<|endoftext|>


<commit_before>wwm.lobby = (function (){
	var jqMap;
	var userInfo;
	function setJqMap($con) {
		jqMap = {
			$con: $con,
			$showCreateroom: $con.find('#show-createroom-modal'),
			$searchroomBtn: $con.find('#searchroom-btn'),
			$list: $con.find('#room-list'),
			$logout: $con.find('#logout-btn'),
			$room: $con.find('.room')
		};
	}
	function initModule($con) {
		userInfo = JSON.parse(localStorage.login);
		console.log('lobby', localStorage.login);
		var src = $('#wwm-lobby').text();
		console.log(src);	dust.render(dust.loadSource(dust.compile(src)), {
			name: userInfo.properties.nickname
		}, function(err, out) {
			console.log(out);
			$con.html(out);
		});
		setJqMap($con);
		getList();
		jqMap.$showCreateroom.click(showCreateroom);
		jqMap.$searchroomBtn.click(onSearchRoom);
		jqMap.$logout.click(logout);
		jqMap.$room.click(enterRoom);
	}
	function showCreateroom() {
		wwm.modal.initModule($('#wwm-createroom'));
	}
	function getList() {
		$.get('/roomlist').done(function(res){
			jqMap.$list.html();
		});
	}
	function changeList(data) {
		var $frag = $(document.createDocumentFragment());
		jqMap.$list.html();
	}
	function onSearchRoom (query) {
		$.get('/search/' + query, function(res) {
			changeList(res);
		});
	}
	function logout() {
		localStorage.removeItem('login');
		location.href = '/logout';
	}
	function enterRoom() {
		wwm.room.initModule(jqMap.$con);
	}
	return {
		initModule: initModule
	};
}());
<commit_msg>text to html<commit_after>wwm.lobby = (function (){
	var jqMap;
	var userInfo;
	function setJqMap($con) {
		jqMap = {
			$con: $con,
			$showCreateroom: $con.find('#show-createroom-modal'),
			$searchroomBtn: $con.find('#searchroom-btn'),
			$list: $con.find('#room-list'),
			$logout: $con.find('#logout-btn'),
			$room: $con.find('.room')
		};
	}
	function initModule($con) {
		userInfo = JSON.parse(localStorage.login);
		console.log('lobby', localStorage.login);
		var src = $('#wwm-lobby').html();
		console.log(userInfo.properties.nickname);	dust.render(dust.loadSource(dust.compile(src)), {
			name: userInfo.properties.nickname
		}, function(err, out) {
			console.log(out);
			$con.html(out);
		});
		setJqMap($con);
		getList();
		jqMap.$showCreateroom.click(showCreateroom);
		jqMap.$searchroomBtn.click(onSearchRoom);
		jqMap.$logout.click(logout);
		jqMap.$room.click(enterRoom);
	}
	function showCreateroom() {
		wwm.modal.initModule($('#wwm-createroom'));
	}
	function getList() {
		$.get('/roomlist').done(function(res){
			jqMap.$list.html();
		});
	}
	function changeList(data) {
		var $frag = $(document.createDocumentFragment());
		jqMap.$list.html();
	}
	function onSearchRoom (query) {
		$.get('/search/' + query, function(res) {
			changeList(res);
		});
	}
	function logout() {
		localStorage.removeItem('login');
		location.href = '/logout';
	}
	function enterRoom() {
		wwm.room.initModule(jqMap.$con);
	}
	return {
		initModule: initModule
	};
}());
<|endoftext|>


<commit_before>module.exports = function (chapter) {
        //console.log("creating new chapter");
        //this.pois = new Pois(chapter);
        //var track = new Route(chapter);
        var pois = new Pois(chapter);
        var measurements = new Measurements(chapter);
    	var story;

    	$.get('data/'+ chapter +'/'+ chapter + '.htm', function(data) {
    		//console.log('data/'+ chapter +'/'+ chapter + '.htm');
    		story = data;
    	});

    	this.getStory = function () {
    		return story;
    	};

        this.hide = function (map) {
            measurements.hide(map);
            //track.hide();
            pois.hide(map);
        };

        this.show = function (map) {
            measurements.show(map);
            //track.show();
            pois.show(map);
        };

        this.getMeasurements = function () {
            return measurements;
        };
};

    function Route(chapter) {
        //console.log("creating new route...");
        var geom;
        var state = "hidden";
        this.id = chapter;

        $.getJSON('data/'+chapter+'/track.json', function(data) {
           //console.log(data.type);
           geom = L.geoJson(data, {
               style: {
                   "color": "#FFFFFF",
                   "weight": 5,
                   "opacity": 0.65
               }
           });

           //changeState();
        });

        function changeState(map) {
            if (state === "hidden") {
                //console.log("hiding layer");
                map.removeLayer(geom);
            } else {
                //console.log("showing layer");
                map.addLayer(geom);
            }
        }

        this.hide = function(map) {
            state = "hidden";
            changeState(map);
        };

        this.show = function(map) {
            //console.log("show");
            state = "visible";
            changeState(map);
        };
    }

    function Measurements(chapter) {
        var icon = "",
            geoms = [],
            dates = [],
            values = [],
            state = "hidden";
        console.log("creating measurements");

        var iconProperties = {
            //iconUrl: 'http://static.ndkv.nl/vm/images/measure_white.png',
            iconUrl: 'dist/images/icons/measurements.png',
            iconSize: [10, 10],
            opacity: 0.1
        };

        $.getJSON('data/'+chapter+'/measurements.json', function(data) {
            $.each(data, function(index, value) {
                var marker = L.marker([value.lat, value.lon], {icon: L.icon(iconProperties)});
                marker.bindLabel(value.date);
                geoms.push(marker);
                dates.push(value.date);
                values.push(value.gravity);

                //changeState();
            });
        });

        this.hide = function(map) {
            state = "hidden";
            changeState(map);
        };

        this.show = function(map) {
            //console.log("show");
            state = "visible";
            changeState(map);

        };

        function changeState(map) {
            if (state === "hidden") {
                //console.log("hiding layer");
                $.each(geoms, function(index, value) {
                    map.removeLayer(value);
                });
            } else {
                //console.log("showing layer");
                $.each(geoms, function(index, value) {
                    map.addLayer(value);
                });
            }
        }

        this.getGeometries = function() {
            return geoms;
        };

        this.getDates = function () {
            return dates;
        };

        this.getValues = function () {
            return values;
        };
    }

    function Pois(chapter) {
        var geoms = [];
        var state = "hidden";
        var markersCluster = new L.MarkerClusterGroup();

        //console.log("firing Poi get");
        $.getJSON('data/'+chapter+'/pois/pois.json', function(data) {
            $.each(data, function(index, value) {
                var lon = value.lon;
                var lat = value.lat;
                var content = value.content;
                var icon = value.icon;

                $.get('data/'+chapter+'/pois/'+content+'.html', function(html) {
                    //add CSS centering code
                    //var marker = L.marker([lat, lon], {icon: L.icon({iconUrl: 'resources/images/icons/' + icon + '.png', iconSize: [40, 20]})}).bindPopup(html, {maxWidth: 450});
                    var test = $.parseHTML(html);
                    var marker;

                    //TODO: photos don't need html hence should be out of the .get function
                    if (icon == "photo") {
                        marker = L.marker([lat, lon], {icon: L.icon({iconUrl: 'dist/images/icons/' + icon + '.png', iconSize: [30, 30]})});
                        marker.on('click', function() {
                            $.fancybox.open([
                                {
                                    href: 'data/'+ chapter +'/pois/images/'+ content.slice(6) + '.png'
                                }],
                                {
                                    autoSize: true,
                                    closeClick: true,
                                    autoResize: true,
                                    helpers: {
                                        overlay: {
                                            css: {
                                                'background': 'rgba(0, 0, 0, 0.85)',
                                                'z-index': '1001'
                                            }
                                    }
                                }
                                });
                        });
                    } else {
                        marker = L.marker([lat, lon], {icon: L.icon({iconUrl: 'dist/images/icons/' + icon + '.png', iconSize: [30, 30]})}).bindPopup(html, {maxWidth: 450});
    //                    geoms.push(marker);
                    }
                    markersCluster.addLayer(marker);
                });
            });
        });

        this.hide = function(map) {
            state = "hidden";
            changeState(map);
        };

        this.show = function(map) {
            //console.log("show");
            state = "visible";
            changeState(map);
        };

        function changeState(map) {
            if (state === "hidden") {
                //console.log("hiding layer");
                map.removeLayer(markersCluster);
                // $.each(geoms, function(index, value) {
                //    map.removeLayer(value);
                // });
            } else {
                //console.log("showing layer");
                map.addLayer(markersCluster);
                // $.each(geoms, function(index, value) {
                //    map.addLayer(value);
                // });
            }
        }
    }
<commit_msg>prevent app from loading all images at once<commit_after>module.exports = function (chapter) {
        //console.log("creating new chapter");
        //this.pois = new Pois(chapter);
        //var track = new Route(chapter);
        var pois = new Pois(chapter);
        var measurements = new Measurements(chapter);
    	var story;

    	$.get('data/'+ chapter +'/'+ chapter + '.htm', function(data) {
    		//console.log('data/'+ chapter +'/'+ chapter + '.htm');
    		story = data;
    	});

    	this.getStory = function () {
    		return story;
    	};

        this.hide = function (map) {
            measurements.hide(map);
            //track.hide();
            pois.hide(map);
        };

        this.show = function (map) {
            measurements.show(map);
            //track.show();
            pois.show(map);
        };

        this.getMeasurements = function () {
            return measurements;
        };
};

    function Route(chapter) {
        //console.log("creating new route...");
        var geom;
        var state = "hidden";
        this.id = chapter;

        $.getJSON('data/'+chapter+'/track.json', function(data) {
           //console.log(data.type);
           geom = L.geoJson(data, {
               style: {
                   "color": "#FFFFFF",
                   "weight": 5,
                   "opacity": 0.65
               }
           });

           //changeState();
        });

        function changeState(map) {
            if (state === "hidden") {
                //console.log("hiding layer");
                map.removeLayer(geom);
            } else {
                //console.log("showing layer");
                map.addLayer(geom);
            }
        }

        this.hide = function(map) {
            state = "hidden";
            changeState(map);
        };

        this.show = function(map) {
            //console.log("show");
            state = "visible";
            changeState(map);
        };
    }

    function Measurements(chapter) {
        var icon = "",
            geoms = [],
            dates = [],
            values = [],
            state = "hidden";
        console.log("creating measurements");

        var iconProperties = {
            //iconUrl: 'http://static.ndkv.nl/vm/images/measure_white.png',
            iconUrl: 'dist/images/icons/measurements.png',
            iconSize: [10, 10],
            opacity: 0.1
        };

        $.getJSON('data/'+chapter+'/measurements.json', function(data) {
            $.each(data, function(index, value) {
                var marker = L.marker([value.lat, value.lon], {icon: L.icon(iconProperties)});
                marker.bindLabel(value.date);
                geoms.push(marker);
                dates.push(value.date);
                values.push(value.gravity);

                //changeState();
            });
        });

        this.hide = function(map) {
            state = "hidden";
            changeState(map);
        };

        this.show = function(map) {
            //console.log("show");
            state = "visible";
            changeState(map);

        };

        function changeState(map) {
            if (state === "hidden") {
                //console.log("hiding layer");
                $.each(geoms, function(index, value) {
                    map.removeLayer(value);
                });
            } else {
                //console.log("showing layer");
                $.each(geoms, function(index, value) {
                    map.addLayer(value);
                });
            }
        }

        this.getGeometries = function() {
            return geoms;
        };

        this.getDates = function () {
            return dates;
        };

        this.getValues = function () {
            return values;
        };
    }

    function Pois(chapter) {
        var geoms = [];
        var state = "hidden";
        var markersCluster = new L.MarkerClusterGroup();

        //console.log("firing Poi get");
        $.getJSON('data/'+chapter+'/pois/pois.json', function(data) {
            $.each(data, function(index, value) {
                var lon = value.lon;
                var lat = value.lat;
                var content = value.content;
                var icon = value.icon;

                $.get('data/'+chapter+'/pois/'+content+'.html', function(html) {
                    //add CSS centering code
                    //var marker = L.marker([lat, lon], {icon: L.icon({iconUrl: 'resources/images/icons/' + icon + '.png', iconSize: [40, 20]})}).bindPopup(html, {maxWidth: 450});
                    //var test = $.parseHTML(html);
                    var marker;

                    //TODO: photos don't need html hence should be out of the .get function
                    if (icon == "photo") {
                        marker = L.marker([lat, lon], {icon: L.icon({iconUrl: 'dist/images/icons/' + icon + '.png', iconSize: [30, 30]})});
                        marker.on('click', function() {
                            $.fancybox.open([
                                {
                                    href: 'data/'+ chapter +'/pois/images/'+ content.slice(6) + '.png'
                                }],
                                {
                                    autoSize: true,
                                    closeClick: true,
                                    autoResize: true,
                                    helpers: {
                                        overlay: {
                                            css: {
                                                'background': 'rgba(0, 0, 0, 0.85)',
                                                'z-index': '1001'
                                            }
                                    }
                                }
                                });
                        });
                    } else {
                        marker = L.marker([lat, lon], {icon: L.icon({iconUrl: 'dist/images/icons/' + icon + '.png', iconSize: [30, 30]})}).bindPopup(html, {maxWidth: 450});
    //                    geoms.push(marker);
                    }
                    markersCluster.addLayer(marker);
                });
            });
        });

        this.hide = function(map) {
            state = "hidden";
            changeState(map);
        };

        this.show = function(map) {
            //console.log("show");
            state = "visible";
            changeState(map);
        };

        function changeState(map) {
            if (state === "hidden") {
                //console.log("hiding layer");
                map.removeLayer(markersCluster);
                // $.each(geoms, function(index, value) {
                //    map.removeLayer(value);
                // });
            } else {
                //console.log("showing layer");
                map.addLayer(markersCluster);
                // $.each(geoms, function(index, value) {
                //    map.addLayer(value);
                // });
            }
        }
    }
<|endoftext|>


<commit_before><commit_msg>update dendro<commit_after><|endoftext|>


<commit_before>// Contains a clone of the classic "xclock" demos.

(function(exports) {
    "use strict";

    var Xclock = new Class({
        initialize: function(server) {
            var connection = server.connect();
            this._display = connection.display;
            var port = connection.clientPort;
            port.addEventListener("message", function(messageEvent) {
                this._handleEvent(messageEvent.data);
            }.bind(this));

            this._pointerRootX = -1;
            this._pointerRootY = -1;

            this.windowId = this._display.createWindow({ x: 300, y: 50, width: 150, height: 150 });
            this._display.selectInput({ windowId: this.windowId, events: ["Expose", "ConfigureNotify", "MapNotify", "UnmapNotify"] });
            this._display.changeProperty({ windowId: this.windowId, name: "WM_NAME", value: "xclock.js" });
            this._display.changeProperty({ windowId: this.windowId, name: "MIN_WIDTH", value: 125 });
            this._display.changeProperty({ windowId: this.windowId, name: "MIN_HEIGHT", value: 125 });
            this._exposeHandler = new ClientUtil.ExposeHandler(this._draw.bind(this));
        },
        _start: function() {
            this._intervalId = setInterval(function() {
                this._display.invalidateWindow({ windowId: this.windowId });
            }.bind(this), 1000);
        },
        _stop: function() {
            clearInterval(this._intervalId);
            this._intervalId = 0;
        },
        _configureNotify: function(event) {
            // Invalidate the entire window when we get resized, as we need
            // to repaint all contents to fit the new size.
            if (event.width !== undefined || event.height !== undefined)
                this._display.invalidateWindow({ windowId: this.windowId });
        },
        _handleEvent: function(event) {
            switch(event.type) {
            case "Expose":
                return this._exposeHandler.handleExpose(event);
            case "ConfigureNotify":
                return this._configureNotify(event);
            case "MapNotify":
                return this._start();
            case "UnmapNotify":
                return this._stop();
            }
        },

        _draw: function() {
            var geom = this._display.getGeometry({ drawableId: this.windowId });
            var width = geom.width, height = geom.height;

            var TAU = Math.PI * 2;

            this._display.drawTo(this.windowId, function(ctx) {
                this._exposeHandler.clip(ctx);

                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, width, height);

                var hw = width / 2, hh = height / 2;
                ctx.translate(hw, hh);
                ctx.lineWidth = 2;

                ctx.rotate(-TAU / 4);

                var radius = Math.min(width, height) / 2 - 5;

                ctx.beginPath();
                for (var i = 0; i < 60; i++) {
                    var angle = i * TAU / 60;
                    ctx.save();
                    ctx.rotate(angle);
                    ctx.moveTo(radius, 0);
                    var length = (i % 5) == 0 ? 10 : 4;
                    ctx.lineTo(radius - length, 0);
                    ctx.restore();
                }
                ctx.stroke();

                ctx.fillStyle = 'black';

                ctx.beginPath();
                ctx.arc(0, 0, 5, 0, TAU);
                ctx.fill();

                var now = new Date();

                ctx.save();
                ctx.rotate(now.getMinutes() * TAU / 60);
                ctx.beginPath();
                ctx.moveTo(0, -5);
                ctx.lineTo(radius - 20, 0);
                ctx.lineTo(0, 5);
                ctx.fill();
                ctx.restore();

                ctx.save();
                ctx.rotate(now.getHours() * TAU / 12);
                ctx.beginPath();
                ctx.moveTo(0, -5);
                ctx.lineTo(radius / 2 - 10, 0);
                ctx.lineTo(0, 5);
                ctx.fill();
                ctx.restore();

                ctx.save();
                ctx.rotate(now.getSeconds() * TAU / 60);
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.lineTo(radius - 20, 0);
                ctx.stroke();
                ctx.restore();
            }.bind(this));
        },
    });

    exports.Xclock = Xclock;

})(window);
<commit_msg>xclock: Add gem<commit_after>// Contains a clone of the classic "xclock" demos.

(function(exports) {
    "use strict";

    var Xclock = new Class({
        initialize: function(server) {
            var connection = server.connect();
            this._display = connection.display;
            var port = connection.clientPort;
            port.addEventListener("message", function(messageEvent) {
                this._handleEvent(messageEvent.data);
            }.bind(this));

            this._pointerRootX = -1;
            this._pointerRootY = -1;

            this.windowId = this._display.createWindow({ x: 300, y: 50, width: 150, height: 150 });
            this._display.selectInput({ windowId: this.windowId, events: ["Expose", "ConfigureNotify", "MapNotify", "UnmapNotify"] });
            this._display.changeProperty({ windowId: this.windowId, name: "WM_NAME", value: "xclock.js" });
            this._display.changeProperty({ windowId: this.windowId, name: "MIN_WIDTH", value: 125 });
            this._display.changeProperty({ windowId: this.windowId, name: "MIN_HEIGHT", value: 125 });
            this._exposeHandler = new ClientUtil.ExposeHandler(this._draw.bind(this));
        },
        _start: function() {
            this._intervalId = setInterval(function() {
                this._display.invalidateWindow({ windowId: this.windowId });
            }.bind(this), 1000);
        },
        _stop: function() {
            clearInterval(this._intervalId);
            this._intervalId = 0;
        },
        _configureNotify: function(event) {
            // Invalidate the entire window when we get resized, as we need
            // to repaint all contents to fit the new size.
            if (event.width !== undefined || event.height !== undefined)
                this._display.invalidateWindow({ windowId: this.windowId });
        },
        _handleEvent: function(event) {
            switch(event.type) {
            case "Expose":
                return this._exposeHandler.handleExpose(event);
            case "ConfigureNotify":
                return this._configureNotify(event);
            case "MapNotify":
                return this._start();
            case "UnmapNotify":
                return this._stop();
            }
        },

        _draw: function() {
            var geom = this._display.getGeometry({ drawableId: this.windowId });
            var width = geom.width, height = geom.height;

            var TAU = Math.PI * 2;

            this._display.drawTo(this.windowId, function(ctx) {
                this._exposeHandler.clip(ctx);

                ctx.fillStyle = 'white';
                ctx.fillRect(0, 0, width, height);

                var hw = width / 2, hh = height / 2;
                ctx.translate(hw, hh);
                ctx.lineWidth = 2;

                ctx.rotate(-TAU / 4);

                var radius = Math.min(width, height) / 2 - 5;

                ctx.beginPath();
                for (var i = 0; i < 60; i++) {
                    var angle = i * TAU / 60;
                    ctx.save();
                    ctx.rotate(angle);
                    ctx.moveTo(radius, 0);
                    var length = (i % 5) == 0 ? 10 : 4;
                    ctx.lineTo(radius - length, 0);
                    ctx.restore();
                }
                ctx.stroke();

                ctx.fillStyle = 'black';

                ctx.beginPath();
                ctx.arc(0, 0, 5, 0, TAU);
                ctx.fill();

                var now = new Date();

                ctx.save();
                ctx.rotate(now.getMinutes() * TAU / 60);
                ctx.beginPath();
                ctx.moveTo(0, -5);
                ctx.lineTo(radius - 20, 0);
                ctx.lineTo(0, 5);
                ctx.fill();
                ctx.restore();

                ctx.save();
                ctx.rotate(now.getHours() * TAU / 12);
                ctx.beginPath();
                ctx.moveTo(0, -5);
                ctx.lineTo(radius / 2 - 10, 0);
                ctx.lineTo(0, 5);
                ctx.fill();
                ctx.restore();

                ctx.save();
                ctx.rotate(now.getSeconds() * TAU / 60);
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.lineTo(radius - 20, 0);
                ctx.stroke();
                ctx.beginPath();
                ctx.moveTo(radius - 5, 0);
                ctx.lineTo(radius - 20, -4);
                ctx.lineTo(radius - 30, 0);
                ctx.lineTo(radius - 20, 4);
                ctx.fill();
                ctx.restore();
            }.bind(this));
        },
    });

    exports.Xclock = Xclock;

})(window);
<|endoftext|>


<commit_before>// ERPNext - web based ERP (http://erpnext.com)
// Copyright (C) 2012 Web Notes Technologies Pvt Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

wn.require("app/js/stock_analytics.js");

wn.pages['stock-balance'].onload = function(wrapper) {
	wn.ui.make_app_page({
		parent: wrapper,
		title: 'Stock Balance',
		single_column: true
	});

	new erpnext.StockBalance(wrapper);

	wrapper.appframe.add_home_breadcrumb()
	wrapper.appframe.add_module_breadcrumb("Stock")
	wrapper.appframe.add_breadcrumb("icon-bar-chart")
}

erpnext.StockBalance = erpnext.StockAnalytics.extend({
	init: function(wrapper) {
		this._super(wrapper, {
			title: "Stock Balance",
			doctypes: ["Item", "Item Group", "Warehouse", "Stock Ledger Entry", "Brand",
				"Stock Entry"],
		});
	},
	setup_columns: function() {
		this.columns = [
			{id: "name", name: "Item", field: "name", width: 300,
				formatter: this.tree_formatter},
			{id: "brand", name: "Brand", field: "brand", width: 100},
			{id: "opening", name: "Opening", field: "opening",
				formatter: this.currency_formatter},
			{id: "inflow", name: "In", field: "inflow",
				formatter: this.currency_formatter},
			{id: "outflow", name: "Out", field: "outflow",
				formatter: this.currency_formatter},
			{id: "closing", name: "Closing", field: "closing",
				formatter: this.currency_formatter},
		];
	},

	filters: [
		{fieldtype:"Select", label: "Value or Qty", options:["Value (Weighted Average)",
			"Value (FIFO)", "Quantity"],
			filter: function(val, item, opts, me) {
				return me.apply_zero_filter(val, item, opts, me);
			}},
		{fieldtype:"Select", label: "Brand", link:"Brand",
			default_value: "Select Brand...", filter: function(val, item, opts) {
				return val == opts.default_value || item.brand == val || item._show;
			}, link_formatter: {filter_input: "brand"}},
		{fieldtype:"Select", label: "Warehouse", link:"Warehouse",
			default_value: "Select Warehouse..."},
		{fieldtype:"Date", label: "From Date"},
		{fieldtype:"Label", label: "To"},
		{fieldtype:"Date", label: "To Date"},
		{fieldtype:"Button", label: "Refresh", icon:"icon-refresh icon-white", cssClass:"btn-info"},
		{fieldtype:"Button", label: "Reset Filters"}
	],

	setup_plot_check: function() {
		return;
	},

	prepare_data: function() {
		this.stock_entry_map = this.make_name_map(wn.report_dump.data["Stock Entry"], "name");
		this._super();
	},

	prepare_balances: function() {
		var me = this;
		var from_date = dateutil.str_to_obj(this.from_date);
		var to_date = dateutil.str_to_obj(this.to_date);
		var data = wn.report_dump.data["Stock Ledger Entry"];

		this.item_warehouse = {};

		for(var i=0, j=data.length; i<j; i++) {
			var sl = data[i];
			sl.posting_datetime = sl.posting_date + " " + sl.posting_time;
			var posting_datetime = dateutil.str_to_obj(sl.posting_datetime);

			if(me.is_default("warehouse") ? true : me.warehouse == sl.warehouse) {
				var item = me.item_by_name[sl.item_code];

				if(me.value_or_qty!="Quantity") {
					var wh = me.get_item_warehouse(sl.warehouse, sl.item_code);
					var is_fifo = this.value_or_qty== "Value (FIFO)";
					var diff = me.get_value_diff(wh, sl, is_fifo);
				} else {
					var diff = sl.qty;
				}

				if(posting_datetime < from_date) {
					item.opening += diff;
				} else if(posting_datetime <= to_date) {
					var ignore_inflow_outflow = this.is_default("warehouse")
						&& item.voucher_type=="Stock Entry"
						&& this.stock_entry_map[item.voucher_no].purpose=="Material Transfer";

					if(!ignore_inflow_outflow) {
						if(diff < 0) {
							item.outflow += Math.abs(diff);
						} else {
							item.inflow += diff;
						}
					}

					item.closing += diff;
				} else {
					break;
				}
			}
		}
	},

	update_groups: function() {
		var me = this;

		$.each(this.data, function(i, item) {
			// update groups
			if(!item.is_group && me.apply_filter(item, "brand")) {
				var parent = me.parent_map[item.name];
				while(parent) {
					parent_group = me.item_by_name[parent];
					$.each(me.columns, function(c, col) {
						if (col.formatter == me.currency_formatter) {
							parent_group[col.field] =
								flt(parent_group[col.field])
								+ flt(item[col.field]);
						}
					});

					// show parent if filtered by brand
					if(item.brand == me.brand)
						parent_group._show = true;

					parent = me.parent_map[parent];
				}
			}
		});
	},

	get_plot_data: function() {
		return;
	}
});<commit_msg>fix in stock balance report<commit_after>// ERPNext - web based ERP (http://erpnext.com)
// Copyright (C) 2012 Web Notes Technologies Pvt Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

wn.require("app/js/stock_analytics.js");

wn.pages['stock-balance'].onload = function(wrapper) {
	wn.ui.make_app_page({
		parent: wrapper,
		title: 'Stock Balance',
		single_column: true
	});

	new erpnext.StockBalance(wrapper);

	wrapper.appframe.add_home_breadcrumb()
	wrapper.appframe.add_module_breadcrumb("Stock")
	wrapper.appframe.add_breadcrumb("icon-bar-chart")
}

erpnext.StockBalance = erpnext.StockAnalytics.extend({
	init: function(wrapper) {
		this._super(wrapper, {
			title: "Stock Balance",
			doctypes: ["Item", "Item Group", "Warehouse", "Stock Ledger Entry", "Brand",
				"Stock Entry"],
		});
	},
	setup_columns: function() {
		this.columns = [
			{id: "name", name: "Item", field: "name", width: 300,
				formatter: this.tree_formatter},
			{id: "brand", name: "Brand", field: "brand", width: 100},
			{id: "opening", name: "Opening", field: "opening",
				formatter: this.currency_formatter},
			{id: "inflow", name: "In", field: "inflow",
				formatter: this.currency_formatter},
			{id: "outflow", name: "Out", field: "outflow",
				formatter: this.currency_formatter},
			{id: "closing", name: "Closing", field: "closing",
				formatter: this.currency_formatter},
		];
	},

	filters: [
		{fieldtype:"Select", label: "Value or Qty", options:["Value (Weighted Average)",
			"Value (FIFO)", "Quantity"],
			filter: function(val, item, opts, me) {
				return me.apply_zero_filter(val, item, opts, me);
			}},
		{fieldtype:"Select", label: "Brand", link:"Brand",
			default_value: "Select Brand...", filter: function(val, item, opts) {
				return val == opts.default_value || item.brand == val || item._show;
			}, link_formatter: {filter_input: "brand"}},
		{fieldtype:"Select", label: "Warehouse", link:"Warehouse",
			default_value: "Select Warehouse..."},
		{fieldtype:"Date", label: "From Date"},
		{fieldtype:"Label", label: "To"},
		{fieldtype:"Date", label: "To Date"},
		{fieldtype:"Button", label: "Refresh", icon:"icon-refresh icon-white", cssClass:"btn-info"},
		{fieldtype:"Button", label: "Reset Filters"}
	],

	setup_plot_check: function() {
		return;
	},

	prepare_data: function() {
		this.stock_entry_map = this.make_name_map(wn.report_dump.data["Stock Entry"], "name");
		this._super();
	},

	prepare_balances: function() {
		var me = this;
		var from_date = dateutil.str_to_obj(this.from_date);
		var to_date = dateutil.str_to_obj(this.to_date);
		var data = wn.report_dump.data["Stock Ledger Entry"];

		this.item_warehouse = {};

		for(var i=0, j=data.length; i<j; i++) {
			var sl = data[i];
			sl.posting_datetime = sl.posting_date + " " + sl.posting_time;
			var posting_datetime = dateutil.str_to_obj(sl.posting_datetime);

			if(me.is_default("warehouse") ? true : me.warehouse == sl.warehouse) {
				var item = me.item_by_name[sl.item_code];

				if(me.value_or_qty!="Quantity") {
					var wh = me.get_item_warehouse(sl.warehouse, sl.item_code);
					var is_fifo = this.value_or_qty== "Value (FIFO)";
					var diff = me.get_value_diff(wh, sl, is_fifo);
				} else {
					var diff = sl.qty;
				}

				if(posting_datetime < from_date) {
					item.opening += diff;
				} else if(posting_datetime <= to_date) {
					var ignore_inflow_outflow = this.is_default("warehouse")
						&& sl.voucher_type=="Stock Entry"
						&& this.stock_entry_map[sl.voucher_no].purpose=="Material Transfer";

					if(!ignore_inflow_outflow) {
						if(diff < 0) {
							item.outflow += Math.abs(diff);
						} else {
							item.inflow += diff;
						}
					}

					item.closing += diff;
				} else {
					break;
				}
			}
		}
	},

	update_groups: function() {
		var me = this;

		$.each(this.data, function(i, item) {
			// update groups
			if(!item.is_group && me.apply_filter(item, "brand")) {
				var parent = me.parent_map[item.name];
				while(parent) {
					parent_group = me.item_by_name[parent];
					$.each(me.columns, function(c, col) {
						if (col.formatter == me.currency_formatter) {
							parent_group[col.field] =
								flt(parent_group[col.field])
								+ flt(item[col.field]);
						}
					});

					// show parent if filtered by brand
					if(item.brand == me.brand)
						parent_group._show = true;

					parent = me.parent_map[parent];
				}
			}
		});
	},

	get_plot_data: function() {
		return;
	}
});<|endoftext|>