<commit_before>var assert = require('assert');
var sinon = require('sinon');
var support = require('../support');
var couchbase = main.couchbase.client(main.settings.couchbase.connection);

describe("lib/couchbase/client.js",  function () {
    var key;
    var val;
    var fake_err;

    beforeEach(function () {
        key = support.random.string();
        val = support.random.string();
    });

    afterEach(function (done) {
        couchbase.del(key, function () {
            done(); // ignore errors
        });
    });

    describe("set()",  function () {
        context("when key is null", function () {
            beforeEach(function () {
                key = null;
            });

            it("returns 'key invalid' error", function (done) {
                couchbase.set(key, val, function (err) {
                    assert.ok(err.message.match(/invalid key/i));

                    couchbase.get('null', function (err, result) {
                        assert.ifError(err);
                        assert.strictEqual(result, null);
                        done();
                    });
                });
            });
        });

        context("when key is a string", function () {
            it("returns the new record", function (done) {
                couchbase.set(key, val, function (err, result) {
                    assert.ifError(err);
                    assert.equal(result.value, val);
                    done();
                });
            });
        });

        context("when key is a number", function () {
            beforeEach(function () {
                key = support.random.number();
            });

            it("returns the new record", function (done) {
                couchbase.set(key, val, function (err, result) {
                    assert.ifError(err);
                    assert.equal(result.value, val);
                    done();
                });
            });
        });

        context("when value is an object", function () {
            beforeEach(function () {
                val = {foo: support.random.string()};
            });

            it("returns the object", function (done) {
                couchbase.set(key, val, function (err, result) {
                    assert.ifError(err);
                    assert.deepEqual(result.value, val);
                    done();
                });
            });
        });

        context("when connect() errors", function () {
            beforeEach(function () {
                fake_err = support.fake_error();
                sinon.stub(couchbase, 'connect', function (cb) {
                    cb(fake_err);
                });
            });

            afterEach(function () {
                couchbase.connect.restore();
            });

            it("calls back with the connection error", function (done) {
                couchbase.set(key, val, function (err) {
                    assert.equal(err, fake_err);
                    done();
                });
            });
        });

        context("when conn.set() errors", function () {
            beforeEach(function () {
                fake_err = support.fake_error();

                var fake_conn = {
                    set: function (key, value, meta, cb) {
                        cb(fake_err);
                    },

                    release: function () {}
                };

                sinon.stub(couchbase, 'connect', function (cb) {
                    cb(null, fake_conn);
                });
            });

            afterEach(function () {
                couchbase.connect.restore();
            });

            it("calls back with the error from set()", function (done) {
                couchbase.set(key, val, function (err) {
                    assert.equal(err, fake_err);
                    done();
                });
            });
        });

        context("when checking CAS", function () {
            context("and CAS changes", function () {
                it("calls back with an error", function (done) {
                    couchbase.set(key, val, function (err, first_meta) {
                        assert.ifError(err);
                        var new_val = support.random.string();

                        couchbase.set(key, new_val, function (err) {
                            assert.ifError(err);
                            var new_val2 = support.random.string();

                            couchbase.set(key, new_val2, first_meta, function (err) {
                                assert.equal(err.code, couchbase.CAS_ERROR_CODE);
                                done();
                            });
                        });
                    });
                });
            });
        });
    });

    describe("get()", function () {
        context("when record exists", function () {
            beforeEach(function (done) {
                couchbase.set(key, val, done);
            });

            it("returns the record", function (done) {
                couchbase.get(key, function (err, result) {
                    assert.ifError(err);
                    assert.deepEqual(result.value, val);
                    done();
                });
            });
        });

        context("when record does not exist", function () {
            it("returns null", function (done) {
                couchbase.get(key, function (err, result) {
                    assert.ifError(err);
                    assert.strictEqual(result, null);
                    done();
                });
            });
        });

        context("when connect() errors", function () {
            beforeEach(function () {
                fake_err = support.fake_error();
                sinon.stub(couchbase, 'connect', function (cb) {
                    cb(fake_err);
                });
            });

            afterEach(function () {
                couchbase.connect.restore();
            });

            it("calls back with the connection error", function (done) {
                couchbase.get(key, function (err) {
                    assert.equal(err, fake_err);
                    done();
                });
            });
        });
    });

    describe("del()", function () {
        context("when record exists", function () {
            beforeEach(function (done) {
                couchbase.set(key, val, done);
            });

            it("returns meta data", function (done) {
                couchbase.del(key, function (err, result) {
                    assert.ifError(err);
                    assert.ok(result.cas);
                    done();
                });
            });

            it("removes the record", function (done) {
                couchbase.del(key, function (err) {
                    assert.ifError(err);

                    couchbase.get(key, function (err, result) {
                        assert.ifError(err);
                        assert.strictEqual(result, null);
                        done();
                    });
                });
            });

            context("and record is a number", function () {
                beforeEach(function (done) {
                    key = support.random.number();
                    couchbase.set(key, val, done);
                });

                it("removes the record", function (done) {
                    couchbase.del(key, function (err) {
                        assert.ifError(err);

                        couchbase.get(key, function (err, result) {
                            assert.ifError(err);
                            assert.strictEqual(result, null);
                            done();
                        });
                    });
                });
            });

            context("and key is null", function () {
                beforeEach(function () {
                    key = null;
                });

                it("returns 'key is not a string' error", function (done) {
                    couchbase.del(key, function (err) {
                        assert.ok(err.message.match(/key is not a string/i));
                        done();
                    });
                });
            });
        });

        context("when record does not exist", function () {
            it("returns empty meta object", function (done) {
                couchbase.del(key, function (err, result) {
                    assert.ifError(err);
                    assert.deepEqual(result, {});
                    done();
                });
            });
        });

        context("when connect() errors", function () {
            beforeEach(function () {
                fake_err = support.fake_error();
                sinon.stub(couchbase, 'connect', function (cb) {
                    cb(fake_err);
                });
            });

            afterEach(function () {
                couchbase.connect.restore();
            });

            it("calls back with the connection error", function (done) {
                couchbase.del(key, function (err) {
                    assert.equal(err, fake_err);
                    done();
                });
            });
        });
    });

    describe("configure_views()", function () {
        it("calls conn.setDesignDoc() with each view config", function (done) {
            var fake_conn = {
                setDesignDoc: function (name, config, cb) {
                    cb(null, {});
                },

                release: function () {}
            };

            sinon.stub(couchbase, 'connect', function (cb) {
                cb(null, fake_conn);
            });

            sinon.spy(fake_conn, 'setDesignDoc');

            var view_config = {
                users: {
                    views: {
                        users: {
                            map: 'blah'
                        }
                    }
                },

                foo: {
                    views: {
                        bar: {
                            map: 'bar'
                        }
                    }
                }
            };

            couchbase.configure_views(view_config, function (err) {
                assert.ifError(err);
                assert.ok(fake_conn.setDesignDoc.calledWith('users', view_config.users));
                assert.ok(fake_conn.setDesignDoc.calledWith('foo', view_config.foo));

                fake_conn.setDesignDoc.restore();
                couchbase.connect.restore();
                done();
            });
        });

        context("when connect() errors", function () {
            beforeEach(function () {
                fake_err = support.fake_error();
                sinon.stub(couchbase, 'connect', function (cb) {
                    cb(fake_err);
                });
            });

            afterEach(function () {
                couchbase.connect.restore();
            });

            it("calls back with the connection error", function (done) {
                var view_config = {foo: 'bar'};

                couchbase.configure_views(view_config, function (err) {
                    assert.equal(err, fake_err);
                    done();
                });
            });
        });
    });
});
<commit_msg>making sure all test docs are removed at end of client tests<commit_after>var assert = require('assert');
var sinon = require('sinon');
var support = require('../support');
var couchbase = main.couchbase.client(main.settings.couchbase.connection);

describe("lib/couchbase/client.js",  function () {
    var key;
    var orig_key;
    var val;
    var fake_err;

    beforeEach(function () {
        key = support.random.string();
        orig_key = key;
        val = support.random.string();
    });

    afterEach(function (done) {
        couchbase.del(key, function () {
            couchbase.del(orig_key, function () {
                done(); // ignore errors
            });
        });
    });

    describe("set()",  function () {
        context("when key is null", function () {
            beforeEach(function () {
                key = null;
            });

            it("returns 'key invalid' error", function (done) {
                couchbase.set(key, val, function (err) {
                    assert.ok(err.message.match(/invalid key/i));

                    couchbase.get('null', function (err, result) {
                        assert.ifError(err);
                        assert.strictEqual(result, null);
                        done();
                    });
                });
            });
        });

        context("when key is a string", function () {
            it("returns the new record", function (done) {
                couchbase.set(key, val, function (err, result) {
                    assert.ifError(err);
                    assert.equal(result.value, val);
                    done();
                });
            });
        });

        context("when key is a number", function () {
            beforeEach(function () {
                key = support.random.number();
            });

            it("returns the new record", function (done) {
                couchbase.set(key, val, function (err, result) {
                    assert.ifError(err);
                    assert.equal(result.value, val);
                    done();
                });
            });
        });

        context("when value is an object", function () {
            beforeEach(function () {
                val = {foo: support.random.string()};
            });

            it("returns the object", function (done) {
                couchbase.set(key, val, function (err, result) {
                    assert.ifError(err);
                    assert.deepEqual(result.value, val);
                    done();
                });
            });
        });

        context("when connect() errors", function () {
            beforeEach(function () {
                fake_err = support.fake_error();
                sinon.stub(couchbase, 'connect', function (cb) {
                    cb(fake_err);
                });
            });

            afterEach(function () {
                couchbase.connect.restore();
            });

            it("calls back with the connection error", function (done) {
                couchbase.set(key, val, function (err) {
                    assert.equal(err, fake_err);
                    done();
                });
            });
        });

        context("when conn.set() errors", function () {
            beforeEach(function () {
                fake_err = support.fake_error();

                var fake_conn = {
                    set: function (key, value, meta, cb) {
                        cb(fake_err);
                    },

                    release: function () {}
                };

                sinon.stub(couchbase, 'connect', function (cb) {
                    cb(null, fake_conn);
                });
            });

            afterEach(function () {
                couchbase.connect.restore();
            });

            it("calls back with the error from set()", function (done) {
                couchbase.set(key, val, function (err) {
                    assert.equal(err, fake_err);
                    done();
                });
            });
        });

        context("when checking CAS", function () {
            context("and CAS changes", function () {
                it("calls back with an error", function (done) {
                    couchbase.set(key, val, function (err, first_meta) {
                        assert.ifError(err);
                        var new_val = support.random.string();

                        couchbase.set(key, new_val, function (err) {
                            assert.ifError(err);
                            var new_val2 = support.random.string();

                            couchbase.set(key, new_val2, first_meta, function (err) {
                                assert.equal(err.code, couchbase.CAS_ERROR_CODE);
                                done();
                            });
                        });
                    });
                });
            });
        });
    });

    describe("get()", function () {
        context("when record exists", function () {
            beforeEach(function (done) {
                couchbase.set(key, val, done);
            });

            it("returns the record", function (done) {
                couchbase.get(key, function (err, result) {
                    assert.ifError(err);
                    assert.deepEqual(result.value, val);
                    done();
                });
            });
        });

        context("when record does not exist", function () {
            it("returns null", function (done) {
                couchbase.get(key, function (err, result) {
                    assert.ifError(err);
                    assert.strictEqual(result, null);
                    done();
                });
            });
        });

        context("when connect() errors", function () {
            beforeEach(function () {
                fake_err = support.fake_error();
                sinon.stub(couchbase, 'connect', function (cb) {
                    cb(fake_err);
                });
            });

            afterEach(function () {
                couchbase.connect.restore();
            });

            it("calls back with the connection error", function (done) {
                couchbase.get(key, function (err) {
                    assert.equal(err, fake_err);
                    done();
                });
            });
        });
    });

    describe("del()", function () {
        context("when record exists", function () {
            beforeEach(function (done) {
                couchbase.set(key, val, done);
            });

            it("returns meta data", function (done) {
                couchbase.del(key, function (err, result) {
                    assert.ifError(err);
                    assert.ok(result.cas);
                    done();
                });
            });

            it("removes the record", function (done) {
                couchbase.del(key, function (err) {
                    assert.ifError(err);

                    couchbase.get(key, function (err, result) {
                        assert.ifError(err);
                        assert.strictEqual(result, null);
                        done();
                    });
                });
            });

            context("and record is a number", function () {
                beforeEach(function (done) {
                    key = support.random.number();
                    couchbase.set(key, val, done);
                });

                it("removes the record", function (done) {
                    couchbase.del(key, function (err) {
                        assert.ifError(err);

                        couchbase.get(key, function (err, result) {
                            assert.ifError(err);
                            assert.strictEqual(result, null);
                            done();
                        });
                    });
                });
            });

            context("and key is null", function () {
                it("returns 'key is not a string' error", function (done) {
                    couchbase.del(null, function (err) {
                        assert.ok(err.message.match(/key is not a string/i));
                        done();
                    });
                });
            });
        });

        context("when record does not exist", function () {
            it("returns empty meta object", function (done) {
                couchbase.del(key, function (err, result) {
                    assert.ifError(err);
                    assert.deepEqual(result, {});
                    done();
                });
            });
        });

        context("when connect() errors", function () {
            beforeEach(function () {
                fake_err = support.fake_error();
                sinon.stub(couchbase, 'connect', function (cb) {
                    cb(fake_err);
                });
            });

            afterEach(function () {
                couchbase.connect.restore();
            });

            it("calls back with the connection error", function (done) {
                couchbase.del(key, function (err) {
                    assert.equal(err, fake_err);
                    done();
                });
            });
        });
    });

    describe("configure_views()", function () {
        it("calls conn.setDesignDoc() with each view config", function (done) {
            var fake_conn = {
                setDesignDoc: function (name, config, cb) {
                    cb(null, {});
                },

                release: function () {}
            };

            sinon.stub(couchbase, 'connect', function (cb) {
                cb(null, fake_conn);
            });

            sinon.spy(fake_conn, 'setDesignDoc');

            var view_config = {
                users: {
                    views: {
                        users: {
                            map: 'blah'
                        }
                    }
                },

                foo: {
                    views: {
                        bar: {
                            map: 'bar'
                        }
                    }
                }
            };

            couchbase.configure_views(view_config, function (err) {
                assert.ifError(err);
                assert.ok(fake_conn.setDesignDoc.calledWith('users', view_config.users));
                assert.ok(fake_conn.setDesignDoc.calledWith('foo', view_config.foo));

                fake_conn.setDesignDoc.restore();
                couchbase.connect.restore();
                done();
            });
        });

        context("when connect() errors", function () {
            beforeEach(function () {
                fake_err = support.fake_error();
                sinon.stub(couchbase, 'connect', function (cb) {
                    cb(fake_err);
                });
            });

            afterEach(function () {
                couchbase.connect.restore();
            });

            it("calls back with the connection error", function (done) {
                var view_config = {foo: 'bar'};

                couchbase.configure_views(view_config, function (err) {
                    assert.equal(err, fake_err);
                    done();
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>(function(undefined){

var global = typeof module !== 'undefined' && module.exports
    ? module.exports
    : window;

var best = function(address) {
    // based on:
    // Javascript to test an IPv6 address for proper format, and to
    // present the "best text representation" according to IETF Draft RFC at
    // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
    // 8 Feb 2010 Rich Brown, Dartware, LLC
    // Please feel free to use this code as long as you provide a link to
    // http://www.intermapper.com
    // http://intermapper.com/support/tools/IPV6-Validator.aspx
    // http://download.dartware.com/thirdparty/ipv6validator.js

    var _address = address.toLowerCase(),
        segments = _address.split(':'),
        length = segments.length,
        total = 8;

    // trim colons (:: or ::a:b:c… or …a:b:c::)
    if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
        // must have been ::
        // remove first two items
        segments.shift();
        segments.shift();
    } else if (segments[0] === '' && segments[1] === '') {
        // must have been ::xxxx
        // remove the first item
        segments.shift();
    } else if (segments[length - 1] === '' && segments[length - 2] === '') {
        // must have been xxxx::
        segments.pop();
    }

    length = segments.length;

    // adjust total segments for IPv4 trailer
    if (segments[length - 1].indexOf('.') !== -1) {
        // found a "." which means IPv4
        total = 7;
    }

    // fill empty segments them with "0000"
    var pos;
    for (pos = 0; pos < length; pos++) {
        if (segments[pos] === '') {
            break;
        }
    }

    if (pos < total) {
        segments.splice(pos, 1, '0000');
        while (segments.length < total) {
            segments.splice(pos, 0, '0000');
        }

        length = segments.length;
    }

    // strip leading zeros
    var _segments;
    for (var i = 0; i < total; i++) {
        _segments = segments[i].split("");
        for (var j = 0; j < 3 ; j++) {
            if (_segments[0] === '0' && _segments.length > 1) {
                _segments.splice(0,1);
            } else {
                break;
            }
        }

        segments[i] = _segments.join("");
    }

    // find longest sequence of zeroes and coalesce them into one segment
    var best = -1,
        _best = 0,
        _current = 0,
        current = -1,
        inzeroes = false;
        // i; already declared

    for (i = 0; i < total; i++) {
        if (inzeroes) {
            if (segments[i] === '0') {
                _current += 1;
            } else {
                inzeroes = false;
                if (_current > _best) {
                    best = current;
                    _best = _current;
                }
            }
        } else {
            if (segments[i] == '0') {
                inzeroes = true;
                current = i;
                _current = 1;
            }
        }
    }

    if (_current > _best) {
        best = current;
        _best = _current;
    }

    if (_best > 1) {
        segments.splice(best, _best, "");
    }

    length = segments.length;

    // assemble remaining segments
    var result = '';
    if (segments[0] === '')  {
        beststr = ":";
    }

    for (i = 0; i < length; i++) {
        result += segments[i];
        if (i === length - 1) {
            break;
        }

        result += ':';
    }

    if (segments[length - 1] === '') {
        result += ":";
    }

    return result;
};

global.IPv6 = {
    best: best
};
})();

/*
var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156",
    _out = IPv6.best(_in),
    _expected = "fe80::204:61ff:fe9d:f156";

console.log(_in, _out, _expected, _out === _expected);
*/
<commit_msg>adding header<commit_after>/*
 * URL.js - Mutating URLs
 * IPv6 Support
 *
 * Version: 1.4.3
 *
 * Author: Rodney Rehm
 * Web: http://medialize.github.com/URI.js/
 *
 * Licensed under
 *   MIT License http://www.opensource.org/licenses/mit-license
 *   GPL v3 http://opensource.org/licenses/GPL-3.0
 *
 */

(function(undefined){

var global = typeof module !== 'undefined' && module.exports
    ? module.exports
    : window;

var best = function(address) {
    // based on:
    // Javascript to test an IPv6 address for proper format, and to
    // present the "best text representation" according to IETF Draft RFC at
    // http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
    // 8 Feb 2010 Rich Brown, Dartware, LLC
    // Please feel free to use this code as long as you provide a link to
    // http://www.intermapper.com
    // http://intermapper.com/support/tools/IPV6-Validator.aspx
    // http://download.dartware.com/thirdparty/ipv6validator.js

    var _address = address.toLowerCase(),
        segments = _address.split(':'),
        length = segments.length,
        total = 8;

    // trim colons (:: or ::a:b:c… or …a:b:c::)
    if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
        // must have been ::
        // remove first two items
        segments.shift();
        segments.shift();
    } else if (segments[0] === '' && segments[1] === '') {
        // must have been ::xxxx
        // remove the first item
        segments.shift();
    } else if (segments[length - 1] === '' && segments[length - 2] === '') {
        // must have been xxxx::
        segments.pop();
    }

    length = segments.length;

    // adjust total segments for IPv4 trailer
    if (segments[length - 1].indexOf('.') !== -1) {
        // found a "." which means IPv4
        total = 7;
    }

    // fill empty segments them with "0000"
    var pos;
    for (pos = 0; pos < length; pos++) {
        if (segments[pos] === '') {
            break;
        }
    }

    if (pos < total) {
        segments.splice(pos, 1, '0000');
        while (segments.length < total) {
            segments.splice(pos, 0, '0000');
        }

        length = segments.length;
    }

    // strip leading zeros
    var _segments;
    for (var i = 0; i < total; i++) {
        _segments = segments[i].split("");
        for (var j = 0; j < 3 ; j++) {
            if (_segments[0] === '0' && _segments.length > 1) {
                _segments.splice(0,1);
            } else {
                break;
            }
        }

        segments[i] = _segments.join("");
    }

    // find longest sequence of zeroes and coalesce them into one segment
    var best = -1,
        _best = 0,
        _current = 0,
        current = -1,
        inzeroes = false;
        // i; already declared

    for (i = 0; i < total; i++) {
        if (inzeroes) {
            if (segments[i] === '0') {
                _current += 1;
            } else {
                inzeroes = false;
                if (_current > _best) {
                    best = current;
                    _best = _current;
                }
            }
        } else {
            if (segments[i] == '0') {
                inzeroes = true;
                current = i;
                _current = 1;
            }
        }
    }

    if (_current > _best) {
        best = current;
        _best = _current;
    }

    if (_best > 1) {
        segments.splice(best, _best, "");
    }

    length = segments.length;

    // assemble remaining segments
    var result = '';
    if (segments[0] === '')  {
        beststr = ":";
    }

    for (i = 0; i < length; i++) {
        result += segments[i];
        if (i === length - 1) {
            break;
        }

        result += ':';
    }

    if (segments[length - 1] === '') {
        result += ":";
    }

    return result;
};

global.IPv6 = {
    best: best
};
})();

/*
var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156",
    _out = IPv6.best(_in),
    _expected = "fe80::204:61ff:fe9d:f156";

console.log(_in, _out, _expected, _out === _expected);
*/
<|endoftext|>


<commit_before>const EventEmitter = require('events');
const uuid = require('node-uuid');
const ItemType = require('./ItemType');

/**
 * @property {Area}    area        Area the item belongs to (warning: this is not the area is currently in but the
 *                                 area it belongs to on a fresh load)
 * @property {object}  attributes  Essentially a blob of whatever attrs the item designer wanted to add
 * @property {array|string}  behaviors Single or list of behaviors this object uses
 * @property {string}  description Long description seen when looking at it
 * @property {number}  id          vnum
 * @property {boolean} isEquipped  Whether or not item is currently equipped
 * @property {Map}     inventory   Current items this item contains
 * @property {boolean} isHeld      Whether or not item is currently in an inventory (npc, player, or another object)
 * @property {string}  name        Name shown in inventory and when equipped
 * @property {Room}    room        Room the item is currently in
 * @property {string}  roomDesc    Description shown when item is seen in a room
 * @property {string}  script      A custom script for this item
 * @property {ItemType|string} type
 * @property {string}  uuid        UUID differentiating all instances of this item
 */
class Item extends EventEmitter {
  constructor (area, item) {
    super();
    const validate = ['keywords', 'name', 'id'];

    for (const prop of validate) {
      if (!(prop in item)) {
        throw new ReferenceError(`Item in area [${area.name}] missing required property [${prop}]`)
      }
    }

    this.area = area;
    this.attributes  = item.attributes  || {};
    this.behaviors   = item.behaviors   || null;
    this.defaultInv  = item.defaultInv  || null;
    this.description = item.description || 'Nothing special.';
    this.id          = item.id;
    this.inventory   = item.inventory   || new Map();
    this.isEquipped  = item.isEquipped  || false;
    this.isHeld      = item.isHeld      || false;
    this.keywords    = item.keywords;
    this.name        = item.name;
    this.room        = item.room        || null;
    this.roomDesc    = item.roomDesc || '';
    this.script      = item.script      || null;
    this.type        = typeof item.type === 'string' ? ItemTypes.resolve(item.type) : (item.type || ItemType.OBJECT);
    this.uuid        = item.uuid        || uuid.v4();
  }

  getAttribute(attr) {
    return this.attributes[attr];
  }

  setAttribute(attr, val) {
    this.attributes[attr] = val;
  }

  hasKeyword(keyword) {
    return this.keywords.indexOf(keyword) !== -1;
  }

  addItem(item) {
    if (this.inventory === null) {
      this.inventory = new Map();
    }
    this.inventory.set(item.uuid, item);
  }

  removeItem(item) {
    this.inventory.delete(item.uuid);

    // if we removed the last item unset the inventory
    // This ensures that when it's reloaded it won't try to set
    // its default inventory. Instead it will persist the fact
    // that all the items were removed from it
    if (!this.inventory.size) {
      this.inventory = null;
    }
  }

  hydrate(state) {
    if (typeof this.area === 'string') {
      this.area = state.AreaManager.getArea(this.area);
    }
    // TODO: repopulate any stored items on save
    // this.inventory.doStuff();
  }

  serialize() {
    console.log(this.attributes);
    const data = {
      area: this.area.name,
      attributes: this.attributes,
      behaviors: this.behaviors,
      defaultInv: this.defaultInv,
      description: this.description,
      id: this.id,
      isEquipped: this.isEquipped,
      isHeld: this.isHeld,
      keywords: this.keywords,
      name: this.name,
      room: this.room ? this.room.id : null,
      roomDesc: this.roomDesc,
      script: this.script,
      type: this.type,
      uuid: this.uuid,
    };

    data.inventory = this.inventory ?
      Array.from(this.inventory.values()).map(item => item.serialize) :
      this.inventory
    ;

    console.log({ data });
    return data;
  }
}

module.exports = Item;
<commit_msg>Remove errant console.log<commit_after>const EventEmitter = require('events');
const uuid = require('node-uuid');
const ItemType = require('./ItemType');

/**
 * @property {Area}    area        Area the item belongs to (warning: this is not the area is currently in but the
 *                                 area it belongs to on a fresh load)
 * @property {object}  attributes  Essentially a blob of whatever attrs the item designer wanted to add
 * @property {array|string}  behaviors Single or list of behaviors this object uses
 * @property {string}  description Long description seen when looking at it
 * @property {number}  id          vnum
 * @property {boolean} isEquipped  Whether or not item is currently equipped
 * @property {Map}     inventory   Current items this item contains
 * @property {boolean} isHeld      Whether or not item is currently in an inventory (npc, player, or another object)
 * @property {string}  name        Name shown in inventory and when equipped
 * @property {Room}    room        Room the item is currently in
 * @property {string}  roomDesc    Description shown when item is seen in a room
 * @property {string}  script      A custom script for this item
 * @property {ItemType|string} type
 * @property {string}  uuid        UUID differentiating all instances of this item
 */
class Item extends EventEmitter {
  constructor (area, item) {
    super();
    const validate = ['keywords', 'name', 'id'];

    for (const prop of validate) {
      if (!(prop in item)) {
        throw new ReferenceError(`Item in area [${area.name}] missing required property [${prop}]`)
      }
    }

    this.area = area;
    this.attributes  = item.attributes  || {};
    this.behaviors   = item.behaviors   || null;
    this.defaultInv  = item.defaultInv  || null;
    this.description = item.description || 'Nothing special.';
    this.id          = item.id;
    this.inventory   = item.inventory   || new Map();
    this.isEquipped  = item.isEquipped  || false;
    this.isHeld      = item.isHeld      || false;
    this.keywords    = item.keywords;
    this.name        = item.name;
    this.room        = item.room        || null;
    this.roomDesc    = item.roomDesc || '';
    this.script      = item.script      || null;
    this.type        = typeof item.type === 'string' ? ItemTypes.resolve(item.type) : (item.type || ItemType.OBJECT);
    this.uuid        = item.uuid        || uuid.v4();
  }

  getAttribute(attr) {
    return this.attributes[attr];
  }

  setAttribute(attr, val) {
    this.attributes[attr] = val;
  }

  hasKeyword(keyword) {
    return this.keywords.indexOf(keyword) !== -1;
  }

  addItem(item) {
    if (this.inventory === null) {
      this.inventory = new Map();
    }
    this.inventory.set(item.uuid, item);
  }

  removeItem(item) {
    this.inventory.delete(item.uuid);

    // if we removed the last item unset the inventory
    // This ensures that when it's reloaded it won't try to set
    // its default inventory. Instead it will persist the fact
    // that all the items were removed from it
    if (!this.inventory.size) {
      this.inventory = null;
    }
  }

  hydrate(state) {
    if (typeof this.area === 'string') {
      this.area = state.AreaManager.getArea(this.area);
    }
    // TODO: repopulate any stored items on save
    // this.inventory.doStuff();
  }

  serialize() {
    const data = {
      area: this.area.name,
      attributes: this.attributes,
      behaviors: this.behaviors,
      defaultInv: this.defaultInv,
      description: this.description,
      id: this.id,
      isEquipped: this.isEquipped,
      isHeld: this.isHeld,
      keywords: this.keywords,
      name: this.name,
      room: this.room ? this.room.id : null,
      roomDesc: this.roomDesc,
      script: this.script,
      type: this.type,
      uuid: this.uuid,
    };

    data.inventory = this.inventory ?
      Array.from(this.inventory.values()).map(item => item.serialize) :
      this.inventory
    ;

    return data;
  }
}

module.exports = Item;
<|endoftext|>


<commit_before>//default language code, can be overwritten with lang parameter in URL
var lang = "en"; //for available codes see array availableLanguages in file GlobalOptions.js

//new namespace for QGIS extensions
//do not modify those three lines
if (!window.QGIS) {
    window.QGIS = {};
}

//Base URL for WMS server
var serverAndCGI = "http://localhost/cgi-bin/qgis_mapserv.fcgi";
//var serverAndCGI = "http://localhost/wms";

//search URLs
//URL for queries while typing
//at a later time QGIS server may provide query results, currently one needs a separate script
var searchBoxQueryURL = "/wsgi/search.wsgi?query=";
var searchBoxGetGeomURL = "/wsgi/getSearchGeom.wsgi";

//first part of titlebar text
var titleBarText = "GIS-Browser - "; // will be appended with project title

//EPSG projection code
var epsgcode = 4326;

// OpenLayers global options
// see http://dev.openlayers.org/releases/OpenLayers-2.10/doc/apidocs/files/OpenLayers/Map-js.html
var MapOptions = {
	projection: new OpenLayers.Projection("EPSG:"+epsgcode),
	units: "m",
	maxScale:50,
	minScale:40000,
	fractionalZoom: true,
	transitionEffect:"resize",
	controls: []
};

//overview map settings - do not change variable names!
var OverviewMapOptions = {
	projection: new OpenLayers.Projection("EPSG:"+epsgcode),
	units: "m",
	maxScale:50,
	minScale:250000,
	transitionEffect:"resize"
};
var OverviewMapSize = new OpenLayers.Size(200,200);
var overviewLayer = new OpenLayers.Layer.WMS("Pixelkarte",
			serverAndCGI + "/NaturalEarth",
			{layers:"HYP_50M_SR_W",format:"image/jpeg"},
			{buffer:0,singleTile:true,transitionEffect:"resize"});

//print options - scales and dpi
var printCapabilities={
    "scales":[
	{"name":"1:100","value":"100"},
	{"name":"1:200","value":"200"},
	{"name":"1:250","value":"250"},
	{"name":"1:500","value":"500"},
	{"name":"1:1'000","value":"1000"},
	{"name":"1:2'000","value":"2000"},
	{"name":"1:3'000","value":"3000"},
	{"name":"1:5'000","value":"5000"},
	{"name":"1:7'500","value":"7500"},
	{"name":"1:10'000","value":"10000"},
	{"name":"1:12'000","value":"12000"},
	{"name":"1:15'000","value":"15000"},
	{"name":"1:20'000","value":"20000"},
	{"name":"1:25'000","value":"25000"},
	{"name":"1:30'000","value":"30000"},
	{"name":"1:50'000","value":"50000"}
     ],
    "dpis":[
	{"name":"150 dpi","value":"150"},
	{"name":"300 dpi","value":"300"},
	{"name":"600 dpi","value":"600"},
	{"name":"1200 dpi","value":"1200"}
    ],
    "layouts":[]
};

//styling definitions for highlightLayer
//is used for hightlighting features (GetFeatureInfo and search result visualization)
//see http://dev.openlayers.org/releases/OpenLayers-2.10/doc/apidocs/files/OpenLayers/Style-js.html
var symbolizersHighLightLayer = {
	"Point": {
		pointRadius: 4,
		graphicName: "circle",
		fillColor: "#FF8C00",
		fillOpacity: 0.3,
		strokeWidth: 1,
		strokeColor: "#FF8C00"
	},
	"Line": {
		strokeWidth: 3,
		strokeOpacity: 1,
		strokeColor: "#FF8C00",
		strokeDashstyle: "dash"
	},
	"Polygon": {
		strokeWidth: 2,
		strokeColor: "#FF8C00",
		fillColor: "none"
	}
};

//styling for measure controls (distance and area)
var sketchSymbolizersMeasureControls = {
	"Point": {
		pointRadius: 4,
		graphicName: "square",
		fillColor: "#FFFFFF",
		fillOpacity: 1,
		strokeWidth: 1,
		strokeOpacity: 1,
		strokeColor: "#FF0000"
	},
	"Line": {
		strokeWidth: 3,
		strokeOpacity: 1,
		strokeColor: "#FF0000",
		strokeDashstyle: "dash"
	},
	"Polygon": {
		strokeWidth: 2,
		strokeOpacity: 1,
		strokeColor: "#FF0000",
		fillColor: "#FFFFFF",
		fillOpacity: 0.3
	}
};
<commit_msg>Omit host in CGI URL<commit_after>//default language code, can be overwritten with lang parameter in URL
var lang = "en"; //for available codes see array availableLanguages in file GlobalOptions.js

//new namespace for QGIS extensions
//do not modify those three lines
if (!window.QGIS) {
    window.QGIS = {};
}

//Base URL for WMS server
var serverAndCGI = "/cgi-bin/qgis_mapserv.fcgi";
//var serverAndCGI = "/wms";

//search URLs
//URL for queries while typing
//at a later time QGIS server may provide query results, currently one needs a separate script
var searchBoxQueryURL = "/wsgi/search.wsgi?query=";
var searchBoxGetGeomURL = "/wsgi/getSearchGeom.wsgi";

//first part of titlebar text
var titleBarText = "GIS-Browser - "; // will be appended with project title

//EPSG projection code
var epsgcode = 4326;

// OpenLayers global options
// see http://dev.openlayers.org/releases/OpenLayers-2.10/doc/apidocs/files/OpenLayers/Map-js.html
var MapOptions = {
	projection: new OpenLayers.Projection("EPSG:"+epsgcode),
	units: "m",
	maxScale:50,
	minScale:40000,
	fractionalZoom: true,
	transitionEffect:"resize",
	controls: []
};

//overview map settings - do not change variable names!
var OverviewMapOptions = {
	projection: new OpenLayers.Projection("EPSG:"+epsgcode),
	units: "m",
	maxScale:50,
	minScale:250000,
	transitionEffect:"resize"
};
var OverviewMapSize = new OpenLayers.Size(200,200);
var overviewLayer = new OpenLayers.Layer.WMS("Pixelkarte",
			serverAndCGI + "/NaturalEarth",
			{layers:"HYP_50M_SR_W",format:"image/jpeg"},
			{buffer:0,singleTile:true,transitionEffect:"resize"});

//print options - scales and dpi
var printCapabilities={
    "scales":[
	{"name":"1:100","value":"100"},
	{"name":"1:200","value":"200"},
	{"name":"1:250","value":"250"},
	{"name":"1:500","value":"500"},
	{"name":"1:1'000","value":"1000"},
	{"name":"1:2'000","value":"2000"},
	{"name":"1:3'000","value":"3000"},
	{"name":"1:5'000","value":"5000"},
	{"name":"1:7'500","value":"7500"},
	{"name":"1:10'000","value":"10000"},
	{"name":"1:12'000","value":"12000"},
	{"name":"1:15'000","value":"15000"},
	{"name":"1:20'000","value":"20000"},
	{"name":"1:25'000","value":"25000"},
	{"name":"1:30'000","value":"30000"},
	{"name":"1:50'000","value":"50000"}
     ],
    "dpis":[
	{"name":"150 dpi","value":"150"},
	{"name":"300 dpi","value":"300"},
	{"name":"600 dpi","value":"600"},
	{"name":"1200 dpi","value":"1200"}
    ],
    "layouts":[]
};

//styling definitions for highlightLayer
//is used for hightlighting features (GetFeatureInfo and search result visualization)
//see http://dev.openlayers.org/releases/OpenLayers-2.10/doc/apidocs/files/OpenLayers/Style-js.html
var symbolizersHighLightLayer = {
	"Point": {
		pointRadius: 4,
		graphicName: "circle",
		fillColor: "#FF8C00",
		fillOpacity: 0.3,
		strokeWidth: 1,
		strokeColor: "#FF8C00"
	},
	"Line": {
		strokeWidth: 3,
		strokeOpacity: 1,
		strokeColor: "#FF8C00",
		strokeDashstyle: "dash"
	},
	"Polygon": {
		strokeWidth: 2,
		strokeColor: "#FF8C00",
		fillColor: "none"
	}
};

//styling for measure controls (distance and area)
var sketchSymbolizersMeasureControls = {
	"Point": {
		pointRadius: 4,
		graphicName: "square",
		fillColor: "#FFFFFF",
		fillOpacity: 1,
		strokeWidth: 1,
		strokeOpacity: 1,
		strokeColor: "#FF0000"
	},
	"Line": {
		strokeWidth: 3,
		strokeOpacity: 1,
		strokeColor: "#FF0000",
		strokeDashstyle: "dash"
	},
	"Polygon": {
		strokeWidth: 2,
		strokeOpacity: 1,
		strokeColor: "#FF0000",
		fillColor: "#FFFFFF",
		fillOpacity: 0.3
	}
};
<|endoftext|>


<commit_before>'use strict';

var Harness = require('./support');
var Table = require(__dirname + '/../../lib/table');

var userWithSchema = Table.define({
  schema: 'staging',
  name: 'user',
  quote: true,
  columns: ['id', 'name']
});

Harness.test({
  query: userWithSchema.select(userWithSchema.id).from(userWithSchema),
  pg: {
    text  : 'SELECT "staging"."user"."id" FROM "staging"."user"',
    string: 'SELECT "staging"."user"."id" FROM "staging"."user"'
  },
  sqlite: {
    text  : 'SELECT "staging"."user"."id" FROM "staging"."user"',
    string: 'SELECT "staging"."user"."id" FROM "staging"."user"'
  },
  mysql: {
    text  : 'SELECT `staging`.`user`.`id` FROM `staging`.`user`',
    string: 'SELECT `staging`.`user`.`id` FROM `staging`.`user`'
  },
  params: []
});

Harness.test({
  query: userWithSchema.select(userWithSchema.id, userWithSchema.name).from(userWithSchema),
  pg: {
    text  : 'SELECT "staging"."user"."id", "staging"."user"."name" FROM "staging"."user"',
    string: 'SELECT "staging"."user"."id", "staging"."user"."name" FROM "staging"."user"'
  },
  sqlite: {
    text  : 'SELECT "staging"."user"."id", "staging"."user"."name" FROM "staging"."user"',
    string: 'SELECT "staging"."user"."id", "staging"."user"."name" FROM "staging"."user"'
  },
  mysql: {
    text  : 'SELECT `staging`.`user`.`id`, `staging`.`user`.`name` FROM `staging`.`user`',
    string: 'SELECT `staging`.`user`.`id`, `staging`.`user`.`name` FROM `staging`.`user`'
  },
  params: []
});

var uws = userWithSchema.as('uws');
Harness.test({
  query: uws.select(uws.name).from(uws),
  pg: {
    text  : 'SELECT "uws"."name" FROM "staging"."user" AS "uws"',
    string: 'SELECT "uws"."name" FROM "staging"."user" AS "uws"'
  },
  sqlite: {
    text  : 'SELECT "uws"."name" FROM "staging"."user" AS "uws"',
    string: 'SELECT "uws"."name" FROM "staging"."user" AS "uws"'
  },
  mysql: {
    text  : 'SELECT `uws`.`name` FROM `staging`.`user` AS `uws`',
    string: 'SELECT `uws`.`name` FROM `staging`.`user` AS `uws`'
  },
  params: []
});

var postWithSchema = Table.define({
  schema: 'dev',
  name: 'post',
  columns: ['id', 'userId', 'content']
});

Harness.test({
  query: userWithSchema.select(userWithSchema.name, postWithSchema.content).from(userWithSchema.join(postWithSchema).on(userWithSchema.id.equals(postWithSchema.userId))),
  pg: {
    text  : 'SELECT "staging"."user"."name", "dev"."post"."content" FROM "staging"."user" INNER JOIN "dev"."post" ON ("staging"."user"."id" = "dev"."post"."userId")',
    string: 'SELECT "staging"."user"."name", "dev"."post"."content" FROM "staging"."user" INNER JOIN "dev"."post" ON ("staging"."user"."id" = "dev"."post"."userId")'
  },
  sqlite: {
    text  : 'SELECT "staging"."user"."name", "dev"."post"."content" FROM "staging"."user" INNER JOIN "dev"."post" ON ("staging"."user"."id" = "dev"."post"."userId")',
    string: 'SELECT "staging"."user"."name", "dev"."post"."content" FROM "staging"."user" INNER JOIN "dev"."post" ON ("staging"."user"."id" = "dev"."post"."userId")'
  },
  mysql: {
    text  : 'SELECT `staging`.`user`.`name`, `dev`.`post`.`content` FROM `staging`.`user` INNER JOIN `dev`.`post` ON (`staging`.`user`.`id` = `dev`.`post`.`userId`)',
    string: 'SELECT `staging`.`user`.`name`, `dev`.`post`.`content` FROM `staging`.`user` INNER JOIN `dev`.`post` ON (`staging`.`user`.`id` = `dev`.`post`.`userId`)'
  },
  params: []
});

Harness.test({
  query: uws.select(uws.name, postWithSchema.content).from(uws.join(postWithSchema).on(uws.id.equals(postWithSchema.userId))),
  pg: {
    text  : 'SELECT "uws"."name", "dev"."post"."content" FROM "staging"."user" AS "uws" INNER JOIN "dev"."post" ON ("uws"."id" = "dev"."post"."userId")',
    string: 'SELECT "uws"."name", "dev"."post"."content" FROM "staging"."user" AS "uws" INNER JOIN "dev"."post" ON ("uws"."id" = "dev"."post"."userId")'
  },
  sqlite: {
    text  : 'SELECT "uws"."name", "dev"."post"."content" FROM "staging"."user" AS "uws" INNER JOIN "dev"."post" ON ("uws"."id" = "dev"."post"."userId")',
    string: 'SELECT "uws"."name", "dev"."post"."content" FROM "staging"."user" AS "uws" INNER JOIN "dev"."post" ON ("uws"."id" = "dev"."post"."userId")'
  },
  mysql: {
    text  : 'SELECT `uws`.`name`, `dev`.`post`.`content` FROM `staging`.`user` AS `uws` INNER JOIN `dev`.`post` ON (`uws`.`id` = `dev`.`post`.`userId`)',
    string: 'SELECT `uws`.`name`, `dev`.`post`.`content` FROM `staging`.`user` AS `uws` INNER JOIN `dev`.`post` ON (`uws`.`id` = `dev`.`post`.`userId`)'
  },
  params: []
});
<commit_msg>test for schema with aggregation<commit_after>'use strict';

var Harness = require('./support');
var Table = require(__dirname + '/../../lib/table');

var userWithSchema = Table.define({
  schema: 'staging',
  name: 'user',
  quote: true,
  columns: ['id', 'name']
});

Harness.test({
  query: userWithSchema.select(userWithSchema.id).from(userWithSchema),
  pg: {
    text  : 'SELECT "staging"."user"."id" FROM "staging"."user"',
    string: 'SELECT "staging"."user"."id" FROM "staging"."user"'
  },
  sqlite: {
    text  : 'SELECT "staging"."user"."id" FROM "staging"."user"',
    string: 'SELECT "staging"."user"."id" FROM "staging"."user"'
  },
  mysql: {
    text  : 'SELECT `staging`.`user`.`id` FROM `staging`.`user`',
    string: 'SELECT `staging`.`user`.`id` FROM `staging`.`user`'
  },
  params: []
});

Harness.test({
  query: userWithSchema.select(userWithSchema.id.count()).from(userWithSchema),
  pg: {
    text  : 'SELECT COUNT("staging"."user"."id") AS "id_count" FROM "staging"."user"',
    string: 'SELECT COUNT("staging"."user"."id") AS "id_count" FROM "staging"."user"'
  },
  sqlite: {
    text  : 'SELECT COUNT("staging"."user"."id") AS "id_count" FROM "staging"."user"',
    string: 'SELECT COUNT("staging"."user"."id") AS "id_count" FROM "staging"."user"'
  },
  mysql: {
    text  : 'SELECT COUNT(`staging`.`user`.`id`) AS `id_count` FROM `staging`.`user`',
    string: 'SELECT COUNT(`staging`.`user`.`id`) AS `id_count` FROM `staging`.`user`'
  },
  params: []
});

Harness.test({
  query: userWithSchema.select(userWithSchema.id, userWithSchema.name).from(userWithSchema),
  pg: {
    text  : 'SELECT "staging"."user"."id", "staging"."user"."name" FROM "staging"."user"',
    string: 'SELECT "staging"."user"."id", "staging"."user"."name" FROM "staging"."user"'
  },
  sqlite: {
    text  : 'SELECT "staging"."user"."id", "staging"."user"."name" FROM "staging"."user"',
    string: 'SELECT "staging"."user"."id", "staging"."user"."name" FROM "staging"."user"'
  },
  mysql: {
    text  : 'SELECT `staging`.`user`.`id`, `staging`.`user`.`name` FROM `staging`.`user`',
    string: 'SELECT `staging`.`user`.`id`, `staging`.`user`.`name` FROM `staging`.`user`'
  },
  params: []
});

var uws = userWithSchema.as('uws');
Harness.test({
  query: uws.select(uws.name).from(uws),
  pg: {
    text  : 'SELECT "uws"."name" FROM "staging"."user" AS "uws"',
    string: 'SELECT "uws"."name" FROM "staging"."user" AS "uws"'
  },
  sqlite: {
    text  : 'SELECT "uws"."name" FROM "staging"."user" AS "uws"',
    string: 'SELECT "uws"."name" FROM "staging"."user" AS "uws"'
  },
  mysql: {
    text  : 'SELECT `uws`.`name` FROM `staging`.`user` AS `uws`',
    string: 'SELECT `uws`.`name` FROM `staging`.`user` AS `uws`'
  },
  params: []
});

var postWithSchema = Table.define({
  schema: 'dev',
  name: 'post',
  columns: ['id', 'userId', 'content']
});

Harness.test({
  query: userWithSchema.select(userWithSchema.name, postWithSchema.content).from(userWithSchema.join(postWithSchema).on(userWithSchema.id.equals(postWithSchema.userId))),
  pg: {
    text  : 'SELECT "staging"."user"."name", "dev"."post"."content" FROM "staging"."user" INNER JOIN "dev"."post" ON ("staging"."user"."id" = "dev"."post"."userId")',
    string: 'SELECT "staging"."user"."name", "dev"."post"."content" FROM "staging"."user" INNER JOIN "dev"."post" ON ("staging"."user"."id" = "dev"."post"."userId")'
  },
  sqlite: {
    text  : 'SELECT "staging"."user"."name", "dev"."post"."content" FROM "staging"."user" INNER JOIN "dev"."post" ON ("staging"."user"."id" = "dev"."post"."userId")',
    string: 'SELECT "staging"."user"."name", "dev"."post"."content" FROM "staging"."user" INNER JOIN "dev"."post" ON ("staging"."user"."id" = "dev"."post"."userId")'
  },
  mysql: {
    text  : 'SELECT `staging`.`user`.`name`, `dev`.`post`.`content` FROM `staging`.`user` INNER JOIN `dev`.`post` ON (`staging`.`user`.`id` = `dev`.`post`.`userId`)',
    string: 'SELECT `staging`.`user`.`name`, `dev`.`post`.`content` FROM `staging`.`user` INNER JOIN `dev`.`post` ON (`staging`.`user`.`id` = `dev`.`post`.`userId`)'
  },
  params: []
});

Harness.test({
  query: uws.select(uws.name, postWithSchema.content).from(uws.join(postWithSchema).on(uws.id.equals(postWithSchema.userId))),
  pg: {
    text  : 'SELECT "uws"."name", "dev"."post"."content" FROM "staging"."user" AS "uws" INNER JOIN "dev"."post" ON ("uws"."id" = "dev"."post"."userId")',
    string: 'SELECT "uws"."name", "dev"."post"."content" FROM "staging"."user" AS "uws" INNER JOIN "dev"."post" ON ("uws"."id" = "dev"."post"."userId")'
  },
  sqlite: {
    text  : 'SELECT "uws"."name", "dev"."post"."content" FROM "staging"."user" AS "uws" INNER JOIN "dev"."post" ON ("uws"."id" = "dev"."post"."userId")',
    string: 'SELECT "uws"."name", "dev"."post"."content" FROM "staging"."user" AS "uws" INNER JOIN "dev"."post" ON ("uws"."id" = "dev"."post"."userId")'
  },
  mysql: {
    text  : 'SELECT `uws`.`name`, `dev`.`post`.`content` FROM `staging`.`user` AS `uws` INNER JOIN `dev`.`post` ON (`uws`.`id` = `dev`.`post`.`userId`)',
    string: 'SELECT `uws`.`name`, `dev`.`post`.`content` FROM `staging`.`user` AS `uws` INNER JOIN `dev`.`post` ON (`uws`.`id` = `dev`.`post`.`userId`)'
  },
  params: []
});
<|endoftext|>


<commit_before>window.ParsleyConfig = window.ParsleyConfig || {};

(function ($) {
  window.ParsleyConfig = $.extend( true, {}, window.ParsleyConfig, {
    validators: {
      minwords: function ( val, nbWords ) {
        val = val.replace( /(^\s*)|(\s*$)/gi, "" );
        val = val.replace( /[ ]{2,}/gi, " " );
        val = val.replace( /\n /, "\n" );
        val = val.split(' ').length;

        return val >= nbWords;
      }

      , maxwords : function ( val, nbWords ) {
        val = val.replace( /(^\s*)|(\s*$)/gi, "" );
        val = val.replace( /[ ]{2,}/gi, " " );
        val = val.replace( /\n /, "\n" );
        val = val.split(' ').length;

        return val <= nbWords;
      }

      , rangewords: function ( val, obj ) {
        val = val.replace( /(^\s*)|(\s*$)/gi, "" );
        val = val.replace( /[ ]{2,}/gi, " " );
        val = val.replace( /\n /, "\n" );
        val = val.split(' ').length;

        return val >= obj[0] && val <= obj[1];
      }

      , greaterthan: function ( val, elem, self ) {
        self.options.validateIfUnchanged = true;

        return new Number(val) > new Number($( elem ).val());
      }

      , lessthan: function ( val, elem, self ) {
        self.options.validateIfUnchanged = true;

        return new Number(val) < new Number($( elem ).val());
      }
    }
    , messages: {
        minwords:       "This value should have %s words at least."
      , maxwords:       "This value should have %s words maximum."
      , rangewords:     "This value should have between %s and %s words."
      , greaterthan:    "This value should be greater than %s."
      , lessthan:       "This value should be less than %s."
    }
  });
}(window.jQuery || window.Zepto));
<commit_msg>Added before date and after date validations.<commit_after>window.ParsleyConfig = window.ParsleyConfig || {};

(function ($) {
  window.ParsleyConfig = $.extend( true, {}, window.ParsleyConfig, {
    validators: {
      minwords: function ( val, nbWords ) {
        val = val.replace( /(^\s*)|(\s*$)/gi, "" );
        val = val.replace( /[ ]{2,}/gi, " " );
        val = val.replace( /\n /, "\n" );
        val = val.split(' ').length;

        return val >= nbWords;
      }

      , maxwords : function ( val, nbWords ) {
        val = val.replace( /(^\s*)|(\s*$)/gi, "" );
        val = val.replace( /[ ]{2,}/gi, " " );
        val = val.replace( /\n /, "\n" );
        val = val.split(' ').length;

        return val <= nbWords;
      }

      , rangewords: function ( val, obj ) {
        val = val.replace( /(^\s*)|(\s*$)/gi, "" );
        val = val.replace( /[ ]{2,}/gi, " " );
        val = val.replace( /\n /, "\n" );
        val = val.split(' ').length;

        return val >= obj[0] && val <= obj[1];
      }

      , greaterthan: function ( val, elem, self ) {
        self.options.validateIfUnchanged = true;

        return new Number(val) > new Number($( elem ).val());
      }

      , lessthan: function ( val, elem, self ) {
        self.options.validateIfUnchanged = true;

        return new Number(val) < new Number($( elem ).val());
      }

      , beforedate: function ( val, elem, self) {
        before_date = Date.parse(val);
        after_date = Date.parse($(elem).val());
        return before_date < after_date;
      }

      , afterdate: function ( val, elem, self) {
        after_date = Date.parse(val);
        before_date = Date.parse($(elem).val());
        return before_date < after_date;
      }
    }
    , messages: {
        minwords:       "This value should have %s words at least."
      , maxwords:       "This value should have %s words maximum."
      , rangewords:     "This value should have between %s and %s words."
      , greaterthan:    "This value should be greater than %s."
      , lessthan:       "This value should be less than %s."
      , beforedate:     "This date should be before %s."
      , afterdate:      "This date should be after %s."
    }
  });
}(window.jQuery || window.Zepto));
<|endoftext|>


<commit_before>import ngeoCustomEvent from 'ngeo/CustomEvent.js';
import * as olEvents from 'ol/events.js';
import olOverlay from 'ol/Overlay.js';
import olOverlayPositioning from 'ol/OverlayPositioning.js';

/**
 * The options for an action item for the contextual menu overlay.
 *
 * @typedef {Object} MenuActionOptions
 * @property {string} [cls] CSS class name(s) to use for the icon of the action item.
 * @property {string} [label] The label to display for the action item. If not defined, the name is used.
 * @property {string} name unique name for the menu action, which is used in the event fired when
 * the action is clicked.
 */

/**
 * The options for the contextual menu overlay.
 *
 * @typedef {Object} MenuOptions
 * @property {Array.<MenuActionOptions>} actions A list of menu actions.
 * @property {boolean} [autoClose=true] Whether to automatically close the contextual menu when an action is
 * clicked or not.
 * @property {string} [title] A title to display as header of the contextual menu.
 * }} MenuOptions
 */

/**
 * An OpenLayers overlay that shows a contextual menu with configurable actions
 * anchored from its top left to a specific location. An event is fired when
 * any of the action is clicked.
 */
export default class extends olOverlay {
  /**
   * @param {MenuOptions=} menuOptions Menu options.
   * @param {import('ol/Overlay.js').Options=} options Overlay options.
   */
  constructor(menuOptions, options = {}) {
    super(options);

    options.positioning = olOverlayPositioning.TOP_LEFT;

    /**
     * @type {Array.<import("ol/events.js").EventsKey>}
     * @private
     */
    this.listenerKeys_ = [];

    /**
     * @type {?import("ol/events.js").EventsKey}
     * @private
     */
    this.clickOutListenerKey_ = null;

    const contentEl = $('<div/>', {
      'class': 'panel panel-default'
    });

    /**
     * @type {boolean}
     * @private
     */
    this.autoClose_ = menuOptions.autoClose !== undefined ?
      menuOptions.autoClose : true;

    // titleEl
    if (menuOptions.title) {
      const headerEl = $('<div>', {
        'class': 'panel-heading'
      }).appendTo(contentEl);

      $('<span>', {
        text: menuOptions.title
      }).appendTo(headerEl);
    }

    // actionsEl
    const actionsEl = $('<div>', {
      'class': 'list-group'
    }).appendTo(contentEl);

    /**
     * @type {Array.<JQuery>}
     * @private
     */
    this.actions_ = [];

    menuOptions.actions.forEach((action) => {
      this.actions_.push(
        $('<button>', {
          'class': 'list-group-item btn',
          'data-name': action.name,
          'text': [
            ' ',
            (action.label) !== undefined ? action.label : action.name
          ].join('')
        })
          .appendTo(actionsEl)
          .prepend($('<span>', {
            'class': action.cls !== undefined ? action.cls : ''
          }))
      );
    });

    options.element = contentEl[0];
  }

  /**
   * @param {import("ol/PluggableMap.js").default|undefined} map Map.
   * @export
   * @override
   */
  setMap(map) {
    const currentMap = this.getMap();
    if (currentMap) {
      this.listenerKeys_.forEach(olEvents.unlistenByKey);
      this.listenerKeys_.length = 0;
    }

    olOverlay.prototype.setMap.call(this, map);

    if (map) {
      this.actions_.forEach((action) => {
        const data = action.data();
        this.listenerKeys_.push(
          olEvents.listen(
            action[0],
            'click',
            this.handleActionClick_.bind(this, data.name)
          )
        );
      });

      // Autoclose the menu when clicking anywhere else than the menu
      this.listenerKeys_.push(
        olEvents.listen(
          map,
          'pointermove',
          this.handleMapPointerMove_,
          this
        )
      );
    }
  }

  /**
   * Opens the menu at the desited coordinate. Also starts listening for the
   * clickout if autoClose is enabled.
   * @param {import("ol/coordinate.js").Coordinate} coordinate Where to open the menu.
   * @export
   */
  open(coordinate) {
    this.setPosition(coordinate);
    if (this.autoClose_) {
      this.clickOutListenerKey_ = olEvents.listen(
        document.documentElement,
        'mousedown',
        this.handleClickOut_,
        this
      );
    }
  }

  /**
   * @export
   */
  close() {
    this.setPosition(undefined);

    if (this.clickOutListenerKey_ !== null) {
      olEvents.unlistenByKey(this.clickOutListenerKey_);
    }
  }

  /**
   * @param {string} action The action name that was clicked.
   * @param {Event} evt Event.
   * @private
   */
  handleActionClick_(action, evt) {

    this.dispatchEvent(new ngeoCustomEvent('actionclick', {
      action: action
    }));

    if (this.autoClose_) {
      this.close();
    }

    evt.stopPropagation();
  }

  /**
   * Handles clicks out of the menu. If the menu is visible, close it.
   * @param {Event} evt Event.
   * @private
   */
  handleClickOut_(evt) {
    const element = this.getElement();
    if (element && $(evt.target).closest(element).length === 0) {
      this.close();
    }
  }

  /**
   * When the mouse is hovering the menu, set the event coordinate and pixel
   * values to Infinity to do as if the mouse had been move out of range of the
   * map. This prevents behaviours such as vertex still appearing while mouse
   * hovering edges of features bound to an active modify control while the
   * cursor is on top of the menu.
   * @param {import("ol/MapBrowserEvent.js").default} evt Event.
   * @private
   */
  handleMapPointerMove_(evt) {
    const target = evt.originalEvent.target;
    const element = this.getElement();
    if (target instanceof Element && element instanceof Element && element.contains(target)) {
      evt.coordinate = [Infinity, Infinity];
      evt.pixel = [Infinity, Infinity];
    }
  }
}
<commit_msg>Fix element setting in Menu<commit_after>import ngeoCustomEvent from 'ngeo/CustomEvent.js';
import * as olEvents from 'ol/events.js';
import olOverlay from 'ol/Overlay.js';
import olOverlayPositioning from 'ol/OverlayPositioning.js';

/**
 * The options for an action item for the contextual menu overlay.
 *
 * @typedef {Object} MenuActionOptions
 * @property {string} [cls] CSS class name(s) to use for the icon of the action item.
 * @property {string} [label] The label to display for the action item. If not defined, the name is used.
 * @property {string} name unique name for the menu action, which is used in the event fired when
 * the action is clicked.
 */

/**
 * The options for the contextual menu overlay.
 *
 * @typedef {Object} MenuOptions
 * @property {Array.<MenuActionOptions>} actions A list of menu actions.
 * @property {boolean} [autoClose=true] Whether to automatically close the contextual menu when an action is
 * clicked or not.
 * @property {string} [title] A title to display as header of the contextual menu.
 * }} MenuOptions
 */

/**
 * An OpenLayers overlay that shows a contextual menu with configurable actions
 * anchored from its top left to a specific location. An event is fired when
 * any of the action is clicked.
 */
export default class extends olOverlay {
  /**
   * @param {MenuOptions=} menuOptions Menu options.
   * @param {import('ol/Overlay.js').Options=} options Overlay options.
   */
  constructor(menuOptions, options = {}) {
    super(options);

    options.positioning = olOverlayPositioning.TOP_LEFT;

    /**
     * @type {Array.<import("ol/events.js").EventsKey>}
     * @private
     */
    this.listenerKeys_ = [];

    /**
     * @type {?import("ol/events.js").EventsKey}
     * @private
     */
    this.clickOutListenerKey_ = null;

    const contentEl = $('<div/>', {
      'class': 'panel panel-default'
    });

    /**
     * @type {boolean}
     * @private
     */
    this.autoClose_ = menuOptions.autoClose !== undefined ?
      menuOptions.autoClose : true;

    // titleEl
    if (menuOptions.title) {
      const headerEl = $('<div>', {
        'class': 'panel-heading'
      }).appendTo(contentEl);

      $('<span>', {
        text: menuOptions.title
      }).appendTo(headerEl);
    }

    // actionsEl
    const actionsEl = $('<div>', {
      'class': 'list-group'
    }).appendTo(contentEl);

    /**
     * @type {Array.<JQuery>}
     * @private
     */
    this.actions_ = [];

    menuOptions.actions.forEach((action) => {
      this.actions_.push(
        $('<button>', {
          'class': 'list-group-item btn',
          'data-name': action.name,
          'text': [
            ' ',
            (action.label) !== undefined ? action.label : action.name
          ].join('')
        })
          .appendTo(actionsEl)
          .prepend($('<span>', {
            'class': action.cls !== undefined ? action.cls : ''
          }))
      );
    });

    this.setElement(contentEl[0]);
  }

  /**
   * @param {import("ol/PluggableMap.js").default|undefined} map Map.
   * @export
   * @override
   */
  setMap(map) {
    const currentMap = this.getMap();
    if (currentMap) {
      this.listenerKeys_.forEach(olEvents.unlistenByKey);
      this.listenerKeys_.length = 0;
    }

    olOverlay.prototype.setMap.call(this, map);

    if (map) {
      this.actions_.forEach((action) => {
        const data = action.data();
        this.listenerKeys_.push(
          olEvents.listen(
            action[0],
            'click',
            this.handleActionClick_.bind(this, data.name)
          )
        );
      });

      // Autoclose the menu when clicking anywhere else than the menu
      this.listenerKeys_.push(
        olEvents.listen(
          map,
          'pointermove',
          this.handleMapPointerMove_,
          this
        )
      );
    }
  }

  /**
   * Opens the menu at the desited coordinate. Also starts listening for the
   * clickout if autoClose is enabled.
   * @param {import("ol/coordinate.js").Coordinate} coordinate Where to open the menu.
   * @export
   */
  open(coordinate) {
    this.setPosition(coordinate);
    if (this.autoClose_) {
      this.clickOutListenerKey_ = olEvents.listen(
        document.documentElement,
        'mousedown',
        this.handleClickOut_,
        this
      );
    }
  }

  /**
   * @export
   */
  close() {
    this.setPosition(undefined);

    if (this.clickOutListenerKey_ !== null) {
      olEvents.unlistenByKey(this.clickOutListenerKey_);
    }
  }

  /**
   * @param {string} action The action name that was clicked.
   * @param {Event} evt Event.
   * @private
   */
  handleActionClick_(action, evt) {

    this.dispatchEvent(new ngeoCustomEvent('actionclick', {
      action: action
    }));

    if (this.autoClose_) {
      this.close();
    }

    evt.stopPropagation();
  }

  /**
   * Handles clicks out of the menu. If the menu is visible, close it.
   * @param {Event} evt Event.
   * @private
   */
  handleClickOut_(evt) {
    const element = this.getElement();
    if (element && $(evt.target).closest(element).length === 0) {
      this.close();
    }
  }

  /**
   * When the mouse is hovering the menu, set the event coordinate and pixel
   * values to Infinity to do as if the mouse had been move out of range of the
   * map. This prevents behaviours such as vertex still appearing while mouse
   * hovering edges of features bound to an active modify control while the
   * cursor is on top of the menu.
   * @param {import("ol/MapBrowserEvent.js").default} evt Event.
   * @private
   */
  handleMapPointerMove_(evt) {
    const target = evt.originalEvent.target;
    const element = this.getElement();
    if (target instanceof Element && element instanceof Element && element.contains(target)) {
      evt.coordinate = [Infinity, Infinity];
      evt.pixel = [Infinity, Infinity];
    }
  }
}
<|endoftext|>


<commit_before>var MJS = {};

MJS.fakeGuid = function () {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }

    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};

function _emptyStringIfNull(obj) {
    try {
        return obj ? obj : "";
    } catch (ex) {

    }

    return "";
}

MJS.infoToGridHtml = function (info, options) {
    opt = {
        labelSize: 4,
        labelBold: true,
        labelClasses: "",
        rowClasses: "half-margin"
    }

    if (options) {
        if (options.labelSize && options.labelSize <= 11)
            opt.labelSize = options.labelSize;
        if (options.labelBold != undefined && typeof options.labelBold == "boolean")
            opt.labelBold = options.labelBold;
        if (options.labelClasses != undefined && typeof options.labelClasses == "string")
            opt.labelClasses = options.labelClasses;
    }

    var text = "";

    var labelTag = "b";
    var infoTag = "span";

    if (!opt.labelBold) {
        labelTag = "span";
    }

    $.each(info, function (i, o) {
        //if(i > 0) text += "
";

        text += "
";
        text += "
<" + labelTag + " class='" + opt.labelClasses + "'>" + o.label + "</" + labelTag + ">
";
        text += "
<" + infoTag + "'>" + o.info + "</" + infoTag + ">
";
        text += "
";
    });

    text += "
";

    return text;
};

MJS.buttonHtml = function (info) {
    if (!info)
        info = {};
    if (typeof info != "object") {
        toast("Error: MaterializeJS.buttonHtml - info must be an object!", 2500);
        return;
    }
    var res = "" + (info.icon_classes == null ? "" : "") + _emptyStringIfNull(info.text) + "";
    return res;
};

MJS.imageCardHtml = function (info) {
    var res = "
\n" + "
\n" + (info.image ? "
\n" : "") + "
\n" + "
\n" + "        " + info.title + "\n" + "
" + info.text + "
\n" + "
\n" +
	//"
\n" +
	//"        This is a link\n" +
	//"        This is a link\n" +
	//"
\n" +
	"
";
    return res;
};

MJS.plainPanelCardHtml = function (info) {
    var res = "
" + "" + _emptyStringIfNull(info.text) + " " + "
" + "
";
    return res;
};

MJS.revealCardHtml = function (id, title, image, info) {
    var res = "
" + "
" + (image ? "" : "") + "
" + "
" + "" + title + "" + "" +
	//"
This is a link
" +
	"
" + "
" + "" + title + "" + "
" + info + "
" + "
" + "
";
    return res;
};

MJS.makeCardDraggable = function (element) {

    var mc = new Hammer.Manager(element);

    mc.add(new Hammer.Pan({
        threshold: 0,
        pointers: 0
    }));
    mc.add(new Hammer.Swipe()).recognizeWith(mc.get('pan'));

    mc.on("panstart panmove", MaterializeJS.onCardDrag);
    mc.on("panend", MaterializeJS.onCardDragEnd);
};

MJS.makeCardsDraggable = function (selector) {

    $.each($(selector), function (i, o) {
        MaterializeJS.makeCardDraggable(o);
    });
};

// listen to events...
MJS.onCardDrag = function (ev) {
    // Get the events target element
    var elem = ev.target;

    // Make sure we work on the card instead of one of its childern
    if (!$(elem).hasClass(".card-panel")) {
        elem = $(elem).closest(".card-panel")[0];
    }

    $(elem).setTranslate2D(ev.deltaX, ev.deltaY);
    var pos = $(elem)[0].getBoundingClientRect();
    $("#posSpan").text("X: " + pos.left + " Y: " + pos.top);
};

MJS.onCardDragEnd = function (ev) {
    $("#posSpan").text("");

    // Get the events target element
    var elem = ev.target;

    // Make sure we work on the card instead of one of its children
    if (!$(elem).hasClass(".card-panel")) {
        elem = $(elem).closest(".card-panel")[0];
    }

    $(elem).velocity({
        translateX: ev.deltaX,
        translateY: ev.deltaY
    }, 1).velocity({
        translateX: 0,
        translateY: 0
    }, 500);
};

///////////////////////////////////////////////////////////////////
// MJS List Class /////////////////////////////////////////////////

MJS.list = function () {
    this.items = [];
    this.listIndex = 0;
    this.multiList = false;
    this.options = {
        ID: "MJS_list" + MJS.fakeGuid(),
        onSelect: null,
        selectedClasses: "grey white-text",
        itemClasses: "white grey-text text-darken-2"
    };
    this._element = null;
    this.onSelect = null;
};

// Todo List Label, and ID options

MJS.list.prototype.help = function () {
    var text  = "items format: \"[{text, value}, ...]\" for a single list\n";
        text += "items format: \"[{topic: \"\", items: [{text, value}, ...]}, ...]\" for a multi list";
    console.log(text);
    return text;
};

MJS.list.prototype.getElement = function () {
    return this._element;
};

MJS.list.prototype.clearSelection = function (text) {
    this._element.children().removeClass("active");
    this._element.children().removeClass(this.options.selectedClasses);
    this._element.children().addClass(this.options.itemClasses);
};

MJS.list.prototype.selectFirstItem = function (text) {
    this._element.children().first().click();
};

MJS.list.prototype.selectItemByText = function (text) {
    this._element.children().filter(function () {
        return $(this).text() == text
    }).click();
};

MJS.list.prototype.getSelectedText = function () {
    return this._element.children(".active").text();
};

// collection-header
MJS.list.prototype.buildHeader = function () {
	if(!this.multiList) return;

	var list    = this;
	var element = this.getElement();
	var header  = element.children(".collection-header");

	if(!header.length){
		header = $("");
		element.prepend(header);
	}

	header.empty();

	$.each(this.items, function (i, o) {
		if(i < list.listIndex){
			header.append("" + o.topic + "");
		}else if(i == list.listIndex){
			header.append("" + o.topic + "");
		}
	});
}

MJS.list.prototype.buildItems = function () {
    var list = this;
    var items;

    if (!this.multiList) {
        items = this.items;
    }
    else {
        items = this.items[this.listIndex].items;
    }

    $.each(items, function (i, o) {
        var itemElement = $("" + o.text + "");
        itemElement.click(function () {
            var o = $(this);

            //
            o.siblings().removeClass("active");
            o.siblings().removeClass(list.options.selectedClasses);
            o.siblings().addClass(list.options.itemClasses);

            //
            o.removeClass(list.options.itemClasses);
            o.addClass("active");
            o.addClass(list.options.selectedClasses);

            if (list.onSelect) list.onSelect();
        });
        list.getElement().append(itemElement);
    });
};

MJS.list.prototype.infoToList = function (info, options) {
    if (options) {
        if (options.selectedClasses != undefined && typeof options.selectedClasses == "string")
            this.options.selectedClasses = options.selectedClasses;
        if (options.itemClasses != undefined && typeof options.itemClasses == "string")
            this.options.itemClasses = options.itemClasses;
    }

    if (info.items) {
        this.items = info.items;
        this.multiList = false;
    }
    else if (info.length) {
        this.items = info;
        this.multiList = true;
    }

    // Create list element
    this._element = $("

");

    this.buildHeader();
    this.buildItems();

    this.clearSelection();
    return this.getElement();
};

///////////////////////////////////////////////////////////////////
// jQuery Plug-ins /////////////////////////////////////////////////

jQuery.fn.makeCardsDraggable = function (info) {
    $.each(this, function (i, o) {
        MaterializeJS.makeCardDraggable(o);
    });
};

jQuery.fn.addButton = function (info) {
    // It's your element
    var o = $(this[0]);

    newElement = $($.parseHTML(MaterializeJS.buttonHtml(info)));
    newElement.addClass("btn");
    newElement.addClass(_emptyStringIfNull(info.classes));
    newElement.attr("onclick", _emptyStringIfNull(info.onClick));
    newElement.width(info.width);
    o.append(newElement);
};

jQuery.fn.addImageCard = function (info) {
    var o = $(this[0]);
    // It's your element
    newElement = $($.parseHTML(MaterializeJS.imageCardHtml(info)));
    newElement.attr("onclick", _emptyStringIfNull(info.onclick));
    o.append(newElement);
};

jQuery.fn.addPlainPanelCard = function (info) {
    var o = $(this[0]);
    // It's your element
    newElement = $($.parseHTML(MaterializeJS.plainPanelCardHtml(info)));

    newElement.addClass(_emptyStringIfNull(info.classes));
    o.append(newElement);
};

jQuery.fn.setTranslate2D = function (x, y) {
    // It's your element
    var el = $(this[0])[0];

    var value = 'translateX(' + x + 'px) translateY(' + y + 'px)';

    //el.style.webkitTransform = value;
    //el.style.mozTransform = value;
    el.style.transform = value;
    ticking = false;
};

jQuery.fn.MaterializeJS_Data = function (info) {
    // Get the jQuery element
    var o = $(this[0]);

    // If the user passes data commit it to the element
    if (info) {
        o.data("MaterializeJS", info);
    }

        // Otherwise return the data from the element to the user
    else {
        var data = o.data("MaterializeJS");
        return data ? data : {};
    }
};

jQuery.fn.openNewDialogue = function (info) {
    // Get the jQuery element
    var o = $(this[0]);

    // Create div for the dialogue
    var newElement = $("

");

    // Add styling to the div
    // newElement.addClass("card-panel z-depth-3");
    newElement.height(info.fillTarget.height());
    newElement.width(info.fillTarget.width());
    newElement.css("background-color", o.css("background-color"));
    //newElement.css("border-radius", "500px");
    newElement.css("opacity", "0");
    newElement.css("margin", "0px");
    newElement.css("top", (o.offset().top + o.height() * 0.5 - newElement.height() * 0.5) + "px");
    newElement.css("left", (o.offset().left + o.width() * 0.5 - newElement.width() * 0.5) + "px");

    newElement.velocity({
        "scale": "0"
    }, 0);
    //newElement.velocity("finish");

    // Get MaterializeJS Data for the fill target
    var fData = info.fillTarget.MaterializeJS_Data();
    //debugger
    if (fData.currentDialogue) {
        fData.currentDialogue.closeDialogue(info);
    }

    // Add new div to the DOM
    $("body").append(newElement);
    if (info.onStart && typeof info.onStart == "function") {
        info.onStart(newElement);
    }

    // Set MaterializeJS Data for the fill target
    fData.currentDialogue = newElement;
    info.fillTarget.MaterializeJS_Data(fData);

    //
    var mData = newElement.MaterializeJS_Data();
    mData.origonalOffset = newElement.offset();
    newElement.MaterializeJS_Data(mData);

    newElement.velocity({
        top: info.fillTarget.offset().top + "px",
        left: info.fillTarget.offset().left + "px",
        opacity: 2,
        scale: 1
    }, 300, function () {
        newElement.addClass("card-panel z-depth-3");
    });
};

jQuery.fn.closeDialogue = function (info) {
    // It's your element
    var o = $(this[0]);

    var mData = o.MaterializeJS_Data();
    var returnOffset = mData.origonalOffset;

    o.removeClass("card-panel z-depth-3");

    // Get MaterializeJS Data for the fill target
    var fData = info.fillTarget.MaterializeJS_Data();

    if (fData.currentDialogue == o) {
        fData.currentDialogue = null;
        // Set MaterializeJS Data for the fill target
        info.fillTarget.MaterializeJS_Data(fData);
    }

    o.velocity({
        scale: "0",
        top: returnOffset.top + "px",
        left: returnOffset.left + "px"
    }, {
        duration: 300,
        /* Log all the animated divs. */
        complete: function () {
            o.remove();
        }
    });
};

MaterializeJS = MJS;
<commit_msg>Make list value & text fields configureable<commit_after>var MJS = {};

MJS.fakeGuid = function () {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }

    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};

function _emptyStringIfNull(obj) {
    try {
        return obj ? obj : "";
    } catch (ex) {

    }

    return "";
}

MJS.infoToGridHtml = function (info, options) {
    opt = {
        labelSize: 4,
        labelBold: true,
        labelClasses: "",
        rowClasses: "half-margin"
    }

    if (options) {
        if (options.labelSize && options.labelSize <= 11)
            opt.labelSize = options.labelSize;
        if (options.labelBold != undefined && typeof options.labelBold == "boolean")
            opt.labelBold = options.labelBold;
        if (options.labelClasses != undefined && typeof options.labelClasses == "string")
            opt.labelClasses = options.labelClasses;
    }

    var text = "";

    var labelTag = "b";
    var infoTag = "span";

    if (!opt.labelBold) {
        labelTag = "span";
    }

    $.each(info, function (i, o) {
        //if(i > 0) text += "
";

        text += "
";
        text += "
<" + labelTag + " class='" + opt.labelClasses + "'>" + o.label + "</" + labelTag + ">
";
        text += "
<" + infoTag + "'>" + o.info + "</" + infoTag + ">
";
        text += "
";
    });

    text += "
";

    return text;
};

MJS.buttonHtml = function (info) {
    if (!info)
        info = {};
    if (typeof info != "object") {
        toast("Error: MaterializeJS.buttonHtml - info must be an object!", 2500);
        return;
    }
    var res = "" + (info.icon_classes == null ? "" : "") + _emptyStringIfNull(info.text) + "";
    return res;
};

MJS.imageCardHtml = function (info) {
    var res = "
\n" + "
\n" + (info.image ? "
\n" : "") + "
\n" + "
\n" + "        " + info.title + "\n" + "
" + info.text + "
\n" + "
\n" +
	//"
\n" +
	//"        This is a link\n" +
	//"        This is a link\n" +
	//"
\n" +
	"
";
    return res;
};

MJS.plainPanelCardHtml = function (info) {
    var res = "
" + "" + _emptyStringIfNull(info.text) + " " + "
" + "
";
    return res;
};

MJS.revealCardHtml = function (id, title, image, info) {
    var res = "
" + "
" + (image ? "" : "") + "
" + "
" + "" + title + "" + "" +
	//"
This is a link
" +
	"
" + "
" + "" + title + "" + "
" + info + "
" + "
" + "
";
    return res;
};

MJS.makeCardDraggable = function (element) {

    var mc = new Hammer.Manager(element);

    mc.add(new Hammer.Pan({
        threshold: 0,
        pointers: 0
    }));
    mc.add(new Hammer.Swipe()).recognizeWith(mc.get('pan'));

    mc.on("panstart panmove", MaterializeJS.onCardDrag);
    mc.on("panend", MaterializeJS.onCardDragEnd);
};

MJS.makeCardsDraggable = function (selector) {

    $.each($(selector), function (i, o) {
        MaterializeJS.makeCardDraggable(o);
    });
};

// listen to events...
MJS.onCardDrag = function (ev) {
    // Get the events target element
    var elem = ev.target;

    // Make sure we work on the card instead of one of its childern
    if (!$(elem).hasClass(".card-panel")) {
        elem = $(elem).closest(".card-panel")[0];
    }

    $(elem).setTranslate2D(ev.deltaX, ev.deltaY);
    var pos = $(elem)[0].getBoundingClientRect();
    $("#posSpan").text("X: " + pos.left + " Y: " + pos.top);
};

MJS.onCardDragEnd = function (ev) {
    $("#posSpan").text("");

    // Get the events target element
    var elem = ev.target;

    // Make sure we work on the card instead of one of its children
    if (!$(elem).hasClass(".card-panel")) {
        elem = $(elem).closest(".card-panel")[0];
    }

    $(elem).velocity({
        translateX: ev.deltaX,
        translateY: ev.deltaY
    }, 1).velocity({
        translateX: 0,
        translateY: 0
    }, 500);
};

///////////////////////////////////////////////////////////////////
// MJS List Class /////////////////////////////////////////////////

MJS.list = function () {
    this.items = [];
  	this.textField = "text";
  	this.valueField = "value";
    this.listIndex = 0;
    this.multiList = false;
    this.options = {
        ID: "MJS_list" + MJS.fakeGuid(),
        onSelect: null,
        selectedClasses: "grey white-text",
        itemClasses: "white grey-text text-darken-2"
    };
    this._element = null;
    this.onSelect = null;
};

// Todo List Label, and ID options

MJS.list.prototype.help = function () {
    var text  = "items format: \"[{text, value}, ...]\" for a single list\n";
        text += "items format: \"[{topic: \"\", items: [{text, value}, ...]}, ...]\" for a multi list";
    console.log(text);
    return text;
};

MJS.list.prototype.getElement = function () {
    return this._element;
};

MJS.list.prototype.clearSelection = function (text) {
    this._element.children().removeClass("active");
    this._element.children().removeClass(this.options.selectedClasses);
    this._element.children().addClass(this.options.itemClasses);
};

MJS.list.prototype.selectFirstItem = function (text) {
    this._element.children().first().click();
};

MJS.list.prototype.selectItemByText = function (text) {
    this._element.children().filter(function () {
        return $(this).text() == text
    }).click();
};

MJS.list.prototype.getSelectedText = function () {
    return this._element.children(".active").text();
};

MJS.list.prototype.getSelectedValue = function () {
    return this._element.children(".active").data().value;
};

// collection-header
MJS.list.prototype.buildHeader = function () {
	if(!this.multiList) return;

	var list    = this;
	var element = this.getElement();
	var header  = element.children(".collection-header");

	if(!header.length){
		header = $("");
		element.prepend(header);
	}

	header.empty();

	$.each(this.items, function (i, o) {
		if(i < list.listIndex){
			header.append("" + o.topic + "");
		}else if(i == list.listIndex){
			header.append("" + o.topic + "");
		}
	});
}

MJS.list.prototype.buildItems = function () {
    var list = this;
    var items;

    if (!this.multiList) {
        items = this.items;
    }
    else {
        items = this.items[this.listIndex].items;
    }

    $.each(items, function (i, o) {
        var itemElement = $("" + o[list.textField] + "");
      	itemElement.data("value", o[list.valueField]);
        itemElement.click(function () {
            var o = $(this);

            //
            o.siblings().removeClass("active");
            o.siblings().removeClass(list.options.selectedClasses);
            o.siblings().addClass(list.options.itemClasses);

            //
            o.removeClass(list.options.itemClasses);
            o.addClass("active");
            o.addClass(list.options.selectedClasses);

            if (list.onSelect) list.onSelect();
        });
        list.getElement().append(itemElement);
    });
};

MJS.list.prototype.infoToList = function (info, options) {
    if (options) {
        if (options.selectedClasses != undefined && typeof options.selectedClasses == "string")
            this.options.selectedClasses = options.selectedClasses;
        if (options.itemClasses != undefined && typeof options.itemClasses == "string")
            this.options.itemClasses = options.itemClasses;
    }

    if (info.items) {
        this.items = info.items;
        this.multiList = false;
    }
    else if (info.length) {
        this.items = info;
        this.multiList = true;
    }

    // Create list element
    this._element = $("

");

    this.buildHeader();
    this.buildItems();

    this.clearSelection();
    return this.getElement();
};

///////////////////////////////////////////////////////////////////
// jQuery Plug-ins /////////////////////////////////////////////////

jQuery.fn.makeCardsDraggable = function (info) {
    $.each(this, function (i, o) {
        MaterializeJS.makeCardDraggable(o);
    });
};

jQuery.fn.addButton = function (info) {
    // It's your element
    var o = $(this[0]);

    newElement = $($.parseHTML(MaterializeJS.buttonHtml(info)));
    newElement.addClass("btn");
    newElement.addClass(_emptyStringIfNull(info.classes));
    newElement.attr("onclick", _emptyStringIfNull(info.onClick));
    newElement.width(info.width);
    o.append(newElement);
};

jQuery.fn.addImageCard = function (info) {
    var o = $(this[0]);
    // It's your element
    newElement = $($.parseHTML(MaterializeJS.imageCardHtml(info)));
    newElement.attr("onclick", _emptyStringIfNull(info.onclick));
    o.append(newElement);
};

jQuery.fn.addPlainPanelCard = function (info) {
    var o = $(this[0]);
    // It's your element
    newElement = $($.parseHTML(MaterializeJS.plainPanelCardHtml(info)));

    newElement.addClass(_emptyStringIfNull(info.classes));
    o.append(newElement);
};

jQuery.fn.setTranslate2D = function (x, y) {
    // It's your element
    var el = $(this[0])[0];

    var value = 'translateX(' + x + 'px) translateY(' + y + 'px)';

    //el.style.webkitTransform = value;
    //el.style.mozTransform = value;
    el.style.transform = value;
    ticking = false;
};

jQuery.fn.MaterializeJS_Data = function (info) {
    // Get the jQuery element
    var o = $(this[0]);

    // If the user passes data commit it to the element
    if (info) {
        o.data("MaterializeJS", info);
    }

        // Otherwise return the data from the element to the user
    else {
        var data = o.data("MaterializeJS");
        return data ? data : {};
    }
};

jQuery.fn.openNewDialogue = function (info) {
    // Get the jQuery element
    var o = $(this[0]);

    // Create div for the dialogue
    var newElement = $("

");

    // Add styling to the div
    // newElement.addClass("card-panel z-depth-3");
    newElement.height(info.fillTarget.height());
    newElement.width(info.fillTarget.width());
    newElement.css("background-color", o.css("background-color"));
    //newElement.css("border-radius", "500px");
    newElement.css("opacity", "0");
    newElement.css("margin", "0px");
    newElement.css("top", (o.offset().top + o.height() * 0.5 - newElement.height() * 0.5) + "px");
    newElement.css("left", (o.offset().left + o.width() * 0.5 - newElement.width() * 0.5) + "px");

    newElement.velocity({
        "scale": "0"
    }, 0);
    //newElement.velocity("finish");

    // Get MaterializeJS Data for the fill target
    var fData = info.fillTarget.MaterializeJS_Data();
    //debugger
    if (fData.currentDialogue) {
        fData.currentDialogue.closeDialogue(info);
    }

    // Add new div to the DOM
    $("body").append(newElement);
    if (info.onStart && typeof info.onStart == "function") {
        info.onStart(newElement);
    }

    // Set MaterializeJS Data for the fill target
    fData.currentDialogue = newElement;
    info.fillTarget.MaterializeJS_Data(fData);

    //
    var mData = newElement.MaterializeJS_Data();
    mData.origonalOffset = newElement.offset();
    newElement.MaterializeJS_Data(mData);

    newElement.velocity({
        top: info.fillTarget.offset().top + "px",
        left: info.fillTarget.offset().left + "px",
        opacity: 2,
        scale: 1
    }, 300, function () {
        newElement.addClass("card-panel z-depth-3");
    });
};

jQuery.fn.closeDialogue = function (info) {
    // It's your element
    var o = $(this[0]);

    var mData = o.MaterializeJS_Data();
    var returnOffset = mData.origonalOffset;

    o.removeClass("card-panel z-depth-3");

    // Get MaterializeJS Data for the fill target
    var fData = info.fillTarget.MaterializeJS_Data();

    if (fData.currentDialogue == o) {
        fData.currentDialogue = null;
        // Set MaterializeJS Data for the fill target
        info.fillTarget.MaterializeJS_Data(fData);
    }

    o.velocity({
        scale: "0",
        top: returnOffset.top + "px",
        left: returnOffset.left + "px"
    }, {
        duration: 300,
        /* Log all the animated divs. */
        complete: function () {
            o.remove();
        }
    });
};

MaterializeJS = MJS;
<|endoftext|>