<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 Junil Um

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.

github: https://github.com/powerumc/Javascript-OOP-AOP-IoC
blog  : http://blog.powerumc.kr/
*/

;
var oop = (function() {

    var LOG   = function() { console.log.apply(console, arguments); };
    var DEBUG = function() { (console.debug || console.warn).apply(console, arguments); };
    var TRACE = function() { console.trace.apply(console, arguments); };
    var ERROR = function() { console.error.apply(console, arguments); };

    (function() {
        var __id = 1;
        Object.defineProperty(Object.prototype, "__object_id", {
            writable: true
        });
        Object.defineProperty(Object.prototype, "objectId", {
            get: function() {
                if (this.__object_id == undefined)
                    this.__object_id = __id++;
                return this.__object_id;
            }
        });
    }());

    function isObject(obj) {
        return typeof obj === "object" && obj.constructor.name !== "Array";
    }

    function isProperty(obj) {
        return isObject(obj) && (obj.get || obj.set);
    }

    function isFunction(obj) {
        return typeof obj === "function";
    }

    function isArray(obj) {
        return typeof obj === "object" && obj.constructor.name === "Array";
    }

    function isString(obj) {
        return typeof obj === "string";
    }

    function isNumber(obj) {
        return typeof obj === "number";
    }

    function isStatic(obj) {
        return typeof obj === "string" && obj === "static";
    }

    var setStaticMethod = function(type, static_objects) {
        for(var p in static_objects) {
            if (!static_objects.hasOwnProperty(p)) continue;
            type[p] = static_objects[p];
        }
    };

    var setProperty = function(self, propName, funcGet, funcSet) {
        Object.defineProperty(self, propName, { get: funcGet, set: funcSet });
    };

    var getProperties = function(clazz) {
        var propList = [];
        var type = clazz;
        for(var p in type) {
            if (!type.hasOwnProperty(p)) continue;
            propList.push({ "name":p, "object":type[p] });
        }
        return propList;
    };

    var getClassFromLiterals = function(literals) {
        var props = getProperties(literals);
        function ____() { }

        for(var p in props) {
            setPropertySpecification(____, props[p]);
        }

        return ____;
    };

    var setPropertySpecification = function(type, p) {
        var target = p.object;

        if (isStatic(p.name)) {
            setStaticMethod(type, target);
            return;
        }

        if (isProperty(target)) {
            setProperty(type.prototype, p.name, target.get, target.set);
            return;
        }

        if (isFunction(target)) {
            target = injectMethod(target);
            target.name = p.name;
            type.prototype[p.name] = target;
            type.prototype[p.name].prototype.name = p.name;
            type.prototype[p.name].constructor = type;
            return;
        } else {
            type.prototype[p.name] = target;
            return;
        }
    };

    var getFunctionParameters = function(func) {
        var pattern         = /function[\s\w]*\(([(\w\s, ^\/\*,) ]+)\)/g;
        var pattern_comment = /(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(\/\/.*)/gm;
        var match = pattern.exec(func.toString());
        if (!match) return [];
        var params = match[1].replace(/ |\n/g, "").replace(pattern_comment, "").split(',');
        return params || [];
    };

    var getFunctionBody = function(func) {
        var pattern = /[^{]{((?:[^}])|(?:[^{]))*}[^}]/gm;
        return func.toString().match(pattern)[0].trim().substring(2)
    };

    var surroundTryCatch = function(func, exceptionFunc) {
        if (!func && !exceptionFunc) return "";

        return "\ntry {" + func + "} catch(err) { " + (exceptionFunc || "throw err;") + "}";
    };

    var surroundTryCatchFinally = function(func, exceptionFunc, finallyFunc) {
        if (!func && !exceptionFunc && !finallyFunc) return "";

        return "\ntry {" + func + "} catch(err) { " + (exceptionFunc || "throw err;") + "} " + (finallyFunc ? "finally { " + (finallyFunc || "") + " }" : "");
    };

    var surroundBehavior = function(func, behavior) {
        behavior          = behavior || {};
        var beforeFunc    = surroundTryCatch(immediateFunc(behavior.before || ""));
        var proc_func     = surroundTryCatch(func);
        var afterFunc     = surroundTryCatch(immediateFunc(behavior.after || ""));
        return surroundTryCatchFinally(beforeFunc + proc_func + afterFunc, immediateFunc(behavior.exception), immediateFunc(behavior.finally));
    };

    var InterceptionFunc = function(func, behavior) {
        var params       = getFunctionParameters(func);
        var proxyFunc    = getFunctionBody(func);
        proxyFunc        = surroundBehavior(proxyFunc, behavior);

        DEBUG("params ", params);

        var interceptionFunc         = new Function(params.join(","), proxyFunc);
        interceptionFunc.constructor = func.constructor;
        interceptionFunc.prototype   = func.prototype;
        interceptionFunc.constructor.prototype[interceptionFunc.prototype.name] = interceptionFunc;
    };

    var Interception = function(func, behavior) {
        if (isFunction(func)) { InterceptionFunc(func, behavior); }
        else if (isObject(func) && func.constructor && func.constructor.name === "____") {
            for(var p in func) {
                if (isFunction(func[p])) { InterceptionFunc(func[p], behavior); }
            }
        }
    };

    function immediateFunc(func, args) {
        args = args || [];
        if (!func) return "";

        var func_body = "";
        var func_args = "";
        if (func) {
            func_body = "(" + func + ")";
            if (args) { func_args = "(" + args.join(",") + ")"; }
        }

        return func_body + func_args;
    }

    var injectMethod = function(m, b) {
        var p                = getFunctionParameters(m);
        var func_param       = [];
        var func_param_ahead = [];

        if (p && p.length > 0) {
            for(var i=0; i<p.length; i++) {
                if (p[i] == "base") func_param.push("this.__base__");
                else if(p[i] == "self") func_param.push("this");
                else {
                    func_param.push(p[i]);
                    func_param_ahead.push(p[i]);
                }
            }
        }

        var func_body = immediateFunc(m, func_param);
        func_body     = surroundTryCatch(func_body);

        return new Function(func_param_ahead.join(","), func_body);
    };

    var Inject = function() {
        var methods = Array.prototype.slice.apply(arguments, []);
        var ret = [];
        for(var m in methods) {
            m = methods[m];
            p = getFunctionParameters(m);
            ret.push(injectMethod(p, m));
        }
        return ret;
    };

    var InterceptionBehavior = function(before, after, exception, finally_) {

        this.before     = before;
        this.after      = after;
        this.finally_   = finally_;
        this.exception  = exception;

        return {
            "before"   : this.before,
            "after"    : this.after,
            "finally"  : this.finally_,
            "exception": this.exception
        };
    };

    var Class = function(parents, classInfo) {
        classInfo      = Array.prototype.slice.apply(arguments, [-1])[0];
        var arrParents = Array.prototype.slice.apply(arguments, [0, arguments.length-1]);
        if (arrParents && arrParents.length <= 1) { parents = undefined }
        LOG("[classInfo] ", classInfo);

        if (classInfo === undefined) {
            classInfo = parents;
            parents = undefined;
        }

        var parent_object;
        var self_arguments = arguments;
        var self           = this;
        var type           = this.constructor;
        var ret            = {};
        var clazz_def      = getClassFromLiterals(classInfo);

        for(var parent in arrParents) {
            parent = arrParents[parent];
            parent = (self.constructor && self.constructor.name !== "Window") ? parent : undefined;
            if (parent) {
                oop.extend(parent, clazz_def)
            }
        }

        return clazz_def;
    };

    return {
        extend: function(parent, clazz) {
            var parent_object;
            (function() {
                if (parent) {
                    parent_object = Object.create(parent.prototype);
                }
                if (clazz.init) {
                    clazz.init.apply(self, arguments);
                }
            })();

            for(var p in parent_object) { if (!clazz.prototype[p]) { clazz.prototype[p] = parent_object[p]; } }
            clazz.prototype.constructor = clazz;
            clazz.prototype.__base__    = parent_object;

            return clazz;
        },
        class: function(parents, classInfo) {
            return Class.apply(this, arguments);
        },
        inject: function(method) {
            return Inject.apply(this, arguments);
        },
        interceptionBehavior : function(before, after, exception, finally_) {
            return InterceptionBehavior(before, after, exception, finally_);
        },
        interception: function(func, behavior) {
            return Interception(func, behavior);
        },
        getset: function(get, set) {
            this.get = get;
            this.set = set;
        },
        get: function(funcGet) { setProperty(this, "prop2", funcGet, undefined); return "A"; },
        set: function(value) { },
        static: function(static_objects) {
        },
        isObject: isObject,
        isFunction: isFunction,
        isNumber: isNumber,
        isString: isString,
        isArray: isArray,
        isProperty: isProperty,
        isStatic: isStatic,
        objects: []
    }

})();

(function(oop) {
    var msie = document.documentMode;
    var createHttpRequest = function() {
        if (window.ActiveXObject && msie && msie < 8) {
            return new window.ActiveXObject("Microsoft.XMLHTTP");
        } else if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        }
    };

    var commonXhr = function(self) {
        return {
            open: function(method, url, isAsync) {
                this.xhr = createHttpRequest();
                this.xhr.open(method, url, isAsync);
                return self;
            },
            send: function(data) {
                this.xhr.send(data || null);
                return void(0);
            },
            success: function(callback) {
                this.xhr.onload = function(e) { callback(e.target.response); };
                return this;
            },
            error: function(callback) {
                this.xhr.onerror = function(e) { callback(e.target.response); };
                return this;
            },
            timeout: function(callback) {
                this.ontimeout = function(e) { callback(e.target.response); };
                return this;
            }
        };
    };

    function getContentType(data) {
        if (oop.isObject(data)) return "application/json";
        else if (oop.isString(data) || oop.isNumber(data)) return "text/plain";

        return "text/xml";
    }

    oop.xhr = {
        "get": function(url, data, isAsync) {
            isAsync = isAsync || true;
            var xhr = commonXhr(xhr);
            xhr.open.apply(xhr, ["get", url, isAsync]);
            xhr.xhr.setRequestHeader("Content-Type", getContentType(data));
            xhr.xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            return xhr;
        },
        "post": function(url, data, isAsync) {
            isAsync = isAsync || true;
            var xhr = commonXhr(xhr);
            xhr.open.apply(xhr, ["post", url, isAsync]);
            xhr.xhr.setRequestHeader("Content-Type", getContentType(data));
            xhr.xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            return xhr;
        }
    };
})(oop);

(function(oop) {
    var require = function(url, sourceKind, callback) {
        var source;

        if (!url) return;

        if (sourceKind === "js") {
            source = document.createElement("script");
            source.type = "text/javascript";
            source.src = url;
        } else if (sourceKind === "css") {
            source = document.createElement("link");
            source.type = "text/css";
            source.rel = "stylesheet";
            source.href = url;
        } else if (sourceKind === "template") {
            var xhr = oop.xhr.get(url, function(result) {
                console.info(result);
            })
            .success(function(result) {
                var uniqueId = getFilenameWithoutExtension(url);
                if (!document.getElementById(uniqueId)) {

                source = document.createElement("script");
                source.type = "text/x-nexon-template";
                source.id = uniqueId;
                source.innerText = result;

                append();
                }

                if (callback) callback(result);
            })
            .error(function(result) {
                callback(result);
            });

            xhr.send();
        }

        if (!source) return;

        append();

        function append() {
            var dom = document.getElementsByTagName("head") || document.getElementsByTagName("body");
            if (dom.length > 0) {
                dom[0].appendChild(source);
                if (callback) callback();
            }
        }

        function getFilenameWithoutExtension(url) {
            return url.split('/').pop().split('.')[0];
        }
    };

    oop.import = function(url, sourceKind, callback) {
        sourceKind = sourceKind || "js";
        require.call(this, url, sourceKind, callback);
    };

})(oop);

/**
 * OOP Flow
 */
(function(oop) {

    oop.flow = function(obj) {
        return {
            "then": function() {
                console.info("then");
                return this;
            },
            "with": function() {
                console.info("then");
                return this;
            }
        };
    };

})(oop);

(function(oop) {
    oop.behaviors = {
            LoggingBehavior: oop.interceptionBehavior(function() {
                                                                    this.date = new Date();
                                                                    if (!this.date) {
                                                                    console.log(this.date.toLocaleString() + " [js.oop] LoggingBehavior Begin ");
                                                                    var options = {
                                                                          year: 'numeric', month: 'numeric', day: 'numeric',
                                                                          hour: 'numeric', minute: 'numeric', second: 'numeric',
                                                                          hour12: false
                                                                        };
                                                                    }
                                                                    console.log("["+this.date.toLocaleString('en-US', this.options)+"] ", arguments);
                                                                },
                                                                function() {
                                                                    console.log(this.date.toLocaleString() + " [js.oop] LoggingBehavior End ")
                                                                }, undefined,undefined),
            ExceptionBehavior: oop.interceptionBehavior(undefined,undefined,undefined,undefined)
        };
})(oop);<commit_msg>fixed a few bugs for templates<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 Junil Um

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.

github: https://github.com/powerumc/Javascript-OOP-AOP-IoC
blog  : http://blog.powerumc.kr/
*/

;
var oop = (function() {

    var LOG   = function() { console.log.apply(console, arguments); };
    var DEBUG = function() { (console.debug || console.warn).apply(console, arguments); };
    var TRACE = function() { console.trace.apply(console, arguments); };
    var ERROR = function() { console.error.apply(console, arguments); };

    (function() {
        var __id = 1;
        Object.defineProperty(Object.prototype, "__object_id", {
            writable: true
        });
        Object.defineProperty(Object.prototype, "objectId", {
            get: function() {
                if (this.__object_id == undefined)
                    this.__object_id = __id++;
                return this.__object_id;
            }
        });
    }());

    function isObject(obj) {
        return typeof obj === "object" && obj.constructor.name !== "Array";
    }

    function isProperty(obj) {
        return isObject(obj) && (obj.get || obj.set);
    }

    function isFunction(obj) {
        return typeof obj === "function";
    }

    function isArray(obj) {
        return typeof obj === "object" && obj.constructor.name === "Array";
    }

    function isString(obj) {
        return typeof obj === "string";
    }

    function isNumber(obj) {
        return typeof obj === "number";
    }

    function isStatic(obj) {
        return typeof obj === "string" && obj === "static";
    }

    var setStaticMethod = function(type, static_objects) {
        for(var p in static_objects) {
            if (!static_objects.hasOwnProperty(p)) continue;
            type[p] = static_objects[p];
        }
    };

    var setProperty = function(self, propName, funcGet, funcSet) {
        Object.defineProperty(self, propName, { get: funcGet, set: funcSet });
    };

    var getProperties = function(clazz) {
        var propList = [];
        var type = clazz;
        for(var p in type) {
            if (!type.hasOwnProperty(p)) continue;
            propList.push({ "name":p, "object":type[p] });
        }
        return propList;
    };

    var getClassFromLiterals = function(literals) {
        var props = getProperties(literals);
        function ____() { }

        for(var p in props) {
            setPropertySpecification(____, props[p]);
        }

        return ____;
    };

    var setPropertySpecification = function(type, p) {
        var target = p.object;

        if (isStatic(p.name)) {
            setStaticMethod(type, target);
            return;
        }

        if (isProperty(target)) {
            setProperty(type.prototype, p.name, target.get, target.set);
            return;
        }

        if (isFunction(target)) {
            target = injectMethod(target);
            target.name = p.name;
            type.prototype[p.name] = target;
            type.prototype[p.name].prototype.name = p.name;
            type.prototype[p.name].constructor = type;
            return;
        } else {
            type.prototype[p.name] = target;
            return;
        }
    };

    var getFunctionParameters = function(func) {
        var pattern         = /function[\s\w]*\(([(\w\s, ^\/\*,) ]+)\)/g;
        var pattern_comment = /(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(\/\/.*)/gm;
        var match = pattern.exec(func.toString());
        if (!match) return [];
        var params = match[1].replace(/ |\n/g, "").replace(pattern_comment, "").split(',');
        return params || [];
    };

    var getFunctionBody = function(func) {
        var pattern = /[^{]{((?:[^}])|(?:[^{]))*}[^}]/gm;
        return func.toString().match(pattern)[0].trim().substring(2)
    };

    var surroundTryCatch = function(func, exceptionFunc) {
        if (!func && !exceptionFunc) return "";

        return "\ntry {" + func + "} catch(err) { " + (exceptionFunc || "throw err;") + "}";
    };

    var surroundTryCatchFinally = function(func, exceptionFunc, finallyFunc) {
        if (!func && !exceptionFunc && !finallyFunc) return "";

        return "\ntry {" + func + "} catch(err) { " + (exceptionFunc || "throw err;") + "} " + (finallyFunc ? "finally { " + (finallyFunc || "") + " }" : "");
    };

    var surroundBehavior = function(func, behavior) {
        behavior          = behavior || {};
        var beforeFunc    = surroundTryCatch(immediateFunc(behavior.before || ""));
        var proc_func     = surroundTryCatch(func);
        var afterFunc     = surroundTryCatch(immediateFunc(behavior.after || ""));
        return surroundTryCatchFinally(beforeFunc + proc_func + afterFunc, immediateFunc(behavior.exception), immediateFunc(behavior.finally));
    };

    var InterceptionFunc = function(func, behavior) {
        var params       = getFunctionParameters(func);
        var proxyFunc    = getFunctionBody(func);
        proxyFunc        = surroundBehavior(proxyFunc, behavior);

        DEBUG("params ", params);

        var interceptionFunc         = new Function(params.join(","), proxyFunc);
        interceptionFunc.constructor = func.constructor;
        interceptionFunc.prototype   = func.prototype;
        interceptionFunc.constructor.prototype[interceptionFunc.prototype.name] = interceptionFunc;
    };

    var Interception = function(func, behavior) {
        if (isFunction(func)) { InterceptionFunc(func, behavior); }
        else if (isObject(func) && func.constructor && func.constructor.name === "____") {
            for(var p in func) {
                if (isFunction(func[p])) { InterceptionFunc(func[p], behavior); }
            }
        }
    };

    function immediateFunc(func, args) {
        args = args || [];
        if (!func) return "";

        var func_body = "";
        var func_args = "";
        if (func) {
            func_body = "(" + func + ")";
            if (args) { func_args = "(" + args.join(",") + ")"; }
        }

        return func_body + func_args;
    }

    var injectMethod = function(m, b) {
        var p                = getFunctionParameters(m);
        var func_param       = [];
        var func_param_ahead = [];

        if (p && p.length > 0) {
            for(var i=0; i<p.length; i++) {
                if (p[i] == "base") func_param.push("this.__base__");
                else if(p[i] == "self") func_param.push("this");
                else {
                    func_param.push(p[i]);
                    func_param_ahead.push(p[i]);
                }
            }
        }

        var func_body = immediateFunc(m, func_param);
        func_body     = surroundTryCatch(func_body);

        return new Function(func_param_ahead.join(","), func_body);
    };

    var Inject = function() {
        var methods = Array.prototype.slice.apply(arguments, []);
        var ret = [];
        for(var m in methods) {
            m = methods[m];
            p = getFunctionParameters(m);
            ret.push(injectMethod(p, m));
        }
        return ret;
    };

    var InterceptionBehavior = function(before, after, exception, finally_) {

        this.before     = before;
        this.after      = after;
        this.finally_   = finally_;
        this.exception  = exception;

        return {
            "before"   : this.before,
            "after"    : this.after,
            "finally"  : this.finally_,
            "exception": this.exception
        };
    };

    var Class = function(parents, classInfo) {
        classInfo      = Array.prototype.slice.apply(arguments, [-1])[0];
        var arrParents = Array.prototype.slice.apply(arguments, [0, arguments.length-1]);
        if (arrParents && arrParents.length <= 1) { parents = undefined }
        LOG("[classInfo] ", classInfo);

        if (classInfo === undefined) {
            classInfo = parents;
            parents = undefined;
        }

        var parent_object;
        var self_arguments = arguments;
        var self           = this;
        var type           = this.constructor;
        var ret            = {};
        var clazz_def      = getClassFromLiterals(classInfo);

        for(var parent in arrParents) {
            parent = arrParents[parent];
            parent = (self.constructor && self.constructor.name !== "Window") ? parent : undefined;
            if (parent) {
                oop.extend(parent, clazz_def)
            }
        }

        return clazz_def;
    };

    return {
        extend: function(parent, clazz) {
            var parent_object;
            (function() {
                if (parent) {
                    parent_object = Object.create(parent.prototype);
                }
                if (clazz.init) {
                    clazz.init.apply(self, arguments);
                }
            })();

            for(var p in parent_object) { if (!clazz.prototype[p]) { clazz.prototype[p] = parent_object[p]; } }
            clazz.prototype.constructor = clazz;
            clazz.prototype.__base__    = parent_object;

            return clazz;
        },
        class: function(parents, classInfo) {
            return Class.apply(this, arguments);
        },
        inject: function(method) {
            return Inject.apply(this, arguments);
        },
        interceptionBehavior : function(before, after, exception, finally_) {
            return InterceptionBehavior(before, after, exception, finally_);
        },
        interception: function(func, behavior) {
            return Interception(func, behavior);
        },
        getset: function(get, set) {
            this.get = get;
            this.set = set;
        },
        get: function(funcGet) { setProperty(this, "prop2", funcGet, undefined); return "A"; },
        set: function(value) { },
        static: function(static_objects) {
        },
        isObject: isObject,
        isFunction: isFunction,
        isNumber: isNumber,
        isString: isString,
        isArray: isArray,
        isProperty: isProperty,
        isStatic: isStatic,
        objects: []
    }

})();

oop.xhr = (function(oop) {
    var msie = document.documentMode;
    var createHttpRequest = function() {
        if (window.ActiveXObject && msie && msie < 8) {
            return new window.ActiveXObject("Microsoft.XMLHTTP");
        } else if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        }
    };

    var commonXhr = function(self) {
        return {
            open: function(method, url, isAsync) {
                this.xhr = createHttpRequest();
                this.xhr.open(method, url, isAsync);
                return self;
            },
            send: function(data) {
                this.xhr.send(data || null);
                return void(0);
            },
            success: function(callback) {
                this.xhr.onload = function(e) { callback(e.target.response); };
                return this;
            },
            error: function(callback) {
                this.xhr.onerror = function(e) { callback(e.target.response); };
                return this;
            },
            timeout: function(callback) {
                this.ontimeout = function(e) { callback(e.target.response); };
                return this;
            }
        };
    };

    function getContentType(data) {
        if (oop.isObject(data)) return "application/json";
        else if (oop.isString(data) || oop.isNumber(data)) return "text/plain";

        return "text/xml";
    }

    return {
        "get": function(url, data, isAsync) {
            isAsync = isAsync || true;
            var xhr = commonXhr(xhr);
            xhr.open.apply(xhr, ["get", url, isAsync]);
            xhr.xhr.setRequestHeader("Content-Type", getContentType(data));
            xhr.xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            return xhr;
        },
        "post": function(url, data, isAsync) {
            isAsync = isAsync || true;
            var xhr = commonXhr(xhr);
            xhr.open.apply(xhr, ["post", url, isAsync]);
            xhr.xhr.setRequestHeader("Content-Type", getContentType(data));
            xhr.xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            return xhr;
        }
    };
})(oop);

oop.import = (function(url, sourceKind, callback, isLiteral, preHandler) {
    var require = function(url, sourceKind, callback, isLiteral, preHandler) {
        var source;
        if (!url) return;

        isLiteral = isLiteral === undefined ? false : true;

        if (!sourceKind) {
            var arr = url.split(".").slice(-1);
            if (arr.length > 0) {
                sourceKind = arr[0];
            }
        }

        if (!isLiteral) {
            if (sourceKind === "js") {
                source = document.createElement("script");
                source.type = "text/javascript";
                source.src = url;

                if (preHandler) preHandler(source);
                append("head");
            } else if (sourceKind === "css") {
                source = document.createElement("link");
                source.type = "text/css";
                source.rel = "stylesheet";
                source.href = url;

                if (preHandler) preHandler(source);
                append("head");
            }
        } else {
            var xhr = oop.xhr.get(url, function(result) {
                console.info(result);
            })
            .success(function(result) {
                result = result.replace("\n", "");
                var uniqueId = getFilenameWithoutExtension(url);
                if (!document.getElementById(uniqueId)) {
                    source = document.createElement("script");
                    source.id = uniqueId;
                    source.innerHTML = result;

                    if (preHandler) preHandler(source);
                    append("head");
                }

            })
            .error(function(result) {
                if (callback) callback(result);
            });

            xhr.send();
        }

        function append(nodeName) {
            var dom = document.getElementsByTagName(nodeName) || document.getElementsByTagName("head");
            if (dom.length > 0) {
                dom[0].appendChild(source);
                if (callback) callback();
            }
        }

        function getFilenameWithoutExtension(url) {
            return url.split('/').pop().split('.')[0];
        }
    };

    require.call(this, url, sourceKind, callback, isLiteral, preHandler);

});

oop.importTemplate = (function(url, callback) {
    oop.import(url, "", callback, true, function(source) {
        source.id = source.id + "-template";
        source.type = "x-nexon-template";
    });
});

/**
 * OOP Flow
 */
(function(oop) {

    oop.flow = function(obj) {
        return {
            "then": function() {
                console.info("then");
                return this;
            },
            "with": function() {
                console.info("then");
                return this;
            }
        };
    };

})(oop);

(function(oop) {
    oop.behaviors = {
            LoggingBehavior: oop.interceptionBehavior(function() {
                                                                    this.date = new Date();
                                                                    if (!this.date) {
                                                                    console.log(this.date.toLocaleString() + " [js.oop] LoggingBehavior Begin ");
                                                                    var options = {
                                                                          year: 'numeric', month: 'numeric', day: 'numeric',
                                                                          hour: 'numeric', minute: 'numeric', second: 'numeric',
                                                                          hour12: false
                                                                        };
                                                                    }
                                                                    console.log("["+this.date.toLocaleString('en-US', this.options)+"] ", arguments);
                                                                },
                                                                function() {
                                                                    console.log(this.date.toLocaleString() + " [js.oop] LoggingBehavior End ")
                                                                }, undefined,undefined),
            ExceptionBehavior: oop.interceptionBehavior(undefined,undefined,undefined,undefined)
        };

})(oop);
<|endoftext|>


<commit_before>$(function() {

  var cues = {
    curtain: 7 * 1000,
    voice: 20 * 1000,
    marquee: 22 * 1000,
    cats: 24 * 1000
  };

  function curtain() {
    console.log('curtain');
    $('#curtain').fadeOut('slow');
  }

  function voice() {
    console.log('voice');
    var audioElement = document.getElementById("welcomeVader");
    audioElement.playbackRate = 0.5;
    audioElement.play();
  }

  function marquee() {
    $('marquee#welcome').css('display', 'block');
  }

  function cats() {
    console.log('meow!');
    $('.leftcat').animate({ left: "0px", bottom: "0px"}, 30 * 1000)
      $('.ritecat').animate({ right: "0px", bottom: "0px"}, 30 * 1000)
  }

  setTimeout(curtain, cues.curtain);
  setTimeout(voice, cues.voice);
  setTimeout(marquee, cues.marquee);
  setTimeout(cats, cues.cats);
});

<commit_msg>alphabetically sort<commit_after>$(function() {

  var cues = {
    cats: 24 * 1000,
    curtain: 7 * 1000,
    marquee: 22 * 1000,
    voice: 20 * 1000
  };

  function curtain() {
    console.log('curtain');
    $('#curtain').fadeOut('slow');
  }

  function voice() {
    console.log('voice');
    var audioElement = document.getElementById("welcomeVader");
    audioElement.playbackRate = 0.5;
    audioElement.play();
  }

  function marquee() {
    $('marquee#welcome').css('display', 'block');
  }

  function cats() {
    console.log('meow!');
    $('.leftcat').animate({ left: "0px", bottom: "0px"}, 30 * 1000)
      $('.ritecat').animate({ right: "0px", bottom: "0px"}, 30 * 1000)
  }

  setTimeout(curtain, cues.curtain);
  setTimeout(voice, cues.voice);
  setTimeout(marquee, cues.marquee);
  setTimeout(cats, cues.cats);
});

<|endoftext|>


<commit_before>
;
var DEBUG = function() { console.log(arguments[0]); }

var oop = (function(oop) {
    ;

    var Accessor = {
        Public: "public",
        Private: "private"
    };

    var getProperties = function(clazz) {
        var type = (clazz instanceof Object) ? clazz : clazz;
        var propList = [];
        for(var p in type) {
            if (!type.hasOwnProperty(p)) continue;
            propList.push(p);
        }
        return propList;
    };

    var Class = function(classInfo) {

        //parent = parent || {};
        //clazz  = clazz | function() { };

        return (function() {
            var self = this;
            var type = this.constructor;

            (function() {
            })();

            return self;
        });

    };

    oop = {
        extend: function(parent, clazz) {
            for(var p in clazz) {
                if (parent.hasOwnProperty(p)) {
                    clazz[p] = parent[p];
                    console.log(p);
                };

                var extend_proxy            = function() {};
                extend_proxy.prototype      = parent.prototype;
                clazz.prototype             = new extend_proxy();
                clazz.prototype.constructor = clazz;
            }
        },
        class: function(classInfo) {
            return new Class(classInfo);
        },
        getset: function(get, set) {
            this.get = get;
            this.set = set;
        },
        get: function() { },
        set: function(value) { }

    };

    Object.defineProperty(oop, "public", {
        get: function() { return oop; }
    });

/*
    function IProgram() {
        console.log("IProgram.IProgram");
        this.name = "POWERUMC";
        IProgram.prototype.func = function() { console.log("base.func"); };
    }

    var Program = (function(type) {
        oop.extend(type, Program);

        var self = this;
        var base = type.prototype;

        function Program() {
            console.log("Program.Program");
            type.apply(this, arguments)
        }

        Program.prototype.func = function() {
            console.log("Program.func");
            type.prototype.func.apply(this, arguments);
        }

        return Program;
    })(IProgram);

*/

/*
    var Program = oop.public.class({
        Program: function() { },
        static: {

        },
        Id: oop.getset(function() { return _id; },
                       function(value) { _id = value; })
    });
*/

    return oop;

})(oop);

var Program = oop.public.class({
    Program: function() { },
    Init: function() { },
    static: {
        Version: "1.0.0",
        Date: "2014-10-27"
    },
    A: "A"
});

DEBUG("---------------");
DEBUG("program");
DEBUG(new Program());

<commit_msg>test for Class<commit_after>
;
var DEBUG = function() { console.log(arguments[0]); }

var oop = (function(oop) {
    ;

    var Accessor = {
        Public: "public",
        Private: "private"
    };

    function isObject(obj) {
        return typeof obj === "object" && obj.constructor.name !== "Array";
    }

    function isProperty(obj) {
        return isObject(obj) && obj.get && obj.set;
    }

    function isFunction(obj) {
        return typeof obj === "function";
    }

    function isArray(obj) {
        return typeof obj === "object" && obj.constructor.name === "Array";
    }

    function isStatic(obj) {

    }

    var getProperties = function(clazz) {
        DEBUG("----------- getProperties ---------");
        var type = clazz[0];
        var propList = [];
        for(var p in type) {
            if (!type.hasOwnProperty(p)) continue;
            DEBUG( "name:" + p + "   object:" + type[p] );
            propList.push({ "name":p, "object":type[p] });
        }
        DEBUG(propList);
        return propList;
    };

    var Class = function(parents, classInfo) {
        DEBUG("Class -------------");

        classInfo      = Array.prototype.slice.apply(arguments, [-1]);
        var arrParents = Array.prototype.slice.apply(arguments, [0, arguments.length-1]);
        if (arrParents && arrParents.length <= 1) { parents = undefined; }
        DEBUG("parents: " + parents);
        DEBUG("classInfo: " + classInfo);

        if (classInfo === undefined) {
            DEBUG("classInfo === undefined");
            classInfo = parents;
            parents = undefined;
        }

        return (function() {
                DEBUG(parents);
                if (parents) oop.extend(parents, this);

                var self  = this;
                var type  = this.constructor;
                var props = getProperties(classInfo);

                /*
                for(var i=0; i<props.length; i++) {
                    if (props[i].name == "static") {
                        type[props[i].name] = props[i].object[props[i.name]];
                    } else {
                        DEBUG("COPY " + props[i].name);
                        type.prototype[props[i].name] = props[i].object;
                    }
                }*/
                for(var p in props) {
                    if (!props.hasOwnProperty(p)) continue;
                    if (props[p].name == "static") {
                        var static_object = props[p].object;
                        for(var pp in static_object) {
                            type[pp] = static_object[pp];
                        }
                    } else {
                        DEBUG("COPY " + props[p].name);
                        type.prototype[props[p].name] = props[p].object;
                    }
                }

                (function() {
                    DEBUG("call constructor...");
                    if (parents) {
                        DEBUG("call constructor...parent...");
                        DEBUG(parents);
                        parents.apply(this, arguments);
                    }
                    // if (self.init) {
                    //     DEBUG("call constructor...self...");
                    //     self.init.apply(this, arguments);
                    // }
                })();

                return this;
        });
    };

    oop = {
        extend: function(parent, clazz) {
            DEBUG("oop.extend...");
            for(var p in parent) if (parent.hasOwnProperty(p)) clazz[p] = parent[p];

            var extend_proxy            = function() { };
            extend_proxy.prototype      = parent.prototype;
            clazz.prototype             = new extend_proxy();
            clazz.prototype.constructor = clazz;
        },
        class: function(parents, classInfo) {
            return Class.apply(this, arguments);
        },
        getset: function(get, set) {
            this.get = get;
            this.set = set;
        },
        get: function() { },
        set: function(value) { }

    };

    Object.defineProperty(oop, "public", {
        get: function() { return oop; }
    });

    return oop;

})(oop);

/*
var IProgram = oop.public.class({
    interface1: function() { console.log("IProgram.prototype.interface1();"); }
});

var Program = oop.public.class({
    init: function() { console.log("Program.prototype.init()"); },
    say: function(msg) { console.log("Hello " + msg); },
    static: {
        Version: "1.0.0",
        Date: "2014-10-27"
    },
    Name: "Junil Um"
});
*/

function IProgram() {
    console.log("IProgram.IProgram");
    this.name = "POWERUMC";
    IProgram.prototype.func = function() { console.log("base.func"); };
}

var Program = (function(type) {
    oop.extend(type, Program);

    var self = this;
    var base = type.prototype;

    function Program() {
        console.log("Program.Program");
        type.apply(this, arguments)
    }

    Program.prototype.func = function() {
        console.log("Program.func");
        type.prototype.func.apply(this, arguments);
    }

    return Program;
})(IProgram);
var p = new Program();
DEBUG("Program ------------------");
DEBUG(p);

// var Program = oop.public.class({
//     Program: function() { },
//     static: {

//     },
//     Id: oop.getset(function() { return _id; },
//                    function(value) { _id = value; })
// });

function IIProgram() {
    console.log("call IIProgram");
    this.user = "POWERUMC";
    IIProgram.prototype.func = function() { console.log("base.func"); };
}

var ProgramImpl = oop.public.class(IIProgram, {
    interface2: function() { console.log("ProgramImpl.prototype.interface2"); },
    interface3: function() { console.log("ProgramImpl.prototype.interface3"); },
    interface4: function() { console.log("ProgramImpl.prototype.interface3"); },
    static: {
        Name: "POWERUMC",
        getName: function() { return this.Name; }
    },
    prop1 : {
        get: function() { return this._name; },
        set: function(value) { this._name = value; }
    }
});

DEBUG("pimpl ---------------");
var pimpl = new ProgramImpl();
DEBUG(pimpl);
<|endoftext|>


<commit_before>//TODO This is a test function, adapt to real usage
function sendTestMessage() {
    // Prepare the message, for the keys see appKeys in appinfo.json
    var message = {
        KEY_USER_SETTINGS: 'settings go here'
    };

    // Send it
    var transactionId = Pebble.sendAppMessage(message,
        function onSendSuccess(e) {
            console.log('Successfully delivered message with transactionId=' + e.data.transactionId);
        },
        function onSendError(e) {
            console.log('Unable to deliver message with transactionId=' + e.data.transactionId + ' Error is: ' + e.error.message);
        }
    );
}

// All the code has been run, once Pebble is ready we kickstart the app
Pebble.addEventListener('ready', function onAppReady(e) {
    console.log('Initializing JavaScript app...');

    //TODO Remove, this is just to test the communication
    sendTestMessage();

    console.log('JavaScript app initialized');
});
<commit_msg>Added event listener to open the configuration page on the phone<commit_after>//TODO This is a test function, adapt to real usage
function sendTestMessage() {
    // Prepare the message, for the keys see appKeys in appinfo.json
    var message = {
        KEY_USER_SETTINGS: 'settings go here'
    };

    // Send it
    var transactionId = Pebble.sendAppMessage(message,
        function onSendSuccess(e) {
            console.log('Successfully delivered message with transactionId=' + e.data.transactionId);
        },
        function onSendError(e) {
            console.log('Unable to deliver message with transactionId=' + e.data.transactionId + ' Error is: ' + e.error.message);
        }
    );
}

// Listener triggered when the user presses the configuration button
Pebble.addEventListener('showConfiguration', function onShowConfiguration(e) {
    //TODO Change URL to the final one
    Pebble.openURL('http://10.0.0.5/ruter-pebble-config');
});

// All the code has been run, once Pebble is ready we kickstart the app
Pebble.addEventListener('ready', function onAppReady(e) {
    console.log('Initializing JavaScript app...');

    //TODO Remove, this is just to test the communication
    sendTestMessage();

    console.log('JavaScript app initialized');
});
<|endoftext|>


<commit_before>var live = 'http://api.streetsupport.net'
var dev = 'http://localhost:55881' // eslint-disable-line

var domainRoot = live

var serviceProvidersUrl = '/v1/service-providers/'
var serviceCategoriesUrl = '/v1/service-categories/'
var categoryServiceProvidersUrl = '/v1/categorised-service-providers/show/'
var categoryServiceProvidersWithSubsUrl = '/v2/categorised-service-providers/show/'
var organisationUrl = '/v1/service-providers/show/'

module.exports = {
  serviceProviders: domainRoot + serviceProvidersUrl,
  serviceCategories: domainRoot + serviceCategoriesUrl,
  categoryServiceProviders: domainRoot + categoryServiceProvidersUrl,
  subCategoryServiceProviders: domainRoot + categoryServiceProvidersWithSubsUrl,
  organisation: domainRoot + organisationUrl
}
<commit_msg>added staging domain<commit_after>var live = 'http://api.streetsupport.net'
var dev = 'http://localhost:55881' // eslint-disable-line
var staging = 'http://streetsupport-api-staging.apphb.com' // eslint-disable-line

var domainRoot = staging

var serviceProvidersUrl = '/v1/service-providers/'
var serviceCategoriesUrl = '/v1/service-categories/'
var categoryServiceProvidersUrl = '/v1/categorised-service-providers/show/'
var categoryServiceProvidersWithSubsUrl = '/v2/categorised-service-providers/show/'
var organisationUrl = '/v1/service-providers/show/'

module.exports = {
  serviceProviders: domainRoot + serviceProvidersUrl,
  serviceCategories: domainRoot + serviceCategoriesUrl,
  categoryServiceProviders: domainRoot + categoryServiceProvidersUrl,
  subCategoryServiceProviders: domainRoot + categoryServiceProvidersWithSubsUrl,
  organisation: domainRoot + organisationUrl
}
<|endoftext|>


<commit_before>// JS Goes here - ES6 supported
if (window.netlifyIdentity) {
  window.netlifyIdentity.on('login', () => {
    document.location.href = '/admin/';
  });
}
<commit_msg>Fix issue with always redirecting to /admin when logged in<commit_after>// JS Goes here - ES6 supported
if (window.netlifyIdentity && !window.netlifyIdentity.currentUser()) {
  window.netlifyIdentity.on('login', () => {
    document.location.href = '/admin/';
  });
}
<|endoftext|>


<commit_before>//import Vue from 'vue';
import Vue from 'vue/dist/vue.js';

//Vue Component Library
import BugsModule from "./components/modules/sub_modules/BugsModule.vue";
import CustomersModule from "./components/modules/sub_modules/CustomersModule.vue";
import DocumentsModule from "./components/modules/sub_modules/DocumentsModule.vue";
import GetStakeholders from './components/organisations/GetStakeholders.vue';
import GroupPermissions from "./components/permissions/GroupPermissions.vue";
import GroupsAndUsersModule from "./components/modules/sub_modules/GroupsAndUsersModule.vue";
import ParentModules from "./components/modules/ParentModules.vue";
import MiscModule from "./components/modules/sub_modules/MiscModule.vue";
import AddBugWizard from "./components/modules/wizards/AddBugWizard.vue";
import AddCustomerWizard from "./components/modules/wizards/AddCustomerWizard.vue";
import AddFolderWizard from "./components/modules/wizards/AddFolderWizard.vue";
import AddGroupWizard from "./components/modules/wizards/AddGroupWizard.vue";
import AddLinkWizard from "./components/modules/wizards/AddLinkWizard.vue";
import AddUserWizard from "./components/modules/wizards/AddUserWizard.vue";
import NewCustomer from './components/customers/NewCustomer.vue';
import NewOrganisation from './components/organisations/NewOrganisation.vue';
import NewRequirements from './components/requirements/NewRequirement.vue';
import NewHistoryNoteWizard from "./components/modules/wizards/NewHistoryNoteWizard.vue";
import NewRequirementItemWizard from "./components/modules/wizards/NewRequirementItemWizard.vue";
import NewRequirementLinkWizard from "./components/modules/wizards/NewRequirementLinkWizard.vue";
import RequirementInformation from './components/requirements/RequirementInformation.vue';
import RequirementItemLinksModule from "./components/modules/sub_modules/RequirementItemLinksModule.vue";
import RequirementItemsModule from "./components/modules/sub_modules/RequirementItemsModule.vue";
import RequirementLinksModule from "./components/modules/sub_modules/RequirementLinksModule.vue";
import UploadDocumentWizard from "./components/modules/wizards/UploadDocumentWizard.vue";
import RequirementItemInformation from "./components/requirement_items/RequirementItemInformation.vue";
import ListOrganisations from "./components/organisations/ListOrganisations.vue";
import SearchOrganisations from "./components/search/SearchOrganisations.vue";
import OrganisationInformation from "./components/organisations/OrganisationInformation.vue";
import OrganisationModules from "./components/organisations/OrganisationModules.vue";
import CustomersListModule from "./components/modules/sub_modules/CustomersListModule.vue";
import AssociatedObjects from "./components/modules/sub_modules/AssociatedObjects.vue";
import NewCustomerForm from "./components/customers/NewCustomerForm.vue";
import NewCustomerModal from "./components/customers/NewCustomerModal.vue";
import SearchCustomers from "./components/search/SearchCustomers.vue";
import ListCustomers from "./components/customers/ListCustomers.vue";
import CustomerInformation from "./components/customers/CustomerInformation.vue";
import SearchObjects from "./components/search/SearchObjects.vue";
import ListSearchResults from "./components/search/ListSearchResults.vue";
import ProjectInformation from "./components/projects/ProjectInformation.vue";
import NewProject from "./components/projects/NewProject.vue";
import TaskInformation from "./components/tasks/TaskInformation.vue";
import NewTask from "./components/tasks/NewTask.vue";
import BetweenDates from "./components/dates/BetweenDates.vue";
import StakeholderInformation from "./components/organisations/StakeholderInformation.vue";
import NewKanban from "./components/kanban/NewKanban.vue";
import KanbanPropertyOrder from "./components/kanban/KanbanPropertyOrder.vue";
import KanbanInformation from "./components/kanban/KanbanInformation.vue";
import KanbanCard from "./components/kanban/KanbanCard.vue";
import KanbanBoard from "./components/kanban/KanbanBoard.vue";
import KanbanRow from "./components/kanban/KanbanRow.vue";
import DashboardBugList from "./components/dashboard/DashboardBugList.vue";
import NewKanbanCard from "./components/modules/wizards/NewKanbanCard.vue";
import CardInformation from "./components/kanban/CardInformation.vue";
import ListNotes from "./components/modules/sub_modules/ListNotes.vue";
import NewKanbanLinkWizard from "./components/modules/wizards/NewKanbanLinkWizard.vue";
import DashboardMyObjects from "./components/dashboard/DashboardMyObjects.vue";
import RenderObjectTable from "./components/render/RenderObjectTable.vue";
import ObjectLinks from "./components/modules/sub_modules/ObjectLinks.vue";
import NewLinkWizard from "./components/modules/wizards/NewLinkWizard.vue";
import NewRequestForChange from "./components/request_for_change/NewRequestForChange.vue";
import RfcBackoutPlan from "./components/request_for_change/tabs/RfcBackoutPlan.vue";
import RfcDetails from "./components/request_for_change/tabs/RfcDetails.vue";
import RfcImplementationPlan from "./components/request_for_change/tabs/RfcImplementationPlan.vue";
import RfcRisk from "./components/request_for_change/tabs/RfcRisk.vue";
import RfcTestPlan from "./components/request_for_change/tabs/RfcTestPlan.vue";
import RfcDescription from "./components/request_for_change/tabs/RfcDescription.vue";
import RfcInformation from "./components/request_for_change/RfcInformation.vue";
import RfcModules from "./components/request_for_change/RfcModules.vue";
import RfcNewRunItem from "./components/request_for_change/modules/RfcNewRunItem.vue";
import RfcRunSheetList from "./components/request_for_change/modules/RfcRunSheetList.vue";
import DashboardRfcApprovals from "./components/dashboard/DashboardRfcApprovals.vue";
import RfcApprovalButtons from "./components/request_for_change/modules/RfcApprovalButtons.vue";
import SearchGroups from "./components/search/SearchGroups.vue";
import SearchPermissionSets from "./components/search/SearchPermissionSets.vue";
import SearchUsers from "./components/search/SearchUsers.vue";
import NewGroup from "./components/groups/NewGroup.vue";
import GroupInformation from "./components/groups/GroupInformation.vue";
import UserList from "./components/administration/UserList.vue";
import AdminAddUser from "./components/administration/AdminAddUser.vue";
import PermissionInformation from "./components/permissions/PermissionInformation.vue";
import SinglePermissionProperties from "./components/permissions/SinglePermissionProperties.vue";
import NewPermissionSet from "./components/permissions/NewPermissionSet.vue";
import NewUser from "./components/users/NewUser.vue";
import UserInformation from "./components/users/UserInformation.vue";
import ResetUserPassword from "./components/users/ResetUserPassword.vue";

//Import Bootstrap
import { createPopper } from '@popperjs/core';
import bootstrap from 'bootstrap'

//SCSS Library
import '../sass/main.scss';

//TinyMce
import Editor from '@tinymce/tinymce-vue'

//vSelect
import vSelect from "vue-select";

//VueSortable
import draggable from 'vuedraggable';

//custom javascript
import './global.js';

//D3 Elements
//import * as d3 from "d3";

//Import axios for ajax
const axios = require('axios');
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
axios.defaults.xsrfCookieName = "csrftoken"

//Global Vue Components
Vue.component('vSelect',vSelect);
Vue.component('Editor',Editor);
Vue.component('draggable',draggable);

//Global NearBeach Vue Components
Vue.component('AddBugWizard',AddBugWizard);
Vue.component('AddCustomerWizard',AddCustomerWizard);
Vue.component('AddFolderWizard',AddFolderWizard);
Vue.component('AddGroupWizard',AddGroupWizard);
Vue.component('AddLinkWizard',AddLinkWizard);
Vue.component('AddUserWizard',AddUserWizard);
Vue.component('BugsModule',BugsModule);
Vue.component('CustomersModule',CustomersModule);
Vue.component('DocumentsModule',DocumentsModule);
Vue.component('GetStakeholders',GetStakeholders);
Vue.component('GroupPermissions',GroupPermissions);
Vue.component('GroupsAndUsersModule',GroupsAndUsersModule);
Vue.component('ParentModules',ParentModules);
Vue.component('MiscModule',MiscModule);
Vue.component('NewCustomer',NewCustomer);
Vue.component('NewOrganisation',NewOrganisation);
Vue.component('NewRequirements',NewRequirements);
Vue.component('NewHistoryNoteWizard',NewHistoryNoteWizard);
Vue.component('NewRequirementItemWizard',NewRequirementItemWizard);
Vue.component('NewRequirementLinkWizard',NewRequirementLinkWizard);
Vue.component('RequirementInformation',RequirementInformation);
Vue.component('RequirementItemsModule',RequirementItemsModule);
Vue.component('RequirementItemLinksModule',RequirementItemLinksModule);
Vue.component('RequirementLinksModule',RequirementLinksModule);
Vue.component('UploadDocumentWizard',UploadDocumentWizard);
Vue.component('RequirementItemInformation',RequirementItemInformation);
Vue.component('ListOrganisations',ListOrganisations);
Vue.component('SearchOrganisations',SearchOrganisations);
Vue.component('OrganisationInformation',OrganisationInformation);
Vue.component('OrganisationModules',OrganisationModules);
Vue.component('CustomersListModule',CustomersListModule);
Vue.component('AssociatedObjects',AssociatedObjects);
Vue.component('NewCustomerForm',NewCustomerForm);
Vue.component('NewCustomerModal',NewCustomerModal);
Vue.component('SearchCustomers',SearchCustomers);
Vue.component('ListCustomers',ListCustomers);
Vue.component('CustomerInformation',CustomerInformation);
Vue.component('SearchObjects',SearchObjects);
Vue.component('ListSearchResults',ListSearchResults);
Vue.component('ProjectInformation',ProjectInformation);
Vue.component('NewProject',NewProject);
Vue.component('TaskInformation',TaskInformation);
Vue.component('NewTask',NewTask);
Vue.component('BetweenDates',BetweenDates);
Vue.component('StakeholderInformation',StakeholderInformation);
Vue.component('NewKanban',NewKanban);
Vue.component('KanbanPropertyOrder',KanbanPropertyOrder);
Vue.component('KanbanInformation',KanbanInformation);
Vue.component('KanbanCard',KanbanCard);
Vue.component('KanbanBoard',KanbanBoard);
Vue.component('KanbanRow',KanbanRow);
Vue.component('DashboardBugList',DashboardBugList);
Vue.component('NewKanbanCard',NewKanbanCard);
Vue.component('CardInformation',CardInformation);
Vue.component('ListNotes',ListNotes);
Vue.component('NewKanbanLinkWizard',NewKanbanLinkWizard);
Vue.component('DashboardMyObjects',DashboardMyObjects);
Vue.component('RenderObjectTable',RenderObjectTable);
Vue.component('ObjectLinks',ObjectLinks);
Vue.component('NewLinkWizard',NewLinkWizard);
Vue.component('NewRequestForChange',NewRequestForChange);
Vue.component('RfcBackoutPlan',RfcBackoutPlan);
Vue.component('RfcDetails',RfcDetails);
Vue.component('RfcImplementationPlan',RfcImplementationPlan);
Vue.component('RfcRisk',RfcRisk);
Vue.component('RfcTestPlan',RfcTestPlan);
Vue.component('RfcDescription',RfcDescription);
Vue.component('RfcInformation',RfcInformation);
Vue.component('RfcModules',RfcModules);
Vue.component('RfcNewRunItem',RfcNewRunItem);
Vue.component('RfcRunSheetList',RfcRunSheetList);
Vue.component('DashboardRfcApprovals',DashboardRfcApprovals);
Vue.component('RfcApprovalButtons',RfcApprovalButtons);
Vue.component('SearchGroups',SearchGroups);
Vue.component('SearchPermissionSets',SearchPermissionSets);
Vue.component('SearchUsers',SearchUsers);
Vue.component('NewGroup', NewGroup);
Vue.component('GroupInformation', GroupInformation);
Vue.component('UserList', UserList);
Vue.component('AdminAddUser', AdminAddUser);
Vue.component('PermissionInformation', PermissionInformation);
Vue.component('SinglePermissionProperties', SinglePermissionProperties);
Vue.component('NewPermissionSet', NewPermissionSet);
Vue.component('NewUser', NewUser);
Vue.component('UserInformation', UserInformation);
Vue.component('ResetUserPassword', ResetUserPassword);

//Validation
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)

//Vue-datetime
import { Datetime } from 'vue-datetime';
import 'vue-datetime/dist/vue-datetime.css'
Vue.use(Datetime);
Vue.component('datetime', Datetime);

//Feater Icons
const feather = require('feather-icons')

//Construction of the VUE App
window.vm = new Vue({
    el: "#app",
    components: {
        //Validation
        Vuelidate,

        //Icons
        feather,
    },
    data() {
        return {};
    },
    methods: {},
    mounted() {
        //Remove the loader
        var loader_elem = document.getElementById("loader");
        loader_elem.style.transform = "translateY(-100vh)";

        //Run the feather app
        feather.replace();
    }
});
<commit_msg>Fix to bug - removing loader when we are finished with it<commit_after>//import Vue from 'vue';
import Vue from 'vue/dist/vue.js';

//Vue Component Library
import BugsModule from "./components/modules/sub_modules/BugsModule.vue";
import CustomersModule from "./components/modules/sub_modules/CustomersModule.vue";
import DocumentsModule from "./components/modules/sub_modules/DocumentsModule.vue";
import GetStakeholders from './components/organisations/GetStakeholders.vue';
import GroupPermissions from "./components/permissions/GroupPermissions.vue";
import GroupsAndUsersModule from "./components/modules/sub_modules/GroupsAndUsersModule.vue";
import ParentModules from "./components/modules/ParentModules.vue";
import MiscModule from "./components/modules/sub_modules/MiscModule.vue";
import AddBugWizard from "./components/modules/wizards/AddBugWizard.vue";
import AddCustomerWizard from "./components/modules/wizards/AddCustomerWizard.vue";
import AddFolderWizard from "./components/modules/wizards/AddFolderWizard.vue";
import AddGroupWizard from "./components/modules/wizards/AddGroupWizard.vue";
import AddLinkWizard from "./components/modules/wizards/AddLinkWizard.vue";
import AddUserWizard from "./components/modules/wizards/AddUserWizard.vue";
import NewCustomer from './components/customers/NewCustomer.vue';
import NewOrganisation from './components/organisations/NewOrganisation.vue';
import NewRequirements from './components/requirements/NewRequirement.vue';
import NewHistoryNoteWizard from "./components/modules/wizards/NewHistoryNoteWizard.vue";
import NewRequirementItemWizard from "./components/modules/wizards/NewRequirementItemWizard.vue";
import NewRequirementLinkWizard from "./components/modules/wizards/NewRequirementLinkWizard.vue";
import RequirementInformation from './components/requirements/RequirementInformation.vue';
import RequirementItemLinksModule from "./components/modules/sub_modules/RequirementItemLinksModule.vue";
import RequirementItemsModule from "./components/modules/sub_modules/RequirementItemsModule.vue";
import RequirementLinksModule from "./components/modules/sub_modules/RequirementLinksModule.vue";
import UploadDocumentWizard from "./components/modules/wizards/UploadDocumentWizard.vue";
import RequirementItemInformation from "./components/requirement_items/RequirementItemInformation.vue";
import ListOrganisations from "./components/organisations/ListOrganisations.vue";
import SearchOrganisations from "./components/search/SearchOrganisations.vue";
import OrganisationInformation from "./components/organisations/OrganisationInformation.vue";
import OrganisationModules from "./components/organisations/OrganisationModules.vue";
import CustomersListModule from "./components/modules/sub_modules/CustomersListModule.vue";
import AssociatedObjects from "./components/modules/sub_modules/AssociatedObjects.vue";
import NewCustomerForm from "./components/customers/NewCustomerForm.vue";
import NewCustomerModal from "./components/customers/NewCustomerModal.vue";
import SearchCustomers from "./components/search/SearchCustomers.vue";
import ListCustomers from "./components/customers/ListCustomers.vue";
import CustomerInformation from "./components/customers/CustomerInformation.vue";
import SearchObjects from "./components/search/SearchObjects.vue";
import ListSearchResults from "./components/search/ListSearchResults.vue";
import ProjectInformation from "./components/projects/ProjectInformation.vue";
import NewProject from "./components/projects/NewProject.vue";
import TaskInformation from "./components/tasks/TaskInformation.vue";
import NewTask from "./components/tasks/NewTask.vue";
import BetweenDates from "./components/dates/BetweenDates.vue";
import StakeholderInformation from "./components/organisations/StakeholderInformation.vue";
import NewKanban from "./components/kanban/NewKanban.vue";
import KanbanPropertyOrder from "./components/kanban/KanbanPropertyOrder.vue";
import KanbanInformation from "./components/kanban/KanbanInformation.vue";
import KanbanCard from "./components/kanban/KanbanCard.vue";
import KanbanBoard from "./components/kanban/KanbanBoard.vue";
import KanbanRow from "./components/kanban/KanbanRow.vue";
import DashboardBugList from "./components/dashboard/DashboardBugList.vue";
import NewKanbanCard from "./components/modules/wizards/NewKanbanCard.vue";
import CardInformation from "./components/kanban/CardInformation.vue";
import ListNotes from "./components/modules/sub_modules/ListNotes.vue";
import NewKanbanLinkWizard from "./components/modules/wizards/NewKanbanLinkWizard.vue";
import DashboardMyObjects from "./components/dashboard/DashboardMyObjects.vue";
import RenderObjectTable from "./components/render/RenderObjectTable.vue";
import ObjectLinks from "./components/modules/sub_modules/ObjectLinks.vue";
import NewLinkWizard from "./components/modules/wizards/NewLinkWizard.vue";
import NewRequestForChange from "./components/request_for_change/NewRequestForChange.vue";
import RfcBackoutPlan from "./components/request_for_change/tabs/RfcBackoutPlan.vue";
import RfcDetails from "./components/request_for_change/tabs/RfcDetails.vue";
import RfcImplementationPlan from "./components/request_for_change/tabs/RfcImplementationPlan.vue";
import RfcRisk from "./components/request_for_change/tabs/RfcRisk.vue";
import RfcTestPlan from "./components/request_for_change/tabs/RfcTestPlan.vue";
import RfcDescription from "./components/request_for_change/tabs/RfcDescription.vue";
import RfcInformation from "./components/request_for_change/RfcInformation.vue";
import RfcModules from "./components/request_for_change/RfcModules.vue";
import RfcNewRunItem from "./components/request_for_change/modules/RfcNewRunItem.vue";
import RfcRunSheetList from "./components/request_for_change/modules/RfcRunSheetList.vue";
import DashboardRfcApprovals from "./components/dashboard/DashboardRfcApprovals.vue";
import RfcApprovalButtons from "./components/request_for_change/modules/RfcApprovalButtons.vue";
import SearchGroups from "./components/search/SearchGroups.vue";
import SearchPermissionSets from "./components/search/SearchPermissionSets.vue";
import SearchUsers from "./components/search/SearchUsers.vue";
import NewGroup from "./components/groups/NewGroup.vue";
import GroupInformation from "./components/groups/GroupInformation.vue";
import UserList from "./components/administration/UserList.vue";
import AdminAddUser from "./components/administration/AdminAddUser.vue";
import PermissionInformation from "./components/permissions/PermissionInformation.vue";
import SinglePermissionProperties from "./components/permissions/SinglePermissionProperties.vue";
import NewPermissionSet from "./components/permissions/NewPermissionSet.vue";
import NewUser from "./components/users/NewUser.vue";
import UserInformation from "./components/users/UserInformation.vue";
import ResetUserPassword from "./components/users/ResetUserPassword.vue";

//Import Bootstrap
import { createPopper } from '@popperjs/core';
import bootstrap from 'bootstrap'

//SCSS Library
import '../sass/main.scss';

//TinyMce
import Editor from '@tinymce/tinymce-vue'

//vSelect
import vSelect from "vue-select";

//VueSortable
import draggable from 'vuedraggable';

//custom javascript
import './global.js';

//D3 Elements
//import * as d3 from "d3";

//Import axios for ajax
const axios = require('axios');
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
axios.defaults.xsrfCookieName = "csrftoken"

//Global Vue Components
Vue.component('vSelect',vSelect);
Vue.component('Editor',Editor);
Vue.component('draggable',draggable);

//Global NearBeach Vue Components
Vue.component('AddBugWizard',AddBugWizard);
Vue.component('AddCustomerWizard',AddCustomerWizard);
Vue.component('AddFolderWizard',AddFolderWizard);
Vue.component('AddGroupWizard',AddGroupWizard);
Vue.component('AddLinkWizard',AddLinkWizard);
Vue.component('AddUserWizard',AddUserWizard);
Vue.component('BugsModule',BugsModule);
Vue.component('CustomersModule',CustomersModule);
Vue.component('DocumentsModule',DocumentsModule);
Vue.component('GetStakeholders',GetStakeholders);
Vue.component('GroupPermissions',GroupPermissions);
Vue.component('GroupsAndUsersModule',GroupsAndUsersModule);
Vue.component('ParentModules',ParentModules);
Vue.component('MiscModule',MiscModule);
Vue.component('NewCustomer',NewCustomer);
Vue.component('NewOrganisation',NewOrganisation);
Vue.component('NewRequirements',NewRequirements);
Vue.component('NewHistoryNoteWizard',NewHistoryNoteWizard);
Vue.component('NewRequirementItemWizard',NewRequirementItemWizard);
Vue.component('NewRequirementLinkWizard',NewRequirementLinkWizard);
Vue.component('RequirementInformation',RequirementInformation);
Vue.component('RequirementItemsModule',RequirementItemsModule);
Vue.component('RequirementItemLinksModule',RequirementItemLinksModule);
Vue.component('RequirementLinksModule',RequirementLinksModule);
Vue.component('UploadDocumentWizard',UploadDocumentWizard);
Vue.component('RequirementItemInformation',RequirementItemInformation);
Vue.component('ListOrganisations',ListOrganisations);
Vue.component('SearchOrganisations',SearchOrganisations);
Vue.component('OrganisationInformation',OrganisationInformation);
Vue.component('OrganisationModules',OrganisationModules);
Vue.component('CustomersListModule',CustomersListModule);
Vue.component('AssociatedObjects',AssociatedObjects);
Vue.component('NewCustomerForm',NewCustomerForm);
Vue.component('NewCustomerModal',NewCustomerModal);
Vue.component('SearchCustomers',SearchCustomers);
Vue.component('ListCustomers',ListCustomers);
Vue.component('CustomerInformation',CustomerInformation);
Vue.component('SearchObjects',SearchObjects);
Vue.component('ListSearchResults',ListSearchResults);
Vue.component('ProjectInformation',ProjectInformation);
Vue.component('NewProject',NewProject);
Vue.component('TaskInformation',TaskInformation);
Vue.component('NewTask',NewTask);
Vue.component('BetweenDates',BetweenDates);
Vue.component('StakeholderInformation',StakeholderInformation);
Vue.component('NewKanban',NewKanban);
Vue.component('KanbanPropertyOrder',KanbanPropertyOrder);
Vue.component('KanbanInformation',KanbanInformation);
Vue.component('KanbanCard',KanbanCard);
Vue.component('KanbanBoard',KanbanBoard);
Vue.component('KanbanRow',KanbanRow);
Vue.component('DashboardBugList',DashboardBugList);
Vue.component('NewKanbanCard',NewKanbanCard);
Vue.component('CardInformation',CardInformation);
Vue.component('ListNotes',ListNotes);
Vue.component('NewKanbanLinkWizard',NewKanbanLinkWizard);
Vue.component('DashboardMyObjects',DashboardMyObjects);
Vue.component('RenderObjectTable',RenderObjectTable);
Vue.component('ObjectLinks',ObjectLinks);
Vue.component('NewLinkWizard',NewLinkWizard);
Vue.component('NewRequestForChange',NewRequestForChange);
Vue.component('RfcBackoutPlan',RfcBackoutPlan);
Vue.component('RfcDetails',RfcDetails);
Vue.component('RfcImplementationPlan',RfcImplementationPlan);
Vue.component('RfcRisk',RfcRisk);
Vue.component('RfcTestPlan',RfcTestPlan);
Vue.component('RfcDescription',RfcDescription);
Vue.component('RfcInformation',RfcInformation);
Vue.component('RfcModules',RfcModules);
Vue.component('RfcNewRunItem',RfcNewRunItem);
Vue.component('RfcRunSheetList',RfcRunSheetList);
Vue.component('DashboardRfcApprovals',DashboardRfcApprovals);
Vue.component('RfcApprovalButtons',RfcApprovalButtons);
Vue.component('SearchGroups',SearchGroups);
Vue.component('SearchPermissionSets',SearchPermissionSets);
Vue.component('SearchUsers',SearchUsers);
Vue.component('NewGroup', NewGroup);
Vue.component('GroupInformation', GroupInformation);
Vue.component('UserList', UserList);
Vue.component('AdminAddUser', AdminAddUser);
Vue.component('PermissionInformation', PermissionInformation);
Vue.component('SinglePermissionProperties', SinglePermissionProperties);
Vue.component('NewPermissionSet', NewPermissionSet);
Vue.component('NewUser', NewUser);
Vue.component('UserInformation', UserInformation);
Vue.component('ResetUserPassword', ResetUserPassword);

//Validation
import Vuelidate from 'vuelidate'
Vue.use(Vuelidate)

//Vue-datetime
import { Datetime } from 'vue-datetime';
import 'vue-datetime/dist/vue-datetime.css'
Vue.use(Datetime);
Vue.component('datetime', Datetime);

//Feater Icons
const feather = require('feather-icons')

//Construction of the VUE App
window.vm = new Vue({
    el: "#app",
    components: {
        //Validation
        Vuelidate,

        //Icons
        feather,
    },
    data() {
        return {};
    },
    methods: {},
    mounted() {
        //Remove the loader
        var loader_elem = document.getElementById("loader");
        loader_elem.style.transform = "translateY(-100vh)";

        //Remove the element when we are finished with it
        setTimeout(() => {
            //Destroy the evidance
            loader_elem.remove();
        },500)

        //Run the feather app
        feather.replace();
    }
});
<|endoftext|>


<commit_before>import 'aframe';
import 'babel-polyfill';
import {Animation, Entity, Scene} from 'aframe-react';
import React from 'react';
import ReactDOM from 'react-dom';

import Camera from './components/Camera';
import Cursor from './components/Cursor';
import Sky from './components/Sky';

class SpaceScene extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: 'red'
    }
  }

  changeColor = () => {
    const colors = ['red', 'orange', 'yellow', 'green', 'blue'];
    this.setState({
      color: colors[Math.floor(Math.random() * colors.length)],
    });
  };

  render () {
    return (
      <Scene>
        <Camera><Cursor/></Camera>

        <Sky/>

        <Entity light={{type: 'ambient', color: '#888'}}/>
        <Entity light={{type: 'directional', intensity: 0.5}} position={[-1, 1, 0]}/>
        <Entity light={{type: 'directional', intensity: 1}} position={[1, 1, 0]}/>

        <Entity geometry="primitive: box" material={{color: this.state.color}}
                onClick={this.changeColor}
                position="0 0 -5">
          <Animation attribute="rotation" dur="5000" repeat="indefinite" to="0 360 360"/>
        </Entity>
      </Scene>
    );
  }
}

ReactDOM.render(<SpaceScene/>, document.querySelector('.scene-container'));
<commit_msg>Test change to lighting<commit_after>import 'aframe';
import 'babel-polyfill';
import {Animation, Entity, Scene} from 'aframe-react';
import React from 'react';
import ReactDOM from 'react-dom';

import Camera from './components/Camera';
import Cursor from './components/Cursor';
import Sky from './components/Sky';

class SpaceScene extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: 'red'
    }
  }

  changeColor = () => {
    const colors = ['red', 'orange', 'yellow', 'green', 'blue'];
    this.setState({
      color: colors[Math.floor(Math.random() * colors.length)],
    });
  };

  render () {
    return (
      <Scene>
        <Camera><Cursor/></Camera>

        <Sky/>

        <Entity light={{type: 'ambient', color: '#888'}}/>
        <Entity light={{type: 'directional', intensity: 0.2}} position={[-1, 1, 0]}/>
        <Entity light={{type: 'directional', intensity: 1}} position={[1, 1, 0]}/>

        <Entity geometry="primitive: box" material={{color: this.state.color}}
                onClick={this.changeColor}
                position="0 0 -5">
          <Animation attribute="rotation" dur="5000" repeat="indefinite" to="0 360 360"/>
        </Entity>
      </Scene>
    );
  }
}

ReactDOM.render(<SpaceScene/>, document.querySelector('.scene-container'));
<|endoftext|>


<commit_before>require.config({
  baseUrl: 'src/js',
  paths: {
    jquery: '//code.jquery.com/jquery-2.1.4',
    bootstrap: '//netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap',
    jui : ''
  },
  shim: {
    bootstrap: ['jquery']
  },
  packages: [{
    name: 'summernote',
    main: 'summernote',
    location: './'
  }]
});

require([
  'jquery',
  'summernote',
  'summernote/lite/settings',
  'summernote/jui/settings',
  'summernote/bs3/settings'
], function ($, summernote, lite, jui, bs3) {
  // editor type setting
  switch ($('script[data-editor-type]').data('editor-type')) {
    case 'lite':
      $.summernote = $.extend($.summernote, lite);
      break;
    case 'jui':
      $.summernote = $.extend($.summernote, jui);
      break;
    case 'bs3':
      $.summernote = $.extend($.summernote, bs3);
      break;
  }

  // initialize summernote
  $('.summernote').summernote({
    height: 300
  });
});
<commit_msg>Rollback #3c0d567 for developing bootstrap version.<commit_after>require.config({
  baseUrl: 'src/js',
  paths: {
    jquery: '//code.jquery.com/jquery-2.1.4',
    bootstrap: '//netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap'
  },
  shim: {
    bootstrap: ['jquery']
  },
  packages: [{
    name: 'summernote',
    main: 'summernote',
    location: './'
  }]
});

require([
  'jquery',
  'bootstrap',
  'summernote',
  'summernote/lite/settings',
  'summernote/bs3/settings'
], function ($, bootstrap, summernote, lite, bs3) {
  // editor type setting
  switch ($('script[data-editor-type]').data('editor-type')) {
    case 'lite':
      $.summernote = $.extend($.summernote, lite);
      break;
    case 'bs3':
      $.summernote = $.extend($.summernote, bs3);
      break;
  }

  // initialize summernote
  $('.summernote').summernote({
    height: 300
  });
});
<|endoftext|>


<commit_before>(function ($) {
    $('body').prepend('
It runs!
');

    $.ajax({
        method: 'GET',
        url: 'data/data.json'
    }).done(function (todos) {
        console.log(todos);
        // Got data of all existing todo's, produce the DOM and append to container
        $('#todo-list').append(
            todos.map(function (todo, index) {
                return '' +
                    '
' +
                        '' +
                            '<input type="checkbox" id="todo-input-' + index + '"> ' +
                             todo +
                        '' +
                    '
';
            }));
    });

    // handler for add item to the to do list
    $('#add-todo-form').on('submit', function (e) {
        e.preventDefault();
        console.log('submitting to do item', e);

        var newItem = $('#add-todo-form > input').val();

        if (!newItem) {
            alert('Please put something in the input');
            return;
        }

        $.ajax({
            method: 'GET',
            url: 'data/add-item.json'
        }).done(function (data) {
            console.log('add item data', data);
            alert('Item added!');
            // Server responds OK, item added. Now we sync the UI.
            var todo = newItem;
            var index  = $('#todo-list > li').length;
            $('#todo-list').append('' +
                '
' +
                    '' +
                        '<input type="checkbox" id="todo-input-' + index + '"> ' +
                         todo +
                    '' +
                '
')
        }).fail(function (xhr) {
            console.warn('add item fail', xhr);
        });

    });

}(jQuery));
<commit_msg>DRY - todo item maker<commit_after>(function ($) {
    $('body').prepend('
It runs!
');

    $.ajax({
        method: 'GET',
        url: 'data/data.json'
    }).done(function (todos) {
        console.log(todos);
        // Got data of all existing todo's, produce the DOM and append to container
        $('#todo-list').append(
            todos.map(function (todo, index) {
                return makeTodoItem(todo, index);
            }));
    });

    // handler for add item to the to do list
    $('#add-todo-form').on('submit', function (e) {
        e.preventDefault();
        console.log('submitting to do item', e);

        var newItem = $('#add-todo-form > input').val();

        if (!newItem) {
            alert('Please put something in the input');
            return;
        }

        $.ajax({
            method: 'GET',
            url: 'data/add-item.json'
        }).done(function (data) {
            console.log('add item data', data);
            alert('Item added!');
            // Server responds OK, item added. Now we sync the UI.
            var todo = newItem;
            var index  = $('#todo-list > li').length;
            $('#todo-list').append(makeTodoItem(todo, index));
        }).fail(function (xhr) {
            console.warn('add item fail', xhr);
        });

    });

    function makeTodoItem (text, index) {
        return '
' +
                    '' +
                        '<input type="checkbox" id="todo-input-' + index + '"> ' +
                         text +
                    '' +
                '
';
    }

}(jQuery));
<|endoftext|>


<commit_before>// Get Hash on hashchange
$(window).bind('hashchange', function () {
  getHash()
})

// Get Hash on loading page
$(document).ready(function () {
  initHolder()
  initInfo()
  getHash()
})

// Get the hash and start torrent if there is an hash
function getHash () {
  var hash = window.location.hash.substring(1)
  hash = cleanHash(hash)
  if (hash.length > 0) {
    console.log('New Hash: ' + hash)
    var $holder = $('.holder')
    $holder.css('background', 'no-repeat center url("src/css/dashinfinity.gif")')
    var $instructions = $('.instructions')
    $instructions.text('Fetching metadata')
    download(hash)
  }
}

// turn magnet into hash
function cleanHash (hash) {
  var r = new RegExp('.*:')
  var r2 = new RegExp('&.*')
  return hash.replace(r, '').replace(r2, '')
}

// Initialise seed torrent
function initHolder () {
  var $holder = $('.holder')
  var $upload = $('.holder .upload .button')
  var $uploadBut = $('.holder .upload-but')
  var $state = $('.status')

  if (typeof window.FileReader === 'undefined') {
    $state.attr('id', 'fail')
    $state.text('Instant Share indisponible')
  } else {
    $state.attr('id', 'success')
    $state.text('Instant Share disponible')
  }

  $holder.on('dragover', function (event) {
    event.preventDefault()
    event.stopPropagation()
    this.id = 'hover'
    return false
  })

  $holder.on('dragleave', function (event) {
    event.preventDefault()
    event.stopPropagation()
    this.id = ''
    return false
  })

  $holder.on('drop', function (event) {
    this.id = ''
    event.preventDefault()
    event.stopPropagation()
    var file = event.originalEvent.dataTransfer.files[0]
    $holder.html(
      $('<p>').text(file.name)
    )
    seed(file)
  })

  $upload.click(function () {
    $uploadBut.trigger('click')
  })

  $uploadBut.on('change', function () {
    $holder.html(
      $('<p>').text(this.files[0].name)
    )
    seed(this.files[0])
  })
}

// Seed a file
function seed (file) {
  console.log(file)
  var client = new WebTorrent()
  client.seed(file, {
    announce: [
      'ws://torrent.lunik.xyz:8000'
    ]
  }, onTorrentSeed)
}

// Initialise event on torrent
function initTorrent (torrent) {
  var $holder = $('.holder')
  var $instructions = $('.instructions')

  torrent.on('done', function () {
    console.log('torrent finished downloading')
    updatePeer(torrent.numPeers)
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    $holder.css('background', '')
    appendHolder(torrent)
  })

  torrent.on('wire', function (wire) {
    console.log('new peer: ' + wire.remoteAddress + ':' + wire.remotePort)
    updatePeer(torrent.numPeers)
  })

  torrent.on('download', function (chunkSize) {
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
    $instructions.text('Downloading')
    updateProgress(Math.round(torrent.progress * 100))
  })

  torrent.on('upload', function (data) {
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
    $instructions.text('Uploading')
  })

  torrent.on('noPeers', function () {
    console.log('no peers')
    $instructions.text('Seeding')
    updateProgress(Math.round(torrent.progress * 100))
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
  })
}

// Download a torrent
function download (hash) {
  cleanBody()
  var client = new WebTorrent()
  client.add({
    infoHash: hash,
    announce: [
      'ws://torrent.lunik.xyz:8000'
    ]
  }, onTorrentDownload)
}

// Callback on torrent finish
function onTorrentDownload (torrent) {
  console.log('Downloading ' + torrent.name)
  initTorrent(torrent)
  appendHolder(torrent)
  destroy(torrent)
}

// Clean holder body
function cleanBody () {
  $('.holder').html('')
}

// Callback function when torrent is seeding
function onTorrentSeed (torrent) {
  console.log('Seeding ' + torrent.name)
  console.log('Hash: ' + torrent.infoHash)
  updatePeer(torrent.numPeers)
  initTorrent(torrent)
  appendHolder(torrent)
  prompt('Partager le lien:', document.location.hostname + document.location.pathname + '/#' + torrent.infoHash)
  destroy(torrent)
}

// Attempt to shutdown gracefully
function destroy (torrent) {
  window.addEventListener('beforeunload', function (e) {
    torrent.destroy(console.log('torrent destroyed'))
  })
}

// Show the input with the current url
function showInputUrl (url) {
  $('.url-input').val(url)
  $('.share-link').show()
}

// Show the download button for downloading the file
function showDownloadButton (fileName, url) {
  var $but = $('.download-url')
  $but.text('Télécharger ' + fileName)
  $but.attr('href', url)
  $but.attr('download', fileName)
}

// append a torrent to the holder
function appendHolder (torrent) {
  torrent.files.forEach(function (file) {
    file.appendTo('.holder', function (err) {
      if (err) {
        appendFileIcon(file.name.split('.')[file.name.split('.').length - 1])
      } else {
        $('.holder p').remove()
      }
    })
    file.getBlobURL(function (err, url) {
      if (err) {
        console.log(err)
      }
      showDownloadButton(file.name, url)
      showInputUrl(document.location.hostname + document.location.pathname + '/#' + torrent.infoHash)
    })
  })
}

function appendFileIcon(extention){
  var $icon = $('<i>').addClass('file-icon fa fa-5x')
  switch (extention) {
    case 'zip':
    case 'rar':
    case 'tar':
    case 'gz':
      $icon.addClass('fa-file-archive-o')
      break;

    case 'avi':
    case 'mkv':
    case 'mov':
      $icon.addClass('fa-file-video-o')
      break;

    default:
      $icon.addClass('fa-file-o')
  }
  $icon.appendTo('.holder')
}

// initialize values for torrent info
function initInfo () {
  updateProgress(0)
  updateData(0, 0, 0, 0)
  updatePeer(0)
}

// bytes to formated data
function formatData (bytes) {
  var sizes = ['B', 'kB', 'MB', 'GB', 'TB']
  if (bytes === 0) return '0 B'
  var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10)
  return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]
}

// bits to formated speed
function formatSpeed (bits) {
  var sizes = ['b/s', 'kb/s', 'Mb/s', 'Gb/s', 'Tb/s']
  if (bits === 0) return '0 b/s'
  var i = parseInt(Math.floor(Math.log(bits) / Math.log(1024)), 10)
  return Math.round(bits / Math.pow(1024, i), 2) + ' ' + sizes[i]
}

// Update progress percentage
function updateProgress (percent) {
  var $progress = $('.torrent-infos .progress p')
  $progress.text(percent + '%')
}

// Update value of peer
function updatePeer (peerNum) {
  var $peer = $('.torrent-infos .peer p')
  $peer.text(peerNum)
}

// update the value of downloaded bytes
function updateData (upBytes, downBytes, upSpeed, downSpeed) {
  var $upData = $('.torrent-infos .uploaded-data p')
  $upData.text(formatData(upBytes) + ' @' + formatSpeed(upSpeed))
  var $downData = $('.torrent-infos .downloaded-data p')
  $downData.text(formatData(downBytes) + ' @' + formatSpeed(downSpeed))
}
<commit_msg>standard<commit_after>// Get Hash on hashchange
$(window).bind('hashchange', function () {
  getHash()
})

// Get Hash on loading page
$(document).ready(function () {
  initHolder()
  initInfo()
  getHash()
})

// Get the hash and start torrent if there is an hash
function getHash () {
  var hash = window.location.hash.substring(1)
  hash = cleanHash(hash)
  if (hash.length > 0) {
    console.log('New Hash: ' + hash)
    var $holder = $('.holder')
    $holder.css('background', 'no-repeat center url("src/css/dashinfinity.gif")')
    var $instructions = $('.instructions')
    $instructions.text('Fetching metadata')
    download(hash)
  }
}

// turn magnet into hash
function cleanHash (hash) {
  var r = new RegExp('.*:')
  var r2 = new RegExp('&.*')
  return hash.replace(r, '').replace(r2, '')
}

// Initialise seed torrent
function initHolder () {
  var $holder = $('.holder')
  var $upload = $('.holder .upload .button')
  var $uploadBut = $('.holder .upload-but')
  var $state = $('.status')

  if (typeof window.FileReader === 'undefined') {
    $state.attr('id', 'fail')
    $state.text('Instant Share indisponible')
  } else {
    $state.attr('id', 'success')
    $state.text('Instant Share disponible')
  }

  $holder.on('dragover', function (event) {
    event.preventDefault()
    event.stopPropagation()
    this.id = 'hover'
    return false
  })

  $holder.on('dragleave', function (event) {
    event.preventDefault()
    event.stopPropagation()
    this.id = ''
    return false
  })

  $holder.on('drop', function (event) {
    this.id = ''
    event.preventDefault()
    event.stopPropagation()
    var file = event.originalEvent.dataTransfer.files[0]
    $holder.html(
      $('<p>').text(file.name)
    )
    seed(file)
  })

  $upload.click(function () {
    $uploadBut.trigger('click')
  })

  $uploadBut.on('change', function () {
    $holder.html(
      $('<p>').text(this.files[0].name)
    )
    seed(this.files[0])
  })
}

// Seed a file
function seed (file) {
  console.log(file)
  var client = new WebTorrent()
  client.seed(file, {
    announce: [
      'ws://torrent.lunik.xyz:8000'
    ]
  }, onTorrentSeed)
}

// Initialise event on torrent
function initTorrent (torrent) {
  var $holder = $('.holder')
  var $instructions = $('.instructions')

  torrent.on('done', function () {
    console.log('torrent finished downloading')
    updatePeer(torrent.numPeers)
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    $holder.css('background', '')
    appendHolder(torrent)
  })

  torrent.on('wire', function (wire) {
    console.log('new peer: ' + wire.remoteAddress + ':' + wire.remotePort)
    updatePeer(torrent.numPeers)
  })

  torrent.on('download', function (chunkSize) {
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
    $instructions.text('Downloading')
    updateProgress(Math.round(torrent.progress * 100))
  })

  torrent.on('upload', function (data) {
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
    $instructions.text('Uploading')
  })

  torrent.on('noPeers', function () {
    console.log('no peers')
    $instructions.text('Seeding')
    updateProgress(Math.round(torrent.progress * 100))
    updateData(torrent.uploaded, torrent.downloaded, torrent.uploadSpeed, torrent.downloadSpeed)
    updatePeer(torrent.numPeers)
  })
}

// Download a torrent
function download (hash) {
  cleanBody()
  var client = new WebTorrent()
  client.add({
    infoHash: hash,
    announce: [
      'ws://torrent.lunik.xyz:8000'
    ]
  }, onTorrentDownload)
}

// Callback on torrent finish
function onTorrentDownload (torrent) {
  console.log('Downloading ' + torrent.name)
  initTorrent(torrent)
  appendHolder(torrent)
  destroy(torrent)
}

// Clean holder body
function cleanBody () {
  $('.holder').html('')
}

// Callback function when torrent is seeding
function onTorrentSeed (torrent) {
  console.log('Seeding ' + torrent.name)
  console.log('Hash: ' + torrent.infoHash)
  updatePeer(torrent.numPeers)
  initTorrent(torrent)
  appendHolder(torrent)
  prompt('Partager le lien:', document.location.hostname + document.location.pathname + '/#' + torrent.infoHash)
  destroy(torrent)
}

// Attempt to shutdown gracefully
function destroy (torrent) {
  window.addEventListener('beforeunload', function (e) {
    torrent.destroy(console.log('torrent destroyed'))
  })
}

// Show the input with the current url
function showInputUrl (url) {
  $('.url-input').val(url)
  $('.share-link').show()
}

// Show the download button for downloading the file
function showDownloadButton (fileName, url) {
  var $but = $('.download-url')
  $but.text('Télécharger ' + fileName)
  $but.attr('href', url)
  $but.attr('download', fileName)
}

// append a torrent to the holder
function appendHolder (torrent) {
  torrent.files.forEach(function (file) {
    file.appendTo('.holder', function (err) {
      if (err) {
        appendFileIcon(file.name.split('.')[file.name.split('.').length - 1])
      } else {
        $('.holder p').remove()
      }
    })
    file.getBlobURL(function (err, url) {
      if (err) {
        console.log(err)
      }
      showDownloadButton(file.name, url)
      showInputUrl(document.location.hostname + document.location.pathname + '/#' + torrent.infoHash)
    })
  })
}

function appendFileIcon (extention) {
  var $icon = $('<i>').addClass('file-icon fa fa-5x')
  switch (extention) {
    case 'zip':
    case 'rar':
    case 'tar':
    case 'gz':
      $icon.addClass('fa-file-archive-o')
      break

    case 'avi':
    case 'mkv':
    case 'mov':
      $icon.addClass('fa-file-video-o')
      break

    default:
      $icon.addClass('fa-file-o')
  }
  $icon.appendTo('.holder')
}

// initialize values for torrent info
function initInfo () {
  updateProgress(0)
  updateData(0, 0, 0, 0)
  updatePeer(0)
}

// bytes to formated data
function formatData (bytes) {
  var sizes = ['B', 'kB', 'MB', 'GB', 'TB']
  if (bytes === 0) return '0 B'
  var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10)
  return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]
}

// bits to formated speed
function formatSpeed (bits) {
  var sizes = ['b/s', 'kb/s', 'Mb/s', 'Gb/s', 'Tb/s']
  if (bits === 0) return '0 b/s'
  var i = parseInt(Math.floor(Math.log(bits) / Math.log(1024)), 10)
  return Math.round(bits / Math.pow(1024, i), 2) + ' ' + sizes[i]
}

// Update progress percentage
function updateProgress (percent) {
  var $progress = $('.torrent-infos .progress p')
  $progress.text(percent + '%')
}

// Update value of peer
function updatePeer (peerNum) {
  var $peer = $('.torrent-infos .peer p')
  $peer.text(peerNum)
}

// update the value of downloaded bytes
function updateData (upBytes, downBytes, upSpeed, downSpeed) {
  var $upData = $('.torrent-infos .uploaded-data p')
  $upData.text(formatData(upBytes) + ' @' + formatSpeed(upSpeed))
  var $downData = $('.torrent-infos .downloaded-data p')
  $downData.text(formatData(downBytes) + ' @' + formatSpeed(downSpeed))
}
<|endoftext|>