<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013 Kevin Conway

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/*global require, define, module

*/
(function (ctx, factory) {
    "use strict";

    var env = factory.env,
        def = factory.def,
        deps = {
            amd: ['./node_modules/modelo/modelo.js', './node_modules/eventjs/event.js', './node_modules/deferjs/defer.js'],
            node: ['modelo', 'eventjs', 'deferjs'],
            browser: ['Modelo', 'Event', 'defer']
        };

    def.call(ctx, 'Deferred', deps[env], function (Modelo, Event, defer) {

        var Deferred,
            DeferredObject,
            PromiseObject,
            PromiseCollectionObject,
            callWithValue;

        // This specialized scope is used later on to allow function that are
        // executed asynchronously to be passed an input value.
        callWithValue = function (fn, value) {

            return function () {

                fn(value);

            };

        };

        // PromiseObjects in this context are specialized wrappers around
        // DeferredObjects that limit what actions can be performed on the
        // deferred. Basically the intent is to prevent the manipulation or
        // premature resolution/error of a deferred at runtime.
        //
        // Yes, I have read the proposed commonJS specification for promises.
        // I've purposefully chosen to break from the current proposals because
        // A) none of them are ratified yet and B) they all over complicate the
        // purpose of a promise.
        //
        // In this module, promises are simply limited interfaces to a deferred.
        // Promises do not expose a set of half-baked flow control functions.
        //
        // They simply allow interactions with a DeferredObject which is
        // documented below.
        PromiseObject = Modelo.define(function (options) {

            this.callback = function (fn) {
                options.deferred.callback(fn);
                return this;
            };
            this.done = this.callback;
            this.succeess = this.callback;

            this.errback = function (fn) {
                options.deferred.errback(fn);
                return this;
            };
            this.failure = this.errback;
            this.error = this.errback;

            this.resolved = function () {
                return options.deferred.resolved;
            };
            this.failed = function () {
                return options.deferred.failed;
            };
            this.completed = function () {
                return options.deferred.completed;
            };

            this.value = function () {
                return options.deferred.value;
            };

        });

        // Deferreds are another construct that tend to be over complicated.
        //
        // For example, in Twisted Python's implementation of a deferred
        // (http://twistedmatrix.com/documents/current/core/howto/defer.html#auto3)
        // the callbacks and errbacks registered with the deferred are called
        // in sequence and the choice of executing a callback or errback is
        // determined by the result of the previously executed callback or
        // errback. There may, indeed, be a million use cases for this type of
        // logic but they have mixed flow control with their deferred
        // implementation.
        //
        // In this module, deferreds do one thing only: represent a future
        // resource.
        //
        // When that resource is ready all callback functions are
        // executed asynchronously, in no given order, and with the resolved
        // value as a single input parameter.
        //
        // When that resource is failed to load all errback function are
        // executed asynchronously, in no given order, and with the error
        // that caused the failure as a single input parameter.
        DeferredObject = Event.extend(function (options) {

            this.callbacks = [];
            this.errbacks = [];
            this.resolved = false;
            this.failed = false;
            this.completed = false;

        });

        // This method, and its aliases `success` and `done`, can be used
        // to register a callbcak function with the deferred. All callbacks
        // registered using this method, or its aliases, are passed in a
        // single value as input. This input parameter is the resolved
        // value for the deferred.
        //
        // If the value of the deferred is unimportant to the callback
        // it can, alternatively, be bound to the `success` and `done`
        // events that are emitted.
        DeferredObject.prototype.callback = function (fn) {

            if (this.resolved === true) {
                defer(callWithValue(fn, this.value));
                return this;
            }

            if (typeof fn === "function") {
                this.callbacks.push(fn);
            }

            return this;

        };
        DeferredObject.prototype.succeess = DeferredObject.prototype.callback;
        DeferredObject.prototype.done = DeferredObject.prototype.callback;

        // This method, and its aliases `failure` and `error`, can be used
        // to register callbacks with the deferred that are executed when
        // an error is thrown. Callbacks registered using this method, and
        // its aliases, are passed a single input parameter that contains
        // the error that was thrown.
        //
        // If the value of the error is unimportant there is the option
        // of binding the callback to the `fail`, `failure`, and `error`
        // events that are triggered.
        DeferredObject.prototype.errback = function (fn) {

            if (this.failed === true) {
                defer(callWithValue(fn, this.value));
                return this;
            }

            if (typeof fn === "function") {
                this.errbacks.push(fn);
            }

            return this;

        };
        DeferredObject.prototype.failure = DeferredObject.prototype.errback;
        DeferredObject.prototype.error = DeferredObject.prototype.errback;

        // This method is used to mark the deferred as resolved and
        // to execute all the success callbacks registered. The value
        // passed to this method is the value that will be passed to
        // all callbacks.
        //
        // This method only triggers the callbacks once after which
        // neither it nor the `fail` method have any effect.
        DeferredObject.prototype.resolve = function (value) {

            var x;

            if (this.completed === true) {
                return this;
            }

            this.resolved = true;
            this.completed = true;
            this.value = value;

            for (x = 0; x < this.callbacks.length; x = x + 1) {

                defer(callWithValue(this.callbacks[x], value));

            }

            this.trigger('success').trigger('done');
            this.trigger('complete');

            return this;

        };

        // This method is used to mark the deferred as failed and
        // to execute all the failure errbacks registered. The error value
        // passed to this method is the value that will be passed to
        // all errbacks.
        //
        // This method only triggers the errbacks once after which
        // neither it nor the `resolve` method have any effect.
        DeferredObject.prototype.fail = function (value) {

            var x;

            if (this.completed === true) {
                return this;
            }

            this.failed = true;
            this.completed = true;
            this.value = value;

            for (x = 0; x < this.errbacks.length; x = x + 1) {

                defer(callWithValue(this.errbacks[x], value));

            }

            this.trigger('fail').trigger('failure').trigger('error');
            this.trigger('complete');

            return this;

        };

        // Deferreds should never be returned directly to avoid the potential
        // of runtime manipulation. Instead, return the value of this method
        // any time that you would normally want to return the deferred.
        DeferredObject.prototype.promise = function () {

            return new PromiseObject({"deferred": this});

        };

        // Admittedly, this construct borders on flow control. Promise
        // collections basically allow for the combination of multiple
        // promises into a single promise that resolved when all the contained
        // promises have been resolved. Likewise, the collection fails when
        // any of the contained promises fail.
        //
        // Unlike standard promises, the value passed to succes callbacks
        // are always object literals. These object literals contain key=>value
        // pairs of the values returned by the contained callbacks. The keys
        // are determined when the promises are given to the promise collection.
        //
        // For example, assume that p1, p2, and p3 are promises returned by
        // asynchronous functions that will be resolved to the values 1, 2, and
        // 3 respectively::
        //
        //      var collection = new PromiseCollectionObject({
        //          "p1": p1,
        //          "p2": p2,
        //          "p3": p3
        //      });
        //
        //      collection.callback(function (values) { console.log(values); });
        //
        //      // Some time later...
        //      // CONSOLE OUTPUT: {"p1": 1, "p2": 2, "p3": 3}
        PromiseCollectionObject = DeferredObject.extend(function (options) {

            this.promiseCollection = {};
            this.numberOfPromises = 0;
            this.numberOfResolvedPromises = 0;

            var x;

            for (x in options.promises) {

                if (options.promises.hasOwnProperty(x)) {

                    this.add(x, options.promises[x]);

                }

            }

        });

        // This method can be used to add promises to the collection after
        // the initial creation of the collection. As an important note,
        // it currently fails silently if you try to use it after the
        // the collection has already been resolved or failed.
        PromiseCollectionObject.prototype.add = function (key, promise) {

            this.promiseCollection[key] = promise;
            this.numberOfPromises = this.numberOfPromises + 1;

            var op = this;

            promise.callback(function (value) {

                var x,
                    finalValue = {};

                op.numberOfResolvedPromises = op.numberOfResolvedPromises + 1;

                if (op.numberOfResolvedPromises >= op.numberOfPromises) {

                    for (x in op.promiseCollection) {

                        if (op.promiseCollection.hasOwnProperty(x)) {

                            finalValue[x] = op.promiseCollection[x].value();

                        }

                    }

                    op.resolve(finalValue);

                }

            });

            promise.errback(function (err) {

                op.fail(err);

            });

            return this;

        };

        // This exposes an interface identical to a promise except
        // it adds the `add` method.
        PromiseCollectionObject.prototype.promise = function () {

            var promise = new PromiseObject({"deferred": this}),
                op = this;

            promise.add = function (key, value) {

                op.add(key, value);
                return this;

            };

            return promise;

        };

        // Similar to other modules in this package, the interface returned
        // by this module is a set of wrappers around the actual objects.
        //
        // In this case deferred objects can be created in any of the following
        // ways::
        //
        //      new Deferred();
        //      Deferred();
        //      new Deferred.Deferred();
        //      Deferred.Deferred();
        //
        // The choice comes down to style and preference.
        Deferred = function () {
            return new DeferredObject();
        };
        Deferred.Deferred = Deferred;

        // Deferred.Promise exposes a secondary interface for creating promises.
        // Using the `promise` method of a deferred and creating a new promise
        // object while passing in your deferred have the same effect.
        Deferred.Promise = function (d) {
            return new PromiseObject({"deferred": d});
        };

        // Expects a key=>value store of promises and outputs an extended
        // promise interface that contains the `add` method.
        Deferred.PromiseCollection = function (promises) {

            promises = promises || {};

            return new PromiseCollectionObject({"promises": promises}).promise();

        };

        return Deferred;

    });

}(this, (function (ctx) {
    "use strict";

    var currentEnvironment,
        generator;

    // Check the environment to determine the dependency management strategy.

    if (typeof define === "function" && !!define.amd) {

        currentEnvironment = 'amd';

    } else if (typeof require === "function" &&
                        module !== undefined && !!module.exports) {

        currentEnvironment = 'node';

    } else if (ctx.window !== undefined) {

        currentEnvironment = 'browser';

    }

    generator = (function () {
        switch (currentEnvironment) {

        case 'amd':

            // If RequireJS is used to load this module then return the global
            // define() function.
            return function (name, deps, mod) {
                define(deps, mod);
            };

        case 'node':

            // If this module is loaded in Node, require each of the
            // dependencies and pass them along.
            return function (name, deps, mod) {

                var x,
                    dep_list = [];

                for (x = 0; x < deps.length; x = x + 1) {

                    dep_list.push(require(deps[x]));

                }

                module.exports = mod.apply(ctx, dep_list);

            };

        case 'browser':

            // If this module is being used in a browser environment first
            // generate a list of dependencies, run the provided definition
            // function with the list of dependencies, and insert the returned
            // object into the global namespace using the provided module name.
            return function (name, deps, mod) {

                var namespaces = name.split('/'),
                    root = ctx,
                    dep_list = [],
                    current_scope,
                    current_dep,
                    i,
                    x;

                for (i = 0; i < deps.length; i = i + 1) {

                    current_scope = root;
                    current_dep = deps[i].split('/');

                    for (x = 0; x < current_dep.length; x = x + 1) {

                        current_scope = current_scope[current_dep[x]] || {};

                    }

                    dep_list.push(current_scope);

                }

                current_scope = root;
                for (i = 1; i < namespaces.length; i = i + 1) {

                    current_scope = current_scope[namespaces[i - 1]] =
                                    current_scope[namespaces[i - 1]] || {};

                }

                current_scope[namespaces[i - 1]] = mod.apply(ctx, dep_list);

            };

        default:
            throw new Error("Unrecognized environment.");

        }

    }());

    return {
        env: currentEnvironment,
        def: generator
    };

}(this))));
<commit_msg>Fix: JSLint errors and comment wording<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013 Kevin Conway

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/*global require, define, module

*/
(function (ctx, factory) {
    "use strict";

    var env = factory.env,
        def = factory.def,
        deps = {
            amd: ['./node_modules/modelo/modelo.js', './node_modules/eventjs/event.js', './node_modules/deferjs/defer.js'],
            node: ['modelo', 'eventjs', 'deferjs'],
            browser: ['Modelo', 'Event', 'defer']
        };

    def.call(ctx, 'Deferred', deps[env], function (Modelo, Event, defer) {

        var Deferred,
            DeferredObject,
            PromiseObject,
            PromiseCollectionObject,
            callWithValue;

        // This specialized scope is used later on to allow function that are
        // executed asynchronously to be passed an input value.
        callWithValue = function (fn, value) {

            return function () {

                fn(value);

            };

        };

        // PromiseObjects in this context are specialized wrappers around
        // DeferredObjects that limit what actions can be performed on the
        // deferred. Basically the intent is to prevent the manipulation or
        // premature resolution/error of a deferred at runtime.
        //
        // Yes, I have read the proposed commonJS specification for promises.
        // I've purposefully chosen to break from the current proposals because
        // A) none of them are ratified yet and B) they all over complicate the
        // purpose of a promise.
        //
        // In this module, promises are simply limited interfaces to a
        // deferred. Promises do not expose any form of flow control functions.
        //
        // They simply allow interactions with a DeferredObject which is
        // documented below.
        PromiseObject = Modelo.define(function (options) {

            this.callback = function (fn) {
                options.deferred.callback(fn);
                return this;
            };
            this.done = this.callback;
            this.succeess = this.callback;

            this.errback = function (fn) {
                options.deferred.errback(fn);
                return this;
            };
            this.failure = this.errback;
            this.error = this.errback;

            this.resolved = function () {
                return options.deferred.resolved;
            };
            this.failed = function () {
                return options.deferred.failed;
            };
            this.completed = function () {
                return options.deferred.completed;
            };

            this.value = function () {
                return options.deferred.value;
            };

        });

        // Deferreds are another construct that tend to be over complicated.
        //
        // For example, in Twisted Python's implementation of a deferred
        // (http://twistedmatrix.com/documents/current/core/howto/defer.html#auto3)
        // the callbacks and errbacks registered with the deferred are called
        // in sequence and the choice of executing a callback or errback is
        // determined by the result of the previously executed callback or
        // errback. There may, indeed, be a million use cases for this type of
        // logic but they have mixed flow control with their deferred
        // implementation.
        //
        // In this module, deferreds do one thing only: represent a future
        // resource.
        //
        // When that resource is ready all callback functions are
        // executed asynchronously, in no given order, and with the resolved
        // value as a single input parameter.
        //
        // When that resource is failed to load all errback function are
        // executed asynchronously, in no given order, and with the error
        // that caused the failure as a single input parameter.
        DeferredObject = Event.extend(function () {

            this.callbacks = [];
            this.errbacks = [];
            this.resolved = false;
            this.failed = false;
            this.completed = false;

        });

        // This method, and its aliases `success` and `done`, can be used
        // to register a callbcak function with the deferred. All callbacks
        // registered using this method, or its aliases, are passed in a
        // single value as input. This input parameter is the resolved
        // value for the deferred.
        //
        // If the value of the deferred is unimportant to the callback
        // it can, alternatively, be bound to the `success` and `done`
        // events that are emitted from the deferred.
        DeferredObject.prototype.callback = function (fn) {

            if (this.resolved === true) {
                defer(callWithValue(fn, this.value));
                return this;
            }

            if (typeof fn === "function") {
                this.callbacks.push(fn);
            }

            return this;

        };
        DeferredObject.prototype.succeess = DeferredObject.prototype.callback;
        DeferredObject.prototype.done = DeferredObject.prototype.callback;

        // This method, and its aliases `failure` and `error`, can be used
        // to register callbacks with the deferred that are executed when
        // an error is thrown. Callbacks registered using this method, and
        // its aliases, are passed a single input parameter that contains
        // the error that was thrown.
        //
        // If the value of the error is unimportant there is the option
        // of binding the callback to the `fail`, `failure`, and `error`
        // events that are triggered.
        DeferredObject.prototype.errback = function (fn) {

            if (this.failed === true) {
                defer(callWithValue(fn, this.value));
                return this;
            }

            if (typeof fn === "function") {
                this.errbacks.push(fn);
            }

            return this;

        };
        DeferredObject.prototype.failure = DeferredObject.prototype.errback;
        DeferredObject.prototype.error = DeferredObject.prototype.errback;

        // This method is used to mark the deferred as resolved and
        // to execute all the success callbacks registered. The value
        // passed to this method is the value that will be passed to
        // all callbacks.
        //
        // This method only triggers the callbacks once after which
        // neither it nor the `fail` method have any effect.
        DeferredObject.prototype.resolve = function (value) {

            var x;

            if (this.completed === true) {
                return this;
            }

            this.resolved = true;
            this.completed = true;
            this.value = value;

            for (x = 0; x < this.callbacks.length; x = x + 1) {

                defer(callWithValue(this.callbacks[x], value));

            }

            this.trigger('success').trigger('done');
            this.trigger('complete');

            return this;

        };

        // This method is used to mark the deferred as failed and
        // to execute all the failure errbacks registered. The error value
        // passed to this method is the value that will be passed to
        // all errbacks.
        //
        // This method only triggers the errbacks once after which
        // neither it nor the `resolve` method have any effect.
        DeferredObject.prototype.fail = function (value) {

            var x;

            if (this.completed === true) {
                return this;
            }

            this.failed = true;
            this.completed = true;
            this.value = value;

            for (x = 0; x < this.errbacks.length; x = x + 1) {

                defer(callWithValue(this.errbacks[x], value));

            }

            this.trigger('fail').trigger('failure').trigger('error');
            this.trigger('complete');

            return this;

        };

        // Deferreds should never be returned directly to avoid the potential
        // of runtime manipulation. Instead, return the value of this method
        // any time that you would normally want to return the deferred.
        DeferredObject.prototype.promise = function () {

            return new PromiseObject({"deferred": this});

        };

        // Admittedly, this construct borders on flow control. Promise
        // collections basically allow for the combination of multiple
        // promises into a single promise that resolves when all the contained
        // promises have been resolved. Likewise, the collection fails when
        // any of the contained promises fail.
        //
        // Unlike standard promises, the value passed to succes callbacks
        // are always object literals. These object literals contain key=>value
        // pairs of the values returned by the contained callbacks. The keys
        // are determined when the promises are given to the promise
        // collection.
        //
        // For example, assume that p1, p2, and p3 are promises returned by
        // asynchronous functions that will be resolved to the values 1, 2, and
        // 3 respectively::
        //
        //      var collection = new PromiseCollectionObject({
        //          "p1": p1,
        //          "p2": p2,
        //          "p3": p3
        //      });
        //
        //      collection.callback(function (values) { console.log(values); });
        //
        //      // Some time later...
        //      // CONSOLE OUTPUT: {"p1": 1, "p2": 2, "p3": 3}
        PromiseCollectionObject = DeferredObject.extend(function (options) {

            this.promiseCollection = {};
            this.numberOfPromises = 0;
            this.numberOfResolvedPromises = 0;

            var x;

            for (x in options.promises) {

                if (options.promises.hasOwnProperty(x)) {

                    this.add(x, options.promises[x]);

                }

            }

        });

        // This method can be used to add promises to the collection after
        // the initial creation of the collection. As an important note,
        // it currently fails silently if you try to use it after the
        // the collection has already been resolved or failed.
        PromiseCollectionObject.prototype.add = function (key, promise) {

            this.promiseCollection[key] = promise;
            this.numberOfPromises = this.numberOfPromises + 1;

            var op = this;

            promise.callback(function () {

                var x,
                    finalValue = {};

                op.numberOfResolvedPromises = op.numberOfResolvedPromises + 1;

                if (op.numberOfResolvedPromises >= op.numberOfPromises) {

                    for (x in op.promiseCollection) {

                        if (op.promiseCollection.hasOwnProperty(x)) {

                            finalValue[x] = op.promiseCollection[x].value();

                        }

                    }

                    op.resolve(finalValue);

                }

            });

            promise.errback(function (err) {

                op.fail(err);

            });

            return this;

        };

        // This exposes an interface identical to a promise except
        // it adds the `add` method.
        PromiseCollectionObject.prototype.promise = function () {

            var promise = new PromiseObject({"deferred": this}),
                op = this;

            promise.add = function (key, value) {

                op.add(key, value);
                return this;

            };

            return promise;

        };

        // Similar to other modules in this package, the interface returned
        // by this module is a set of wrappers around the actual objects.
        //
        // In this case deferred objects can be created in any of the following
        // ways::
        //
        //      new Deferred();
        //      Deferred();
        //      new Deferred.Deferred();
        //      Deferred.Deferred();
        //
        // The choice comes down to style and preference.
        Deferred = function () {
            return new DeferredObject();
        };
        Deferred.Deferred = Deferred;

        // Deferred.Promise exposes a secondary interface for creating promises.
        // Using the `promise` method of a deferred and creating a new promise
        // object while passing in your deferred have the same effect.
        Deferred.Promise = function (d) {
            return new PromiseObject({"deferred": d});
        };

        // Expects a key=>value store of promises and outputs an extended
        // promise interface that contains the `add` method.
        Deferred.PromiseCollection = function (promises) {

            promises = promises || {};

            return new PromiseCollectionObject({"promises": promises}).promise();

        };

        return Deferred;

    });

}(this, (function (ctx) {
    "use strict";

    var currentEnvironment,
        generator;

    // Check the environment to determine the dependency management strategy.

    if (typeof define === "function" && !!define.amd) {

        currentEnvironment = 'amd';

    } else if (typeof require === "function" &&
                        module !== undefined && !!module.exports) {

        currentEnvironment = 'node';

    } else if (ctx.window !== undefined) {

        currentEnvironment = 'browser';

    }

    generator = (function () {
        switch (currentEnvironment) {

        case 'amd':

            // If RequireJS is used to load this module then return the global
            // define() function.
            return function (name, deps, mod) {
                define(deps, mod);
            };

        case 'node':

            // If this module is loaded in Node, require each of the
            // dependencies and pass them along.
            return function (name, deps, mod) {

                var x,
                    dep_list = [];

                for (x = 0; x < deps.length; x = x + 1) {

                    dep_list.push(require(deps[x]));

                }

                module.exports = mod.apply(ctx, dep_list);

            };

        case 'browser':

            // If this module is being used in a browser environment first
            // generate a list of dependencies, run the provided definition
            // function with the list of dependencies, and insert the returned
            // object into the global namespace using the provided module name.
            return function (name, deps, mod) {

                var namespaces = name.split('/'),
                    root = ctx,
                    dep_list = [],
                    current_scope,
                    current_dep,
                    i,
                    x;

                for (i = 0; i < deps.length; i = i + 1) {

                    current_scope = root;
                    current_dep = deps[i].split('/');

                    for (x = 0; x < current_dep.length; x = x + 1) {

                        current_scope = current_scope[current_dep[x]] || {};

                    }

                    dep_list.push(current_scope);

                }

                current_scope = root;
                for (i = 1; i < namespaces.length; i = i + 1) {

                    current_scope = current_scope[namespaces[i - 1]] =
                                    current_scope[namespaces[i - 1]] || {};

                }

                current_scope[namespaces[i - 1]] = mod.apply(ctx, dep_list);

            };

        default:
            throw new Error("Unrecognized environment.");

        }

    }());

    return {
        env: currentEnvironment,
        def: generator
    };

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


<commit_before>/**
 * @ngdoc function
 * @name Plugin
 * @description
 * Plugin object, that can be loaded by mwc.loadPlugin
 */

/**
 * @ngdoc function
 * @name Plugin.name
 * @description
 * Unique (in the scope of project) plugin name
 * @type {string}
 */
exports.name = 'pluginExample';
/**
 * @ngdoc function
 * @name Plugin.dependencies
 * @description
 * Plugins, that are required to be loaded previously  - not implemented yet
 * @type {Array}
 */
exports.dependencies = ['mwc_plugin_foo','mwc_plugin_bar']; //we throw error it this plugins are not loaded in application

/**
 * @ngdoc function
 * @name Plugin.core
 * @type {object}
 * @description
 * Object, that will be supplied as argument to mwc.extencCore function
 * @example
 * ```javascript
 * exports.core = {
 *   'parameterOne': 1,
 *   'parameterTwo': [1, 2, 3, 4, 5],
 *   'parameterThree': {},
 *   'getSum': function (config) {
 *     return function (a, b) {
 *       return (a + b) * (config.multipyKoefficient);
 *     }
 *   }
 * };
 *
 * ```
 */
exports.core = {
  'parameterOne': 1,
  'parameterTwo': [1, 2, 3, 4, 5],
  'parameterThree': {},
  'getSum': function (config) {
    return function (a, b) {
      return (a + b) * (config.multipyKoefficient);
    }
  }
};

/**
 * @ngdoc function
 * @name Plugin.model
 * @type {object}
 * @description
 * Object, that will be supplied as argument to mwc.extendModel function
 * @example
 *```javascript
 * exports.model = {
 *  'Cats': function (mongoose, config) {
 *   var CatsSchema = new mongoose.Schema({
 *     'nickname': String
 *   });
 *
 *  return mongoose.model('cats', CatsSchema);
 * },
 * 'Dogs': function (mongoose, config) {
 *   var DogsSchema = new mongoose.Schema({
 *     'nickname': String
 *   });
 *  return mongoose.model('Dogs', DogsSchema);
 * }
 *};
 *```
 */
exports.model = {
  'Cats': function (mongoose, config) {
    var CatsSchema = new mongoose.Schema({
      'nickname': String
    });

    CatsSchema.index({
      nickname: 1
    });
    return mongoose.model('cats', CatsSchema);
  },

  'Dogs': function (mongoose, config) {
    var DogsSchema = new mongoose.Schema({
      'nickname': String
    });

    DogsSchema.index({
      nickname: 1
    });

    return mongoose.model('Dogs', DogsSchema);
  }
};

/**
 * @ngdoc function
 * @name Plugin.app
 * @type {function}
 * @description
 * Function, that will be supplied as argument to mwc.extendApp function
 * @example
 * ```javascript
 * exports.app = function (mwc) {
 *   mwc.app.set('someValue',42);
 * };
 * ```
 */
exports.app = function (mwc) {
  mwc.app.set('someValue',42);
};

var LinkedInStrategy = require('passport-linkedin').Strategy;

//sorry, only one(!) passportJS strategy per plugin!
exports.strategy = {
  'strategy': function (mwc) {
    return new LinkedInStrategy({
      consumerKey: mwc.config.passport.LINKEDIN_API_KEY,
      consumerSecret: mwc.config.passport.LINKEDIN_SECRET_KEY,
      callbackURL: mwc.config.hostUrl + 'auth/linkedin/callback'
    }, function (token, tokenSecret, profile, done) {
      console.log('==============');
      console.log(profile);
      console.log('==============');
      var email = profile.emails[0].value;
      if (email) {
        mwc.model.Users.processOAuthProfile(email, done);
      } else {
        return done(new Error('There is something strange instead of user profile'));
      }
    });
  },
  'routes': function (passport, core) {
    core.app.get('/auth/linkedin', passport.authenticate('linkedin'), function (req, res) {
    });
    core.app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/' }),
      function (req, res) {
        res.redirect('/');
      });
  }
};

//the most hard to understand function
//because middleware conception is tricky and it do need the core object, for example,
// in this way or maybe in some other way. But it do need the core!!!
//for simplicity of code of plugin all middlewares are setted to all enviroments and are mounted to path /
exports.middleware = [
  function (mwc) {
    return function (request, response, next) {
      request.model.Cats.count({name: 'Grumpy'}, function (err, numberOfCats) {
        if (numberOfCats > core.parameterOne) {
          request.getSum = core.getSum; //DI of core methods or values
          next();
        } else {
          response.send(500, 'There is not enough cats called "Grumpy" to run this application!');
        }
      });
    };
  },
  function (mwc) {
    return function (request, response, next) {
      request.model.Dogs.count({name: 'Strelka'}, function (err, numberOfDogs) {
        if (numberOfDogs > core.parameterOne) {
          request.getSum = core.getSum; //DI of core methods or values
          next();
        } else {
          response.send(500, 'There is not enough Dogs called "Strelka" to run this application!');
        }
      });
    };
  }
];

/**
 * @ngdoc function
 * @name Plugin.routes
 * @type {function}
 * @description
 * Extend appliction routes, sends the value as argument to a function mwc.extendRoutes
 * @example
 * ```javascript
 *  exports.routes = function(mwc){
 *   mwc.app.get('/kittens',function(request,response){
 *     request.model.Cats.find({},function(err,cats){
 *       if(err) throw err;
 *       response.json(cats);
 *     });
 *   });
 *
 *   mwc.app.get('/dogs',function(request,response){
 *     request.model.Dogs.find({},function(err,dogs){
 *       if(err) throw err;
 *       response.json(dogs);
 *     });
 *   });
 * };
 * ```
 */
exports.routes = function(mwc){
  mwc.app.get('/kittens',function(request,response){
    request.model.Cats.find({},function(err,cats){
      if(err) throw err;
      response.json(cats);
    });
  });

  mwc.app.get('/dogs',function(request,response){
    request.model.Dogs.find({},function(err,dogs){
      if(err) throw err;
      response.json(dogs);
    });
  });
};

/**
 * @ngdoc function
 * @name Plugin.listeners
 * @type {object}
 * @description
 * Object, that will be supplied as argument to mwc.extendListeners function
 * Field names are the vent types, values are function called against this events
 * @example
 * ```javascript
 *  exports.listeners = {
 *  'panic': function (panic) {
 *   console.log(alert);
 *  }
 * };
 * ```
 */
exports.listeners = {
  'alert': function (panic) {
    console.log(panic);
  }
};

<commit_msg>[documentation] - example of plugin<commit_after>/**
 * @ngdoc function
 * @name Plugin
 * @description
 * Plugin object, that can be loaded by mwc.loadPlugin
 * @example
 * ```javascript
 * exports.name ='testPlugin333';
 *
 * exports.core = {
 *   'parameterOne': 1,
 *   'parameterTwo': [1, 2, 3, 4, 5],
 *   'parameterThree': {},
 *   'getSum': function (config) {
 *     return function (a, b) {
 *       return (a + b) * (config.multipyKoefficient);
 *     }
 *   }
 * };
 *
 * exports.model = {
 *   'Cats': function (mongoose, config) {
 *    var CatsSchema = new mongoose.Schema({
 *      'nickname': String
 *    });
 *
 *   return mongoose.model('cats', CatsSchema);
 *  },
 *  'Dogs': function (mongoose, config) {
 *    var DogsSchema = new mongoose.Schema({
 *      'nickname': String
 *    });
 *   return mongoose.model('Dogs', DogsSchema);
 *  }
 * };
 *
 * exports.app = function (mwc) {
 *   mwc.app.set('someValue',42);
 * };
 *
 *  exports.routes = function(mwc){
 *   mwc.app.get('/kittens',function(request,response){
 *     request.model.Cats.find({},function(err,cats){
 *       if(err) throw err;
 *       response.json(cats);
 *     });
 *   });
 *
 *   mwc.app.get('/dogs',function(request,response){
 *     request.model.Dogs.find({},function(err,dogs){
 *       if(err) throw err;
 *       response.json(dogs);
 *     });
 *   });
 * };
 *  exports.listeners = {
 *  'panic': function (panic) {
 *   console.log(alert);
 *  }
 * };
 * ```
 */

/**
 * @ngdoc function
 * @name Plugin.name
 * @description
 * Unique (in the scope of project) plugin name
 * @type {string}
 */
exports.name = 'pluginExample';
/**
 * @ngdoc function
 * @name Plugin.dependencies
 * @description
 * Plugins, that are required to be loaded previously  - not implemented yet
 * @type {Array}
 */
exports.dependencies = ['mwc_plugin_foo','mwc_plugin_bar']; //we throw error it this plugins are not loaded in application

/**
 * @ngdoc function
 * @name Plugin.core
 * @type {object}
 * @description
 * Object, that will be supplied as argument to mwc.extencCore function
 * @example
 * ```javascript
 * exports.core = {
 *   'parameterOne': 1,
 *   'parameterTwo': [1, 2, 3, 4, 5],
 *   'parameterThree': {},
 *   'getSum': function (config) {
 *     return function (a, b) {
 *       return (a + b) * (config.multipyKoefficient);
 *     }
 *   }
 * };
 * ```
 */
exports.core = {
  'parameterOne': 1,
  'parameterTwo': [1, 2, 3, 4, 5],
  'parameterThree': {},
  'getSum': function (config) {
    return function (a, b) {
      return (a + b) * (config.multipyKoefficient);
    }
  }
};

/**
 * @ngdoc function
 * @name Plugin.model
 * @type {object}
 * @description
 * Object, that will be supplied as argument to mwc.extendModel function
 * @example
 *```javascript
 * exports.model = {
 *  'Cats': function (mongoose, config) {
 *   var CatsSchema = new mongoose.Schema({
 *     'nickname': String
 *   });
 *
 *  return mongoose.model('cats', CatsSchema);
 * },
 * 'Dogs': function (mongoose, config) {
 *   var DogsSchema = new mongoose.Schema({
 *     'nickname': String
 *   });
 *  return mongoose.model('Dogs', DogsSchema);
 * }
 *};
 *```
 */
exports.model = {
  'Cats': function (mongoose, config) {
    var CatsSchema = new mongoose.Schema({
      'nickname': String
    });

    CatsSchema.index({
      nickname: 1
    });
    return mongoose.model('cats', CatsSchema);
  },

  'Dogs': function (mongoose, config) {
    var DogsSchema = new mongoose.Schema({
      'nickname': String
    });

    DogsSchema.index({
      nickname: 1
    });

    return mongoose.model('Dogs', DogsSchema);
  }
};

/**
 * @ngdoc function
 * @name Plugin.app
 * @type {function}
 * @description
 * Function, that will be supplied as argument to mwc.extendApp function
 * @example
 * ```javascript
 * exports.app = function (mwc) {
 *   mwc.app.set('someValue',42);
 * };
 * ```
 */
exports.app = function (mwc) {
  mwc.app.set('someValue',42);
};

var LinkedInStrategy = require('passport-linkedin').Strategy;

//sorry, only one(!) passportJS strategy per plugin!
exports.strategy = {
  'strategy': function (mwc) {
    return new LinkedInStrategy({
      consumerKey: mwc.config.passport.LINKEDIN_API_KEY,
      consumerSecret: mwc.config.passport.LINKEDIN_SECRET_KEY,
      callbackURL: mwc.config.hostUrl + 'auth/linkedin/callback'
    }, function (token, tokenSecret, profile, done) {
      console.log('==============');
      console.log(profile);
      console.log('==============');
      var email = profile.emails[0].value;
      if (email) {
        mwc.model.Users.processOAuthProfile(email, done);
      } else {
        return done(new Error('There is something strange instead of user profile'));
      }
    });
  },
  'routes': function (passport, core) {
    core.app.get('/auth/linkedin', passport.authenticate('linkedin'), function (req, res) {
    });
    core.app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/' }),
      function (req, res) {
        res.redirect('/');
      });
  }
};

//the most hard to understand function
//because middleware conception is tricky and it do need the core object, for example,
// in this way or maybe in some other way. But it do need the core!!!
//for simplicity of code of plugin all middlewares are setted to all enviroments and are mounted to path /
exports.middleware = [
  function (mwc) {
    return function (request, response, next) {
      request.model.Cats.count({name: 'Grumpy'}, function (err, numberOfCats) {
        if (numberOfCats > core.parameterOne) {
          request.getSum = core.getSum; //DI of core methods or values
          next();
        } else {
          response.send(500, 'There is not enough cats called "Grumpy" to run this application!');
        }
      });
    };
  },
  function (mwc) {
    return function (request, response, next) {
      request.model.Dogs.count({name: 'Strelka'}, function (err, numberOfDogs) {
        if (numberOfDogs > core.parameterOne) {
          request.getSum = core.getSum; //DI of core methods or values
          next();
        } else {
          response.send(500, 'There is not enough Dogs called "Strelka" to run this application!');
        }
      });
    };
  }
];

/**
 * @ngdoc function
 * @name Plugin.routes
 * @type {function}
 * @description
 * Extend appliction routes, sends the value as argument to a function mwc.extendRoutes
 * @example
 * ```javascript
 *  exports.routes = function(mwc){
 *   mwc.app.get('/kittens',function(request,response){
 *     request.model.Cats.find({},function(err,cats){
 *       if(err) throw err;
 *       response.json(cats);
 *     });
 *   });
 *
 *   mwc.app.get('/dogs',function(request,response){
 *     request.model.Dogs.find({},function(err,dogs){
 *       if(err) throw err;
 *       response.json(dogs);
 *     });
 *   });
 * };
 * ```
 */
exports.routes = function(mwc){
  mwc.app.get('/kittens',function(request,response){
    request.model.Cats.find({},function(err,cats){
      if(err) throw err;
      response.json(cats);
    });
  });

  mwc.app.get('/dogs',function(request,response){
    request.model.Dogs.find({},function(err,dogs){
      if(err) throw err;
      response.json(dogs);
    });
  });
};

/**
 * @ngdoc function
 * @name Plugin.listeners
 * @type {object}
 * @description
 * Object, that will be supplied as argument to mwc.extendListeners function
 * Field names are the vent types, values are function called against this events
 * @example
 * ```javascript
 *  exports.listeners = {
 *  'panic': function (panic) {
 *   console.log(alert);
 *  }
 * };
 * ```
 */
exports.listeners = {
  'alert': function (panic) {
    console.log(panic);
  }
};

<|endoftext|>


<commit_before>var win = Titanium.UI.currentWindow;

//We load our state data, this is a big file...
var meta = require('poly_meta');
//Bring the module into the example
var map = require('bencoding.map');

var bClearMap = Ti.UI.createButton({
	title:'Clear Map', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

win.setRightNavButton(bClearMap);

//Remove all polygons added
bClearMap.addEventListener('click', function(){
	mapView.removeAllPolygons();
});

//Create mapView
//We support all of the same functions the native Ti.Map.View does
var mapView = map.createView({
	mapType: Ti.Map.STANDARD_TYPE,
	animate:true,
	userLocation:true,
	userTrackingMode:{
		animated: true,
		mode: 2
	}
});

mapView.setUserTrackingMode({
		animated: true,
		mode: 2
	});

//Add to Window
win.add(mapView);

var bZoomIn = Ti.UI.createButton({
	title:'+', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

var bZoomOut = Ti.UI.createButton({
	title:'-', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

bZoomIn.addEventListener('click',function() {
	mapView.zoom(1);
});

bZoomOut.addEventListener('click',function() {
	mapView.zoom(-1);
});

var zoomControl = Titanium.UI.iOS.createToolbar({
	items:[bZoomIn,bZoomOut],
	top:0,width:70,left:0, borderRadius:5,
	borderTop:true, borderBottom:false, translucent:true
});
win.add(zoomControl);

var flexSpace = Ti.UI.createButton({ systemButton:Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE });

var bAddUK = Ti.UI.createButton({
	title:'+ UK', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

var bRemoveUK = Ti.UI.createButton({
	title:'- UK', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

bAddUK.addEventListener('click',function() {
	var ukData = meta.ukPolygons();
	var iLength = ukData.length; //Should be 50 unless something changed...

	//Now we start looping...
	for (var iLoop=0;iLoop<iLength;iLoop++){
		mapView.addPolygon(ukData[iLoop]);
	}
});

bRemoveUK.addEventListener('click',function() {
	//UK is a multi part polygon
	//But, since we use the title to delete the polygon
	//We just need to pass in any part to remove the polygon from the map
	var poly = { title:'United Kingdom' };
	mapView.removePolygon(poly);
});

var bAddNY = Ti.UI.createButton({
	title:'+ NY', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

bAddNY.addEventListener('click',function() {
	var iLength = meta.statesPolygons.states.length; //Should be 50 unless something changed...

	//Now we start looping...until we find NY
	for (var iLoop=0;iLoop<iLength;iLoop++){
		if(meta.statesPolygons.states[iLoop].title=='New York'){
			mapView.addPolygon(meta.statesPolygons.states[iLoop]);
			break;
		}
	}
});

var bRemoveNY = Ti.UI.createButton({
	title:'- NY', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

bRemoveNY.addEventListener('click',function() {
	//Provide title of the polygon to be deleted
	var poly = { title:'New York' };
	mapView.removePolygon(poly);
});

var bAddStates = Ti.UI.createButton({
	title:'+ States', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

//Load each state as a polgyon
bAddStates.addEventListener('click', function(){
	//This is just a demo, please don't try this in your production apps....
	var iLength = meta.statesPolygons.states.length; //Should be 50 unless something changed...

	//Now we start looping...
	for (var iLoop=0;iLoop<iLength;iLoop++){
		Ti.API.info("Adding State " + meta.statesPolygons.states[iLoop].title);
		mapView.addPolygon(meta.statesPolygons.states[iLoop]);
	}
});

var bottomToolbar = Ti.UI.iOS.createToolbar({
	items:[bAddStates,bAddNY,bRemoveNY,bAddUK,bRemoveUK],
	bottom:0
});
win.add(bottomToolbar);

mapView.addEventListener("userTrackingMode", function(e){
	alert("Mode: " + e.mode);
});

setTimeout(function() {
	mapView.setUserTrackingMode({
		animated: true,
		mode: 2
	});
	alert("timeout");
}, 5000);

<commit_msg>Revert example/polygon_sample.js to its original state.<commit_after>var win = Titanium.UI.currentWindow;

//We load our state data, this is a big file...
var meta = require('poly_meta');
//Bring the module into the example
var map = require('bencoding.map');

var bClearMap = Ti.UI.createButton({
	title:'Clear Map', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

win.setRightNavButton(bClearMap);

//Remove all polygons added
bClearMap.addEventListener('click', function(){
	mapView.removeAllPolygons();
});

//Create mapView
//We support all of the same functions the native Ti.Map.View does
var mapView = map.createView({
	mapType: Ti.Map.STANDARD_TYPE,
	animate:true,
	userLocation:true
});

//Add to Window
win.add(mapView);

var bZoomIn = Ti.UI.createButton({
	title:'+', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

var bZoomOut = Ti.UI.createButton({
	title:'-', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

bZoomIn.addEventListener('click',function() {
	mapView.zoom(1);
});

bZoomOut.addEventListener('click',function() {
	mapView.zoom(-1);
});

var zoomControl = Titanium.UI.iOS.createToolbar({
	items:[bZoomIn,bZoomOut],
	top:0,width:70,left:0, borderRadius:5,
	borderTop:true, borderBottom:false, translucent:true
});
win.add(zoomControl);

var flexSpace = Ti.UI.createButton({ systemButton:Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE });

var bAddUK = Ti.UI.createButton({
	title:'+ UK', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

var bRemoveUK = Ti.UI.createButton({
	title:'- UK', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

bAddUK.addEventListener('click',function() {
	var ukData = meta.ukPolygons();
	var iLength = ukData.length; //Should be 50 unless something changed...

	//Now we start looping...
	for (var iLoop=0;iLoop<iLength;iLoop++){
		mapView.addPolygon(ukData[iLoop]);
	}
});

bRemoveUK.addEventListener('click',function() {
	//UK is a multi part polygon
	//But, since we use the title to delete the polygon
	//We just need to pass in any part to remove the polygon from the map
	var poly = { title:'United Kingdom' };
	mapView.removePolygon(poly);
});

var bAddNY = Ti.UI.createButton({
	title:'+ NY', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

bAddNY.addEventListener('click',function() {
	var iLength = meta.statesPolygons.states.length; //Should be 50 unless something changed...

	//Now we start looping...until we find NY
	for (var iLoop=0;iLoop<iLength;iLoop++){
		if(meta.statesPolygons.states[iLoop].title=='New York'){
			mapView.addPolygon(meta.statesPolygons.states[iLoop]);
			break;
		}
	}
});

var bRemoveNY = Ti.UI.createButton({
	title:'- NY', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

bRemoveNY.addEventListener('click',function() {
	//Provide title of the polygon to be deleted
	var poly = { title:'New York' };
	mapView.removePolygon(poly);
});

var bAddStates = Ti.UI.createButton({
	title:'+ States', style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
});

//Load each state as a polgyon
bAddStates.addEventListener('click', function(){
	//This is just a demo, please don't try this in your production apps....
	var iLength = meta.statesPolygons.states.length; //Should be 50 unless something changed...

	//Now we start looping...
	for (var iLoop=0;iLoop<iLength;iLoop++){
		Ti.API.info("Adding State " + meta.statesPolygons.states[iLoop].title);
		mapView.addPolygon(meta.statesPolygons.states[iLoop]);
	}
});

var bottomToolbar = Ti.UI.iOS.createToolbar({
	items:[bAddStates,bAddNY,bRemoveNY,bAddUK,bRemoveUK],
	bottom:0
});
win.add(bottomToolbar);
<|endoftext|>


<commit_before>import RL from "../../src/relayer.js"
import {Module, Injector, Config} from "a1atscript";

class Chapter extends RL.Resource {
}

RL.Describe(Chapter, (desc) => {
  desc.hasOne("section", Section);
  desc.hasOne("act", Act);
});

class Act extends RL.Resource {
}

RL.Describe(Act, (desc) => {
  desc.hasOne("book", Book, {});
  desc.hasList("chapters", Chapter, []);
});

class Section extends RL.Resource {
}

RL.Describe(Section, (desc) => {
  desc.property("title", "");
  desc.property("kind", "");
  desc.property("resolution", "")
  var chapter = desc.hasOne("chapter", Chapter);
  chapter.initializeOnCreate = false;
  var book = desc.hasOne("book", Book);
  book.initializeOnCreate = true;
  var paragraphs = desc.hasList("paragraphs", Paragraph)
  paragraphs.initializeOnCreate = false;
});

class Paragraph extends RL.Resource {

}

RL.Describe(Paragraph, (desc) => {
  desc.property("kind", "");
  desc.property("body", "");
  desc.hasOne("book", Book)
  desc.hasOne("section", Section);
  desc.hasList("characters", Character);
});

class Character extends RL.Resource {

}

RL.Describe(Character, (desc) => {
  desc.property("name", "")
  desc.hasOne("book", Book);
});

class Book extends RL.Resource {
}

RL.Describe(Book, (desc) => {
  desc.property("title", "");
  desc.hasList("acts", Act, []);
  desc.hasList("sections", Section, []);
  //desc.hasOne("owner", User, {});
  var characters = desc.hasList("characters", Character, []);
  characters.canCreate = true;
});

class Resources extends RL.Resource {
}

RL.Describe(Resources, (desc) => {
  var books = desc.hasList("books", Book, [])
  books.linkTemplate = "book";
  books.canCreate = true;
});

// this is horrible -- no easy way to get Babel and Traceur to compile the same config block
class AppConfig {
  @Config("relayerProvider")
  setupResources(relayerProvider) {
    relayerProvider.createApi("resources", Resources, "http://www.example.com/resources")
  }
}

var AppModule = new Module("AppModule", [RL, AppConfig.prototype]);

describe("initialization", function() {
  var section;
  beforeEach(function() {
    section = new Section();
  });

  it("should not initialize relationships when initializeOnCreate is false", function() {
    expect(section.relationships).toEqual({book: jasmine.any(Book)});
  });
});

describe("Loading relationships test", function() {
  var resources, book, act, chapter, chapters, section, paragraph, character, $httpBackend, $rootScope;

  beforeEach(function () {
    var injector = new Injector();
    injector.instantiate(AppModule);
    angular.mock.module('AppModule');

    var mockHttp = function(Promise, params) {
      if (params.url == "http://www.example.com/resources") {
        return Promise.resolve({
          status: 200,
          headers() {
            return {
              ETag: "1348"
            }
          },
          data: {
            data: {},
            links: {
              books: "/books",
              book: "/books/{id}"
            }
          }
        });
      } else if (params.url == "http://www.example.com/books/1") {
        return Promise.resolve({
          status: 200,
          headers() {
            return {
              ETag: "1567"
            }
          },
          data: {
            links: {
              self: "/books/1",
              acts: "/books/1/acts",
              sections: "/books/1/sections",
              owner: "/users/2"
            },
            data: {
              title: "Hamlet",

              acts: {
                links: {
                  self: "/books/1/acts",
                  book: "/books/1",
                  template: "/acts/{id}"
                },
                data: [
                  { links: { self: '/acts/1' }},
                  { links: { self: '/acts/2' }},
                  { links: { self: '/acts/3' }}
                ]
              }
            }
          }
        });
      } else if (params.method == "GET" && params.url == "http://www.example.com/acts/2") {
        return Promise.resolve({
          status: 200,
          headers() {
            return {
              ETag: "1448"
            }
          },
          data: {
            links: {
              self:    "/acts/2",
              book: "/books/1"
            },
            data: {
              // Chapters is LinkedResourceList object
              chapters: {
                links: {
                  self: "/acts/2/chapters",  // see ActChapters
                  act:  "/acts/2",
                  template: "/chapters/{id}" // template for a single chapter url
                },

                // The data themselves are Chapter objects that only contain links.
                // A chapter is really just a link to its first section.
                data: [
                  { links: { self: '/chapters/1', section: "/sections/1", act: "/acts/2" }},
                  { links: { self: '/chapters/2', section: "/sections/4", act: "/acts/2" }},
                  { links: { self: '/chapters/3', section: "/sections/7", act: "/acts/2" }}
                ]
              }
            }
          }
        });
      } else if (params.method == "PUT" && params.url == "http://www.example.com/acts/2/chapters") {
        return Promise.resolve({
          status: 200,
          headers() {
            return {
              ETag: "1449"
            }
          },
          data: {
            links: {
              self: "/acts/2/chapters",  // see ActChapters
              act:  "/acts/2",
              template: "/chapters/{id}" // template for a single chapter url
            },

            // The data themselves are Chapter objects that only contain links.
            // A chapter is really just a link to its first section.
            data: [
              { links: { self: '/chapters/1', section: "/sections/1", act: "/acts/2" }},
              { links: { self: '/chapters/2', section: "/sections/4", act: "/acts/2" }},
              { links: { self: '/chapters/3', section: "/sections/7", act: "/acts/2" }},
              { links: { self: '/chapters/4', act: "/acts/2" }}
            ]
          }
        });
      } else if (params.url == "http://www.example.com/sections/4") {
        return Promise.resolve({
          status: 200,
          headers() {
            return {
              ETag: "148"
            }
          },
          data: {
            links: {
              self:    '/sections/4',
              chapter:   '/chapters/1',
              book: '/books/1',
            },
            data: {
              title: "To Be Or Not To Be",
              kind: 'dramatic',
              resolution: 'positive',
              paragraphs: {
                links: {
                  self: '/sections/4/paragraphs',
                  section: '/sections/4',
                  book: '/books/1',
                  template: '/paragraphs/{id}' // template for a single paragraph url
                },

                data: [

                  // First Paragraph of the Section
                  {
                    links: {
                      self:       "/paragraphs/1",
                      characters: "/paragraphs/1/characters",
                      section:       "/sections/4"
                    },
                    data: {
                      kind:  'dialog',
                      body:  "To Be Or Not To Be",
                      characters: {
                        links: {
                          self: '/paragraphs/1/characters',
                          template: "/characters/{id}", // template for a single character url
                          paragraph: "/paragraphs/1"
                        },
                        data: [
                          {
                            // characters link to the book they are defined for, as well as self.
                            links: { self: "/characters/1", book: "/books/1" },
                            data:  { name: "Hamlet"  }
                          }
                        ]
                      }
                    }
                  },
                  // Second Paragraph of the Section
                  {
                    links: {
                      self:       "/paragraphs/3",
                      characters: "/paragraphs/3/characters",
                      section:       "/sections/4"
                    },
                    data: {
                      kind:  'dialog',
                      body:  "Whether Tis Nobler To Do Something Or Something else blah blah blah",
                      characters: {
                        links: {
                          self: '/paragraphs/3/characters',
                          template: "/characters/{id}", // template for a single character url
                          paragraph: "/paragraphs/3"
                        },
                        data: [
                          {
                            // characters link to the book they are defined for, as well as self.
                            links: { self: "/characters/1", book: "/books/1" },
                            data:  { name: "Hamlet"  }
                          }
                        ]
                      }
                    }
                  }
                ]
              }
            }
          }
        });
      }
    }
    angular.mock.module(function($provide) {
      $provide.factory("$http", function(RelayerPromise) {
        return function(params) {
          return mockHttp(RelayerPromise, params);
        };
      });
    });
    inject(function($injector, _resources_, _$rootScope_) {
      resources = _resources_;
      $rootScope = _$rootScope_;
    });
  });

  describe("book", function() {
    var promise;

    beforeEach(function(done) {
      promise = resources.books({id: 1}).load();
      promise.then((_book_) => {
        book = _book_;
        done();
      });
      $rootScope.$apply();
    });

    it("should resolve the book", function() {
      expect(book.title).toEqual("Hamlet");
    });

    describe("update", function() {
      beforeEach(function(done) {
        promise = book.acts({id: 2}).chapters().load().then((currentChapters) => {
          chapter = currentChapters.new();
          currentChapters.push(chapter);
          currentChapters.update().then((newChapters) => {
            chapters = newChapters;
            done();
          });
        });
      });

      it("should add the new chapter on update", function() {
        expect(chapters.length).toEqual(4);
      });
    });

    describe("section", function() {
      beforeEach(function(done) {
        promise = book.acts({id: 2}).chapters({id: 2}).section().load();
        promise.then((_section_) => {
          section = _section_;
          done();
        });
      });

      it("should resolve the section", function() {
        expect(section.title).toEqual("To Be Or Not To Be");
        expect(section.kind).toEqual('dramatic');
        expect(section.resolution).toEqual('positive');
      });

      describe("character", function() {
        beforeEach(function(done) {
          promise = section.paragraphs({id: 3}).characters({id: 1}).load();
          promise.then((_character_) => {
            character = _character_;
            done();
          });
        });

        it("should resolve the section", function() {
          expect(character.name).toEqual("Hamlet")
        });
      });
    });
  });
});
<commit_msg>Add integration test<commit_after>import RL from "../../src/relayer.js"
import {Module, Injector, Config} from "a1atscript";
import {TemplatedUrl} from "../../src/relayer/TemplatedUrl.js";

class Chapter extends RL.Resource {
}

RL.Describe(Chapter, (desc) => {
  desc.hasOne("section", Section);
  desc.hasOne("act", Act);
});

class Act extends RL.Resource {
}

RL.Describe(Act, (desc) => {
  desc.hasOne("book", Book, {});
  desc.hasList("chapters", Chapter, []);
});

class Section extends RL.Resource {
}

RL.Describe(Section, (desc) => {
  desc.property("title", "");
  desc.property("kind", "");
  desc.property("resolution", "")
  var chapter = desc.hasOne("chapter", Chapter);
  chapter.initializeOnCreate = false;
  var book = desc.hasOne("book", Book);
  book.initializeOnCreate = true;
  var paragraphs = desc.hasList("paragraphs", Paragraph)
  paragraphs.initializeOnCreate = false;
});

class Paragraph extends RL.Resource {

}

RL.Describe(Paragraph, (desc) => {
  desc.property("kind", "");
  desc.property("body", "");
  desc.hasOne("book", Book)
  desc.hasOne("section", Section);
  desc.hasList("characters", Character);
});

class Character extends RL.Resource {

}

RL.Describe(Character, (desc) => {
  desc.property("name", "")
  desc.hasOne("book", Book);
});

class Book extends RL.Resource {
}

RL.Describe(Book, (desc) => {
  desc.property("title", "");
  desc.hasList("acts", Act, []);
  desc.hasList("sections", Section, []);
  //desc.hasOne("owner", User, {});
  var characters = desc.hasList("characters", Character, []);
  characters.canCreate = true;
});

class Resources extends RL.Resource {
}

RL.Describe(Resources, (desc) => {
  var books = desc.hasList("books", Book, [])
  books.linkTemplate = "book";
  books.canCreate = true;
});

// this is horrible -- no easy way to get Babel and Traceur to compile the same config block
class AppConfig {
  @Config("relayerProvider")
  setupResources(relayerProvider) {
    relayerProvider.createApi("resources", Resources, "http://www.example.com/resources")
  }
}

var AppModule = new Module("AppModule", [RL, AppConfig.prototype]);

describe("initialization", function() {
  var section;
  beforeEach(function() {
    section = new Section();
  });

  it("should not initialize relationships when initializeOnCreate is false", function() {
    expect(section.relationships).toEqual({book: jasmine.any(Book)});
  });
});

describe("Loading relationships test", function() {
  var resources, book, act, chapter, chapters, section, paragraph, character, $httpBackend, $rootScope;

  beforeEach(function () {
    var injector = new Injector();
    injector.instantiate(AppModule);
    angular.mock.module('AppModule');

    var mockHttp = function(Promise, params) {
      if (params.url == "http://www.example.com/resources") {
        return Promise.resolve({
          status: 200,
          headers() {
            return {
              ETag: "1348"
            }
          },
          data: {
            data: {},
            links: {
              books: "/books",
              book: "/books/{id}"
            }
          }
        });
      } else if (params.url == "http://www.example.com/books/1") {
        return Promise.resolve({
          status: 200,
          headers() {
            return {
              ETag: "1567"
            }
          },
          data: {
            links: {
              self: "/books/1",
              acts: "/books/1/acts",
              sections: "/books/1/sections",
              owner: "/users/2"
            },
            data: {
              title: "Hamlet",

              acts: {
                links: {
                  self: "/books/1/acts",
                  book: "/books/1",
                  template: "/acts/{id}"
                },
                data: [
                  { links: { self: '/acts/1' }},
                  { links: { self: '/acts/2' }},
                  { links: { self: '/acts/3' }}
                ]
              }
            }
          }
        });
      } else if (params.method == "GET" && params.url == "http://www.example.com/acts/2") {
        return Promise.resolve({
          status: 200,
          headers() {
            return {
              ETag: "1448"
            }
          },
          data: {
            links: {
              self:    "/acts/2",
              book: "/books/1"
            },
            data: {
              // Chapters is LinkedResourceList object
              chapters: {
                links: {
                  self: "/acts/2/chapters",  // see ActChapters
                  act:  "/acts/2",
                  template: "/chapters/{id}" // template for a single chapter url
                },

                // The data themselves are Chapter objects that only contain links.
                // A chapter is really just a link to its first section.
                data: [
                  { links: { self: '/chapters/1', section: "/sections/1", act: "/acts/2" }},
                  { links: { self: '/chapters/2', section: "/sections/4", act: "/acts/2" }},
                  { links: { self: '/chapters/3', section: "/sections/7", act: "/acts/2" }}
                ]
              }
            }
          }
        });
      } else if (params.method == "PUT" && params.url == "http://www.example.com/acts/2/chapters") {
        return Promise.resolve({
          status: 200,
          headers() {
            return {
              ETag: "1449"
            }
          },
          data: {
            links: {
              self: "/acts/2/chapters",  // see ActChapters
              act:  "/acts/2",
              template: "/chapters/{id}" // template for a single chapter url
            },

            // The data themselves are Chapter objects that only contain links.
            // A chapter is really just a link to its first section.
            data: [
              { links: { self: '/chapters/1', section: "/sections/1", act: "/acts/2" }},
              { links: { self: '/chapters/2', section: "/sections/4", act: "/acts/2" }},
              { links: { self: '/chapters/3', section: "/sections/7", act: "/acts/2" }},
              { links: { self: '/chapters/4', act: "/acts/2" }}
            ]
          }
        });
      } else if (params.url == "http://www.example.com/sections/4") {
        return Promise.resolve({
          status: 200,
          headers() {
            return {
              ETag: "148"
            }
          },
          data: {
            links: {
              self:    '/sections/4',
              chapter:   '/chapters/1',
              book: '/books/1',
            },
            data: {
              title: "To Be Or Not To Be",
              kind: 'dramatic',
              resolution: 'positive',
              paragraphs: {
                links: {
                  self: '/sections/4/paragraphs',
                  section: '/sections/4',
                  book: '/books/1',
                  template: '/paragraphs/{id}' // template for a single paragraph url
                },

                data: [

                  // First Paragraph of the Section
                  {
                    links: {
                      self:       "/paragraphs/1",
                      characters: "/paragraphs/1/characters",
                      section:       "/sections/4"
                    },
                    data: {
                      kind:  'dialog',
                      body:  "To Be Or Not To Be",
                      characters: {
                        links: {
                          self: '/paragraphs/1/characters',
                          template: "/characters/{id}", // template for a single character url
                          paragraph: "/paragraphs/1"
                        },
                        data: [
                          {
                            // characters link to the book they are defined for, as well as self.
                            links: { self: "/characters/1", book: "/books/1" },
                            data:  { name: "Hamlet"  }
                          }
                        ]
                      }
                    }
                  },
                  // Second Paragraph of the Section
                  {
                    links: {
                      self:       "/paragraphs/3",
                      characters: "/paragraphs/3/characters",
                      section:       "/sections/4"
                    },
                    data: {
                      kind:  'dialog',
                      body:  "Whether Tis Nobler To Do Something Or Something else blah blah blah",
                      characters: {
                        links: {
                          self: '/paragraphs/3/characters',
                          template: "/characters/{id}", // template for a single character url
                          paragraph: "/paragraphs/3"
                        },
                        data: [
                          {
                            // characters link to the book they are defined for, as well as self.
                            links: { self: "/characters/1", book: "/books/1" },
                            data:  { name: "Hamlet"  }
                          }
                        ]
                      }
                    }
                  }
                ]
              }
            }
          }
        });
      }
    }
    angular.mock.module(function($provide) {
      $provide.factory("$http", function(RelayerPromise) {
        return function(params) {
          return mockHttp(RelayerPromise, params);
        };
      });
    });
    inject(function($injector, _resources_, _$rootScope_) {
      resources = _resources_;
      $rootScope = _$rootScope_;
    });
  });

  describe("book", function() {
    var promise;

    beforeEach(function(done) {
      promise = resources.books({id: 1}).load();
      promise.then((_book_) => {
        book = _book_;
        done();
      });
      $rootScope.$apply();
    });

    it("should resolve the book", function() {
      expect(book.title).toEqual("Hamlet");
    });

    describe("update", function() {
      beforeEach(function(done) {
        promise = book.acts({id: 2}).chapters().load().then((currentChapters) => {
          chapter = currentChapters.new();
          currentChapters.push(chapter);
          currentChapters.update().then((newChapters) => {
            chapters = newChapters;
            done();
          });
        });
      });

      it("should add the new chapter on update", function() {
        expect(chapters.length).toEqual(4);
      });
    });

    describe("section", function() {
      beforeEach(function(done) {
        promise = book.acts({id: 2}).chapters({id: 2}).section().load();
        promise.then((_section_) => {
          section = _section_;
          done();
        });
      });

      it("should verify relationships present and accessible", function() {
        expect(section.book().present()).toBe(true);
        expect(section.chapter().present()).toBe(true);
        expect(section.paragraphs().present()).toBe(true);
        expect(section.book().get()).toEqual(jasmine.any(TemplatedUrl));
        expect(section.paragraphs().get()[0]).toEqual(jasmine.any(Paragraph));
      });

      it("should resolve the section", function() {
        expect(section.title).toEqual("To Be Or Not To Be");
        expect(section.kind).toEqual('dramatic');
        expect(section.resolution).toEqual('positive');
      });

      describe("character", function() {
        beforeEach(function(done) {
          promise = section.paragraphs({id: 3}).characters({id: 1}).load();
          promise.then((_character_) => {
            character = _character_;
            done();
          });
        });

        it("should resolve the section", function() {
          expect(character.name).toEqual("Hamlet")
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Copyright 2015 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  createFixtureIframe,
  expectBodyToBecomeVisible,
} from '../../testing/iframe.js';
import {getStyle} from '../../src/style';

const timeout = window.ampTestRuntimeConfig.mochaTimeout;

describe.configure().retryOnSaucelabs().run('Old Opacity Boilerplate', () => {
  let fixture;
  beforeEach(() => {
    return createFixtureIframe(
        'test/fixtures/boilerplate-old-opacity.html', 1000).then(f => {
          fixture = f;
        });
  });

  it('should show the body when opacity boilerplate is used', () => {
    return expectBodyToBecomeVisible(fixture.win, timeout).then(() => {
      expect(getStyle(fixture.win.document.body, 'opacity')).to.equal('1');
    });
  });
});

describe.configure().run('New Visibility Boilerplate', () => {

  let fixture;
  beforeEach(() => {
    return createFixtureIframe(
        'test/fixtures/boilerplate-new-visibility.html', 10000).then(f => {
          fixture = f;
        });
  });

  it('should show the body in boilerplate test', () => {
    return expectBodyToBecomeVisible(fixture.win, timeout).then(() => {
      expect(getStyle(
          fixture.win.document.body, 'visibility')).to.equal('visible');
      // Firefox spells out the values when assigning none.
      const ffValue = '0s ease 0s normal none 1 running none';
      const animation = getStyle(fixture.win.document.body, 'animation');
      if (animation == ffValue) {
        expect(animation).to.equal(ffValue);
      } else {
        expect(animation).to.equal('none');
      }
    });
  });
});
<commit_msg>Remove firefox special case (#12272)<commit_after>/**
 * Copyright 2015 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  createFixtureIframe,
  expectBodyToBecomeVisible,
} from '../../testing/iframe.js';
import {getStyle} from '../../src/style';

const timeout = window.ampTestRuntimeConfig.mochaTimeout;

describe.configure().retryOnSaucelabs().run('Old Opacity Boilerplate', () => {
  let fixture;
  beforeEach(() => {
    return createFixtureIframe(
        'test/fixtures/boilerplate-old-opacity.html', 1000).then(f => {
          fixture = f;
        });
  });

  it('should show the body when opacity boilerplate is used', () => {
    return expectBodyToBecomeVisible(fixture.win, timeout).then(() => {
      expect(getStyle(fixture.win.document.body, 'opacity')).to.equal('1');
    });
  });
});

describe.configure().run('New Visibility Boilerplate', () => {

  let fixture;
  beforeEach(() => {
    return createFixtureIframe(
        'test/fixtures/boilerplate-new-visibility.html', 10000).then(f => {
          fixture = f;
        });
  });

  it('should show the body in boilerplate test', () => {
    return expectBodyToBecomeVisible(fixture.win, timeout).then(() => {
      expect(getStyle(
          fixture.win.document.body, 'visibility')).to.equal('visible');
      // Firefox spells out the values when assigning none.
      const ffValue = '0s ease 0s 1 normal none running none';
      const animation = getStyle(fixture.win.document.body, 'animation');
      if (animation == ffValue) {
        expect(animation).to.equal(ffValue);
      } else {
        expect(animation).to.equal('none');
      }
    });
  });
});
<|endoftext|>


<commit_before>
$(document).ready(function() {

  //TABS
  //When page loads...
  $(".tabsContent").hide(); //Hide all content
  $("ul.liveTabs li:first").addClass("active").show(); //Activate first tab
  $(".tabsContent:first").show(); //Show first tab content

  //On Click Event
  $("ul.liveTabs li").click(function() {
    $("ul.liveTabs li").removeClass("active"); //Remove any "active" class
    $(this).addClass("active"); //Add "active" class to selected tab
    $(".tabsContent").hide(); //Hide all tab content
    var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
    $(activeTab).fadeIn(); //Fade in the active ID content
    return false;
  });

  //OPTIONAL: For underlined tabs navigation
  //When page loads...
  $(".tabContent").hide(); //Hide all content
  $("ul.tabs li:first").addClass("active").show(); //Activate first tab
  $(".tabContent:first").show(); //Show first tab content
  //On Click Event

  $("ul.tabs li").click(function() {
    $("ul.tabs li").removeClass("active"); //Remove any "active" class
    $(this).addClass("active"); //Add "active" class to selected tab
    $(".tabContent").hide(); //Hide all tab content
    var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
    $(activeTab).fadeIn(); //Fade in the active ID content
    return false;
  });
});

<commit_msg>Formatted javascript<commit_after>$( document ).ready( function() {

  //TABS
  //When page loads...
  $( ".tabsContent" ).hide(); //Hide all content
  $( "ul.liveTabs li:first" ).addClass( "active" ).show(); //Activate first tab
  $( ".tabsContent:first" ).show(); //Show first tab content
  //On Click Event
  $( "ul.liveTabs li" ).click( function() {
    $( "ul.liveTabs li" ).removeClass( "active" ); //Remove any "active" class
    $( this ).addClass( "active" ); //Add "active" class to selected tab
    $( ".tabsContent" ).hide(); //Hide all tab content
    var activeTab = $( this ).find( "a" ).attr( "href" ); //Find the href attribute value to identify the active tab + content
    $( activeTab ).fadeIn(); //Fade in the active ID content
    return false;
  } );

  //OPTIONAL: For underlined tabs navigation
  //When page loads...
  $( ".tabContent" ).hide(); //Hide all content
  $( "ul.tabs li:first" ).addClass( "active" ).show(); //Activate first tab
  $( ".tabContent:first" ).show(); //Show first tab content
  //On Click Event
  $( "ul.tabs li" ).click( function() {
    $( "ul.tabs li" ).removeClass( "active" ); //Remove any "active" class
    $( this ).addClass( "active" ); //Add "active" class to selected tab
    $( ".tabContent" ).hide(); //Hide all tab content
    var activeTab = $( this ).find( "a" ).attr( "href" ); //Find the href attribute value to identify the active tab + content
    $( activeTab ).fadeIn(); //Fade in the active ID content
    return false;
  } );

} );
<|endoftext|>


<commit_before>function writeHeader() {
    return '\
    \

\
        ICSME 2019\
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">\
            \
        </button>\
\

\

\

\
                Registration\

\
\

\
                Venue & Travel\

\
                    Hotel Venue\
                    Traveling to Cleveland\
                    Visa Invitation\
                    Cleveland Tourism\

\

\
\

\
                Program\

\
                    Program Overview\
                    Full Program\
                    Code of Conduct\
                    Keynotes\
                    Accepted Papers\

\

\
\

\
                Call for Papers\

\
                    Research Track\
                    Short Paper Track\
                    Late Breaking Ideas Track\
                    Tool Demo Track\
                    Industry Track\
                    Artifacts Track\
                    Journal First Track\
                    Doctoral Symposium\

\

\
\

\
                Team\

\
                    Organizing Committee\
                    Program Committee\

\

\
\

\
                Social\

\
                    LGBTIQ Lunch Event\

\

\
\

\
                Co-Located Events\

\
                    SCAM\
                    VISSOFT\

\

\
\
            \
\
            \
\
            \
\
            \
\

\

\

\
    \
\
    \

\
    ';
}
<commit_msg>Reorder menu with CFPs at the end<commit_after>function writeHeader() {
    return '\
    \

\
        ICSME 2019\
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">\
            \
        </button>\
\

\

\

\
                Registration\

\
\

\
                Venue & Travel\

\
                    Hotel Venue\
                    Traveling to Cleveland\
                    Visa Invitation\
                    Cleveland Tourism\

\

\
\

\
                Program\

\
                    Program Overview\
                    Full Program\
                    Code of Conduct\
                    Keynotes\
                    Accepted Papers\

\

\
\

\
                Team\

\
                    Organizing Committee\
                    Program Committee\

\

\
\

\
                Social\

\
                    LGBTIQ Lunch Event\

\

\
\

\
                Co-Located Events\

\
                    SCAM\
                    VISSOFT\

\

\
\
            \
\
            \
\
            \
\
            \
\

\
                Call for Papers\

\
                    Research Track\
                    Short Paper Track\
                    Late Breaking Ideas Track\
                    Tool Demo Track\
                    Industry Track\
                    Artifacts Track\
                    Journal First Track\
                    Doctoral Symposium\

\

\
\

\

\

\
    \
\
    \

\
    ';
}
<|endoftext|>


<commit_before>/*
 * LocalStorage Events
 *
 * Use a cookie to capture which key changed for IE8
 * Use a cookie to ignore "storage" events that I triggered
*/

var Cookies = require('js-cookie');
var assign = require('./util/assign');
var bind = require('./util/bind');
var lsWrapper = require('./util/ls-wrapper');
var support = require('./util/support');

var instanceId = Math.floor(Math.random() * 1000) + '' + +new Date;

function LocalStorageEventListener(storage, onStorage) {
  this.onStorage = onStorage;
  this._onStorage = bind(this._onStorage, this);

  var destroy = storage.destroy;
  var decorator = this;
  storage.destroy = function() {
    storage.destroy = destroy;
    support.off(support.storageEventTarget, 'storage', decorator._onStorage);
    if (typeof destroy === 'function') {
      return destroy.apply(storage, arguments);
    }
  }

  support.on(support.storageEventTarget, 'storage', this._onStorage);

  return storage;
}

LocalStorageEventListener.prototype = {

  _onStorage: function(evt) {
    this.onStorage(evt);
  }

};

function LocalStorageEventNormalizer(storage, onStorage, cookieName) {
  this.cookieName = cookieName;

  var set = storage.set;
  var destroy = storage.destroy;
  storage.set = function(key) {
    // Before setting the value, set a version flag indicating that the
    // last write came from this window and targeted the given key.
    Cookies.set(cookieName, instanceId + ':' + key);
    return set.apply(storage, arguments);
  }
  storage.destroy = function() {
    storage.set = set;
    storage.destroy = destroy;
    if (typeof destroy === 'function') {
      return destroy.apply(storage, arguments);
    }
  }

  return LocalStorageEventListener.apply(this, arguments);
}

LocalStorageEventNormalizer.prototype = {

  _onStorage: function(evt) {
    // IE8: to accurately determine `evt.newValue`, we must read it during the event
    // callback. Oddly, it returns the old value instead of the new one until the call
    // stack clears. More oddly, I was unable to reproduce this with a minimal test
    // case, yet it always seems to behave this way here.
    if (!support.storageEventProvidesKey) {
      setTimeout(bind(function() {
        this._processStorageEvt(evt);
      }, this), 0);
    } else {
      this._processStorageEvt(evt);
    }
  },

  // Ignore the event if it originated in this window. Tell IE8 which `key` changed
  // and grab it's `newValue`.
  _processStorageEvt: function(evt) {
    var ref = (Cookies.get(this.cookieName) || ':').split(':'),
        writerId = ref[0], key = ref[1];

    // For all IE
    if (writerId == instanceId) return;

    // For IE8
    if (!support.storageEventProvidesKey) {
      evt = {
        key: key,
        newValue: localStorage.getItem(key)
      };
    }

    this.onStorage(evt);
  }

};

// Decorate a LocalStorage interface to properly trigger "storage" events in IE.
var LSEvents = function(storage, onStorage, cookieName) {

  // `storage` interface is optional
  if (typeof storage === 'function') {
    cookieName = onStorage;
    onStorage = storage;
    storage = lsWrapper;
  }

  // Sensible defaults for no args passed
  if (typeof storage === 'undefined') {
    storage = lsWrapper;
    onStorage = function(){};
  }

  // Default value for cookieName
  if (typeof cookieName !== 'string') {
    cookieName = 'lsevents-version';
  }

  if (support.myWritesTrigger) {
    return new LocalStorageEventNormalizer(storage, onStorage, cookieName);
  } else {
    return new LocalStorageEventListener(storage, onStorage);
  }

};

LSEvents.support = support;

module.exports = LSEvents;
<commit_msg>Consistent use of uppercase LSWrapper<commit_after>/*
 * LocalStorage Events
 *
 * Use a cookie to capture which key changed for IE8
 * Use a cookie to ignore "storage" events that I triggered
*/

var Cookies = require('js-cookie');
var assign = require('./util/assign');
var bind = require('./util/bind');
var LSWrapper = require('./util/ls-wrapper');
var support = require('./util/support');

var instanceId = Math.floor(Math.random() * 1000) + '' + +new Date;

function LocalStorageEventListener(storage, onStorage) {
  this.onStorage = onStorage;
  this._onStorage = bind(this._onStorage, this);

  var destroy = storage.destroy;
  var decorator = this;
  storage.destroy = function() {
    storage.destroy = destroy;
    support.off(support.storageEventTarget, 'storage', decorator._onStorage);
    if (typeof destroy === 'function') {
      return destroy.apply(storage, arguments);
    }
  }

  support.on(support.storageEventTarget, 'storage', this._onStorage);

  return storage;
}

LocalStorageEventListener.prototype = {

  _onStorage: function(evt) {
    this.onStorage(evt);
  }

};

function LocalStorageEventNormalizer(storage, onStorage, cookieName) {
  this.cookieName = cookieName;

  var set = storage.set;
  var destroy = storage.destroy;
  storage.set = function(key) {
    // Before setting the value, set a version flag indicating that the
    // last write came from this window and targeted the given key.
    Cookies.set(cookieName, instanceId + ':' + key);
    return set.apply(storage, arguments);
  }
  storage.destroy = function() {
    storage.set = set;
    storage.destroy = destroy;
    if (typeof destroy === 'function') {
      return destroy.apply(storage, arguments);
    }
  }

  return LocalStorageEventListener.apply(this, arguments);
}

LocalStorageEventNormalizer.prototype = {

  _onStorage: function(evt) {
    // IE8: to accurately determine `evt.newValue`, we must read it during the event
    // callback. Oddly, it returns the old value instead of the new one until the call
    // stack clears. More oddly, I was unable to reproduce this with a minimal test
    // case, yet it always seems to behave this way here.
    if (!support.storageEventProvidesKey) {
      setTimeout(bind(function() {
        this._processStorageEvt(evt);
      }, this), 0);
    } else {
      this._processStorageEvt(evt);
    }
  },

  // Ignore the event if it originated in this window. Tell IE8 which `key` changed
  // and grab it's `newValue`.
  _processStorageEvt: function(evt) {
    var ref = (Cookies.get(this.cookieName) || ':').split(':'),
        writerId = ref[0], key = ref[1];

    // For all IE
    if (writerId == instanceId) return;

    // For IE8
    if (!support.storageEventProvidesKey) {
      evt = {
        key: key,
        newValue: localStorage.getItem(key)
      };
    }

    this.onStorage(evt);
  }

};

// Decorate a LocalStorage interface to properly trigger "storage" events in IE.
var LSEvents = function(storage, onStorage, cookieName) {

  // `storage` interface is optional
  if (typeof storage === 'function') {
    cookieName = onStorage;
    onStorage = storage;
    storage = LSWrapper;
  }

  // Sensible defaults for no args passed
  if (typeof storage === 'undefined') {
    storage = LSWrapper;
    onStorage = function(){};
  }

  // Default value for cookieName
  if (typeof cookieName !== 'string') {
    cookieName = 'lsevents-version';
  }

  if (support.myWritesTrigger) {
    return new LocalStorageEventNormalizer(storage, onStorage, cookieName);
  } else {
    return new LocalStorageEventListener(storage, onStorage);
  }

};

LSEvents.support = support;

module.exports = LSEvents;
<|endoftext|>