<commit_before>define(function(require) {
    "use strict";

    var Event = require("../models/event");
    var EventHelper = require("../helpers/event-helper");
    var StringHelper = require("../helpers/string-helper");
    var UuidHelper = require("../helpers/uuid-helper");

    var _key = {};
    var _getAttributes = UuidHelper.generateUuid();

    /*
        @abstract
        @class Model

        @classdesc Model class.
    */

    /*
        @constructor Model

        Constructs a Model instance.

        @param {string} modelName       The desired model name
        @param {string[]} attributes    The desired model attributes
    */
    var Model = function(modelName, modelAttributes) {
        //Private instance members
        var attributes = {
            id: null,
            attributes: {},
            validationRules: {}
        };

        for (var i = 0, length = modelAttributes.length; i < length; i++) {
            attributes.attributes[modelAttributes[i]] = null;
        }

        //Public instance members
        //(None)

        //Special instance method for private member access
        this[_getAttributes] = function(key) {
            if (key === _key) {
                return attributes.attributes;
            }
        };

        //Return instance
        return this;
    };

    //Public instance members
    Model.init = function(name, model) {
        model.prototype = (function(prototype) {
            //Private static members
            var staticAttributes = {
                modelName: name,
                validationRules: {}
            };

            //Public static members
            /*
                @function addMethod

                Adds the specified method to the model's prototype.

                @param {string} name        The desired method name
                @param {string} method      The desired method
            */
            model.addMethod = function(name, method) {
                model.prototype[name] = method;
            };

            /*
                @function removeMethod

                Removes the specified method from the model's prototype.

                @param {string} name        The desired method name
            */
            model.removeMethod = function(name) {
                delete model.prototype[name];
            };

            /*
                @function hasMethod

                Checks if the specified method exists in the model's prototype.

                @param {string} name        The desired method name

                @return {boolean}
            */
            model.hasMethod = function(name) {
                return typeof model.prototype[name] === "function";
            };

            /*
                @function addStaticMethod

                Adds the specified method to the model.

                @param {string} name        The desired method name
                @param {string} method      The desired method
            */
            model.addStaticMethod = function(name, method) {
                model[name] = method;
            };

            /*
                @function removeStaticMethod

                Removes the specified method from the model.

                @param {string} name        The desired method name
            */
            model.removeStaticMethod = function(name) {
                delete model[name];
            };

            /*
                @function hasStaticMethod

                Checks if the specified method exists in the model.

                @param {string} name        The desired method name

                @return {boolean}
            */
            model.hasStaticMethod = function(name) {
                return typeof model[name] === "function" && typeof model.prototype[name] !== "function";
            };

            /*
                @function addStaticAttribute

                Adds the specified attribute to the model.

                @param {string} name        The desired method name
                @param {string} value       The desired value
            */
            model.addStaticAttribute = function(name, value) {
                model[name] = value;
            };

            /*
                @function removeStaticAttribute

                Removes the specified attribute from the model.

                @param {object} name        The desired attribute name
            */
            model.removeStaticAttribute = function(name) {
                delete model[name];
            };

            /*
                @function hasStaticMethod

                Checks if the specified method exists in the model.

                @param {string} name        The desired method name

                @return {boolean}
            */
            model.hasStaticAttribute = function(name) {
                var type = typeof model[name];
                return  type !== "undefined"  && type !== "function" && typeof model.prototype[name] !== type;
            };

            /*
                @function getModelName()

                Gets the model's name.

                @return {string}
            */
            model.getModelName = function() {
                return staticAttributes.modelName;
            };

            /*
                @function getValidationRules

                Gets the validation rules for the specified model.

                @param {object} model       The desired model

                @return {object[]}
            */
            model.getValidationRules = function() {
                return staticAttributes.validationRules;
            };

            /*
                @function setValidationRules

                Sets the specified validation rules for the specified model.

                @param {object} model       The desired model
                @param {string} rules       The desired validation rules
            */
            model.setValidationRules = function(rules) {
                staticAttributes.validationRules = rules;
            };

            //Public prototype members
            /*
                @function get

                Gets the specified attribute.

                @param {string} attribute       The desired attribute

                @return {mixed}
            */
            prototype.get = function(attribute) {
                return this[_getAttributes](_key)[attribute];
            };

            /*
                @function set

                Sets the specified attribute.

                @param {string|object} attribute                The desired attribute OR attribute-value dictionary
                @param {mixed} value                            The desired value
                @param [{object}] options                       Additional options for the method
                @param [{boolean = false}] options.silent       Flag indicating whether the change event should be
                                                                triggered
            */
            prototype.set = function(attribute, value, options) {
                var silent = options && options.silent === true;

                var changes = [];
                var change, oldValue;

                if (typeof attribute !== "object" && typeof value !== "undefined") {
                    oldValue = this[_getAttributes](_key)[attribute];
                    this[_getAttributes](_key)[attribute] = value;

                    //Trigger events if necessary
                    if (oldValue !== value) {
                        changes.push({
                            attribute: attribute,
                            oldValue: oldValue,
                            newValue: value
                        });
                    }
                }
                else {
                    silent = value && value.silent === true;

                    for (var key in attribute) {
                        oldValue = this[_getAttributes](_key)[key];
                        this[_getAttributes](_key)[key] = attribute[key];

                        if (oldValue !== attribute[key]) {
                            changes.push({
                                attribute: key,
                                oldValue: oldValue,
                                newValue: attribute[key]
                            });
                        }
                    }
                }

                if (changes.length > 0) {
                    for (var i = 0, length = changes.length; i < length; i++) {
                        change = changes[i];

                        if (!silent) {
                            this.trigger("change:" + change.attribute, {
                                oldValue: change.oldValue,
                                newValue: change.newValue
                            });
                        }
                    }

                    if (!silent) {
                        this.trigger("change", changes);
                    }
                }
            };

            /*
                @function has

                Checks if the specified attribute is defined and not null.

                @param {string} attribute       The desired attribute

                @return {boolean}
            */
            prototype.has = function(attribute) {
                return typeof this[_getAttributes](_key)[attribute] !== "undefined" &&
                    this[_getAttributes](_key)[attribute] !== null;
            };

            /*
                @function getId

                Returns the instance identifier.

                @return {int}
            */
            prototype.getId = function() {
                return this[_getAttributes](_key).id;
            };

            /*
                @function setId

                Sets the instance identifier.
            */
            prototype.setId = function(id) {
                var oldValue = this[_getAttributes](_key).id;
                if (oldValue !== id) {
                    this.trigger("change:id", {
                        oldValue: oldValue,
                        newValue: id
                    });

                    this.trigger("change", [{
                        attribute: "id",
                        oldValue: oldValue,
                        newValue: id
                    }]);
                }

                this[_getAttributes](_key).id = id;
            };

            /*
                @function getModel()

                Gets the model of the item.

                @return {function}
            */
            prototype.getModel = function() {
                return model;
            };

            /*
                @function toObject

                Gets an object representation of the item.

                @return {object}
            */
            prototype.toObject = function() {
                var returnData = {};

                var attributes = this[_getAttributes](_key);

                for (var attribute in attributes) {
                    returnData[attribute] = attributes[attribute];
                }

                return returnData;
            };

            /*
                @function trigger

                Triggers an event on the item.

                @param {string} event       The desired event name
                @param [{object}] args      Additional arguments for the event
            */
            prototype.trigger = function(event, args) {
                EventHelper.trigger(new Event(this, event, args));
            };

            /*
                @function validate

                Validates the current item.

                @return {boolean||object[]}
            */
            prototype.validate = function() {
                var modelRules = staticAttributes.validationRules;
                var modelErrors = {};
                var attributeRules, attributeRequired, attributeErrors, attributeOverride, attributeValue,
                attributeName, rule;

                function addError(message) {
                    attributeErrors.push(rule.message || message);
                }

                function isEmpty(value) {
                    return typeof value === "undefined" || value === null || value === "";
                }

                for (var attribute in modelRules) {
                    attributeRules = modelRules[attribute];
                    attributeValue = this[_getAttributes](_key)[attribute];
                    attributeErrors = [];
                    attributeOverride = false;
                    attributeRequired = false;
                    attributeName = StringHelper.uppercaseFirst(StringHelper.humanize(attribute));

                    //Set override flag to allow nulls/etc. for non-required attributes with type checks
                    for (var i = 0, length = attributeRules.length; i < length; i++) {
                        if (attributeRules[i].required === true) {
                            attributeRequired = true;
                            break;
                        }
                    }
                    attributeOverride = (!attributeRequired && (attributeValue === null ||
                        typeof attributeValue === "undefined" || attributeValue === ""));

                    for (i = 0, length = attributeRules.length; i < length; i++) {
                        rule = attributeRules[i];

                        if (rule.required) {
                            if (isEmpty(attributeValue)) {
                                addError(attributeName + " is required.");
                            }
                        }
                        else if (rule.type) {
                            if (!attributeOverride) {
                                if (rule.type === "string" && typeof attributeValue !== "string") {
                                    addError(attributeName + " should be a string.");
                                }
                                else if (rule.type === "int" && (typeof attributeValue !== "number" ||
                                    attributeValue % 1 !== 0)) {
                                    addError(attributeName + " should be an integer.");
                                }
                                else if (rule.type === "number" && typeof attributeValue !== "number") {
                                    addError(attributeName + " should be a number.");
                                }
                                else if (rule.type === "boolean" && typeof attributeValue !== "boolean") {
                                    addError(attributeName + " should be a boolean.");
                                }
                            }
                        }
                        else if (rule.minLength) {
                            if (isEmpty(attributeValue) || typeof attributeValue !== "string" ||
                                attributeValue.length < rule.minLength) {
                                addError(attributeName + " should be at least " + rule.minLength + " characters long.");
                            }
                        }
                        else if (rule.maxLength) {
                            if (isEmpty(attributeValue) || typeof attributeValue !== "string" ||
                                attributeValue.length > rule.maxLength) {
                                addError(attributeName + " should be at most " + rule.maxLength + " characters long.");
                            }
                        }
                        else if (rule.minValue) {
                            if (isEmpty(attributeValue) ||  typeof attributeValue !== "number" ||
                                attributeValue < rule.minValue) {
                                addError(attributeName + " should be at least " + rule.minValue + ".");
                            }
                        }
                        else if (rule.maxValue) {
                            if (isEmpty(attributeValue) || typeof attributeValue !== "number" ||
                                attributeValue > rule.maxValue) {
                                addError(attributeName + " should be at most " + rule.maxValue + ".");
                            }
                        }
                        else if (rule.format) {
                            if (
                                //jshint -W101
                                (rule.format === "email" && !/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(attributeValue)) ||
                                (rule.format === "alpha" && !/^[a-z]*$/i.test(attributeValue)) ||
                                (rule.format === "flag" && attributeValue !== 0 && attributeValue !== 1) ||
                                (rule.format === "alphanumeric" && !/^[a-z0-9]*$/i.test(attributeValue)) ||
                                (rule.format === "creditcard" && !/^(?:4[0-9]{12}(?:[0-9]{3})|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})$/.test(attributeValue))
                                //jshint +W101
                                ) {
                                addError(attributeName + " should be a valid " + rule.format);
                            }
                        }
                        else if (rule.regex) {
                            if (isEmpty(attributeValue) || !rule.regex.test(attributeValue)) {
                                addError(attributeName + " should match " + rule.regex + ".");
                            }
                        }
                        else if (rule.function) {
                            var result = rule.function(attributeValue, this);
                            if (result !== true) {
                                addError(result);
                            }
                        }
                    }

                    if (attributeErrors.length > 0) {
                        modelErrors[attribute] = attributeErrors;
                    }

                }

                return (JSON.stringify(modelErrors) === "{}" || modelErrors);
            };

            /*
                @function isValid

                Validates the current item.

                @return {boolean}
            */
            prototype.isValid = function() {
                return this.validate() === true;
            };

            return prototype;
        })(model.prototype || {});
    };

    return Model;
});
<commit_msg>Core.Model.Model: implemented modelInstance observe() and unobserve() methods.a<commit_after>define(function(require) {
    "use strict";

    var Event = require("../models/event");
    var EventHelper = require("../helpers/event-helper");
    var StringHelper = require("../helpers/string-helper");
    var UuidHelper = require("../helpers/uuid-helper");

    var _key = {};
    var _getAttributes = UuidHelper.generateUuid();

    /*
        @abstract
        @class Model

        @classdesc Model class.
    */

    /*
        @constructor Model

        Constructs a Model instance.

        @param {string} modelName       The desired model name
        @param {string[]} attributes    The desired model attributes
    */
    var Model = function(modelName, modelAttributes) {
        //Private instance members
        var attributes = {
            id: null,
            attributes: {},
            validationRules: {}
        };

        for (var i = 0, length = modelAttributes.length; i < length; i++) {
            attributes.attributes[modelAttributes[i]] = null;
        }

        //Public instance members
        //(None)

        //Special instance method for private member access
        this[_getAttributes] = function(key) {
            if (key === _key) {
                return attributes.attributes;
            }
        };

        //Return instance
        return this;
    };

    //Public instance members
    Model.init = function(name, model) {
        model.prototype = (function(prototype) {
            //Private static members
            var staticAttributes = {
                modelName: name,
                validationRules: {}
            };

            //Public static members
            /*
                @function addMethod

                Adds the specified method to the model's prototype.

                @param {string} name        The desired method name
                @param {string} method      The desired method
            */
            model.addMethod = function(name, method) {
                model.prototype[name] = method;
            };

            /*
                @function removeMethod

                Removes the specified method from the model's prototype.

                @param {string} name        The desired method name
            */
            model.removeMethod = function(name) {
                delete model.prototype[name];
            };

            /*
                @function hasMethod

                Checks if the specified method exists in the model's prototype.

                @param {string} name        The desired method name

                @return {boolean}
            */
            model.hasMethod = function(name) {
                return typeof model.prototype[name] === "function";
            };

            /*
                @function addStaticMethod

                Adds the specified method to the model.

                @param {string} name        The desired method name
                @param {string} method      The desired method
            */
            model.addStaticMethod = function(name, method) {
                model[name] = method;
            };

            /*
                @function removeStaticMethod

                Removes the specified method from the model.

                @param {string} name        The desired method name
            */
            model.removeStaticMethod = function(name) {
                delete model[name];
            };

            /*
                @function hasStaticMethod

                Checks if the specified method exists in the model.

                @param {string} name        The desired method name

                @return {boolean}
            */
            model.hasStaticMethod = function(name) {
                return typeof model[name] === "function" && typeof model.prototype[name] !== "function";
            };

            /*
                @function addStaticAttribute

                Adds the specified attribute to the model.

                @param {string} name        The desired method name
                @param {string} value       The desired value
            */
            model.addStaticAttribute = function(name, value) {
                model[name] = value;
            };

            /*
                @function removeStaticAttribute

                Removes the specified attribute from the model.

                @param {object} name        The desired attribute name
            */
            model.removeStaticAttribute = function(name) {
                delete model[name];
            };

            /*
                @function hasStaticMethod

                Checks if the specified method exists in the model.

                @param {string} name        The desired method name

                @return {boolean}
            */
            model.hasStaticAttribute = function(name) {
                var type = typeof model[name];
                return  type !== "undefined"  && type !== "function" && typeof model.prototype[name] !== type;
            };

            /*
                @function getModelName()

                Gets the model's name.

                @return {string}
            */
            model.getModelName = function() {
                return staticAttributes.modelName;
            };

            /*
                @function getValidationRules

                Gets the validation rules for the specified model.

                @param {object} model       The desired model

                @return {object[]}
            */
            model.getValidationRules = function() {
                return staticAttributes.validationRules;
            };

            /*
                @function setValidationRules

                Sets the specified validation rules for the specified model.

                @param {object} model       The desired model
                @param {string} rules       The desired validation rules
            */
            model.setValidationRules = function(rules) {
                staticAttributes.validationRules = rules;
            };

            //Public prototype members
            /*
                @function get

                Gets the specified attribute.

                @param {string} attribute       The desired attribute

                @return {mixed}
            */
            prototype.get = function(attribute) {
                return this[_getAttributes](_key)[attribute];
            };

            /*
                @function set

                Sets the specified attribute.

                @param {string|object} attribute                The desired attribute OR attribute-value dictionary
                @param {mixed} value                            The desired value
                @param [{object}] options                       Additional options for the method
                @param [{boolean = false}] options.silent       Flag indicating whether the change event should be
                                                                triggered
            */
            prototype.set = function(attribute, value, options) {
                var silent = options && options.silent === true;

                var changes = [];
                var change, oldValue;

                if (typeof attribute !== "object" && typeof value !== "undefined") {
                    oldValue = this[_getAttributes](_key)[attribute];
                    this[_getAttributes](_key)[attribute] = value;

                    //Trigger events if necessary
                    if (oldValue !== value) {
                        changes.push({
                            attribute: attribute,
                            oldValue: oldValue,
                            newValue: value
                        });
                    }
                }
                else {
                    silent = value && value.silent === true;

                    for (var key in attribute) {
                        oldValue = this[_getAttributes](_key)[key];
                        this[_getAttributes](_key)[key] = attribute[key];

                        if (oldValue !== attribute[key]) {
                            changes.push({
                                attribute: key,
                                oldValue: oldValue,
                                newValue: attribute[key]
                            });
                        }
                    }
                }

                if (changes.length > 0) {
                    for (var i = 0, length = changes.length; i < length; i++) {
                        change = changes[i];

                        if (!silent) {
                            this.trigger("change:" + change.attribute, {
                                oldValue: change.oldValue,
                                newValue: change.newValue
                            });
                        }
                    }

                    if (!silent) {
                        this.trigger("change", changes);
                    }
                }
            };

            /*
                @function has

                Checks if the specified attribute is defined and not null.

                @param {string} attribute       The desired attribute

                @return {boolean}
            */
            prototype.has = function(attribute) {
                return typeof this[_getAttributes](_key)[attribute] !== "undefined" &&
                    this[_getAttributes](_key)[attribute] !== null;
            };

            /*
                @function getId

                Returns the instance identifier.

                @return {int}
            */
            prototype.getId = function() {
                return this[_getAttributes](_key).id;
            };

            /*
                @function setId

                Sets the instance identifier.
            */
            prototype.setId = function(id) {
                var oldValue = this[_getAttributes](_key).id;
                if (oldValue !== id) {
                    this.trigger("change:id", {
                        oldValue: oldValue,
                        newValue: id
                    });

                    this.trigger("change", [{
                        attribute: "id",
                        oldValue: oldValue,
                        newValue: id
                    }]);
                }

                this[_getAttributes](_key).id = id;
            };

            /*
                @function getModel()

                Gets the model of the item.

                @return {function}
            */
            prototype.getModel = function() {
                return model;
            };

            /*
                @function toObject

                Gets an object representation of the item.

                @return {object}
            */
            prototype.toObject = function() {
                var returnData = {};

                var attributes = this[_getAttributes](_key);

                for (var attribute in attributes) {
                    returnData[attribute] = attributes[attribute];
                }

                return returnData;
            };

            /*
                @function trigger

                Triggers an event on the item.

                @param {string} event       The desired event name
                @param [{object}] args      Additional arguments for the event
            */
            prototype.trigger = function(event, args) {
                EventHelper.trigger(new Event(this, event, args));
            };

            /*
                @function observe

                Observes the item for the specified event such that the specified event listener is called
                when the aforementioned event fires.

                @param {string} event                   The desired event to be observed
                @param {function} eventListener         The desired event listener
            */
            prototype.observe = function(event, eventListener) {
                EventHelper.observe(this, event, eventListener);
            };

            /*
                @function unobserve

                Stops observing the item for the specified and specified event listener.

                @param {string} event                   The desired event to stop observing
                @param {function} eventListener         The desired event listener
            */
            prototype.unobserve = function(event, eventListener) {
                EventHelper.unobserve(this, event, eventListener);
            };

            /*
                @function validate

                Validates the current item.

                @return {boolean||object[]}
            */
            prototype.validate = function() {
                var modelRules = staticAttributes.validationRules;
                var modelErrors = {};
                var attributeRules, attributeRequired, attributeErrors, attributeOverride, attributeValue,
                attributeName, rule;

                function addError(message) {
                    attributeErrors.push(rule.message || message);
                }

                function isEmpty(value) {
                    return typeof value === "undefined" || value === null || value === "";
                }

                for (var attribute in modelRules) {
                    attributeRules = modelRules[attribute];
                    attributeValue = this[_getAttributes](_key)[attribute];
                    attributeErrors = [];
                    attributeOverride = false;
                    attributeRequired = false;
                    attributeName = StringHelper.uppercaseFirst(StringHelper.humanize(attribute));

                    //Set override flag to allow nulls/etc. for non-required attributes with type checks
                    for (var i = 0, length = attributeRules.length; i < length; i++) {
                        if (attributeRules[i].required === true) {
                            attributeRequired = true;
                            break;
                        }
                    }
                    attributeOverride = (!attributeRequired && (attributeValue === null ||
                        typeof attributeValue === "undefined" || attributeValue === ""));

                    for (i = 0, length = attributeRules.length; i < length; i++) {
                        rule = attributeRules[i];

                        if (rule.required) {
                            if (isEmpty(attributeValue)) {
                                addError(attributeName + " is required.");
                            }
                        }
                        else if (rule.type) {
                            if (!attributeOverride) {
                                if (rule.type === "string" && typeof attributeValue !== "string") {
                                    addError(attributeName + " should be a string.");
                                }
                                else if (rule.type === "int" && (typeof attributeValue !== "number" ||
                                    attributeValue % 1 !== 0)) {
                                    addError(attributeName + " should be an integer.");
                                }
                                else if (rule.type === "number" && typeof attributeValue !== "number") {
                                    addError(attributeName + " should be a number.");
                                }
                                else if (rule.type === "boolean" && typeof attributeValue !== "boolean") {
                                    addError(attributeName + " should be a boolean.");
                                }
                            }
                        }
                        else if (rule.minLength) {
                            if (isEmpty(attributeValue) || typeof attributeValue !== "string" ||
                                attributeValue.length < rule.minLength) {
                                addError(attributeName + " should be at least " + rule.minLength + " characters long.");
                            }
                        }
                        else if (rule.maxLength) {
                            if (isEmpty(attributeValue) || typeof attributeValue !== "string" ||
                                attributeValue.length > rule.maxLength) {
                                addError(attributeName + " should be at most " + rule.maxLength + " characters long.");
                            }
                        }
                        else if (rule.minValue) {
                            if (isEmpty(attributeValue) ||  typeof attributeValue !== "number" ||
                                attributeValue < rule.minValue) {
                                addError(attributeName + " should be at least " + rule.minValue + ".");
                            }
                        }
                        else if (rule.maxValue) {
                            if (isEmpty(attributeValue) || typeof attributeValue !== "number" ||
                                attributeValue > rule.maxValue) {
                                addError(attributeName + " should be at most " + rule.maxValue + ".");
                            }
                        }
                        else if (rule.format) {
                            if (
                                //jshint -W101
                                (rule.format === "email" && !/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(attributeValue)) ||
                                (rule.format === "alpha" && !/^[a-z]*$/i.test(attributeValue)) ||
                                (rule.format === "flag" && attributeValue !== 0 && attributeValue !== 1) ||
                                (rule.format === "alphanumeric" && !/^[a-z0-9]*$/i.test(attributeValue)) ||
                                (rule.format === "creditcard" && !/^(?:4[0-9]{12}(?:[0-9]{3})|5[1-5][0-9]{14}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})$/.test(attributeValue))
                                //jshint +W101
                                ) {
                                addError(attributeName + " should be a valid " + rule.format);
                            }
                        }
                        else if (rule.regex) {
                            if (isEmpty(attributeValue) || !rule.regex.test(attributeValue)) {
                                addError(attributeName + " should match " + rule.regex + ".");
                            }
                        }
                        else if (rule.function) {
                            var result = rule.function(attributeValue, this);
                            if (result !== true) {
                                addError(result);
                            }
                        }
                    }

                    if (attributeErrors.length > 0) {
                        modelErrors[attribute] = attributeErrors;
                    }

                }

                return (JSON.stringify(modelErrors) === "{}" || modelErrors);
            };

            /*
                @function isValid

                Validates the current item.

                @return {boolean}
            */
            prototype.isValid = function() {
                return this.validate() === true;
            };

            return prototype;
        })(model.prototype || {});
    };

    return Model;
});
<|endoftext|>


<commit_before>/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2016 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites,
* with a few extra properties in the data object to handle Weapon specific features.
*
* @class Phaser.Bullet
* @constructor
* @extends Phaser.Sprite
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} x - The x coordinate (in world space) to position the Particle at.
* @param {number} y - The y coordinate (in world space) to position the Particle at.
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.Bullet = function (game, x, y, key, frame) {

    Phaser.Sprite.call(this, game, x, y, key, frame);

    this.anchor.set(0.5);

    this.data = {
        bulletManager: null,
        fromX: 0,
        fromY: 0,
        bodyDirty: true,
        rotateToVelocity: false,
        killType: 0,
        killDistance: 0
    };

};

Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype);
Phaser.Bullet.prototype.constructor = Phaser.Bullet;

/**
* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool.
* Also dispatches the `Weapon.onKill` signal.
*
* @method Phaser.Bullet#kill
* @memberof Phaser.Bullet
*/
Phaser.Bullet.prototype.kill = function () {

    this.alive = false;
    this.exists = false;
    this.visible = false;

    this.data.bulletManager.onKill.dispatch(this);

    return this;

};

/**
* Updates the Bullet, killing as required.
*
* @method Phaser.Bullet#update
* @memberof Phaser.Bullet
*/
Phaser.Bullet.prototype.update = function () {

    if (!this.exists)
    {
        return;
    }

    if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN)
    {
        if (this.data.killType === Phaser.Weapon.KILL_DISTANCE)
        {
            if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance)
            {
                this.kill();
            }
        }
        else
        {
            if (!this.data.bulletManager.bulletBounds.intersects(this))
            {
                this.kill();
            }
        }
    }

    if (this.data.rotateToVelocity)
    {
        this.rotation = this.body.velocity.atan();
    }

    if (this.data.bulletManager.bulletWorldWrap)
    {
        this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding);
    }

};
<commit_msg>Whitespace<commit_after>/**
* @author       Richard Davey <rich@photonstorm.com>
* @copyright    2016 Photon Storm Ltd.
* @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/

/**
* Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites,
* with a few extra properties in the data object to handle Weapon specific features.
*
* @class Phaser.Bullet
* @constructor
* @extends Phaser.Sprite
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} x - The x coordinate (in world space) to position the Particle at.
* @param {number} y - The y coordinate (in world space) to position the Particle at.
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.Bullet = function (game, x, y, key, frame) {

    Phaser.Sprite.call(this, game, x, y, key, frame);

    this.anchor.set(0.5);

    this.data = {
        bulletManager: null,
        fromX: 0,
        fromY: 0,
        bodyDirty: true,
        rotateToVelocity: false,
        killType: 0,
        killDistance: 0
    };

};

Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype);
Phaser.Bullet.prototype.constructor = Phaser.Bullet;

/**
* Kills the Bullet, freeing it up for re-use by the Weapon bullet pool.
* Also dispatches the `Weapon.onKill` signal.
*
* @method Phaser.Bullet#kill
* @memberof Phaser.Bullet
*/
Phaser.Bullet.prototype.kill = function () {

    this.alive = false;
    this.exists = false;
    this.visible = false;

    this.data.bulletManager.onKill.dispatch(this);

    return this;

};

/**
* Updates the Bullet, killing as required.
*
* @method Phaser.Bullet#update
* @memberof Phaser.Bullet
*/
Phaser.Bullet.prototype.update = function () {

    if (!this.exists)
    {
        return;
    }

    if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN)
    {
        if (this.data.killType === Phaser.Weapon.KILL_DISTANCE)
        {
            if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance)
            {
                this.kill();
            }
        }
        else
        {
            if (!this.data.bulletManager.bulletBounds.intersects(this))
            {
                this.kill();
            }
        }
    }

    if (this.data.rotateToVelocity)
    {
        this.rotation = this.body.velocity.atan();
    }

    if (this.data.bulletManager.bulletWorldWrap)
    {
        this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding);
    }

};
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const TestRunnerContext = require('./spec-runner').TestRunnerContext;
const gatherTestSuites = require('./spec-runner').gatherTestSuites;
const generateTopologyTests = require('./spec-runner').generateTopologyTests;

const missingAwsConfiguration =
  process.env.AWS_ACCESS_KEY_ID == null || process.env.AWS_SECRET_ACCESS_KEY == null;
const skipTests = missingAwsConfiguration || process.env.MONGODB_CLIENT_ENCRYPTION == null;

describe('Client Side Encryption', function() {
  if (skipTests) {
    console.log('skipping Client Side Encryption tests due to lack of AWS credentials');
    return;
  }

  const testContext = new TestRunnerContext();
  const testSuites = gatherTestSuites(path.join(__dirname, 'spec', 'client-side-encryption'));
  after(() => testContext.teardown());
  before(function() {
    return testContext.setup(this.configuration);
  });

  generateTopologyTests(testSuites, testContext);
});
<commit_msg>test(encryption): skipping regex test for now<commit_after>'use strict';

const path = require('path');
const TestRunnerContext = require('./spec-runner').TestRunnerContext;
const gatherTestSuites = require('./spec-runner').gatherTestSuites;
const generateTopologyTests = require('./spec-runner').generateTopologyTests;

const missingAwsConfiguration =
  process.env.AWS_ACCESS_KEY_ID == null || process.env.AWS_SECRET_ACCESS_KEY == null;
const skipTests = missingAwsConfiguration || process.env.MONGODB_CLIENT_ENCRYPTION == null;

describe('Client Side Encryption', function() {
  if (skipTests) {
    console.log('skipping Client Side Encryption tests due to lack of AWS credentials');
    return;
  }

  const testContext = new TestRunnerContext();
  const testSuites = gatherTestSuites(path.join(__dirname, 'spec', 'client-side-encryption'));
  after(() => testContext.teardown());
  before(function() {
    return testContext.setup(this.configuration);
  });

  generateTopologyTests(testSuites, testContext, spec => {
    return !spec.description.match(/type=regex/);
  });
});
<|endoftext|>


<commit_before>var path = require('path');
var eejs = require('ep_etherpad-lite/node/eejs');
var toolbar = require("ep_etherpad-lite/node/utils/toolbar");
var hooks = require('ep_etherpad-lite/static/js/pluginfw/hooks');
var settings = require('../../utils/Settings');

exports.expressCreateServer = function (hook_name, args, cb) {
  // expose current stats
  args.app.get('/stats', function(req, res) {
    res.json(require('ep_etherpad-lite/node/stats').toJSON())
  })

  //serve index.html under /
  args.app.get('/', function(req, res)
  {
    res.send(eejs.require("ep_etherpad-lite/templates/index.html"));
  });

  //serve javascript.html
  args.app.get('/javascript', function(req, res)
  {
    res.send(eejs.require("ep_etherpad-lite/templates/javascript.html"));
  });

  //serve robots.txt
  args.app.get('/robots.txt', function(req, res)
  {
    var filePath = path.normalize(__dirname + "/../../../static/custom/robots.txt");
    res.sendFile(filePath, function(err)
    {
      //there is no custom favicon, send the default robots.txt which dissallows all
      if(err)
      {
        filePath = path.normalize(__dirname + "/../../../static/robots.txt");
        res.sendFile(filePath);
      }
    });
  });

  //serve pad.html under /p
  args.app.get('/p/:pad', function(req, res, next)
  {
    // Set language for pad editor for the first time
    // Or if language cookie doesn't exist
    if (req.cookies.language === undefined)
    {
      res.cookie('language', settings.padOptions.lang);
    }

    // The below might break for pads being rewritten
    var isReadOnly = req.url.indexOf("/p/r.") === 0;

    hooks.callAll("padInitToolbar", {
      toolbar: toolbar,
      isReadOnly: isReadOnly
    });

    res.send(eejs.require("ep_etherpad-lite/templates/pad.html", {
      req: req,
      toolbar: toolbar,
      isReadOnly: isReadOnly
    }));
  });

  //serve timeslider.html under /p/$padname/timeslider
  args.app.get('/p/:pad/timeslider', function(req, res, next)
  {
    hooks.callAll("padInitToolbar", {
      toolbar: toolbar
    });

    res.send(eejs.require("ep_etherpad-lite/templates/timeslider.html", {
      req: req,
      toolbar: toolbar
    }));
  });

  //serve favicon.ico from all path levels except as a pad name
  args.app.get( /\/favicon.ico$/, function(req, res)
  {
    var filePath = path.normalize(__dirname + "/../../../static/custom/favicon.ico");
    res.sendFile(filePath, function(err)
    {
      //there is no custom favicon, send the default favicon
      if(err)
      {
        filePath = path.normalize(__dirname + "/../../../static/favicon.ico");
        res.sendFile(filePath);
      }
    });
  });

}
<commit_msg>Change index to redirect to a document<commit_after>var path = require('path');
var eejs = require('ep_etherpad-lite/node/eejs');
var toolbar = require("ep_etherpad-lite/node/utils/toolbar");
var hooks = require('ep_etherpad-lite/static/js/pluginfw/hooks');
var settings = require('../../utils/Settings');

exports.expressCreateServer = function (hook_name, args, cb) {
  // expose current stats
  args.app.get('/stats', function(req, res) {
    res.json(require('ep_etherpad-lite/node/stats').toJSON())
  })

  //serve index.html under /
  args.app.get('/', function(req, res)
  {
    // SANDSTORM EDIT:  Just redirect to a particular pad!
    res.redirect("/p/main");
    // res.send(eejs.require("ep_etherpad-lite/templates/index.html"));
  });

  //serve javascript.html
  args.app.get('/javascript', function(req, res)
  {
    res.send(eejs.require("ep_etherpad-lite/templates/javascript.html"));
  });

  //serve robots.txt
  args.app.get('/robots.txt', function(req, res)
  {
    var filePath = path.normalize(__dirname + "/../../../static/custom/robots.txt");
    res.sendFile(filePath, function(err)
    {
      //there is no custom favicon, send the default robots.txt which dissallows all
      if(err)
      {
        filePath = path.normalize(__dirname + "/../../../static/robots.txt");
        res.sendFile(filePath);
      }
    });
  });

  //serve pad.html under /p
  args.app.get('/p/:pad', function(req, res, next)
  {
    // Set language for pad editor for the first time
    // Or if language cookie doesn't exist
    if (req.cookies.language === undefined)
    {
      res.cookie('language', settings.padOptions.lang);
    }

    // The below might break for pads being rewritten
    var isReadOnly = req.url.indexOf("/p/r.") === 0;

    hooks.callAll("padInitToolbar", {
      toolbar: toolbar,
      isReadOnly: isReadOnly
    });

    res.send(eejs.require("ep_etherpad-lite/templates/pad.html", {
      req: req,
      toolbar: toolbar,
      isReadOnly: isReadOnly
    }));
  });

  //serve timeslider.html under /p/$padname/timeslider
  args.app.get('/p/:pad/timeslider', function(req, res, next)
  {
    hooks.callAll("padInitToolbar", {
      toolbar: toolbar
    });

    res.send(eejs.require("ep_etherpad-lite/templates/timeslider.html", {
      req: req,
      toolbar: toolbar
    }));
  });

  //serve favicon.ico from all path levels except as a pad name
  args.app.get( /\/favicon.ico$/, function(req, res)
  {
    var filePath = path.normalize(__dirname + "/../../../static/custom/favicon.ico");
    res.sendFile(filePath, function(err)
    {
      //there is no custom favicon, send the default favicon
      if(err)
      {
        filePath = path.normalize(__dirname + "/../../../static/favicon.ico");
        res.sendFile(filePath);
      }
    });
  });

}
<|endoftext|>


<commit_before>/**
 * Smartmirror
 * ---
 * @author Michael Pomogajko
 * @version 0.1
 * ---
 * Note: Read the README!
 * ---
 */

var months = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "November", "Dezember"];

var days = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"];

function getStations(data){
    var buff = [];

    var str = data.substring(data.indexOf("<span class=\"stand"), data.indexOf("<div id=\"mobil_impressum"));

    $($(str)[2]).find('td').each(function(){
        buff.push(this);
    });

    var deps = [];

    for (var i = 0; i < 30; i++) {
        if(i%3 === 0){
            var dep = {};
            dep.line = buff[i].innerText;
            dep.to = buff[i+1].innerText;
            dep.time = buff[i+2].innerText;
            deps.push(dep);
        }
    }
    fillStations(deps);
}

function fillStations(stations){
    var table = $("#tbody");
    table.html("");

    var destset = ["Weiden West", "Junkersdorf", "Universität", "Sülz"];

    stations.forEach(function(stat){
        if(destset.indexOf(stat.to) != -1) {
            table.append("
"+stat.line+"	"+stat.to+"	"+stat.time+"
");
        } else {
            table.append("
"+stat.line+"	"+stat.to+"	"+stat.time+"
");
        }
    });
}

function loadClock(){

    // Format: Samstag, 21. Januar 2017

    var displayDate = $('#date');
    var displayClock = $('#clock');

    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth();
    var weekday = date.getDay();
    var day = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes();

    hours < 10 ? hours = "0"+hours:null;
    minutes < 10 ? minutes = "0"+minutes:null;

    displayDate.text(days[weekday] +", "+day+". "+months[month]+" "+year);
    displayClock.text(hours+":"+minutes);
}

function loadDepartures(){
    $.ajax({
        url: "http://www.kvb-koeln.de/qr/"+params.depID,
        type: 'GET',
        success: function(res){
            getStations(res.responseText);
            $('#notif').text("");
        },
        error: function(err){
            $('#notif').text("Warning! Old data!");
        }
    });
}

function loadWeather(){
    var weather = $('#weather').weatherWidget({
        cacheTime: 1,
        lat: 50.941357,
        lon: 6.958307,
        key: params.forecastApi,
        celsius: true,
        imgPath:"./weather/img/"
    });
}

function loadCalendar(){
    var calendar = $('#calendar').fullCalendar({
        googleCalendarApiKey: params.calendarApi,
        locale: "de",
        timeFormat: "HH:mm",
        height: 620,
        eventSources: [
            {
                googleCalendarId: params.calenderaIDs[0]
            },
            {
                googleCalendarId: params.calenderaIDs[1]
            }
        ]
    });
}

function todayBackgroundColor(){
    var date = new Date().getDate();

    $('.fc-day-number').each(function(){
        if(this.innerHTML == date){
            $(this).addClass("today");
        }
    });
}

$(function(){
    todayBackgroundColor();

    loadClock();

    loadWeather();

    loadCalendar();

    loadDepartures();

    setInterval(function(){
        $('#calendar').fullCalendar('refetchEvents');
    }, 1000*60*60);

    setInterval(function(){
        $('#weather').html("");
        loadWeather();
    }, 1000*60*30);

    setInterval(function(){
        loadDepartures();
    }, 1000*10);

    setInterval(function(){
        loadClock();
    }, 1000*10);

});
<commit_msg>Error handling<commit_after>/**
 * Smartmirror
 * ---
 * @author Michael Pomogajko
 * @version 0.1
 * ---
 * Note: Read the README!
 * ---
 */

var months = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "November", "Dezember"];

var days = ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"];

function getStations(data) {

    try {
        var buff = [];

        var str = data.substring(data.indexOf("<span class=\"stand"), data.indexOf("<div id=\"mobil_impressum"));

        $($(str)[2]).find('td').each(function () {
            buff.push(this);
        });

        var deps = [];

        for (var i = 0; i < 30; i++) {
            if (i % 3 === 0) {
                var dep = {};
                dep.line = buff[i].innerText;
                dep.to = buff[i + 1].innerText;
                dep.time = buff[i + 2].innerText;
                deps.push(dep);
            }
        }
        fillStations(deps);
    } catch (err) {
        $('#kvb h2').append("Error!");
    }
}

function fillStations(stations) {
    var table = $("#tbody");
    table.html("");

    var destset = ["Weiden West", "Junkersdorf", "Universität", "Sülz"];

    stations.forEach(function (stat) {
        if (destset.indexOf(stat.to) != -1) {
            table.append("
" + stat.line + "	" + stat.to + "	" + stat.time + "
");
        } else {
            table.append("
" + stat.line + "	" + stat.to + "	" + stat.time + "
");
        }
    });
}

function loadClock() {

    // Format: Samstag, 21. Januar 2017

    var displayDate = $('#date');
    var displayClock = $('#clock');

    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth();
    var weekday = date.getDay();
    var day = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes();

    hours < 10 ? hours = "0" + hours : null;
    minutes < 10 ? minutes = "0" + minutes : null;

    displayDate.text(days[weekday] + ", " + day + ". " + months[month] + " " + year);
    displayClock.text(hours + ":" + minutes);
}

function loadDepartures() {
    $.ajax({
        url: "http://www.kvb-koeln.de/qr/" + params.depID,
        type: 'GET',
        success: function (res) {
            getStations(res.responseText);
            $('#notif').text("");
        },
        error: function (err) {
            $('#notif').text("Warning! Old data!");
        }
    });
}

function loadWeather() {
    var weather = $('#weather').weatherWidget({
        cacheTime: 1,
        lat: 50.941357,
        lon: 6.958307,
        key: params.forecastApi,
        celsius: true,
        imgPath: "./weather/img/"
    });
}

function loadCalendar() {
    var calendar = $('#calendar').fullCalendar({
        googleCalendarApiKey: params.calendarApi,
        locale: "de",
        timeFormat: "HH:mm",
        height: 620,
        eventSources: [
            {
                googleCalendarId: params.calenderaIDs[0]
            },
            {
                googleCalendarId: params.calenderaIDs[1]
            }
        ]
    });
}

function todayBackgroundColor() {
    var date = new Date().getDate();

    $('.fc-day-number').each(function () {
        if (this.innerHTML == date) {
            $(this).addClass("today");
        }
    });
}

$(function () {
    todayBackgroundColor();

    loadClock();

    loadWeather();

    loadCalendar();

    loadDepartures();

    setInterval(function () {
        $('#calendar').fullCalendar('refetchEvents');
    }, 1000 * 60 * 60);

    setInterval(function () {
        $('#weather').html("");
        loadWeather();
    }, 1000 * 60 * 30);

    setInterval(function () {
        loadDepartures();
    }, 1000 * 15);

    setInterval(function () {
        loadClock();
    }, 1000 * 10);

});
<|endoftext|>


<commit_before>import React from 'react';
import { NavLink } from 'fluxible-router';
class Home extends React.Component {

render() {
const heightStyle = {
height: '100px'
};

return (

SlideWiki revolutionises how educational material is authored, shared and used.

Welcome to SlideWiki

Create, edit and share slide decks and other open educational materials. The latest version of SlideWiki includes:

upload and edit existinng PowerPoint or create new decks

version control for slide edits and decks

add comments to slides and decks

As the new SlideWiki platform is still under development, we will be regularly adding new featurses. If you are interested in finding out more about the SlideWiki project follow us on Twitter or visit the SlideWiki project website.

This project has received funding from the EU Framework Programme for Research and Innovation Horizon 2020 under grant agreement no 688095.

Featured Decks

                        <NavLink className="header" href={ '/deck/8'}>
Introduction to SlideWiki
</NavLink>

Creator: ali

Date: 29th September 2016

English

                            20

                            20

                        <NavLink className="header" href={ '/deck/53'}>
Guide to SlideWiki
</NavLink>

Creator: abijames1

Date: 5th October 2016

English

                             5

                             1

                        <NavLink className="header" href={ '/deck/42'}>
Towards a Linked Open Data Infrastructure for Science, Technology & Innovation Studies
</NavLink>

Creator: ali

Date: 3rd October 2016

English

                            13

                             1

);
}
}

export default Home;
<commit_msg>added content and featured decks with hard coded links<commit_after>import React from 'react';
import { NavLink } from 'fluxible-router';
class Home extends React.Component {

render() {
const heightStyle = {
height: '100px'
};

return (

SlideWiki revolutionises how educational material is authored, shared and used.

beta

Welcome to SlideWiki

Create, edit and share slide decks and other open educational materials. The latest version of SlideWiki includes:

upload and edit existing PowerPoint or create new decks

version control for slide edits and decks

add comments to slides and decks

Many people in the world lack access to educational material.
                Help us to create great educational material covering as many domains and as many languages as possible:

Sign in SlideWiki

Search for decks at SlideWiki, whose domain you know

Review the content of decks and help improving them

Add self-assessment questions to the slides (in development)

Translate decks covering topics you know well into your mother tongue (in development)

Look for existing presentations and e-learning material, which could be imported into SlideWiki

As the new SlideWiki platform is still under development, we will be regularly adding new featurses. If you are interested in finding out more about the SlideWiki project follow us on Twitter or visit the SlideWiki project website.

This project has received funding from the EU Framework Programme for Research and Innovation Horizon 2020 under grant agreement no 688095.

Featured Decks

                            <NavLink className="header" href={ '/deck/8'}>
Introduction to SlideWiki
</NavLink>

Creator: ali

Date: 29th September 2016

English

                                20

                                20

                            <NavLink className="header" href={ '/deck/53'}>
Guide to SlideWiki
</NavLink>

Creator: abijames1

Date: 5th October 2016

English

                                 5

                                 1

                            <NavLink className="header" href={ '/deck/42'}>
Towards a Linked Open Data Infrastructure for Science, Technology & Innovation Studies
</NavLink>

Creator: ali

Date: 3rd October 2016

English

                                13

                                 1

);
}
}

export default Home;
<|endoftext|>


<commit_before>//Copyright {2016} {NIIT Limited, Wipro Limited}
//
//   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.
//
//   Name of Developers  Raghav Goel, Kshitij Jain, Lakshay Bansal, Ayush Jain, Saurabh Gupta, Akshay Meher
//                        + Anil Sawant

angular.module('quizRT', ['ngRoute', 'ngCookies'])
    .run(function($cookies,$rootScope,$http,$location) {

      // redirect to user-profile page if the user's cookie exists
      if($cookies.get('isAuthenticated'))
        $location.path('/userProfile');

      $rootScope.stylesheetName = "index"; // name of the css stylesheet to be used while loading the app
      $rootScope.isAuthenticatedCookie = $cookies.get('isAuthenticated');
      $rootScope.$watch('isAuthenticatedCookie', function(nv,ov) { // watch that puts/removes cookie based on $rootScope.isAuthenticatedCookie
        if ( nv ) {
          $cookies.put('isAuthenticated',true);
        } else {
          $cookies.remove('isAuthenticated');
        }
      });
      $rootScope.logInLogOutSuccessMsg = ''; // used on login.html page to display login/logout status msgs
      $rootScope.logInLogOutErrorMsg = '';
      $rootScope.isPlayingAGame = false; // used to identify if the user is playing a game. This is used to hide the footer nav if true
      $rootScope.serverErrorMsg = 'Error! Kindly check your URL.'; // used in eror.html to display Error message received from the server

      $rootScope.$on('login', function(event) {
        $location.path('/login');
      });
      $rootScope.$on('logout', function(event,user) {
        console.log('Hey ' + user.name + "!, you will be logged out.");
        $http.post('auth/logout').then( function( successResponse ){
            $cookies.remove('isAuthenticated');
            $rootScope.loggedInUser = null;
            $rootScope.isAuthenticatedCookie = false;
            $rootScope.logInLogOutSuccessMsg = 'Logged out successfully!'
            $location.path('/login');
          }, function( errorResponse ) {
            $rootScope.loggedInUser = null;
            $rootScope.logInLogOutErrorMsg = 'Something went wrong!  Kindly do a fresh login-logout.'
            $location.path('/login');
          });
      });
      $rootScope.redirectTo = function( location ) {
        $location.path( "/" + location);
      };
    })
    .factory('socket', function ($rootScope) {
      // var socket = io.connect('http://172.23.238.159:8080');
     var socket = io.connect('http://localhost:8080');
      return {
        on: function (eventName, callback) {
         socket.on(eventName, function () {
         var args = arguments;
         $rootScope.$apply(function () {
           callback.apply(socket, args);
          });
         });
        },
        emit: function (eventName, data, callback) {
          socket.emit(eventName, data, function () {
           var args = arguments;
           $rootScope.$apply(function () {
            if (callback) {
            callback.apply(socket, args);
            }
           });
          })
         }
       }
      })
     .config(function($routeProvider){
       $routeProvider
        .when('/404',{
          'templateUrl' : 'html/404.html'
        })
        .when('/error',{
          'templateUrl' : 'html/error.html'
        })
        .when('/',{
          'templateUrl' : 'html/login.html',
          'controller':'authController'
        })
        .when('/login', {
          'templateUrl': 'html/login.html',
          'controller':'authController'
        })
        .when('/locallogin', {
          'templateUrl': 'html/locallogin.html',
          'controller': 'authController'
        })
        .when('/register', {
          'templateUrl': 'html/register.html',
          'controller': 'authController'
        })
        .when('/userProfile',{
          'templateUrl': 'html/userProfile.html',
          'controller': 'userProfileController'
        })
        .when('/userTeams',{
          'templateUrl': 'html/userTeams.html',
          'controller': 'userProfileController'
        })
        .when('/userTournaments',{
          'templateUrl': 'html/userTournaments.html',
          'controller': 'userProfileController'
        })
        .when('/userSettings',{
          'templateUrl': 'html/userSettings.html',
          'controller': 'userSettingsController'
        })
        .when('/categories',{
          'templateUrl': 'html/categories.html',
          'controller': 'categoriesController'
        })
        .when('/category/:categoryID',{
          'templateUrl': 'html/category.html',
          'controller': 'categoryController'
        })
        .when('/topic/:topicID',{
          'templateUrl': 'html/topic.html',
          'controller': 'topicController'
        })
        .when('/quizPlayer',{
          'templateUrl': 'html/quizPlayer.html',
          'controller': 'quizPlayerController',
          'reload':true
        })
        .when('/quizResult/:gameId',{
          'templateUrl': 'html/result.html',
          'controller': 'resultController'
        })
        .when('/tournament',{
          'templateUrl': 'html/tournamentLists.html',
          'controller': 'tournamentController'
        })
        .when('/tournament/:tournamentId' , {
          'templateUrl': 'html/rounds.html',
          'controller': 'roundsController'
        })
        .when('/tournament/tournamentPlayer' , {
          'templateUrl': 'html/tournamentPlayer.html',
          'controller': 'tournamentPlayerController'
        })
        .when('/userProfile',{
          'templateUrl': 'html/userProfile.html',
          'controller': 'userProfileController'
        })
        .when('/userTeams',{
          'templateUrl': 'html/userTeams.html',
          'controller': 'userProfileController'
        })
        .when('/userTournaments',{
          'templateUrl': 'html/userTournaments.html',
          'controller': 'userTournamentsController'
        })
        .when('/userSettings',{
          'templateUrl': 'html/userSettings.html',
          'controller': 'userSettingsController'
        })
        .when('/categories',{
          'templateUrl': 'html/categories.html',
          'controller': 'categoriesController'
        })
        .when('/category/:categoryID',{
          'templateUrl': 'html/category.html',
          'controller': 'categoryController'
        })
        .when('/topic/:topicID',{
          'templateUrl': 'html/topic.html',
          'controller': 'topicController'
        })
        .when('/quizPlayer',{
          'templateUrl': 'html/quizPlayer.html',
          'controller': 'quizPlayerController',
          'reload':true
        })
        .when('/tournament/tournamentPlayer' , {
          'templateUrl': 'html/tournamentPlayer.html',
          'controller': 'tournamentPlayerController'
        })
        .when('/leaderBoard/hallOfFame/:tournamentId' , {
          'templateUrl': 'html/hallOfFame.html',
          'controller': 'halloffameController'
        })
        .when('/createTournament' , {
          'templateUrl': 'html/createTournament.html',
          'controller': 'createTournamentController'
        })
        .otherwise({
          redirectTo : '/404'
        });
    });
<commit_msg>added app level variables, added watch on isPlayingAGame to slideToggle the footer-nav<commit_after>//Copyright {2016} {NIIT Limited, Wipro Limited}
//
//   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.
//
//   Name of Developers  Raghav Goel, Kshitij Jain, Lakshay Bansal, Ayush Jain, Saurabh Gupta, Akshay Meher
//                        + Anil Sawant

angular.module('quizRT', ['ngRoute', 'ngCookies'])
    .run(function($cookies,$rootScope,$http,$location) {

      // redirect to user-profile page if the user's cookie exists
      if($cookies.get('isAuthenticated'))
        $location.path('/userProfile');

      // Add app level variables here
      $rootScope.stylesheetName = "index"; // name of the css stylesheet to be used while loading the app
      $rootScope.isAuthenticatedCookie = $cookies.get('isAuthenticated');
      $rootScope.logInLogOutSuccessMsg = ''; // used on login.html page to display login/logout status msgs
      $rootScope.logInLogOutErrorMsg = '';
      $rootScope.serverErrorMsg = 'Error! Kindly check your URL.'; // used in eror.html to display Error message received from the server
      $rootScope.isPlayingAGame = false; // used to identify if the user is playing a game. This is used to hide the footer nav if true
      $rootScope.recentGames = {}; // save the recent games played by the user since last login. Saved as {gameId:gameBoard}
      $rootScope.recentGamesTopicNames = {}; // save the recent games' topic names played by the user since last login. saved as {gameId:topicname}

      // Added application level watcher here
      $rootScope.$watch('isAuthenticatedCookie', function(nv,ov) { // watch that puts/removes cookie based on $rootScope.isAuthenticatedCookie
        if ( nv ) {
          $cookies.put('isAuthenticated',true);
        } else {
          $cookies.remove('isAuthenticated');
        }
      });
      $rootScope.$watch( 'isPlayingAGame', function(nv,ov) {
        if ( nv ) {
          $( '#footer-nav' ).slideUp();
        } else {
          $( '#footer-nav' ).slideDown();
        }
      });

      // Add app level events here
      $rootScope.$on('login', function(event) {
        $location.path('/login');
      });
      $rootScope.$on('logout', function(event,user) {
        console.log('Hey ' + user.name + "!, you will be logged out.");
        $http.post('auth/logout').then( function( successResponse ){
            $cookies.remove('isAuthenticated');
            $rootScope.loggedInUser = null;
            $rootScope.isAuthenticatedCookie = false;
            $rootScope.logInLogOutSuccessMsg = 'Logged out successfully!'
            $location.path('/login');
          }, function( errorResponse ) {
            $rootScope.loggedInUser = null;
            $rootScope.logInLogOutErrorMsg = 'Something went wrong!  Kindly do a fresh login-logout.'
            $location.path('/login');
          });
      });
      $rootScope.redirectTo = function( location ) {
        $location.path( "/" + location);
      };
    })
    .factory('socket', function ($rootScope) {
      // var socket = io.connect('http://172.23.238.159:8080');
     var socket = io.connect('http://localhost:8080');
      return {
        on: function (eventName, callback) {
         socket.on(eventName, function () {
         var args = arguments;
         $rootScope.$apply(function () {
           callback.apply(socket, args);
          });
         });
        },
        emit: function (eventName, data, callback) {
          socket.emit(eventName, data, function () {
           var args = arguments;
           $rootScope.$apply(function () {
            if (callback) {
            callback.apply(socket, args);
            }
           });
          })
         }
       }
      })
     .config(function($routeProvider){
       $routeProvider
        .when('/404',{
          'templateUrl' : 'html/404.html'
        })
        .when('/error',{
          'templateUrl' : 'html/error.html'
        })
        .when('/',{
          'templateUrl' : 'html/login.html',
          'controller':'authController'
        })
        .when('/login', {
          'templateUrl': 'html/login.html',
          'controller':'authController'
        })
        .when('/locallogin', {
          'templateUrl': 'html/locallogin.html',
          'controller': 'authController'
        })
        .when('/register', {
          'templateUrl': 'html/register.html',
          'controller': 'authController'
        })
        .when('/userProfile',{
          'templateUrl': 'html/userProfile.html',
          'controller': 'userProfileController'
        })
        .when('/userTeams',{
          'templateUrl': 'html/userTeams.html',
          'controller': 'userProfileController'
        })
        .when('/userTournaments',{
          'templateUrl': 'html/userTournaments.html',
          'controller': 'userProfileController'
        })
        .when('/userSettings',{
          'templateUrl': 'html/userSettings.html',
          'controller': 'userSettingsController'
        })
        .when('/categories',{
          'templateUrl': 'html/categories.html',
          'controller': 'categoriesController'
        })
        .when('/category/:categoryID',{
          'templateUrl': 'html/category.html',
          'controller': 'categoryController'
        })
        .when('/topic/:topicId',{
          'templateUrl': 'html/topic.html',
          'controller': 'topicController'
        })
        .when('/quizPlayer',{
          'templateUrl': 'html/quizPlayer.html',
          'controller': 'quizPlayerController',
          'reload':true
        })
        .when('/quizResult/:gameId',{
          'templateUrl': 'html/result.html',
          'controller': 'resultController'
        })
        .when('/tournament',{
          'templateUrl': 'html/tournamentLists.html',
          'controller': 'tournamentController'
        })
        .when('/tournament/:tournamentId' , {
          'templateUrl': 'html/rounds.html',
          'controller': 'roundsController'
        })
        .when('/tournament/tournamentPlayer' , {
          'templateUrl': 'html/tournamentPlayer.html',
          'controller': 'tournamentPlayerController'
        })
        .when('/userProfile',{
          'templateUrl': 'html/userProfile.html',
          'controller': 'userProfileController'
        })
        .when('/userTeams',{
          'templateUrl': 'html/userTeams.html',
          'controller': 'userProfileController'
        })
        .when('/userTournaments',{
          'templateUrl': 'html/userTournaments.html',
          'controller': 'userTournamentsController'
        })
        .when('/userSettings',{
          'templateUrl': 'html/userSettings.html',
          'controller': 'userSettingsController'
        })
        .when('/categories',{
          'templateUrl': 'html/categories.html',
          'controller': 'categoriesController'
        })
        .when('/category/:categoryID',{
          'templateUrl': 'html/category.html',
          'controller': 'categoryController'
        })
        .when('/topic/:topicID',{
          'templateUrl': 'html/topic.html',
          'controller': 'topicController'
        })
        .when('/quizPlayer',{
          'templateUrl': 'html/quizPlayer.html',
          'controller': 'quizPlayerController',
          'reload':true
        })
        .when('/tournament/tournamentPlayer' , {
          'templateUrl': 'html/tournamentPlayer.html',
          'controller': 'tournamentPlayerController'
        })
        .when('/leaderBoard/hallOfFame/:tournamentId' , {
          'templateUrl': 'html/hallOfFame.html',
          'controller': 'halloffameController'
        })
        .when('/createTournament' , {
          'templateUrl': 'html/createTournament.html',
          'controller': 'createTournamentController'
        })
        .otherwise({
          redirectTo : '/404'
        });
    });
<|endoftext|>