<commit_before>openerp.base_import = function (instance) {
    var QWeb = instance.web.qweb;
    var _t = instance.web._t;
    var _lt = instance.web._lt;

    /**
     * Safari does not deal well at all with raw JSON data being
     * returned. As a result, we're going to cheat by using a
     * pseudo-jsonp: instead of getting JSON data in the iframe, we're
     * getting a ``script`` tag which consists of a function call and
     * the returned data (the json dump).
     *
     * The function is an auto-generated name bound to ``window``,
     * which calls back into the callback provided here.
     *
     * @param {Object} form the form element (DOM or jQuery) to use in the call
     * @param {Object} attributes jquery.form attributes object
     * @param {Function} callback function to call with the returned data
     */
    function jsonp(form, attributes, callback) {
        attributes = attributes || {};
        var options = {jsonp: _.uniqueId('import_callback_')};
        window[options.jsonp] = function () {
            delete window[options.jsonp];
            callback.apply(null, arguments);
        };
        if ('data' in attributes) {
            _.extend(attributes.data, options);
        } else {
            _.extend(attributes, {data: options});
        }
        _.extend(attributes, {
            dataType: 'script',
        });
        $(form).ajaxSubmit(attributes);
    }

    instance.web.DataImport = instance.web.Dialog.extend({
        template: 'ImportView',
        dialog_title: _lt("Import Data"),
        opts: [
            {name: 'encoding', label: _lt("Encoding:"), value: 'utf-8'},
            {name: 'separator', label: _lt("Separator:"), value: ','},
            {name: 'quoting', label: _lt("Quoting:"), value: '"'}
        ],
        events: {
            'change .oe_import_grid input': 'import_dryrun',
            'change input.oe_import_file': 'file_update',
            'change input.oe_import_has_header, .oe_import_options input': 'settings_updated',
            'click a.oe_import_csv': function (e) {
                e.preventDefault();
            },
            'click a.oe_import_export': function (e) {
                e.preventDefault();
            },
            'click a.oe_import_toggle': function (e) {
                e.preventDefault();
                var $el = $(e.target);
                ($el.next().length
                        ? $el.next()
                        : $el.parent().next())
                    .toggle();
            }
        },
        init: function (parent, dataset) {
            var self = this;
            this._super(parent, {
                buttons: [
                    {text: _t("Import File"), click: function () {
                        self.do_import();
                    }, 'class': 'oe_import_dialog_button'}
                ]
            });
            this.res_model = parent.model;
            // import object id
            this.id = null;
            this.Import = new instance.web.Model('base_import.import');
        },
        start: function () {
            var self = this;
            return this.Import.call('create', [{
                'res_model': this.res_model
            }]).then(function (id) {
                self.id = id;
                self.$('input[name=import_id]').val(id);
            });
        },

        import_options: function () {
            var self = this;
            var options = {
                headers: this.$('input.oe_import_has_header').prop('checked')
            };
            _(this.opts).each(function (opt) {
                options[opt.name] =
                    self.$('input.oe_import_' + opt.name).val();
            });
            return options;
        },

        //- File & settings change section
        file_update: function (e) {
            if (!this.$('input.oe_import_file').val()) { return; }

            this.$el.removeClass('oe_import_preview oe_import_error');
            jsonp(this.$el, {
                url: '/base_import/set_file'
            }, this.proxy('settings_updated'));
        },
        settings_updated: function () {
            this.$el.addClass('oe_import_with_file');
            // TODO: test that write // succeeded?
            this.Import.call(
                'parse_preview', [this.id, this.import_options()])
                .then(this.proxy('preview'));
        },
        preview: function (result) {
            this.$el.toggleClass(
                'oe_import_noheaders',
                !this.$('input.oe_import_has_header').prop('checked'));
            if (result.error) {
                this.$el.addClass('oe_import_error');
                this.$('.oe_import_error_report').html(
                    QWeb.render('ImportView.preview.error', result));
                return;
            }
            this.$el.addClass('oe_import_preview');
            this.$('table').html(QWeb.render('ImportView.preview', result));

            var $fields = this.$('.oe_import_fields input');
            this.render_fields_matches(result, $fields);
            var data = this.generate_fields_completion(result);
            var item_finder = function (id, items) {
                items = items || data;
                for (var i=0; i < items.length; ++i) {
                    var item = items[i];
                    if (item.id === id) {
                        return item;
                    }
                    var val;
                    if (item.children && (val = item_finder(id, item.children))) {
                        return val;
                    }
                }
                return '';
            };
            $fields.select2({
                allowClear: true,
                minimumInputLength: 0,
                data: data,
                initSelection: function (element, callback) {
                    var default_value = element.val();
                    if (!default_value) {
                        callback('');
                        return;
                    }

                    callback(item_finder(default_value));
                },

                width: 'resolve',
                dropdownCssClass: 'oe_import_selector'
            });
            this.import_dryrun();
        },
        generate_fields_completion: function (root) {
            var basic = [];
            var regulars = [];
            var o2m = [];
            function traverse(field, ancestors, collection) {
                var subfields = field.fields;
                var field_path = ancestors.concat(field);
                var label = _(field_path).pluck('string').join(' / ');
                var id = _(field_path).pluck('name').join('/');

                // If non-relational, m2o or m2m, collection is regulars
                if (!collection) {
                    if (field.name === 'id') {
                        collection = basic
                    } else if (_.isEmpty(subfields)
                            || _.isEqual(_.pluck(subfields, 'name'), ['id', '.id'])) {
                        collection = regulars;
                    } else {
                        collection = o2m;
                    }
                }

                collection.push({
                    id: id,
                    text: label,
                    required: field.required
                });

                for(var i=0, end=subfields.length; i<end; ++i) {
                    traverse(subfields[i], field_path, collection);
                }
            }
            _(root.fields).each(function (field) {
                traverse(field, []);
            });

            return basic.concat([
                { text: _t("Normal Fields"), children: regulars },
                { text: _t("Relation Fields"), children: o2m }
            ]);
        },
        render_fields_matches: function (result, $fields) {
            if (_(result.matches).isEmpty()) { return; }
            $fields.each(function (index, input) {
                var match = result.matches[index];
                if (!match) { return; }

                var current_field = result;
                input.value = _(match).chain()
                    .map(function (name) {
                        // WARNING: does both mapping and folding (over the
                        //          ``field`` iterator variable)
                        return current_field = _(current_field.fields).find(function (subfield) {
                            return subfield.name === name;
                        });
                    })
                    .pluck('name')
                    .value()
                    .join('/');
            });
        },

        //- import itself
        call_import: function (options) {
            var self = this;
            var fields = this.$('.oe_import_fields input.oe_import_match_field').map(function (index, el) {
                return $(el).select2('val') || false;
            }).get();
            return this.Import.call(
                'do', [this.id, fields, this.import_options()], options);
        },
        import_dryrun: function () {
//            this.call_import({ dryrun: true })
//                .then(this.proxy('render_import_errors'));
        },
        do_import: function () {
            var self = this;
            this.call_import({ dryrun: false }).then(function (errors) {
                if (_.isEmpty(errors)) {
                    if (self.getParent().reload_content) {
                        self.getParent().reload_content();
                    }
                    self.close();
                    return;
                }
                self.render_import_errors(errors);
            });
        },
        render_import_errors: function (errors) {
            if (_.isEmpty(errors)) {
                this.$el.removeClass('oe_import_error');
                return;
            }
            // import failed (or maybe just warnings, if we ever get
            // warnings?)
            this.$el.addClass('oe_import_error');
            this.$('.oe_import_error_report').html(
                QWeb.render('ImportView.error', {errors: errors}));
        },
    });
};
<commit_msg>[IMP] base_import: lexicographically sort fields in field-matching UI<commit_after>openerp.base_import = function (instance) {
    var QWeb = instance.web.qweb;
    var _t = instance.web._t;
    var _lt = instance.web._lt;

    /**
     * Safari does not deal well at all with raw JSON data being
     * returned. As a result, we're going to cheat by using a
     * pseudo-jsonp: instead of getting JSON data in the iframe, we're
     * getting a ``script`` tag which consists of a function call and
     * the returned data (the json dump).
     *
     * The function is an auto-generated name bound to ``window``,
     * which calls back into the callback provided here.
     *
     * @param {Object} form the form element (DOM or jQuery) to use in the call
     * @param {Object} attributes jquery.form attributes object
     * @param {Function} callback function to call with the returned data
     */
    function jsonp(form, attributes, callback) {
        attributes = attributes || {};
        var options = {jsonp: _.uniqueId('import_callback_')};
        window[options.jsonp] = function () {
            delete window[options.jsonp];
            callback.apply(null, arguments);
        };
        if ('data' in attributes) {
            _.extend(attributes.data, options);
        } else {
            _.extend(attributes, {data: options});
        }
        _.extend(attributes, {
            dataType: 'script',
        });
        $(form).ajaxSubmit(attributes);
    }

    instance.web.DataImport = instance.web.Dialog.extend({
        template: 'ImportView',
        dialog_title: _lt("Import Data"),
        opts: [
            {name: 'encoding', label: _lt("Encoding:"), value: 'utf-8'},
            {name: 'separator', label: _lt("Separator:"), value: ','},
            {name: 'quoting', label: _lt("Quoting:"), value: '"'}
        ],
        events: {
            'change .oe_import_grid input': 'import_dryrun',
            'change input.oe_import_file': 'file_update',
            'change input.oe_import_has_header, .oe_import_options input': 'settings_updated',
            'click a.oe_import_csv': function (e) {
                e.preventDefault();
            },
            'click a.oe_import_export': function (e) {
                e.preventDefault();
            },
            'click a.oe_import_toggle': function (e) {
                e.preventDefault();
                var $el = $(e.target);
                ($el.next().length
                        ? $el.next()
                        : $el.parent().next())
                    .toggle();
            }
        },
        init: function (parent, dataset) {
            var self = this;
            this._super(parent, {
                buttons: [
                    {text: _t("Import File"), click: function () {
                        self.do_import();
                    }, 'class': 'oe_import_dialog_button'}
                ]
            });
            this.res_model = parent.model;
            // import object id
            this.id = null;
            this.Import = new instance.web.Model('base_import.import');
        },
        start: function () {
            var self = this;
            return this.Import.call('create', [{
                'res_model': this.res_model
            }]).then(function (id) {
                self.id = id;
                self.$('input[name=import_id]').val(id);
            });
        },

        import_options: function () {
            var self = this;
            var options = {
                headers: this.$('input.oe_import_has_header').prop('checked')
            };
            _(this.opts).each(function (opt) {
                options[opt.name] =
                    self.$('input.oe_import_' + opt.name).val();
            });
            return options;
        },

        //- File & settings change section
        file_update: function (e) {
            if (!this.$('input.oe_import_file').val()) { return; }

            this.$el.removeClass('oe_import_preview oe_import_error');
            jsonp(this.$el, {
                url: '/base_import/set_file'
            }, this.proxy('settings_updated'));
        },
        settings_updated: function () {
            this.$el.addClass('oe_import_with_file');
            // TODO: test that write // succeeded?
            this.Import.call(
                'parse_preview', [this.id, this.import_options()])
                .then(this.proxy('preview'));
        },
        preview: function (result) {
            this.$el.toggleClass(
                'oe_import_noheaders',
                !this.$('input.oe_import_has_header').prop('checked'));
            if (result.error) {
                this.$el.addClass('oe_import_error');
                this.$('.oe_import_error_report').html(
                    QWeb.render('ImportView.preview.error', result));
                return;
            }
            this.$el.addClass('oe_import_preview');
            this.$('table').html(QWeb.render('ImportView.preview', result));

            var $fields = this.$('.oe_import_fields input');
            this.render_fields_matches(result, $fields);
            var data = this.generate_fields_completion(result);
            var item_finder = function (id, items) {
                items = items || data;
                for (var i=0; i < items.length; ++i) {
                    var item = items[i];
                    if (item.id === id) {
                        return item;
                    }
                    var val;
                    if (item.children && (val = item_finder(id, item.children))) {
                        return val;
                    }
                }
                return '';
            };
            $fields.select2({
                allowClear: true,
                minimumInputLength: 0,
                data: data,
                initSelection: function (element, callback) {
                    var default_value = element.val();
                    if (!default_value) {
                        callback('');
                        return;
                    }

                    callback(item_finder(default_value));
                },

                width: 'resolve',
                dropdownCssClass: 'oe_import_selector'
            });
            this.import_dryrun();
        },
        generate_fields_completion: function (root) {
            var basic = [];
            var regulars = [];
            var o2m = [];
            function traverse(field, ancestors, collection) {
                var subfields = field.fields;
                var field_path = ancestors.concat(field);
                var label = _(field_path).pluck('string').join(' / ');
                var id = _(field_path).pluck('name').join('/');

                // If non-relational, m2o or m2m, collection is regulars
                if (!collection) {
                    if (field.name === 'id') {
                        collection = basic
                    } else if (_.isEmpty(subfields)
                            || _.isEqual(_.pluck(subfields, 'name'), ['id', '.id'])) {
                        collection = regulars;
                    } else {
                        collection = o2m;
                    }
                }

                collection.push({
                    id: id,
                    text: label,
                    required: field.required
                });

                for(var i=0, end=subfields.length; i<end; ++i) {
                    traverse(subfields[i], field_path, collection);
                }
            }
            _(root.fields).each(function (field) {
                traverse(field, []);
            });

            var cmp = function (field1, field2) {
                return field1.text.localeCompare(field2.text);

            };
            regulars.sort(cmp);
            o2m.sort(cmp);
            return basic.concat([
                { text: _t("Normal Fields"), children: regulars },
                { text: _t("Relation Fields"), children: o2m }
            ]);
        },
        render_fields_matches: function (result, $fields) {
            if (_(result.matches).isEmpty()) { return; }
            $fields.each(function (index, input) {
                var match = result.matches[index];
                if (!match) { return; }

                var current_field = result;
                input.value = _(match).chain()
                    .map(function (name) {
                        // WARNING: does both mapping and folding (over the
                        //          ``field`` iterator variable)
                        return current_field = _(current_field.fields).find(function (subfield) {
                            return subfield.name === name;
                        });
                    })
                    .pluck('name')
                    .value()
                    .join('/');
            });
        },

        //- import itself
        call_import: function (options) {
            var self = this;
            var fields = this.$('.oe_import_fields input.oe_import_match_field').map(function (index, el) {
                return $(el).select2('val') || false;
            }).get();
            return this.Import.call(
                'do', [this.id, fields, this.import_options()], options);
        },
        import_dryrun: function () {
//            this.call_import({ dryrun: true })
//                .then(this.proxy('render_import_errors'));
        },
        do_import: function () {
            var self = this;
            this.call_import({ dryrun: false }).then(function (errors) {
                if (_.isEmpty(errors)) {
                    if (self.getParent().reload_content) {
                        self.getParent().reload_content();
                    }
                    self.close();
                    return;
                }
                self.render_import_errors(errors);
            });
        },
        render_import_errors: function (errors) {
            if (_.isEmpty(errors)) {
                this.$el.removeClass('oe_import_error');
                return;
            }
            // import failed (or maybe just warnings, if we ever get
            // warnings?)
            this.$el.addClass('oe_import_error');
            this.$('.oe_import_error_report').html(
                QWeb.render('ImportView.error', {errors: errors}));
        },
    });
};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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
 */

CLASS({
  package: 'foam.grammars',
  name: 'CSSFont',

  requires: [
    'XHR',
    'foam.util.Base64Encoder',
  ],
  imports: [
    'assert',
    'document',
  ],

  documentation: function() {/* A <b>very permissive</b> ASCII CSS parser that
    rewrites a handful of declarations (decls) to add browser compatability
    prefixed versions. Non-whitespace characters are assumed to be plain-old
    ASCII characters.
  */},

  constants: {
    PREFIXES: [
      '-webkit-'
    ],
    PREFIXED_KEYS: {
      'align-content': true,
      'align-items': true,
      'align-self': true,
      'animation': true,
      'box-shadow': true,
      'column-count': true,
      'column-gap': true,
      'column-rule': true,
      'display': 'flex',
      'filter': true,
      'flex': true,
      'flex-basis': true,
      'flex-direction': true,
      'flex-flow': true,
      'flex-grow': true,
      'flex-shrink': true,
      'flex-wrap': true,
      'font-feature-settings': true,
      'hyphens': true,
      'justify-content': true,
      'keyframes': true,
      'order': true,
      'transform': true,
      'transform-origin': true,
      'user-select': true
    },
  },

  properties: [
    {
      name: 'urls',
      lazyFactory: function() { return {}; },
    },
    {
      name: 'parser',
      lazyFactory: function() {
        var css = this;
        var s = function() { return str(seq.apply(this, arguments)); };
        var r = function() { return str(repeat.apply(this, arguments)); };
        var p = function() { return str(plus.apply(this, arguments)); };
        return SkipGrammar.create({
          __proto__: grammar,

          START: sym('stylesheet'),

          ws: alt(' ', '\t', '\n', '\r', '\f'),
          ws_: repeat0(sym('ws')),
          wsp_: plus0(sym('ws')),

          alphaNum: alt(
              '-',
              range('a', 'z'),
              range('A', 'Z'),
              range('0', '9')),
          // Excludes: ":", ";", "{", "}", "(", ")".
          punct: alt(
              range('!', "'"),
              range('*', '/'),
              range('<', '@'),
              range('[', '`'),
              '|',
              '~'),
          // Alpha-num-punct (excludes: ":", ";", "{", "}", "(", ")").
          anp: alt(sym('alphaNum'), sym('punct')),

          stylesheet: s(
              sym('ws_'),
              r(alt(
                  sym('stmtRule'),
                  sym('blockRule')),
                sym('ws_'))),

          rulePrefix: plus(
              // Alpha-num-punct, but not ";" "{", or "}".
              p(alt(sym('anp'), '(', ')', ':')),
              sym('wsp_')),
          stmtRule: s(sym('rulePrefix'), ';'),
          blockRule: s(sym('rulePrefix'), sym('block')),
          blockList: p(sym('blockRule'), sym('ws_')),

          // Alpha-num-punct, but not "{", "}" or ":".
          declLHS: p(alt(sym('anp'), '(', ')', ';')),
          declRHS: plus(
              alt(sym('url'),
              // Alpha-num-punct, but not "{", "}" or ";".
              p(alt(sym('anp'), '(', ')', ':'))),
              sym('wsp_')),
          decl: seq(
              sym('declLHS'),
              sym('ws_'),
              ':',
              sym('ws_'),
              sym('declRHS')),
          declList: plus(sym('decl'), seq(';', sym('ws_'))),

          url: seq('url(', r(alt(sym('anp'), ':', ';', '{', '}', '(')), ')'),

          block: seq(
              '{',
              sym('ws_'),
              optional(alt(
                  sym('blockList'),
                  sym('declList'))),
              '}'),
        }.addActions({
          rulePrefix: function(parts) {
            // Look for $ signs, and turn them into the model name.
            parts = parts.map(function(p) {
              return p.indexOf('$') >= 0 ? p.replace(/\$/g, css.modelName_) : p;
            });
            return parts.join(' ');
          },
          block: function(parts) {
            return '{' + (parts[2] ? parts[2] : '') + '}';
          },
          declList: function(parts) {
            return parts.join(';');
          },
          declRHS: function(parts) {
            return parts.join(' ');
          },
          decl: function(parts) {
            var key = parts[0];
            var value = parts[4];
            var data = css.PREFIXED_KEYS[key];
            if ( ! data || css.PREFIXES.length === 0 ) return key + ':' + value;

            var rtn = '';
            if ( data === true || data === value ) {
              for ( var i = 0; i < css.PREFIXES.length; ++i ) {
                var prefix = css.PREFIXES[i];
                if ( data === true ) rtn += prefix + key + ':' + value + ';';
                else                 rtn += key + ':' + prefix + value + ';';
              }
            }
            rtn += key + ':' + value;
            return rtn;
          },
          url: function(parts) {
            css.urls[parts[1]] = parts[1];
            return parts.join('');
          },
        }), seq('/*', repeat(not('*/', anyChar)), '*/'));
      },
    },
    {
      name: 'model',
      documentation: 'Optional model which contains this CSS template. Used ' +
          'to expand $ signs in CSS selectors to the model name.',
      postSet: function(old, nu) {
        if (nu) this.modelName_ = nu.CSS_CLASS || cssClassize(nu.id);
      },
    },
    {
      name: 'modelName_',
      documentation: 'The converted model name itself.',
      adapt: function(old, nu) {
        // Turns 'foo-bar quux' into '.foo-bar.quux'
        return '.' + nu.split(/ +/).join('.');
      }
    },
  ],

  methods: [
    function afromUrl(ret, url) {
        this.XHR.create({
          responseType: 'text',
          contentType: '',
        }).asend(function(data, xhr, status) {
          if ( ! status ) { ret(''); return; }
          var css = data;
          this.aparseString(ret, css);
        }.bind(this), url);
    },
    function aparseString(ret, str) {
      var p = this.parser;
      var ps = p.stringPS;
      ps.str = str;
      var res = p.parse(p.START, ps);
      if ( ! (res && typeof res.value === 'string' && res.toString() === '') ) {
        ret(undefined);
        return;
      }
      var css = res.value;
      this.awithDataUrls(ret, css);
    },
    function awithDataUrls(ret, str) {
      var b64e = this.Base64Encoder.create();
      var par = [];

      Object_forEach(this.urls, function(url) {
        par.push(function(ret) {
          this.XHR.create({
            responseType: 'arraybuffer',
            contentType: '',
          }).asend(function(data, xhr, status) {
            if ( ! status ) {
              ret();
              return;
            }
            str = str.replace(
                new RegExp(
                    // RegExp-escape url string.
                    url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")),
                'data:' + xhr.getResponseHeader('Content-Type') + ';base64,' + b64e.encode(data));
            ret();
          }, url);
        }.bind(this));
      });
      apar.apply(null, par)(function() { ret(str); });
    },
  ],
});
<commit_msg>CSSFont: Fix documentation.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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
 */

CLASS({
  package: 'foam.grammars',
  name: 'CSSFont',

  requires: [
    'XHR',
    'foam.util.Base64Encoder',
  ],
  imports: [
    'assert',
    'document',
  ],

  documentation: function() {/* A slightly modified
    $$DOC{ref:'foam.grammars.CSSDecl'} prefix-rewrite parser that also knows how
    to expand remote URLs to dataURLs after fetching the data.
  */},

  constants: {
    PREFIXES: [
      '-webkit-'
    ],
    PREFIXED_KEYS: {
      'align-content': true,
      'align-items': true,
      'align-self': true,
      'animation': true,
      'box-shadow': true,
      'column-count': true,
      'column-gap': true,
      'column-rule': true,
      'display': 'flex',
      'filter': true,
      'flex': true,
      'flex-basis': true,
      'flex-direction': true,
      'flex-flow': true,
      'flex-grow': true,
      'flex-shrink': true,
      'flex-wrap': true,
      'font-feature-settings': true,
      'hyphens': true,
      'justify-content': true,
      'keyframes': true,
      'order': true,
      'transform': true,
      'transform-origin': true,
      'user-select': true
    },
  },

  properties: [
    {
      name: 'urls',
      lazyFactory: function() { return {}; },
    },
    {
      name: 'parser',
      lazyFactory: function() {
        var css = this;
        var s = function() { return str(seq.apply(this, arguments)); };
        var r = function() { return str(repeat.apply(this, arguments)); };
        var p = function() { return str(plus.apply(this, arguments)); };
        return SkipGrammar.create({
          __proto__: grammar,

          START: sym('stylesheet'),

          ws: alt(' ', '\t', '\n', '\r', '\f'),
          ws_: repeat0(sym('ws')),
          wsp_: plus0(sym('ws')),

          alphaNum: alt(
              '-',
              range('a', 'z'),
              range('A', 'Z'),
              range('0', '9')),
          // Excludes: ":", ";", "{", "}", "(", ")".
          punct: alt(
              range('!', "'"),
              range('*', '/'),
              range('<', '@'),
              range('[', '`'),
              '|',
              '~'),
          // Alpha-num-punct (excludes: ":", ";", "{", "}", "(", ")").
          anp: alt(sym('alphaNum'), sym('punct')),

          stylesheet: s(
              sym('ws_'),
              r(alt(
                  sym('stmtRule'),
                  sym('blockRule')),
                sym('ws_'))),

          rulePrefix: plus(
              // Alpha-num-punct, but not ";" "{", or "}".
              p(alt(sym('anp'), '(', ')', ':')),
              sym('wsp_')),
          stmtRule: s(sym('rulePrefix'), ';'),
          blockRule: s(sym('rulePrefix'), sym('block')),
          blockList: p(sym('blockRule'), sym('ws_')),

          // Alpha-num-punct, but not "{", "}" or ":".
          declLHS: p(alt(sym('anp'), '(', ')', ';')),
          declRHS: plus(
              alt(sym('url'),
              // Alpha-num-punct, but not "{", "}" or ";".
              p(alt(sym('anp'), '(', ')', ':'))),
              sym('wsp_')),
          decl: seq(
              sym('declLHS'),
              sym('ws_'),
              ':',
              sym('ws_'),
              sym('declRHS')),
          declList: plus(sym('decl'), seq(';', sym('ws_'))),

          url: seq('url(', r(alt(sym('anp'), ':', ';', '{', '}', '(')), ')'),

          block: seq(
              '{',
              sym('ws_'),
              optional(alt(
                  sym('blockList'),
                  sym('declList'))),
              '}'),
        }.addActions({
          rulePrefix: function(parts) {
            // Look for $ signs, and turn them into the model name.
            parts = parts.map(function(p) {
              return p.indexOf('$') >= 0 ? p.replace(/\$/g, css.modelName_) : p;
            });
            return parts.join(' ');
          },
          block: function(parts) {
            return '{' + (parts[2] ? parts[2] : '') + '}';
          },
          declList: function(parts) {
            return parts.join(';');
          },
          declRHS: function(parts) {
            return parts.join(' ');
          },
          decl: function(parts) {
            var key = parts[0];
            var value = parts[4];
            var data = css.PREFIXED_KEYS[key];
            if ( ! data || css.PREFIXES.length === 0 ) return key + ':' + value;

            var rtn = '';
            if ( data === true || data === value ) {
              for ( var i = 0; i < css.PREFIXES.length; ++i ) {
                var prefix = css.PREFIXES[i];
                if ( data === true ) rtn += prefix + key + ':' + value + ';';
                else                 rtn += key + ':' + prefix + value + ';';
              }
            }
            rtn += key + ':' + value;
            return rtn;
          },
          url: function(parts) {
            css.urls[parts[1]] = parts[1];
            return parts.join('');
          },
        }), seq('/*', repeat(not('*/', anyChar)), '*/'));
      },
    },
    {
      name: 'model',
      documentation: 'Optional model which contains this CSS template. Used ' +
          'to expand $ signs in CSS selectors to the model name.',
      postSet: function(old, nu) {
        if (nu) this.modelName_ = nu.CSS_CLASS || cssClassize(nu.id);
      },
    },
    {
      name: 'modelName_',
      documentation: 'The converted model name itself.',
      adapt: function(old, nu) {
        // Turns 'foo-bar quux' into '.foo-bar.quux'
        return '.' + nu.split(/ +/).join('.');
      }
    },
  ],

  methods: [
    function afromUrl(ret, url) {
        this.XHR.create({
          responseType: 'text',
          contentType: '',
        }).asend(function(data, xhr, status) {
          if ( ! status ) { ret(''); return; }
          var css = data;
          this.aparseString(ret, css);
        }.bind(this), url);
    },
    function aparseString(ret, str) {
      var p = this.parser;
      var ps = p.stringPS;
      ps.str = str;
      var res = p.parse(p.START, ps);
      if ( ! (res && typeof res.value === 'string' && res.toString() === '') ) {
        ret(undefined);
        return;
      }
      var css = res.value;
      this.awithDataUrls(ret, css);
    },
    function awithDataUrls(ret, str) {
      var b64e = this.Base64Encoder.create();
      var par = [];

      Object_forEach(this.urls, function(url) {
        par.push(function(ret) {
          this.XHR.create({
            responseType: 'arraybuffer',
            contentType: '',
          }).asend(function(data, xhr, status) {
            if ( ! status ) {
              ret();
              return;
            }
            str = str.replace(
                new RegExp(
                    // RegExp-escape url string.
                    url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")),
                'data:' + xhr.getResponseHeader('Content-Type') + ';base64,' + b64e.encode(data));
            ret();
          }, url);
        }.bind(this));
      });
      apar.apply(null, par)(function() { ret(str); });
    },
  ],
});
<|endoftext|>


<commit_before>/**
* @fileOverview Produces line chart
*/

/**  */
class DataVisualizer
{
  /**
   * @class DataVisualizer
   * @classdesc DataVisualizer is a wrapper class for line-chart in chart.js.
   *
   * @param {string} id - ID of canvas that chart should be rendered on.
   */
  constructor(id)
  {
      /**
       * Number of total packets added to chart.
       *
       * @private
       * @name DataVisualizer#numPackets
       * @type Integer
       * @default 0
       */
      this.numPackets = 0;

      /**
       * Number of data points to display on line chart.
       *
       * @private
       * @name DataVisualizer#numDisplayPoints
       * @type Integer
       * @default 25
       */
      this.numDisplayPoints = 25;

      /**
       * Chart object to be used by chartjs for chart manipulation>
       *
       * @private
       * @name DataVisualizer#chart
       * @type Object
       */
      this.chart;

      this.toggleData = function(button)
      {
          var dataSetIndex = button.getAttribute('data-data-set-index');
          var dataSet = this.chart.config.data.datasets[dataSetIndex];

          dataSet.hidden = !dataSet.hidden;

          this.chart.update();
      }.bind(this)

      // adding the dataset enum property to each toggle button for use in toggleData function below
      this.initToggleButtons = function()
      {
          var button;

          button = document.getElementById("toggleTemperature");
          button.setAttribute('data-data-set-index', DataSet.TEMPERATURE);

          button = document.getElementById("toggleAltitude");
          button.setAttribute('data-data-set-index', DataSet.ALTITUDE);
      }.bind(this)

      this.addDataPoint = function()
      {
          actualElevationData.push(Math.floor(Math.random() * 50000));
          actualTemperatureData.push(Math.floor(Math.random() * 100));
          actualPacketIndex.push(++this.numPackets);
          temperatureData.length = 0;
          elevationData.length = 0;
          packetIndex.length = 0;

          var startIndex = (this.numPackets > this.numDisplayPoints) ? (this.numPackets - this.numDisplayPoints) : 0;
          var endIndex = (this.numPackets > this.numDisplayPoints) ? (startIndex + this.numDisplayPoints) : this.numPackets;

          for (var i = startIndex; i < endIndex; i++) {
            temperatureData.push(actualTemperatureData[i]);
            elevationData.push(actualElevationData[i]);
            packetIndex.push(actualPacketIndex[i]);
          }

          this.chart.update();
      }.bind(this)

      // creating and configuring chart
      var ctx = document.getElementById(id).getContext("2d");
      this.chart = new Chart(ctx, config);
      Chart.defaults.global.defaultFontColor = "#ebebeb";
      Chart.defaults.global.defaultFontFamily = "'Lato','Helvetica Neue','Helvetica','Arial',sans-serif";

      // initializing toggle buttons
      this.initToggleButtons();
  }
}

// global accessor for html
var chart;
window.onload = function() {
    chart = new DataVisualizer("linechart");
};

<commit_msg>Made toggle button initialization a private method<commit_after>/**
* @fileOverview Produces line chart
*/

class DataVisualizer
{
  /**
   * @class DataVisualizer
   * @classdesc DataVisualizer is a wrapper class for line-chart in chart.js.
   *
   * @param {string} id - ID of canvas that chart should be rendered on.
   */
  constructor(id)
  {
      /**
       * Number of total packets added to chart.
       *
       * @private
       * @name DataVisualizer#numPackets
       * @type Integer
       * @default 0
       */
      this.numPackets = 0;

      /**
       * Number of data points to display on line chart.
       *
       * @private
       * @name DataVisualizer#numDisplayPoints
       * @type Integer
       * @default 25
       */
      this.numDisplayPoints = 25;

      /**
       * Chart object to be used by chartjs for chart manipulation>
       *
       * @private
       * @name DataVisualizer#chart
       * @type Object
       */
      this.chart;

      this.toggleData = function(button)
      {
          var dataSetIndex = button.getAttribute('data-data-set-index');
          var dataSet = this.chart.config.data.datasets[dataSetIndex];

          dataSet.hidden = !dataSet.hidden;

          this.chart.update();
      }.bind(this)

      this.addDataPoint = function()
      {
          actualElevationData.push(Math.floor(Math.random() * 50000));
          actualTemperatureData.push(Math.floor(Math.random() * 100));
          actualPacketIndex.push(++this.numPackets);
          temperatureData.length = 0;
          elevationData.length = 0;
          packetIndex.length = 0;

          var startIndex = (this.numPackets > this.numDisplayPoints) ? (this.numPackets - this.numDisplayPoints) : 0;
          var endIndex = (this.numPackets > this.numDisplayPoints) ? (startIndex + this.numDisplayPoints) : this.numPackets;

          for (var i = startIndex; i < endIndex; i++) {
            temperatureData.push(actualTemperatureData[i]);
            elevationData.push(actualElevationData[i]);
            packetIndex.push(actualPacketIndex[i]);
          }

          this.chart.update();
      }.bind(this)

      /**
       * Initializes toggle buttons to reference correct dataset.
       *
       * @private
       */
      function initToggleButtons()
      {
          var button;

          button = document.getElementById("toggleTemperature");
          button.setAttribute('data-data-set-index', DataSet.TEMPERATURE);

          button = document.getElementById("toggleAltitude");
          button.setAttribute('data-data-set-index', DataSet.ALTITUDE);
      }

      // creating and configuring chart
      var ctx = document.getElementById(id).getContext("2d");
      this.chart = new Chart(ctx, config);
      Chart.defaults.global.defaultFontColor = "#ebebeb";
      Chart.defaults.global.defaultFontFamily = "'Lato','Helvetica Neue','Helvetica','Arial',sans-serif";

      // initializing toggle buttons
      initToggleButtons();
  }
}

// global accessor for html
var chart;
window.onload = function() {
    chart = new DataVisualizer("linechart");
};

<|endoftext|>


<commit_before>/*****************************************************
*													 *
*	Author: Dinesh Vadivel							 *
*	Plugin: jquery.dropList.1.0.0.js				 *
*	Date:	20-06-2013								 *
*													 *
*													 *
*													 *
*													 *
*													 *
*													 *
*****************************************************/

(function($){
   var DropList = function(element, options)
   {
       var elem = $(element);
       var obj = this;
       var rand;
       // Merge options with defaults
       var settings = $.extend({
       	  text		: "Select your car",
          speed		: 200,

          type		: "dropdown",
          search	: false,
          multiple	: false,
          selected	: ""
       }, options || {});

       var matched, browser;
       jQuery.uaMatch = function( ua ) {
	   ua = ua.toLowerCase();
	   var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
        /(msie) ([\w.]+)/.exec( ua ) ||
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        [];

		    return {
		        browser: match[ 1 ] || "",
		        version: match[ 2 ] || "0"
		    };
		};

		matched = jQuery.uaMatch( navigator.userAgent );
		browser = {};

		if ( matched.browser ) {
		    browser[ matched.browser ] = true;
		    browser.version = matched.version;
		}

		// Chrome is Webkit, but Webkit is also Safari.
		if ( browser.chrome ) {
		    browser.webkit = true;
		} else if ( browser.webkit ) {
		    browser.safari = true;
		}

		jQuery.browser = browser;

       GenerateUI(elem, settings, matched.browser);

       // Public method
       this.addhighlight = function()
       {

       };
   };

   function GenerateUI(element, options, browser)
   {
		console.log(options.ar);
		rand=Math.floor((Math.random()*9999999)+9999);

		ID=element.attr('id');
		parentID=element.parent().attr('id');
		$('#'+ID).hide();
		if(options.search==false)
		{

			if(options.selected=="")
			{
				$('#'+parentID).append('

'+options.text+'

'+options.text+'

');
			}
			else
			{
				var json=$.parseJSON( options.selected);
				var parsed=json[0];
				if(options.multiple==false)
				{
				$('#'+parentID).append('

'+parsed+'

'+options.text+'

');
				$('#dlholder_'+rand).siblings('#dlist').children('option[value='+parsed+']').attr('selected', 'selected');
				}
				else
				{	var temp='';

					$.each(json,function(key,value){

						$('#'+ID).children('option[value='+value+']').attr('selected', 'selected');
						//$('#dlholder_'+rand).siblings('#'+ID).children('option[value='+value+']').attr('selected', 'selected');
						temp+=value+',';
					});
					temp=temp.substr(0,temp.length-1);
					$("#dlholder_"+rand).children('#tempdllist').text(temp);
					$('#'+parentID).append('

'+temp+'

'+options.text+'

');

				}
			}

			$('#'+parentID).append('

');
			$('#'+parentID).append('

');
			$('#'+ID+' option').each(function(){
				$('#dldrop_'+rand).append('
'+this.value+'
');
			});

			if(options.multiple==false)
			{
				$('#dlholder_'+rand).click(function(){
					var split=this.id.split("_");
					$('.dListdrop').each(function(){
						if(this.id!="dldrop_"+split[1]&&$('#'+this.id).is(":visible"))
						{
							$("#"+this.id).slideUp();
						}
					});
					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

						$("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).addClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideDown( options.speed, function() {
						});
					}
					else
					{
					    $("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).removeClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {

					  	});
					}
					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

					}
					else
					{
						$(this).removeClass('currentclick');
						$("#dldrop_"+split[1]+" #SelectItem").click(function(){
							selection=$(this).text();
							$('#dlholder_'+split[1]+' #dltext').text(selection);
							$('#dlholder_'+split[1]).siblings('#dlist').children('option:selected').removeAttr('selected');
							$('#dlholder_'+split[1]).siblings('#dlist').children('option[value='+selection+']').attr('selected', 'selected');
							$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {
							});
						});
					}

				});
			}
			else if(options.multiple==true)
			{
				$('#dlholder_'+rand).click(function(){

					var split=this.id.split("_");
					$('.dListdrop').each(function(){
						if(this.id!="dldrop_"+split[1]&&$('#'+this.id).is(":visible"))
						{
							$("#"+this.id).slideUp();
						}
					});
					var Stext=$("#dlholder_"+split[1]).children('#tempdllist').text();
					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

						$("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).addClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideDown( options.speed, function() {
						});
					}
					else
					{
					    $("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).removeClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {

					  	});
					}
					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

					}
					else
					{

						if(Stext==options.text)
						{
							var items=[];
						}
						else
						{
							var items=Stext.split(',');
						}

						//var trainindIdArray =
						$(this).removeClass('currentclick');
						$("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).click(function(){
								var disable=$(this).hasClass('ItemAdded');
								if(disable==false)
								{
									$(this).addClass('ItemAdded');
									var selection=$(this).text();

									items.push(selection);
									$('#dlholder_'+split[1]+' #dltext').text(selection);
									$('#dlholder_'+split[1]).siblings('select').children('option:selected').removeAttr('selected');
									$.each(items,function(e,value){
										$('#dlholder_'+split[1]).siblings('select').children('option[value='+value+']').attr('selected', 'selected');
									});
									var stringme=items+"";
									$('#dlholder_'+split[1]+' #dltext').text(stringme);
									$('#dlholder_'+split[1]+' #tempdllist').text(stringme);

								}
								else
								{
									selection=$(this).text();
									$(this).removeClass('ItemAdded');
									items = jQuery.grep(items, function(value) {
									  return value != selection;
									});
									var stringme=items+"";
									$('#dlholder_'+split[1]+' #dltext').text(stringme);
									$('#dlholder_'+split[1]+' #tempdllist').text(stringme);
									$('#dlholder_'+split[1]).siblings('select').children('option[value='+selection+']').removeAttr('selected');
									if(items.length==0)
									{
										$('#dlholder_'+split[1]+' #dltext').text(options.text);
										$('#dlholder_'+split[1]+' #tempdllist').text(options.text);

									}
								}
							});

						});

					}

				});

			}

		}
		else if(options.search==true&&options.multiple==false)
		{

			$('#'+parentID).append('

<input type="text" name="searchstring" class="dlsearch" placeholder="'+options.text+'" id="dlsrch_'+rand+'">

'+options.text+'

');
			$('#'+parentID).append('

');
			$('#'+parentID).append('

');
			$('#'+ID+' option').each(function(){
				$('#dldrop_'+rand).append('
'+this.value+'
');
			});

			$("#dlsrch_"+rand).keyup(function(e){

				var split=this.id.split("_");
				$('.dListdrop').each(function(){
						if(this.id!="dldrop_"+split[1]&&$('#'+this.id).is(":visible"))
						{
							$("#"+this.id).slideUp();
						}
					});
				var filter = $(this).val(), count = 0;
				if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
				{

						$("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).addClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideDown( options.speed, function() {
						});
				}

				$("#dldrop_"+split[1]+" #SelectItem").each(function(){
					if ($(this).text().search(new RegExp(filter, "i")) < 0) {
		                $(this).hide();

		            } else {
		                $(this).show();
		                count++;
		            }
	            });
	            if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
				{

				}
				else
				{
						$(this).removeClass('currentclick');
						$("#dldrop_"+split[1]+" #SelectItem").click(function(){
							selection=$(this).text();
							$('#dlholder_'+split[1]+' #dltext input').val(selection);
							$('#dlholder_'+split[1]).siblings('#dlist').children('option:selected').removeAttr('selected');
							$('#dlholder_'+split[1]).siblings('#dlist').children('option[value='+selection+']').attr('selected', 'selected');
							$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {
							});
						});
				}
			});

			$('#dlbtn_'+rand).click(function(){
					var split=this.id.split("_");
					$('.dListdrop').each(function(){
						if(this.id!="dldrop_"+split[1]&&$('#'+this.id).is(":visible"))
						{

							$("#"+this.id).slideUp();
						}
					});

					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

						$("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).addClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideDown( options.speed, function() {
						});
					}
					else
					{
					    $("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).removeClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {

					  	});
					}
					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

					}
					else
					{
						$(this).removeClass('currentclick');
						$("#dldrop_"+split[1]+" #SelectItem").click(function(){
							selection=$(this).text();
							$('#dlholder_'+split[1]+' #dltext input').val(selection);
							$('#dlholder_'+split[1]).siblings('#dlist').children('option:selected').removeAttr('selected');
							$('#dlholder_'+split[1]).siblings('#dlist').children('option[value='+selection+']').attr('selected', 'selected');
							$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {
							});
						});
					}
			});

		}

 };

   $.fn.dropList = function(options)
   {
       return this.each(function()
       {
           var element = $(this);

           // Return early if this element already has a plugin instance
           if (element.data('dropList')) return;

           // pass options to plugin constructor
           var dropList = new DropList(this, options);

           // Store plugin object in this element's data
           element.data('dropList', dropList);
       });
   };
})(jQuery);<commit_msg>few selection issues fixed<commit_after>/*****************************************************
*													 *
*	Author: Dinesh Vadivel							 *
*	Plugin: jquery.dropList.1.0.0.js				 *
*	Date:	20-06-2013								 *
*													 *
*													 *
*													 *
*													 *
*													 *
*													 *
*****************************************************/

(function($){
   var DropList = function(element, options)
   {
       var elem = $(element);
       var obj = this;
       var rand;
       // Merge options with defaults
       var settings = $.extend({
       	  text		: "Select your car",
          speed		: 200,

          type		: "dropdown",
          search	: false,
          multiple	: false,
          selected	: ""
       }, options || {});

       var matched, browser;
       jQuery.uaMatch = function( ua ) {
	   ua = ua.toLowerCase();
	   var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
        /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
        /(msie) ([\w.]+)/.exec( ua ) ||
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
        [];

		    return {
		        browser: match[ 1 ] || "",
		        version: match[ 2 ] || "0"
		    };
		};

		matched = jQuery.uaMatch( navigator.userAgent );
		browser = {};

		if ( matched.browser ) {
		    browser[ matched.browser ] = true;
		    browser.version = matched.version;
		}

		// Chrome is Webkit, but Webkit is also Safari.
		if ( browser.chrome ) {
		    browser.webkit = true;
		} else if ( browser.webkit ) {
		    browser.safari = true;
		}

		jQuery.browser = browser;

       GenerateUI(elem, settings, matched.browser);

       // Public method
       this.addhighlight = function()
       {

       };
   };

   function GenerateUI(element, options, browser)
   {
		console.log(options.ar);
		rand=Math.floor((Math.random()*9999999)+9999);

		ID=element.attr('id');
		parentID=element.parent().attr('id');
		$('#'+ID).hide();
		if(options.search==false)
		{

			if(options.selected=="")
			{
				$('#'+parentID).append('

'+options.text+'

'+options.text+'

');
			}
			else
			{
				var json=$.parseJSON( options.selected);
				var parsed=json[0];
				if(options.multiple==false)
				{
				$('#'+parentID).append('

'+parsed+'

'+options.text+'

');
				$('#dlholder_'+rand).siblings('#dlist').children('option[value='+parsed+']').attr('selected', 'selected');
				}
				else
				{	var temp='';

					$.each(json,function(key,value){

						$('#'+ID).children('option[value='+value+']').attr('selected', 'selected');
						//$('#dlholder_'+rand).siblings('#'+ID).children('option[value='+value+']').attr('selected', 'selected');
						temp+=value+',';
					});
					temp=temp.substr(0,temp.length-1);
					$("#dlholder_"+rand).children('#tempdllist').text(temp);
					$('#'+parentID).append('

'+temp+'

'+options.text+'

');

				}
			}

			$('#'+parentID).append('

');
			$('#'+parentID).append('

');
			$('#'+ID+' option').each(function(){
				$('#dldrop_'+rand).append('
'+this.value+'
');
			});

			if(options.multiple==false)
			{
				$('#dlholder_'+rand).click(function(){
					var split=this.id.split("_");
					$('.dListdrop').each(function(){
						if(this.id!="dldrop_"+split[1]&&$('#'+this.id).is(":visible"))
						{
							$("#"+this.id).slideUp();
						}
					});
					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

						$("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).addClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideDown( options.speed, function() {
						});
					}
					else
					{
					    $("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).removeClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {

					  	});
					}
					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

					}
					else
					{
						$(this).removeClass('currentclick');
						$("#dldrop_"+split[1]+" #SelectItem").click(function(){
							selection=$(this).text();
							$('#dlholder_'+split[1]+' #dltext').text(selection);
							$('#dlholder_'+split[1]).siblings('#dlist').children('option:selected').removeAttr('selected');
							$('#dlholder_'+split[1]).siblings('#dlist').children('option[value='+selection+']').attr('selected', 'selected');
							$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {
							});
						});
					}

				});
			}
			else if(options.multiple==true)
			{
				$('#dlholder_'+rand).click(function(){

					var split=this.id.split("_");
					$('.dListdrop').each(function(){
						if(this.id!="dldrop_"+split[1]&&$('#'+this.id).is(":visible"))
						{
							$("#"+this.id).slideUp();
						}
					});
					var Stext=$("#dlholder_"+split[1]).children('#tempdllist').text();
					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

						$("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).addClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideDown( options.speed, function() {
						});
					}
					else
					{
					    $("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).removeClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {

					  	});
					}
					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

					}
					else
					{

						if(Stext==options.text)
						{
							var items=[];
						}
						else
						{
							var items=Stext.split(',');
						}

						//var trainindIdArray =
						$(this).removeClass('currentclick');
						$("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).click(function(){
								var disable=$(this).hasClass('ItemAdded');
								if(disable==false)
								{
									$(this).addClass('ItemAdded');
									var selection=$(this).text();

									items.push(selection);
									$('#dlholder_'+split[1]+' #dltext').text(selection);
									$('#dlholder_'+split[1]).siblings('select').children('option:selected').removeAttr('selected');
									$.each(items,function(e,value){
										$('#dlholder_'+split[1]).siblings('select').children('option[value='+value+']').attr('selected', 'selected');
									});
									var stringme=items+"";
									$('#dlholder_'+split[1]+' #dltext').text(stringme);
									$('#dlholder_'+split[1]+' #tempdllist').text(stringme);

								}
								else
								{
									selection=$(this).text();
									$(this).removeClass('ItemAdded');
									items = jQuery.grep(items, function(value) {
									  return value != selection;
									});
									var stringme=items+"";
									$('#dlholder_'+split[1]+' #dltext').text(stringme);
									$('#dlholder_'+split[1]+' #tempdllist').text(stringme);
									$('#dlholder_'+split[1]).siblings('select').children('option[value='+selection+']').removeAttr('selected');
									if(items.length==0)
									{
										$('#dlholder_'+split[1]+' #dltext').text(options.text);
										$('#dlholder_'+split[1]+' #tempdllist').text(options.text);

									}
								}
							});

						});

					}

				});

			}

		}
		else if(options.search==true&&options.multiple==false)
		{

			$('#'+parentID).append('

<input type="text" name="searchstring" class="dlsearch" placeholder="'+options.text+'" id="dlsrch_'+rand+'">

'+options.text+'

');
			$('#'+parentID).append('

');
			$('#'+parentID).append('

');
			$('#'+ID+' option').each(function(){
				$('#dldrop_'+rand).append('
'+this.value+'
');
			});

			$("#dlsrch_"+rand).keyup(function(e){

				var split=this.id.split("_");
				$('.dListdrop').each(function(){
						if(this.id!="dldrop_"+split[1]&&$('#'+this.id).is(":visible"))
						{
							$("#"+this.id).slideUp();
						}
					});
				var filter = $(this).val(), count = 0;
				if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
				{

						$("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).addClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideDown( options.speed, function() {
						});
				}

				$("#dldrop_"+split[1]+" #SelectItem").each(function(){
					if ($(this).text().search(new RegExp(filter, "i")) < 0) {
		                $(this).hide();

		            } else {
		                $(this).show();
		                count++;
		            }
	            });
	            if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
				{

				}
				else
				{
						$(this).removeClass('currentclick');
						$("#dldrop_"+split[1]+" #SelectItem").click(function(){
							selection=$(this).text();

							$('#dlholder_'+split[1]+' #dltext input').val(selection);
							$('#dlholder_'+split[1]).siblings('#dlist').children('option:selected').removeAttr('selected');
							$('#dlholder_'+split[1]).siblings('#dlist').children('option[value='+selection+']').attr('selected', 'selected');
							$('#'+ID).children().removeAttr('selected');
							$('#'+ID).children('option[value='+selection+']').attr('selected', 'selected');
							$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {
							});
						});
				}
			});

			$('#dlbtn_'+rand).click(function(){
					var split=this.id.split("_");
					$('.dListdrop').each(function(){
						if(this.id!="dldrop_"+split[1]&&$('#'+this.id).is(":visible"))
						{

							$("#"+this.id).slideUp();
						}
					});

					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

						$("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).addClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideDown( options.speed, function() {
						});
					}
					else
					{
					    $("#dldrop_"+split[1]+" #SelectItem").each(function(){
							$(this).removeClass('dlithov');
						});
						$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {

					  	});
					}
					if( $( "#dldrop_"+split[1] ).is( ":hidden" ) )
					{

					}
					else
					{
						$(this).removeClass('currentclick');
						$("#dldrop_"+split[1]+" #SelectItem").click(function(){
							selection=$(this).text();
							$('#dlholder_'+split[1]+' #dltext input').val(selection);
							$('#dlholder_'+split[1]).siblings('#dlist').children('option:selected').removeAttr('selected');
							$('#dlholder_'+split[1]).siblings('#dlist').children('option[value='+selection+']').attr('selected', 'selected');
							$('#'+ID).children().removeAttr('selected');
							$('#'+ID).children('option[value='+selection+']').attr('selected', 'selected');
							$( "#dldrop_"+split[1] ).slideUp( options.speed, function() {
							});
						});
					}
			});

		}

 };

   $.fn.dropList = function(options)
   {
       return this.each(function()
       {
           var element = $(this);

           // Return early if this element already has a plugin instance
           if (element.data('dropList')) return;

           // pass options to plugin constructor
           var dropList = new DropList(this, options);

           // Store plugin object in this element's data
           element.data('dropList', dropList);
       });
   };
})(jQuery);<|endoftext|>


<commit_before>//checkout : https://www.npmjs.com/package/pixelmatch
//http://zschuessler.github.io/DeltaE/
//https://github.com/antimatter15/rgb-lab/blob/master/color.js

var modifyPixel = function(pixel, data) {
    var R = 0,G = 1,B = 2,A = 3;

    if(pixel[A] > 0) {
      data.total += 1;
      var c = data.colorStats[pixel[0] + "-" + pixel[1] + "-" + pixel[2]];
      c = c || 0;
      c += 1;
      data.colorStats[pixel[0] + "-" + pixel[1] + "-" + pixel[2]] = c;
    }
    return [0,0,0,0]//pixel;
  }

  /**
   * Setup landcover tile cache layer as a raster layer
   */
var landcover = new ol.source.Raster({
  sources: [
    new ol.source.XYZ({
      url: 'https://coast.noaa.gov/arcgis/rest/services/CCAP/CCAP_landcover_2010/MapServer/tile/{z}/{y}/{x}',
      crossOrigin: 'anonymous'
    })
  ],
  operation: function(pixels, data) {
    var pixel = pixels[0];
    return modifyPixel(pixel, data);
  },
  lib: {
    landcoverClasses: landcoverClasses,
    rgb2lab: rgb2lab,
    lab2rgb: lab2rgb,
    deltaE: deltaE,
    modifyPixel: modifyPixel
  }
});
landcover.set('lc_class', 0);

landcover.on('beforeoperations', function(event) {
  event.data.total = 0;
  event.data.colorStats = {};
  event.data.classes = landcoverClasses;
  event.data.classes.forEach(function (lcaClass) {
    lcaClass.count = 0;
  });
});

landcover.on('afteroperations', function(event) {
  Object.keys(event.data.colorStats).forEach(function(c){

    // if new pixels are found
    if(event.data.classes[matchMap[c]] === undefined) {
      var cArr = c.split("-");
      var pixel = [parseInt(cArr[0]),parseInt(cArr[1]),parseInt(cArr[2])];
      event.data.classes.forEach(function (lcaClass,i) {
        if(i > 0){
          var matchLab = lcaClass.colorLab;
          var pixelLab = rgb2lab(pixel);
          var deltaEDiff = deltaE(matchLab, pixelLab);
          if (deltaEDiff < 3.0) {
            //console.log(c + " ---------> " +  lcaClass.id);
            lcaClass.count = event.data.colorStats[c]
          }
          else{
            //console.log("no Match for: ", c)
          }
        }
      });
    }
    else{
      event.data.classes[matchMap[c]].count = event.data.colorStats[c];
    }

  });
  //console.log(matchMap);
  scheduleStats({
    total: event.data.total,
    classes: event.data.classes
  },event.resolution);
});

/**
 * Map Setup
 */

var attribution = new ol.Attribution({
  html: 'Tiles © ArcGIS'
});

var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.XYZ({
        attributions: [attribution],
        url: 'https://server.arcgisonline.com/ArcGIS/rest/services/' + 'Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}'
      })
    }),
    new ol.layer.Tile({
      source: new ol.source.XYZ({
        attributions: [attribution],
        url: 'https://coast.noaa.gov/arcgis/rest/services/CCAP/CCAP_landcover_2010/MapServer/tile/{z}/{y}/{x}'
      })
    }),
    new ol.layer.Image({
      source: landcover
    })
  ],
  view: new ol.View({
    center: [-10812411.623547956, 5050417.912951814],
    zoom: 4
  })
});

/**
 * Generate controls
 */

$(function() {
  initializeChart();
  landcoverClasses.forEach(function(i) {
    $('#controls').append('
   ' + i.name + '
');
  });
  $('.legenditem').on('click', function(evt) {
    landcover.set('lc_class', $(this).data('color-id'));
    landcover.changed();

    scheduleStats({title: $(this).find('.legendname').text()});
  });
});

var timer = null;
function scheduleStats(stats,resolution) {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  timer = setTimeout(function(){ displayStats(stats,resolution) }, 1000);
}

function displayStats(stats,resolution){
  console.log("displaying stats");

  if(stats.total) $('#stats #total').text(area(resolution,stats.total) + " square miles");
  if(stats.classes){
    var chartData = [];
    var check = 0;
    stats.classes.forEach(function (lcaClass) {
      $('#class_'+lcaClass.id).find(".value").text(percent(lcaClass.count,stats.total)+ "%");
      check = check + percent(lcaClass.count,stats.total);
      chartData.push({
        name: lcaClass.name,
        y: percent(lcaClass.count,stats.total),
        color: rgbString(lcaClass.color)
      });
    });
    renderChart(chartData);
  }
//area(resolution,stats.class_total)
}

function percent(value,total){
  return Math.round((value * 100) / total);
}
function area(resolution, meterCounts){
  return ((resolution * resolution * meterCounts) * 3.8610216e-07).toFixed(2) ; //convert sq mt to sq mi
}

function rgbString(color) {
  return 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')';
}

function rgbaString(color) {
  return 'rgba(' + color[0] + ',' + color[1] + ',' + color[2] + ',' + color[3] + ')';
}

function initializeChart(){
  return $('#pieChart').highcharts({
          chart: {
              plotBackgroundColor: null,
              plotBorderWidth: null,
              plotShadow: false,
              type: 'pie'
          },
          title: {
              text: null
          },
          tooltip: {
              pointFormat: '{series.name}: {point.percentage:.1f}%'
          },
          plotOptions: {
              pie: {
                  allowPointSelect: true,
                  cursor: 'pointer',
                  dataLabels: {
                      enabled: true
                  }
              }
          },
          series: [{
            name: 'Classes',
            colorByPoint: true,
            data: []
        }]
      });
}

function renderChart(data){
  var chart = $("#pieChart").highcharts();
  chart.series[0].setData(data, true);
}<commit_msg>removed the cached overlay, and letting the pixels write. This is flickers slightly but is loading less data and does not conflict with cross domains on same tiles<commit_after>//checkout : https://www.npmjs.com/package/pixelmatch
//http://zschuessler.github.io/DeltaE/
//https://github.com/antimatter15/rgb-lab/blob/master/color.js

var modifyPixel = function(pixel, data) {
    var R = 0,G = 1,B = 2,A = 3;

    if(pixel[A] > 0) {
      data.total += 1;
      var c = data.colorStats[pixel[0] + "-" + pixel[1] + "-" + pixel[2]];
      c = c || 0;
      c += 1;
      data.colorStats[pixel[0] + "-" + pixel[1] + "-" + pixel[2]] = c;
    }
    return pixel;//[0,0,0,0]//pixel;
  }

  /**
   * Setup landcover tile cache layer as a raster layer
   */
var landcover = new ol.source.Raster({
  sources: [
    new ol.source.XYZ({
      url: 'https://coast.noaa.gov/arcgis/rest/services/CCAP/CCAP_landcover_2010/MapServer/tile/{z}/{y}/{x}',
      crossOrigin: 'anonymous'
    })
  ],
  operation: function(pixels, data) {
    var pixel = pixels[0];
    return modifyPixel(pixel, data);
  },
  lib: {
    landcoverClasses: landcoverClasses,
    rgb2lab: rgb2lab,
    lab2rgb: lab2rgb,
    deltaE: deltaE,
    modifyPixel: modifyPixel
  }
});
landcover.set('lc_class', 0);

landcover.on('beforeoperations', function(event) {
  event.data.total = 0;
  event.data.colorStats = {};
  event.data.classes = landcoverClasses;
  event.data.classes.forEach(function (lcaClass) {
    lcaClass.count = 0;
  });
});

landcover.on('afteroperations', function(event) {
  Object.keys(event.data.colorStats).forEach(function(c){

    // if new pixels are found
    if(event.data.classes[matchMap[c]] === undefined) {
      var cArr = c.split("-");
      var pixel = [parseInt(cArr[0]),parseInt(cArr[1]),parseInt(cArr[2])];
      event.data.classes.forEach(function (lcaClass,i) {
        if(i > 0){
          var matchLab = lcaClass.colorLab;
          var pixelLab = rgb2lab(pixel);
          var deltaEDiff = deltaE(matchLab, pixelLab);
          if (deltaEDiff < 3.0) {
            //console.log(c + " ---------> " +  lcaClass.id);
            lcaClass.count = event.data.colorStats[c]
          }
          else{
            //console.log("no Match for: ", c)
          }
        }
      });
    }
    else{
      event.data.classes[matchMap[c]].count = event.data.colorStats[c];
    }

  });
  //console.log(matchMap);
  scheduleStats({
    total: event.data.total,
    classes: event.data.classes
  },event.resolution);
});

/**
 * Map Setup
 */

var attribution = new ol.Attribution({
  html: 'Tiles © ArcGIS'
});

var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
      source: new ol.source.XYZ({
        attributions: [attribution],
        url: 'https://server.arcgisonline.com/ArcGIS/rest/services/' + 'Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}'
      })
    }),/*
    new ol.layer.Tile({
      source: new ol.source.XYZ({
        attributions: [attribution],
        url: 'https://coast.noaa.gov/arcgis/rest/services/CCAP/CCAP_landcover_2010/MapServer/tile/{z}/{y}/{x}'
      })
    }),*/
    new ol.layer.Image({
      source: landcover
    })
  ],
  view: new ol.View({
    center: [-10812411.623547956, 5050417.912951814],
    zoom: 4
  })
});

/**
 * Generate controls
 */

$(function() {
  initializeChart();
  landcoverClasses.forEach(function(i) {
    $('#controls').append('
   ' + i.name + '
');
  });
  $('.legenditem').on('click', function(evt) {
    landcover.set('lc_class', $(this).data('color-id'));
    landcover.changed();

    scheduleStats({title: $(this).find('.legendname').text()});
  });
});

var timer = null;
function scheduleStats(stats,resolution) {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  timer = setTimeout(function(){ displayStats(stats,resolution) }, 1000);
}

function displayStats(stats,resolution){
  console.log("displaying stats");

  if(stats.total) $('#stats #total').text(area(resolution,stats.total) + " square miles");
  if(stats.classes){
    var chartData = [];
    var check = 0;
    stats.classes.forEach(function (lcaClass) {
      $('#class_'+lcaClass.id).find(".value").text(percent(lcaClass.count,stats.total)+ "%");
      check = check + percent(lcaClass.count,stats.total);
      chartData.push({
        name: lcaClass.name,
        y: percent(lcaClass.count,stats.total),
        color: rgbString(lcaClass.color)
      });
    });
    renderChart(chartData);
  }
//area(resolution,stats.class_total)
}

function percent(value,total){
  return Math.round((value * 100) / total);
}
function area(resolution, meterCounts){
  return ((resolution * resolution * meterCounts) * 3.8610216e-07).toFixed(2) ; //convert sq mt to sq mi
}

function rgbString(color) {
  return 'rgb(' + color[0] + ',' + color[1] + ',' + color[2] + ')';
}

function rgbaString(color) {
  return 'rgba(' + color[0] + ',' + color[1] + ',' + color[2] + ',' + color[3] + ')';
}

function initializeChart(){
  return $('#pieChart').highcharts({
          chart: {
              plotBackgroundColor: null,
              plotBorderWidth: null,
              plotShadow: false,
              type: 'pie'
          },
          title: {
              text: null
          },
          tooltip: {
              pointFormat: '{series.name}: {point.percentage:.1f}%'
          },
          plotOptions: {
              pie: {
                  allowPointSelect: true,
                  cursor: 'pointer',
                  dataLabels: {
                      enabled: true
                  }
              }
          },
          series: [{
            name: 'Classes',
            colorByPoint: true,
            data: []
        }]
      });
}

function renderChart(data){
  var chart = $("#pieChart").highcharts();
  chart.series[0].setData(data, true);
}<|endoftext|>